const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/LeadSiteHome-DBVHB7W6.js","assets/useLeadSiteSearchSuggestions-LWoC_vaB.js","assets/AgentReviewsSection-CAMbwvfx.js","assets/ListingCarouselModule-O78YnZt7.js","assets/imageOptimization-Csrlnz8M.js","assets/ExchangeListingsSection-BRiotzon.js","assets/LeadSiteLuxuryHome-Dr7_WZPX.js","assets/LeadSiteExchangeListings-BvJWLrz4.js","assets/LeadSiteLuxuryHome-DKt_VWIz.css","assets/LeadSiteLandRanchHome-CTZoFn2f.js","assets/LeadSiteSearch-DZ3prAhH.js","assets/LeadSiteListingCardImage-BjxEcy4A.js","assets/LeadSiteMap-BoW-h9Ef.js","assets/LeadSiteLuxurySearch-AeQPiIDm.js","assets/LeadSiteListingDetail-CIAYc0we.js","assets/ListingVideoTour-HR9orsKJ.js","assets/useListingVideos-Cmh5TE4Y.js","assets/LeadSiteLuxuryListingDetail-BQQgFXRL.js","assets/LeadSiteBlog-B6jBsZf_.js","assets/purify.es-BYftNTi7.js","assets/LeadSiteCityPage-CQ7vPKii.js","assets/CityFaqSection-C2lYmBhR.js","assets/LeadSiteSubdivisionPage-C184MseO.js","assets/LeadSiteFocusPage-B-f8mYHf.js","assets/OrgSiteAgents-CuvIleJf.js","assets/OrgSiteHome-BRIrSsyU.js","assets/OrgSitePages-esifGEeS.js","assets/OrgSiteListings-Cc3PXef4.js","assets/PublicLiveEvent-BJdCJSsx.js","assets/useLiveEngagement-pfGhDN49.js","assets/LiveEventConsole-D_ynCJ54.js","assets/StagingStudio-BSqGV00W.js","assets/presets-YfFEjzHB.js","assets/download-BqCckdNk.js","assets/BeforeAfterSlider-DGWLXbGr.js","assets/BuyCreditsDialog-DDDUHcKk.js","assets/StagingLibrary-CU-jj2xO.js","assets/StagingCredits-B1G5gFhS.js","assets/StagingSharePage-MCayCO7y.js","assets/StagingStudioAdmin-CISkjbuI.js","assets/PostcardManager-B53HuS6N.js","assets/usePostcardZones-Cd4ht4Qm.js","assets/MailStudio-adnPkWAo.js","assets/LeadSiteEditor-CNquPZoU.js","assets/ImageUrlField-DUdaaqU0.js","assets/HomepageModuleManager-DVElbfY6.js","assets/LeadSiteEditor-BzY4kI8E.css","assets/AdminLeadSiteThemes-BD_q-s-h.js","assets/AdminFreeWebsiteOfferStudio-BF4t7WxZ.js","assets/MLSListingDetail-BgmTlljF.js","assets/EmailCampaigns-28MqJM_V.js","assets/sesRequest-Bbs2OaEL.js","assets/EmailCampaignComposer-DE6tL_rq.js","assets/EditorModeSelector-C_ahwUge.js","assets/SharedCampaignTemplates-DBbiorWs.js","assets/TemplateEditorDialog-Dw8hLlvw.js","assets/AgentTemplates-0uXH9VVo.js","assets/TheLocalMoveHome-dmWHwbLw.js","assets/tlm-hero-bg-BbD3acLf.js","assets/TheLocalMoveGetStarted-DpqBs5ye.js"])))=>i.map(i=>d[i]); var Zps=Object.defineProperty;var Wft=s=>{throw TypeError(s)};var Xps=(s,t,n)=>t in s?Zps(s,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):s[t]=n;var Nr=(s,t,n)=>Xps(s,typeof t!="symbol"?t+"":t,n),q8e=(s,t,n)=>t.has(s)||Wft("Cannot "+n);var ye=(s,t,n)=>(q8e(s,t,"read from private field"),n?n.call(s):t.get(s)),vs=(s,t,n)=>t.has(s)?Wft("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(s):t.set(s,n),Kt=(s,t,n,r)=>(q8e(s,t,"write to private field"),r?r.call(s,n):t.set(s,n),n),cs=(s,t,n)=>(q8e(s,t,"access private method"),n);var X0=(s,t,n,r)=>({set _(a){Kt(s,t,a,n)},get _(){return ye(s,t,r)}});function Qps(s,t){for(var n=0;nr[a]})}}}return Object.freeze(Object.defineProperty(s,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))r(a);new MutationObserver(a=>{for(const i of a)if(i.type==="childList")for(const l of i.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&r(l)}).observe(document,{childList:!0,subtree:!0});function n(a){const i={};return a.integrity&&(i.integrity=a.integrity),a.referrerPolicy&&(i.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?i.credentials="include":a.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(a){if(a.ep)return;a.ep=!0;const i=n(a);fetch(a.href,i)}})();var Sp=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function ru(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}function Jps(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 CIt={exports:{}},wIe={},AIt={exports:{}},Eu={};/** * @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 uae=Symbol.for("react.element"),egs=Symbol.for("react.portal"),tgs=Symbol.for("react.fragment"),sgs=Symbol.for("react.strict_mode"),ngs=Symbol.for("react.profiler"),rgs=Symbol.for("react.provider"),ags=Symbol.for("react.context"),igs=Symbol.for("react.forward_ref"),ogs=Symbol.for("react.suspense"),lgs=Symbol.for("react.memo"),cgs=Symbol.for("react.lazy"),Kft=Symbol.iterator;function dgs(s){return s===null||typeof s!="object"?null:(s=Kft&&s[Kft]||s["@@iterator"],typeof s=="function"?s:null)}var EIt={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},TIt=Object.assign,MIt={};function FW(s,t,n){this.props=s,this.context=t,this.refs=MIt,this.updater=n||EIt}FW.prototype.isReactComponent={};FW.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")};FW.prototype.forceUpdate=function(s){this.updater.enqueueForceUpdate(this,s,"forceUpdate")};function PIt(){}PIt.prototype=FW.prototype;function eJe(s,t,n){this.props=s,this.context=t,this.refs=MIt,this.updater=n||EIt}var tJe=eJe.prototype=new PIt;tJe.constructor=eJe;TIt(tJe,FW.prototype);tJe.isPureReactComponent=!0;var Yft=Array.isArray,IIt=Object.prototype.hasOwnProperty,sJe={current:null},LIt={key:!0,ref:!0,__self:!0,__source:!0};function RIt(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)IIt.call(t,r)&&!LIt.hasOwnProperty(r)&&(a[r]=t[r]);var o=arguments.length-2;if(o===1)a.children=n;else if(1>>1,J=ae[te];if(0>>1;tea(he,ne))uea(ve,he)?(ae[te]=ve,ae[ue]=ne,te=ue):(ae[te]=he,ae[_e]=ne,te=_e);else if(uea(ve,ne))ae[te]=ve,ae[ue]=ne,te=ue;else break e}}return le}function a(ae,le){var ne=ae.sortIndex-le.sortIndex;return ne!==0?ne: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,y=typeof setTimeout=="function"?setTimeout:null,v=typeof clearTimeout=="function"?clearTimeout:null,b=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function w(ae){for(var 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,Y(A);else{var le=n(d);le!==null&&X(S,le.startTime-ae)}}function A(ae,le){g=!1,x&&(x=!1,v(P),P=-1),f=!0;var ne=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 _e=n(d);_e!==null&&X(S,_e.startTime-le),ce=!1}return ce}finally{h=null,m=ne,f=!1}}var E=!1,I=null,P=-1,R=5,D=-1;function O(){return!(s.unstable_now()-Dae||125te?(ae.sortIndex=ne,t(d,ae),n(c)===null&&ae===n(d)&&(x?(v(P),P=-1):x=!0,X(S,ne-te))):(ae.sortIndex=J,t(c,ae),g||f||(g=!0,Y(A))),ae},s.unstable_shouldYield=O,s.unstable_wrapCallback=function(ae){var le=m;return function(){var ne=m;m=le;try{return ae.apply(this,arguments)}finally{m=ne}}}})(BIt);zIt.exports=BIt;var JQ=zIt.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 _gs=j,k2=JQ;function vi(s){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+s,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Iqe=Object.prototype.hasOwnProperty,wgs=/^[: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]*$/,Xft={},Qft={};function jgs(s){return Iqe.call(Qft,s)?!0:Iqe.call(Xft,s)?!1:wgs.test(s)?Qft[s]=!0:(Xft[s]=!0,!1)}function Ngs(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 kgs(s,t,n,r){if(t===null||typeof t>"u"||Ngs(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 L_(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 kb={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(s){kb[s]=new L_(s,0,!1,s,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(s){var t=s[0];kb[t]=new L_(t,1,!1,s[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(s){kb[s]=new L_(s,2,!1,s.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(s){kb[s]=new L_(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){kb[s]=new L_(s,3,!1,s.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(s){kb[s]=new L_(s,3,!0,s,null,!1,!1)});["capture","download"].forEach(function(s){kb[s]=new L_(s,4,!1,s,null,!1,!1)});["cols","rows","size","span"].forEach(function(s){kb[s]=new L_(s,6,!1,s,null,!1,!1)});["rowSpan","start"].forEach(function(s){kb[s]=new L_(s,5,!1,s.toLowerCase(),null,!1,!1)});var rJe=/[\-:]([a-z])/g;function aJe(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(rJe,aJe);kb[t]=new L_(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(rJe,aJe);kb[t]=new L_(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(rJe,aJe);kb[t]=new L_(t,1,!1,s,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(s){kb[s]=new L_(s,1,!1,s.toLowerCase(),null,!1,!1)});kb.xlinkHref=new L_("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(s){kb[s]=new L_(s,1,!1,s.toLowerCase(),null,!0,!0)});function iJe(s,t,n,r){var a=kb.hasOwnProperty(t)?kb[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{G8e=!1,Error.prepareStackTrace=n}return(s=s?s.displayName||s.name:"")?ZX(s):""}function Sgs(s){switch(s.tag){case 5:return ZX(s.type);case 16:return ZX("Lazy");case 13:return ZX("Suspense");case 19:return ZX("SuspenseList");case 0:case 2:case 15:return s=W8e(s.type,!1),s;case 11:return s=W8e(s.type.render,!1),s;case 1:return s=W8e(s.type,!0),s;default:return""}}function Fqe(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 RU:return"Fragment";case LU:return"Portal";case Lqe:return"Profiler";case oJe:return"StrictMode";case Rqe:return"Suspense";case Dqe:return"SuspenseList"}if(typeof s=="object")switch(s.$$typeof){case qIt:return(s.displayName||"Context")+".Consumer";case UIt:return(s._context.displayName||"Context")+".Provider";case lJe:var t=s.render;return s=s.displayName,s||(s=t.displayName||t.name||"",s=s!==""?"ForwardRef("+s+")":"ForwardRef"),s;case cJe:return t=s.displayName||null,t!==null?t:Fqe(s.type)||"Memo";case eP:t=s._payload,s=s._init;try{return Fqe(s(t))}catch{}}return null}function Cgs(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 Fqe(t);case 8:return t===oJe?"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 vL(s){switch(typeof s){case"boolean":case"number":case"string":case"undefined":return s;case"object":return s;default:return""}}function HIt(s){var t=s.type;return(s=s.nodeName)&&s.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function Ags(s){var t=HIt(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 Yle(s){s._valueTracker||(s._valueTracker=Ags(s))}function GIt(s){if(!s)return!1;var t=s._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return s&&(r=HIt(s)?s.checked?"true":"false":s.value),s=r,s!==n?(t.setValue(s),!0):!1}function zAe(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 Oqe(s,t){var n=t.checked;return Gg({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??s._wrapperState.initialChecked})}function ept(s,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=vL(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 WIt(s,t){t=t.checked,t!=null&&iJe(s,"checked",t,!1)}function zqe(s,t){WIt(s,t);var n=vL(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")?Bqe(s,t.type,n):t.hasOwnProperty("defaultValue")&&Bqe(s,t.type,vL(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(s.defaultChecked=!!t.defaultChecked)}function tpt(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 Bqe(s,t,n){(t!=="number"||zAe(s.ownerDocument)!==s)&&(n==null?s.defaultValue=""+s._wrapperState.initialValue:s.defaultValue!==""+n&&(s.defaultValue=""+n))}var XX=Array.isArray;function vq(s,t,n,r){if(s=s.options,t){t={};for(var a=0;a"+t.valueOf().toString()+"",t=Zle.firstChild;s.firstChild;)s.removeChild(s.firstChild);for(;t.firstChild;)s.appendChild(t.firstChild)}});function jte(s,t){if(t){var n=s.firstChild;if(n&&n===s.lastChild&&n.nodeType===3){n.nodeValue=t;return}}s.textContent=t}var eJ={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},Egs=["Webkit","ms","Moz","O"];Object.keys(eJ).forEach(function(s){Egs.forEach(function(t){t=t+s.charAt(0).toUpperCase()+s.substring(1),eJ[t]=eJ[s]})});function XIt(s,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||eJ.hasOwnProperty(s)&&eJ[s]?(""+t).trim():t+"px"}function QIt(s,t){s=s.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,a=XIt(n,t[n],r);n==="float"&&(n="cssFloat"),r?s.setProperty(n,a):s[n]=a}}var Tgs=Gg({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function qqe(s,t){if(t){if(Tgs[s]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(vi(137,s));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(vi(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(vi(61))}if(t.style!=null&&typeof t.style!="object")throw Error(vi(62))}}function Vqe(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 Hqe=null;function dJe(s){return s=s.target||s.srcElement||window,s.correspondingUseElement&&(s=s.correspondingUseElement),s.nodeType===3?s.parentNode:s}var Gqe=null,bq=null,_q=null;function rpt(s){if(s=fae(s)){if(typeof Gqe!="function")throw Error(vi(280));var t=s.stateNode;t&&(t=CIe(t),Gqe(s.stateNode,s.type,t))}}function JIt(s){bq?_q?_q.push(s):_q=[s]:bq=s}function eLt(){if(bq){var s=bq,t=_q;if(_q=bq=null,rpt(s),t)for(s=0;s>>=0,s===0?32:31-($gs(s)/Ugs|0)|0}var Xle=64,Qle=4194304;function QX(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 qAe(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=QX(o):(i&=l,i!==0&&(r=QX(i)))}else l=n&~a,l!==0?r=QX(l):i!==0&&(r=QX(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 hae(s,t,n){s.pendingLanes|=t,t!==536870912&&(s.suspendedLanes=0,s.pingedLanes=0),s=s.eventTimes,t=31-WS(t),s[t]=n}function Ggs(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=sJ),mpt=" ",fpt=!1;function bLt(s,t){switch(s){case"keyup":return bxs.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function _Lt(s){return s=s.detail,typeof s=="object"&&"data"in s?s.data:null}var DU=!1;function wxs(s,t){switch(s){case"compositionend":return _Lt(t);case"keypress":return t.which!==32?null:(fpt=!0,mpt);case"textInput":return s=t.data,s===mpt&&fpt?null:s;default:return null}}function jxs(s,t){if(DU)return s==="compositionend"||!yJe&&bLt(s,t)?(s=yLt(),rme=pJe=hI=null,DU=!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=ypt(n)}}function kLt(s,t){return s&&t?s===t?!0:s&&s.nodeType===3?!1:t&&t.nodeType===3?kLt(s,t.parentNode):"contains"in s?s.contains(t):s.compareDocumentPosition?!!(s.compareDocumentPosition(t)&16):!1:!1}function SLt(){for(var s=window,t=zAe();t instanceof s.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)s=t.contentWindow;else break;t=zAe(s.document)}return t}function vJe(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 Pxs(s){var t=SLt(),n=s.focusedElem,r=s.selectionRange;if(t!==n&&n&&n.ownerDocument&&kLt(n.ownerDocument.documentElement,n)){if(r!==null&&vJe(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=vpt(n,i);var l=vpt(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,FU=null,Qqe=null,rJ=null,Jqe=!1;function bpt(s,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Jqe||FU==null||FU!==zAe(r)||(r=FU,"selectionStart"in r&&vJe(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}),rJ&&Ete(rJ,r)||(rJ=r,r=GAe(Qqe,"onSelect"),0BU||(s.current=aVe[BU],aVe[BU]=null,BU--)}function Wf(s,t){BU++,aVe[BU]=s.current,s.current=t}var bL={},w1=XL(bL),jw=XL(!1),M7=bL;function iG(s,t){var n=s.type.contextTypes;if(!n)return bL;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 Nw(s){return s=s.childContextTypes,s!=null}function KAe(){Cp(jw),Cp(w1)}function Cpt(s,t,n){if(w1.current!==bL)throw Error(vi(168));Wf(w1,t),Wf(jw,n)}function RLt(s,t,n){var r=s.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var a in r)if(!(a in t))throw Error(vi(108,Cgs(s)||"Unknown",a));return Gg({},n,r)}function YAe(s){return s=(s=s.stateNode)&&s.__reactInternalMemoizedMergedChildContext||bL,M7=w1.current,Wf(w1,s),Wf(jw,jw.current),!0}function Apt(s,t,n){var r=s.stateNode;if(!r)throw Error(vi(169));n?(s=RLt(s,t,M7),r.__reactInternalMemoizedMergedChildContext=s,Cp(jw),Cp(w1),Wf(w1,s)):Cp(jw),Wf(jw,n)}var PA=null,AIe=!1,oze=!1;function DLt(s){PA===null?PA=[s]:PA.push(s)}function Vxs(s){AIe=!0,DLt(s)}function QL(){if(!oze&&PA!==null){oze=!0;var s=0,t=Lm;try{var n=PA;for(Lm=1;s>=l,a-=l,fE=1<<32-WS(t)+a|n<P?(R=I,I=null):R=I.sibling;var D=m(v,I,w[P],S);if(D===null){I===null&&(I=R);break}s&&I&&D.alternate===null&&t(v,I),b=i(D,b,P),E===null?A=D:E.sibling=D,E=D,I=R}if(P===w.length)return n(v,I),Yp&&TR(v,P),A;if(I===null){for(;PP?(R=I,I=null):R=I.sibling;var O=m(v,I,D.value,S);if(O===null){I===null&&(I=R);break}s&&I&&O.alternate===null&&t(v,I),b=i(O,b,P),E===null?A=O:E.sibling=O,E=O,I=R}if(D.done)return n(v,I),Yp&&TR(v,P),A;if(I===null){for(;!D.done;P++,D=w.next())D=h(v,D.value,S),D!==null&&(b=i(D,b,P),E===null?A=D:E.sibling=D,E=D);return Yp&&TR(v,P),A}for(I=r(v,I);!D.done;P++,D=w.next())D=f(I,v,P,D.value,S),D!==null&&(s&&D.alternate!==null&&I.delete(D.key===null?P:D.key),b=i(D,b,P),E===null?A=D:E.sibling=D,E=D);return s&&I.forEach(function(U){return t(v,U)}),Yp&&TR(v,P),A}function y(v,b,w,S){if(typeof w=="object"&&w!==null&&w.type===RU&&w.key===null&&(w=w.props.children),typeof w=="object"&&w!==null){switch(w.$$typeof){case Kle:e:{for(var A=w.key,E=b;E!==null;){if(E.key===A){if(A=w.type,A===RU){if(E.tag===7){n(v,E.sibling),b=a(E,w.props.children),b.return=v,v=b;break e}}else if(E.elementType===A||typeof A=="object"&&A!==null&&A.$$typeof===eP&&Mpt(A)===E.type){n(v,E.sibling),b=a(E,w.props),b.ref=hZ(v,E,w),b.return=v,v=b;break e}n(v,E);break}else t(v,E);E=E.sibling}w.type===RU?(b=Iz(w.props.children,v.mode,S,w.key),b.return=v,v=b):(S=hme(w.type,w.key,w.props,null,v.mode,S),S.ref=hZ(v,b,w),S.return=v,v=S)}return l(v);case LU:e:{for(E=w.key;b!==null;){if(b.key===E)if(b.tag===4&&b.stateNode.containerInfo===w.containerInfo&&b.stateNode.implementation===w.implementation){n(v,b.sibling),b=a(b,w.children||[]),b.return=v,v=b;break e}else{n(v,b);break}else t(v,b);b=b.sibling}b=pze(w,v.mode,S),b.return=v,v=b}return l(v);case eP:return E=w._init,y(v,b,E(w._payload),S)}if(XX(w))return g(v,b,w,S);if(oZ(w))return x(v,b,w,S);ace(v,w)}return typeof w=="string"&&w!==""||typeof w=="number"?(w=""+w,b!==null&&b.tag===6?(n(v,b.sibling),b=a(b,w),b.return=v,v=b):(n(v,b),b=fze(w,v.mode,S),b.return=v,v=b),l(v)):n(v,b)}return y}var lG=BLt(!0),$Lt=BLt(!1),QAe=XL(null),JAe=null,qU=null,jJe=null;function NJe(){jJe=qU=JAe=null}function kJe(s){var t=QAe.current;Cp(QAe),s._currentValue=t}function lVe(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 jq(s,t){JAe=s,jJe=qU=null,s=s.dependencies,s!==null&&s.firstContext!==null&&(s.lanes&t&&(yw=!0),s.firstContext=null)}function lk(s){var t=s._currentValue;if(jJe!==s)if(s={context:s,memoizedValue:t,next:null},qU===null){if(JAe===null)throw Error(vi(308));qU=s,JAe.dependencies={lanes:0,firstContext:s}}else qU=qU.next=s;return t}var s8=null;function SJe(s){s8===null?s8=[s]:s8.push(s)}function ULt(s,t,n,r){var a=t.interleaved;return a===null?(n.next=n,SJe(t)):(n.next=a.next,a.next=n),t.interleaved=n,aT(s,r)}function aT(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 tP=!1;function CJe(s){s.updateQueue={baseState:s.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function qLt(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 kE(s,t){return{eventTime:s,lane:t,tag:0,payload:null,callback:null,next:null}}function PI(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,aT(s,n)}return a=r.interleaved,a===null?(t.next=t,SJe(r)):(t.next=a.next,a.next=t),r.interleaved=t,aT(s,n)}function ime(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,hJe(s,n)}}function Ppt(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 eEe(s,t,n,r){var a=s.updateQueue;tP=!1;var i=a.firstBaseUpdate,l=a.lastBaseUpdate,o=a.shared.pending;if(o!==null){a.shared.pending=null;var c=o,d=c.next;c.next=null,l===null?i=d:l.next=d,l=c;var u=s.alternate;u!==null&&(u=u.updateQueue,o=u.lastBaseUpdate,o!==l&&(o===null?u.firstBaseUpdate=d:o.next=d,u.lastBaseUpdate=c))}if(i!==null){var h=a.baseState;l=0,u=d=c=null,o=i;do{var m=o.lane,f=o.eventTime;if((r&m)===m){u!==null&&(u=u.next={eventTime:f,lane:0,tag:o.tag,payload:o.payload,callback:o.callback,next:null});e:{var g=s,x=o;switch(m=t,f=n,x.tag){case 1:if(g=x.payload,typeof g=="function"){h=g.call(f,h,m);break e}h=g;break e;case 3:g.flags=g.flags&-65537|128;case 0:if(g=x.payload,m=typeof g=="function"?g.call(f,h,m):g,m==null)break e;h=Gg({},h,m);break e;case 2:tP=!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);L7|=l,s.lanes=l,s.memoizedState=h}}function Ipt(s,t,n){if(s=t.effects,t.effects=null,s!==null)for(t=0;tn?n:4,s(!0);var r=cze.transition;cze.transition={};try{s(!1),t()}finally{Lm=n,cze.transition=r}}function i6t(){return ck().memoizedState}function Kxs(s,t,n){var r=LI(s);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},o6t(s))l6t(t,n);else if(n=ULt(s,t,n,r),n!==null){var a=__();KS(n,s,r,a),c6t(n,t,r)}}function Yxs(s,t,n){var r=LI(s),a={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(o6t(s))l6t(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,hC(o,l)){var c=t.interleaved;c===null?(a.next=a,SJe(t)):(a.next=c.next,c.next=a),t.interleaved=a;return}}catch{}finally{}n=ULt(s,t,a,r),n!==null&&(a=__(),KS(n,s,r,a),c6t(n,t,r))}}function o6t(s){var t=s.alternate;return s===Rg||t!==null&&t===Rg}function l6t(s,t){aJ=sEe=!0;var n=s.pending;n===null?t.next=t:(t.next=n.next,n.next=t),s.pending=t}function c6t(s,t,n){if(n&4194240){var r=t.lanes;r&=s.pendingLanes,n|=r,t.lanes=n,hJe(s,n)}}var nEe={readContext:lk,useCallback:Gb,useContext:Gb,useEffect:Gb,useImperativeHandle:Gb,useInsertionEffect:Gb,useLayoutEffect:Gb,useMemo:Gb,useReducer:Gb,useRef:Gb,useState:Gb,useDebugValue:Gb,useDeferredValue:Gb,useTransition:Gb,useMutableSource:Gb,useSyncExternalStore:Gb,useId:Gb,unstable_isNewReconciler:!1},Zxs={readContext:lk,useCallback:function(s,t){return b5().memoizedState=[s,t===void 0?null:t],s},useContext:lk,useEffect:Rpt,useImperativeHandle:function(s,t,n){return n=n!=null?n.concat([s]):null,lme(4194308,4,t6t.bind(null,t,s),n)},useLayoutEffect:function(s,t){return lme(4194308,4,s,t)},useInsertionEffect:function(s,t){return lme(4,2,s,t)},useMemo:function(s,t){var n=b5();return t=t===void 0?null:t,s=s(),n.memoizedState=[s,t],s},useReducer:function(s,t,n){var r=b5();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=Kxs.bind(null,Rg,s),[r.memoizedState,s]},useRef:function(s){var t=b5();return s={current:s},t.memoizedState=s},useState:Lpt,useDebugValue:RJe,useDeferredValue:function(s){return b5().memoizedState=s},useTransition:function(){var s=Lpt(!1),t=s[0];return s=Wxs.bind(null,s[1]),b5().memoizedState=s,[t,s]},useMutableSource:function(){},useSyncExternalStore:function(s,t,n){var r=Rg,a=b5();if(Yp){if(n===void 0)throw Error(vi(407));n=n()}else{if(n=t(),wv===null)throw Error(vi(349));I7&30||WLt(r,t,n)}a.memoizedState=n;var i={value:n,getSnapshot:t};return a.queue=i,Rpt(YLt.bind(null,r,i,s),[s]),r.flags|=2048,Fte(9,KLt.bind(null,r,i,n,t),void 0,null),n},useId:function(){var s=b5(),t=wv.identifierPrefix;if(Yp){var n=pE,r=fE;n=(r&~(1<<32-WS(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=Rte++,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[i4]=t,s[Pte]=r,v6t(s,t,!1,!1),t.stateNode=s;e:{switch(l=Vqe(n,r),n){case"dialog":yp("cancel",s),yp("close",s),a=r;break;case"iframe":case"object":case"embed":yp("load",s),a=r;break;case"video":case"audio":for(a=0;auG&&(t.flags|=128,r=!0,mZ(i,!1),t.lanes=4194304)}else{if(!r)if(s=tEe(l),s!==null){if(t.flags|=128,r=!0,n=s.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),mZ(i,!0),i.tail===null&&i.tailMode==="hidden"&&!l.alternate&&!Yp)return Wb(t),null}else 2*Qx()-i.renderingStartTime>uG&&n!==1073741824&&(t.flags|=128,r=!0,mZ(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=Qx(),t.sibling=null,n=kg.current,Wf(kg,r?n&1|2:n&1),t):(Wb(t),null);case 22:case 23:return $Je(),r=t.memoizedState!==null,s!==null&&s.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?Bj&1073741824&&(Wb(t),t.subtreeFlags&6&&(t.flags|=8192)):Wb(t),null;case 24:return null;case 25:return null}throw Error(vi(156,t.tag))}function rys(s,t){switch(_Je(t),t.tag){case 1:return Nw(t.type)&&KAe(),s=t.flags,s&65536?(t.flags=s&-65537|128,t):null;case 3:return cG(),Cp(jw),Cp(w1),TJe(),s=t.flags,s&65536&&!(s&128)?(t.flags=s&-65537|128,t):null;case 5:return EJe(t),null;case 13:if(Cp(kg),s=t.memoizedState,s!==null&&s.dehydrated!==null){if(t.alternate===null)throw Error(vi(340));oG()}return s=t.flags,s&65536?(t.flags=s&-65537|128,t):null;case 19:return Cp(kg),null;case 4:return cG(),null;case 10:return kJe(t.type._context),null;case 22:case 23:return $Je(),null;case 24:return null;default:return null}}var oce=!1,d1=!1,ays=typeof WeakSet=="function"?WeakSet:Set,Mo=null;function VU(s,t){var n=s.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){gx(s,t,r)}else n.current=null}function xVe(s,t,n){try{n()}catch(r){gx(s,t,r)}}var Gpt=!1;function iys(s,t){if(eVe=VAe,s=SLt(),vJe(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(tVe={focusedElem:s,selectionRange:n},VAe=!1,Mo=t;Mo!==null;)if(t=Mo,s=t.child,(t.subtreeFlags&1028)!==0&&s!==null)s.return=t,Mo=s;else for(;Mo!==null;){t=Mo;try{var g=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(g!==null){var x=g.memoizedProps,y=g.memoizedState,v=t.stateNode,b=v.getSnapshotBeforeUpdate(t.elementType===t.type?x:fS(t.type,x),y);v.__reactInternalSnapshotBeforeUpdate=b}break;case 3:var w=t.stateNode.containerInfo;w.nodeType===1?w.textContent="":w.nodeType===9&&w.documentElement&&w.removeChild(w.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(vi(163))}}catch(S){gx(t,t.return,S)}if(s=t.sibling,s!==null){s.return=t.return,Mo=s;break}Mo=t.return}return g=Gpt,Gpt=!1,g}function iJ(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&&xVe(t,n,i)}a=a.next}while(a!==r)}}function MIe(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 yVe(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 w6t(s){var t=s.alternate;t!==null&&(s.alternate=null,w6t(t)),s.child=null,s.deletions=null,s.sibling=null,s.tag===5&&(t=s.stateNode,t!==null&&(delete t[i4],delete t[Pte],delete t[rVe],delete t[Uxs],delete t[qxs])),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 j6t(s){return s.tag===5||s.tag===3||s.tag===4}function Wpt(s){e:for(;;){for(;s.sibling===null;){if(s.return===null||j6t(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 vVe(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=WAe));else if(r!==4&&(s=s.child,s!==null))for(vVe(s,t,n),s=s.sibling;s!==null;)vVe(s,t,n),s=s.sibling}function bVe(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(bVe(s,t,n),s=s.sibling;s!==null;)bVe(s,t,n),s=s.sibling}var tb=null,MS=!1;function fM(s,t,n){for(n=n.child;n!==null;)N6t(s,t,n),n=n.sibling}function N6t(s,t,n){if(k4&&typeof k4.onCommitFiberUnmount=="function")try{k4.onCommitFiberUnmount(jIe,n)}catch{}switch(n.tag){case 5:d1||VU(n,t);case 6:var r=tb,a=MS;tb=null,fM(s,t,n),tb=r,MS=a,tb!==null&&(MS?(s=tb,n=n.stateNode,s.nodeType===8?s.parentNode.removeChild(n):s.removeChild(n)):tb.removeChild(n.stateNode));break;case 18:tb!==null&&(MS?(s=tb,n=n.stateNode,s.nodeType===8?ize(s.parentNode,n):s.nodeType===1&&ize(s,n),Cte(s)):ize(tb,n.stateNode));break;case 4:r=tb,a=MS,tb=n.stateNode.containerInfo,MS=!0,fM(s,t,n),tb=r,MS=a;break;case 0:case 11:case 14:case 15:if(!d1&&(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)&&xVe(n,t,l),a=a.next}while(a!==r)}fM(s,t,n);break;case 1:if(!d1&&(VU(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(o){gx(n,t,o)}fM(s,t,n);break;case 21:fM(s,t,n);break;case 22:n.mode&1?(d1=(r=d1)||n.memoizedState!==null,fM(s,t,n),d1=r):fM(s,t,n);break;default:fM(s,t,n)}}function Kpt(s){var t=s.updateQueue;if(t!==null){s.updateQueue=null;var n=s.stateNode;n===null&&(n=s.stateNode=new ays),t.forEach(function(r){var a=pys.bind(null,s,r);n.has(r)||(n.add(r),r.then(a,a))})}}function Xk(s,t){var n=t.deletions;if(n!==null)for(var r=0;ra&&(a=l),r&=~i}if(r=a,r=Qx()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*lys(r/1960))-r,10s?16:s,mI===null)var r=!1;else{if(s=mI,mI=null,iEe=0,Nh&6)throw Error(vi(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;cQx()-zJe?Pz(s,0):OJe|=n),kw(s,t)}function P6t(s,t){t===0&&(s.mode&1?(t=Qle,Qle<<=1,!(Qle&130023424)&&(Qle=4194304)):t=1);var n=__();s=aT(s,t),s!==null&&(hae(s,t,n),kw(s,n))}function fys(s){var t=s.memoizedState,n=0;t!==null&&(n=t.retryLane),P6t(s,n)}function pys(s,t){var n=0;switch(s.tag){case 13:var r=s.stateNode,a=s.memoizedState;a!==null&&(n=a.retryLane);break;case 19:r=s.stateNode;break;default:throw Error(vi(314))}r!==null&&r.delete(t),P6t(s,n)}var I6t;I6t=function(s,t,n){if(s!==null)if(s.memoizedProps!==t.pendingProps||jw.current)yw=!0;else{if(!(s.lanes&n)&&!(t.flags&128))return yw=!1,sys(s,t,n);yw=!!(s.flags&131072)}else yw=!1,Yp&&t.flags&1048576&&FLt(t,XAe,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;cme(s,t),s=t.pendingProps;var a=iG(t,w1.current);jq(t,n),a=PJe(null,t,r,s,a,n);var i=IJe();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,Nw(r)?(i=!0,YAe(t)):i=!1,t.memoizedState=a.state!==null&&a.state!==void 0?a.state:null,CJe(t),a.updater=TIe,t.stateNode=a,a._reactInternals=t,dVe(t,r,s,n),t=mVe(null,t,r,!0,i,n)):(t.tag=0,Yp&&i&&bJe(t),a_(null,t,a,n),t=t.child),t;case 16:r=t.elementType;e:{switch(cme(s,t),s=t.pendingProps,a=r._init,r=a(r._payload),t.type=r,a=t.tag=xys(r),s=fS(r,s),a){case 0:t=hVe(null,t,r,s,n);break e;case 1:t=qpt(null,t,r,s,n);break e;case 11:t=$pt(null,t,r,s,n);break e;case 14:t=Upt(null,t,r,fS(r.type,s),n);break e}throw Error(vi(306,r,""))}return t;case 0:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:fS(r,a),hVe(s,t,r,a,n);case 1:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:fS(r,a),qpt(s,t,r,a,n);case 3:e:{if(g6t(t),s===null)throw Error(vi(387));r=t.pendingProps,i=t.memoizedState,a=i.element,qLt(s,t),eEe(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=dG(Error(vi(423)),t),t=Vpt(s,t,r,n,a);break e}else if(r!==a){a=dG(Error(vi(424)),t),t=Vpt(s,t,r,n,a);break e}else for(Zj=MI(t.stateNode.containerInfo.firstChild),n2=t,Yp=!0,FS=null,n=$Lt(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(oG(),r===a){t=iT(s,t,n);break e}a_(s,t,r,n)}t=t.child}return t;case 5:return VLt(t),s===null&&oVe(t),r=t.type,a=t.pendingProps,i=s!==null?s.memoizedProps:null,l=a.children,sVe(r,a)?l=null:i!==null&&sVe(r,i)&&(t.flags|=32),p6t(s,t),a_(s,t,l,n),t.child;case 6:return s===null&&oVe(t),null;case 13:return x6t(s,t,n);case 4:return AJe(t,t.stateNode.containerInfo),r=t.pendingProps,s===null?t.child=lG(t,null,r,n):a_(s,t,r,n),t.child;case 11:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:fS(r,a),$pt(s,t,r,a,n);case 7:return a_(s,t,t.pendingProps,n),t.child;case 8:return a_(s,t,t.pendingProps.children,n),t.child;case 12:return a_(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(QAe,r._currentValue),r._currentValue=l,i!==null)if(hC(i.value,l)){if(i.children===a.children&&!jw.current){t=iT(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=kE(-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),lVe(i.return,n,t),o.lanes|=n;break}c=c.next}}else if(i.tag===10)l=i.type===t.type?null:i.child;else if(i.tag===18){if(l=i.return,l===null)throw Error(vi(341));l.lanes|=n,o=l.alternate,o!==null&&(o.lanes|=n),lVe(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}a_(s,t,a.children,n),t=t.child}return t;case 9:return a=t.type,r=t.pendingProps.children,jq(t,n),a=lk(a),r=r(a),t.flags|=1,a_(s,t,r,n),t.child;case 14:return r=t.type,a=fS(r,t.pendingProps),a=fS(r.type,a),Upt(s,t,r,a,n);case 15:return m6t(s,t,t.type,t.pendingProps,n);case 17:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:fS(r,a),cme(s,t),t.tag=1,Nw(r)?(s=!0,YAe(t)):s=!1,jq(t,n),d6t(t,r,a),dVe(t,r,a,n),mVe(null,t,r,!0,s,n);case 19:return y6t(s,t,n);case 22:return f6t(s,t,n)}throw Error(vi(156,t.tag))};function L6t(s,t){return oLt(s,t)}function gys(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 $N(s,t,n,r){return new gys(s,t,n,r)}function qJe(s){return s=s.prototype,!(!s||!s.isReactComponent)}function xys(s){if(typeof s=="function")return qJe(s)?1:0;if(s!=null){if(s=s.$$typeof,s===lJe)return 11;if(s===cJe)return 14}return 2}function RI(s,t){var n=s.alternate;return n===null?(n=$N(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 hme(s,t,n,r,a,i){var l=2;if(r=s,typeof s=="function")qJe(s)&&(l=1);else if(typeof s=="string")l=5;else e:switch(s){case RU:return Iz(n.children,a,i,t);case oJe:l=8,a|=8;break;case Lqe:return s=$N(12,n,t,a|2),s.elementType=Lqe,s.lanes=i,s;case Rqe:return s=$N(13,n,t,a),s.elementType=Rqe,s.lanes=i,s;case Dqe:return s=$N(19,n,t,a),s.elementType=Dqe,s.lanes=i,s;case VIt:return IIe(n,a,i,t);default:if(typeof s=="object"&&s!==null)switch(s.$$typeof){case UIt:l=10;break e;case qIt:l=9;break e;case lJe:l=11;break e;case cJe:l=14;break e;case eP:l=16,r=null;break e}throw Error(vi(130,s==null?s:typeof s,""))}return t=$N(l,n,t,a),t.elementType=s,t.type=r,t.lanes=i,t}function Iz(s,t,n,r){return s=$N(7,s,r,t),s.lanes=n,s}function IIe(s,t,n,r){return s=$N(22,s,r,t),s.elementType=VIt,s.lanes=n,s.stateNode={isHidden:!1},s}function fze(s,t,n){return s=$N(6,s,null,t),s.lanes=n,s}function pze(s,t,n){return t=$N(4,s.children!==null?s.children:[],s.key,t),t.lanes=n,t.stateNode={containerInfo:s.containerInfo,pendingChildren:null,implementation:s.implementation},t}function yys(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=Y8e(0),this.expirationTimes=Y8e(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Y8e(0),this.identifierPrefix=r,this.onRecoverableError=a,this.mutableSourceEagerHydrationData=null}function VJe(s,t,n,r,a,i,l,o,c){return s=new yys(s,t,n,o,c),t===1?(t=1,i===!0&&(t|=8)):t=0,i=$N(3,null,null,t),s.current=i,i.stateNode=s,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},CJe(i),s}function vys(s,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(O6t)}catch(s){console.error(s)}}O6t(),OIt.exports=D2;var vv=OIt.exports;const z6t=ru(vv);var B6t,sgt=vv;B6t=sgt.createRoot,sgt.hydrateRoot;const Nys="modulepreload",kys=function(s){return"/"+s},ngt={},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=kys(c),c in ngt)return;ngt[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":Nys,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)})},Sys=new Set(["localhost","relevelup.com","thelocalmove.com","www.thelocalmove.com"]),Cys=s=>s.toLowerCase().replace(/:\d+$/,"").replace(/^www\./,"");function Ays(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")||Sys.has(s))}function $6t(s){return U6t(s)!==null}function U6t(s){const t=Cys(s);return Ays(t)?null:t}const Eys=1,Tys=1e6;let gze=0;function Mys(){return gze=(gze+1)%Number.MAX_SAFE_INTEGER,gze.toString()}const xze=new Map,rgt=s=>{if(xze.has(s))return;const t=setTimeout(()=>{xze.delete(s),cJ({type:"REMOVE_TOAST",toastId:s})},Tys);xze.set(s,t)},Pys=(s,t)=>{switch(t.type){case"ADD_TOAST":return{...s,toasts:[t.toast,...s.toasts].slice(0,Eys)};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?rgt(n):s.toasts.forEach(r=>{rgt(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)}}},mme=[];let fme={toasts:[]};function cJ(s){fme=Pys(fme,s),mme.forEach(t=>{t(fme)})}function _a({...s}){const t=Mys(),n=a=>cJ({type:"UPDATE_TOAST",toast:{...a,id:t}}),r=()=>cJ({type:"DISMISS_TOAST",toastId:t});return cJ({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(fme);return j.useEffect(()=>(mme.push(t),()=>{const n=mme.indexOf(t);n>-1&&mme.splice(n,1)}),[s]),{...s,toast:_a,dismiss:n=>cJ({type:"DISMISS_TOAST",toastId:n})}}var Iys=Object.defineProperty,BW=(s,t)=>Iys(s,"name",{value:t,configurable:!0}),q6t=!!(typeof window<"u"&&window.document&&window.document.createElement);function Ra(s,t,{checkForDefaultPrevented:n=!0}={}){return BW(function(a){if(s==null||s(a),n===!1||!a||!a.defaultPrevented)return t==null?void 0:t(a)},"handleEvent")}BW(Ra,"composeEventHandlers");function Lys(s){var t;if(!q6t)throw new Error("Cannot access window outside of the DOM");return((t=s==null?void 0:s.ownerDocument)==null?void 0:t.defaultView)??window}BW(Lys,"getOwnerWindow");function kVe(s){if(!q6t)throw new Error("Cannot access document outside of the DOM");return(s==null?void 0:s.ownerDocument)??document}BW(kVe,"getOwnerDocument");function V6t(s,t=!1){const{activeElement:n}=kVe(s);if(!(n!=null&&n.nodeName))return null;if(H6t(n)&&n.contentDocument)return V6t(n.contentDocument.body,t);if(t){const r=n.getAttribute("aria-activedescendant");if(r){const a=kVe(n).getElementById(r);if(a)return a}}return n}BW(V6t,"getActiveElement");function H6t(s){return s.tagName==="IFRAME"}BW(H6t,"isFrame");var Rys=Object.defineProperty,KJe=(s,t)=>Rys(s,"name",{value:t,configurable:!0});function SVe(s,t){if(typeof s=="function")return s(t);s!=null&&(s.current=t)}KJe(SVe,"setRef");function D7(...s){return t=>{let n=!1;const r=s.map(a=>{const i=SVe(a,t);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let a=0;aDys(s,"name",{value:t,configurable:!0});function Fys(s,t){const n=j.createContext(t);n.displayName=s+"Context";const r=PN(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 PN(a,"useContext"),[r,a]}PN(Fys,"createContext");function tp(s,t=[]){let n=[];function r(i,l){const o=j.createContext(l);o.displayName=i+"Context";const c=n.length;n=[...n,l];const d=PN(h=>{var v;const{scope:m,children:f,...g}=h,x=((v=m==null?void 0:m[s])==null?void 0:v[c])||o,y=j.useMemo(()=>g,Object.values(g));return e.jsx(x.Provider,{value:y,children:f})},"Provider");d.displayName=i+"Provider";function u(h,m,f={}){var v;const{optional:g=!1}=f,x=((v=m==null?void 0:m[s])==null?void 0:v[c])||o,y=j.useContext(x);if(y)return y;if(l!==void 0)return l;if(!g)throw new Error(`\`${h}\` must be used within \`${i}\``)}return PN(u,"useContext"),[d,u]}PN(r,"createContext");const a=PN(()=>{const i=n.map(l=>j.createContext(l));return PN(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,G6t(a,...t)]}PN(tp,"createContextScope");function G6t(...s){const t=s[0];if(s.length===1)return t;const n=PN(()=>{const r=s.map(a=>({useScope:a(),scopeName:a.scopeName}));return PN(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}PN(G6t,"composeContextScopes");var Oys=Object.defineProperty,vC=(s,t)=>Oys(s,"name",{value:t,configurable:!0});function mC(s){const t=j.forwardRef((n,r)=>{let{children:a,...i}=n,l=null,o=!1;const c=[];CVe(a)&&typeof dce=="function"&&(a=dce(a._payload)),j.Children.forEach(a,m=>{var f;if(X6t(m)){o=!0;const g=m;let x="child"in g.props?g.props.child:g.props.children;CVe(x)&&typeof dce=="function"&&(x=dce(x._payload)),l=zys(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?Z6t(l):void 0,u=Vo(r,d);if(!l){if(a||a===0)throw new Error(o?Uys(s):$ys(s));return a}const h=Y6t(i,l.props??{});return l.type!==j.Fragment&&(h.ref=r?u:d),j.cloneElement(l,h)});return t.displayName=`${s}.Slot`,t}vC(mC,"createSlot");var YJe=mC("Slot"),W6t=Symbol.for("radix.slottable");function K6t(s){const t=vC(n=>"child"in n?n.children(n.child):n.children,"Slottable");return t.displayName=`${s}.Slottable`,t.__radixId=W6t,t}vC(K6t,"createSlottable");var zys=vC((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 Y6t(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}}vC(Y6t,"mergeProps");function Z6t(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)}vC(Z6t,"getElementRef");function X6t(s){return j.isValidElement(s)&&typeof s.type=="function"&&"__radixId"in s.type&&s.type.__radixId===W6t}vC(X6t,"isSlottable");var Bys=Symbol.for("react.lazy");function CVe(s){return s!=null&&typeof s=="object"&&"$$typeof"in s&&s.$$typeof===Bys&&"_payload"in s&&Q6t(s._payload)}vC(CVe,"isLazyComponent");function Q6t(s){return typeof s=="object"&&s!==null&&"then"in s}vC(Q6t,"isPromiseLike");var $ys=vC(s=>`${s} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,"createSlotError"),Uys=vC(s=>`${s} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,"createSlottableError"),dce=SB[" use ".trim().toString()],qys=Object.defineProperty,pv=(s,t)=>qys(s,"name",{value:t,configurable:!0});function EB(s){const t=s+"CollectionProvider",[n,r]=tp(t),[a,i]=n(t,{collectionRef:{current:null},itemMap:new Map}),l=pv(x=>{const{scope:y,children:v}=x,b=j.useRef(null),w=j.useRef(new Map).current;return e.jsx(a,{scope:y,itemMap:w,collectionRef:b,children:v})},"CollectionProvider");l.displayName=t;const o=s+"CollectionSlot",c=mC(o),d=j.forwardRef((x,y)=>{const{scope:v,children:b}=x,w=i(o,v),S=Vo(y,w.collectionRef);return e.jsx(c,{ref:S,children:b})});d.displayName=o;const u=s+"CollectionItemSlot",h="data-radix-collection-item",m=mC(u),f=j.forwardRef((x,y)=>{const{scope:v,children:b,...w}=x,S=j.useRef(null),A=Vo(y,S),E=i(u,v);return j.useEffect(()=>(E.itemMap.set(S,{ref:S,...w}),()=>void E.itemMap.delete(S))),e.jsx(m,{[h]:"",ref:A,children:b})});f.displayName=u;function g(x){const y=i(s+"CollectionConsumer",x);return j.useCallback(()=>{const b=y.collectionRef.current;if(!b)return[];const w=Array.from(b.querySelectorAll(`[${h}]`));return Array.from(y.itemMap.values()).sort((E,I)=>w.indexOf(E.ref.current)-w.indexOf(I.ref.current))},[y.collectionRef,y.itemMap])}return pv(g,"useCollection"),[{Provider:l,Slot:d,ItemSlot:f},g,r]}pv(EB,"createCollection");var agt=new WeakMap,Ey,Uj,yze=(Uj=class extends Map{constructor(n){super(n);vs(this,Ey);Kt(this,Ey,[...super.keys()]),agt.set(this,!0)}set(n,r){return agt.get(this)&&(this.has(n)?ye(this,Ey)[ye(this,Ey).indexOf(n)]=n:ye(this,Ey).push(n)),super.set(n,r),this}insert(n,r,a){const i=this.has(r),l=ye(this,Ey).length,o=ZJe(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,Ey)];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 Uj(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 Uj(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 Uj(r)}toReversed(){const n=new Uj;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 Uj(r)}slice(n,r){const a=new Uj;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}},Ey=new WeakMap,pv(Uj,"OrderedDict"),Uj);function pme(s,t){if("at"in Array.prototype)return Array.prototype.at.call(s,t);const n=J6t(s,t);return n===-1?void 0:s[n]}pv(pme,"at");function J6t(s,t){const n=s.length,r=ZJe(t),a=r>=0?r:n+r;return a<0||a>=n?-1:a}pv(J6t,"toSafeIndex");function ZJe(s){return s!==s||s===0?0:Math.trunc(s)}pv(ZJe,"toSafeInteger");function Vys(s){const t=s+"CollectionProvider",[n,r]=tp(t),[a,i]=n(t,{collectionElement:null,collectionRef:{current:null},collectionRefObject:{current:null},itemMap:new yze,setItemMap:pv(()=>{},"setItemMap")}),l=pv(({state:w,...S})=>w?e.jsx(c,{...S,state:w}):e.jsx(o,{...S}),"CollectionProvider");l.displayName=t;const o=pv(w=>{const S=y();return e.jsx(c,{...w,state:S})},"CollectionInit");o.displayName=t+"Init";const c=pv(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=sRt(()=>{});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=mC(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=mC(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);eRt(V.current,I)||(V.current=I);const G=V.current;return j.useEffect(()=>{const Y=G;return W(X=>R?X.has(R)?X.set(R,{...Y,element:R}).toSorted(AVe):(X.set(R,{...Y,element:R}),X.toSorted(AVe)):X),()=>{W(X=>!R||!X.has(R)?X:(X.delete(R),new yze(X)))}},[R,G,W]),e.jsx(g,{[f]:"",ref:O,children:E})});x.displayName=m;function y(){return j.useState(new yze)}pv(y,"useInitCollection");function v(w){const{itemMap:S}=i(s+"CollectionConsumer",w);return S}return pv(v,"useCollection"),[{Provider:l,Slot:h,ItemSlot:x},{createCollectionScope:r,useCollection:v,useInitCollection:y}]}pv(Vys,"createCollection");function eRt(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}pv(eRt,"shallowEqual");function tRt(s,t){return!!(t.compareDocumentPosition(s)&Node.DOCUMENT_POSITION_PRECEDING)}pv(tRt,"isElementPreceding");function AVe(s,t){return!s[1].element||!t[1].element?0:tRt(s[1].element,t[1].element)?-1:1}pv(AVe,"sortByDocumentPosition");function sRt(s){return new MutationObserver(n=>{for(const r of n)if(r.type==="childList"){s();return}})}pv(sRt,"getChildListObserver");var Hys=Object.defineProperty,Gys=(s,t)=>Hys(s,"name",{value:t,configurable:!0}),Wys=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Ei=Wys.reduce((s,t)=>{const n=mC(`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 OIe(s,t){s&&vv.flushSync(()=>s.dispatchEvent(t))}Gys(OIe,"dispatchDiscreteCustomEvent");var Kys=Object.defineProperty,Yys=(s,t)=>Kys(s,"name",{value:t,configurable:!0});function Zp(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)},[])}Yys(Zp,"useCallbackRef");var Zys=Object.defineProperty,p0=(s,t)=>Zys(s,"name",{value:t,configurable:!0}),EVe="dismissableLayer.update",Xys="dismissableLayer.pointerDownOutside",Qys="dismissableLayer.focusOutside",igt,XJe=j.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set,dismissableSurfaces:new Set}),TB=j.forwardRef(p0(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(XJe),[m,f]=j.useState(null),g=(m==null?void 0:m.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,x]=j.useState({}),y=Vo(n,f),v=Array.from(h.layers),[b]=[...h.layersWithOutsidePointerEventsDisabled].slice(-1),w=b?v.indexOf(b):-1,S=m?v.indexOf(m):-1,A=h.layersWithOutsidePointerEventsDisabled.size>0,E=S>=w,I=j.useRef(!1),P=rRt(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=aRt(U=>{if(a&&I.current)return;const W=U.target;[...h.branches].some(G=>G.contains(W))||(o==null||o(U),c==null||c(U),U.defaultPrevented||d==null||d())},g),D=m?S===v.length-1:!1,O=Zp(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&&(igt=g.body.style.pointerEvents,g.body.style.pointerEvents="none"),h.layersWithOutsidePointerEventsDisabled.add(m)),h.layers.add(m),TVe(),()=>{r&&(h.layersWithOutsidePointerEventsDisabled.delete(m),h.layersWithOutsidePointerEventsDisabled.size===0&&(g.body.style.pointerEvents=igt))}},[m,g,r,h]),j.useEffect(()=>()=>{m&&(h.layers.delete(m),h.layersWithOutsidePointerEventsDisabled.delete(m),TVe())},[m,h]),j.useEffect(()=>{const U=p0(()=>x({}),"handleUpdate");return document.addEventListener(EVe,U),()=>document.removeEventListener(EVe,U)},[]),e.jsx(Ei.div,{...u,ref:y,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")),Jys=j.forwardRef(p0(function(t,n){const r=j.useContext(XJe),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 nRt(){const s=j.useContext(XJe),[t,n]=j.useState(null);return j.useEffect(()=>{if(t)return s.dismissableSurfaces.add(t),()=>{s.dismissableSurfaces.delete(t)}},[t,s.dismissableSurfaces]),n}p0(nRt,"useDismissableLayerSurface");var e0s=p0(()=>!0,"IS_TRUE");function rRt(s,t){const{ownerDocument:n=globalThis==null?void 0:globalThis.document,deferPointerDownOutside:r=!1,isDeferredPointerDownOutsideRef:a,dismissableSurfaces:i,shouldHandlePointerDownOutside:l=e0s}=t,o=Zp(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()}p0(m,"resetOutsideInteraction");function f(){return Array.from(u.current.values()).some(Boolean)}p0(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)}p0(g,"handleInteractionCapture");function x(w){d.current&&u.current.set(w.type,!1)}p0(x,"handleInteractionBubble");const y=p0(w=>{if(w.target&&!c.current){let S=function(){n.removeEventListener("click",h.current);const E=f();m(),E||QJe(Xys,o,A,{discrete:!0})};if(p0(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"),v=["pointerup","mousedown","mouseup","touchstart","touchend","click"];for(const w of v)n.addEventListener(w,g,!0),n.addEventListener(w,x);const b=window.setTimeout(()=>{n.addEventListener("pointerdown",y)},0);return()=>{window.clearTimeout(b),n.removeEventListener("pointerdown",y),n.removeEventListener("click",h.current);for(const w of v)n.removeEventListener(w,g,!0),n.removeEventListener(w,x)}},[n,o,r,a,i,l]),{onPointerDownCapture:p0(()=>c.current=!0,"onPointerDownCapture")}}p0(rRt,"usePointerDownOutside");function aRt(s,t=globalThis==null?void 0:globalThis.document){const n=Zp(s),r=j.useRef(!1);return j.useEffect(()=>{const a=p0(i=>{i.target&&!r.current&&QJe(Qys,n,{originalEvent:i},{discrete:!1})},"handleFocus");return t.addEventListener("focusin",a),()=>t.removeEventListener("focusin",a)},[t,n]),{onFocusCapture:p0(()=>r.current=!0,"onFocusCapture"),onBlurCapture:p0(()=>r.current=!1,"onBlurCapture")}}p0(aRt,"useFocusOutside");function TVe(){const s=new CustomEvent(EVe);document.dispatchEvent(s)}p0(TVe,"dispatchUpdate");function QJe(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?OIe(a,i):a.dispatchEvent(i)}p0(QJe,"handleAndDispatchCustomEvent");var t0s=TB,s0s=Jys,Af=globalThis!=null&&globalThis.document?j.useLayoutEffect:()=>{},n0s=Object.defineProperty,r0s=(s,t)=>n0s(s,"name",{value:t,configurable:!0}),gae=j.forwardRef(r0s(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?vv.createPortal(e.jsx(Ei.div,{...a,ref:n}),o):null},"Portal")),a0s=Object.defineProperty,oT=(s,t)=>a0s(s,"name",{value:t,configurable:!0});function iRt(s,t){return j.useReducer((n,r)=>t[n][r]??n,s)}oT(iRt,"useStateMachine");var py=oT(s=>{const{present:t,children:n}=s,r=oRt(t),a=typeof n=="function"?n({present:r.isPresent}):j.Children.only(n),i=lRt(r.ref,cRt(a));return typeof n=="function"||r.isPresent?j.cloneElement(a,{ref:i}):null},"Presence");function oRt(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]=iRt(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??dU(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=dU(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=oT(g=>{const y=dU(r.current).includes(CSS.escape(g.animationName));if(g.target===t&&y&&(d("ANIMATION_END"),!a.current)){const v=t.style.animationFillMode;t.style.animationFillMode="forwards",u=h.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=v)})}},"handleAnimationEnd"),f=oT(g=>{g.target===t&&(i.current=dU(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=dU(h)}else r.current=null;n(u)},[])}}oT(oRt,"usePresence");function MVe(s,t){if(typeof s=="function")return s(t);s!=null&&(s.current=t)}oT(MVe,"setRef");function lRt(...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=MVe(l,n);return!a&&typeof o=="function"&&(a=!0),o});if(a)return()=>{for(let l=0;li0s(s,"name",{value:t,configurable:!0}),ogt=SB[" useEffectEvent ".trim().toString()],lgt=SB[" useInsertionEffect ".trim().toString()];function dRt(s){if(typeof ogt=="function")return ogt(s);const t=j.useRef(()=>{throw new Error("Cannot call an event handler while rendering.")});return typeof lgt=="function"?lgt(()=>{t.current=s}):Af(()=>{t.current=s}),j.useMemo(()=>(...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)},[])}o0s(dRt,"useEffectEvent");var l0s=Object.defineProperty,xae=(s,t)=>l0s(s,"name",{value:t,configurable:!0}),c0s=SB[" useInsertionEffect ".trim().toString()]||Af;function hy({prop:s,defaultProp:t,onChange:n=xae(()=>{},"onChange"),caller:r}){const[a,i,l]=uRt({defaultProp:t,onChange:n}),o=s!==void 0,c=o?s:a,d=j.useCallback(u=>{var h;if(o){const m=hRt(u)?u(s):u;m!==s&&((h=l.current)==null||h.call(l,m))}else i(u)},[o,s,i,l]);return[c,d]}xae(hy,"useControllableState");function uRt({defaultProp:s,onChange:t}){const[n,r]=j.useState(s),a=j.useRef(n),i=j.useRef(t);return c0s(()=>{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]}xae(uRt,"useUncontrolledState");function hRt(s){return typeof s=="function"}xae(hRt,"isFunction");var cgt=Symbol("RADIX:SYNC_STATE");function d0s(s,t,n,r){const{prop:a,defaultProp:i,onChange:l,caller:o}=t,c=a!==void 0,d=dRt(l),u=[{...n,state:i}];r&&u.push(r);const[h,m]=j.useReducer((y,v)=>{if(v.type===cgt)return{...y,state:v.state};const b=s(y,v);return c&&!Object.is(b.state,y.state)&&d(b.state),b},...u),f=h.state,g=j.useRef(f);j.useEffect(()=>{g.current!==f&&(g.current=f,c||d(f))},[f,g,c]);const x=j.useMemo(()=>a!==void 0?{...h,state:a}:h,[h,a]);return j.useEffect(()=>{c&&!Object.is(a,h.state)&&m({type:cgt,state:a})},[a,h.state,c]),[x,m]}xae(d0s,"useControllableStateReducer");var u0s=Object.defineProperty,h0s=(s,t)=>u0s(s,"name",{value:t,configurable:!0}),mRt=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"}),JJe=j.forwardRef(h0s(function(t,n){return e.jsx(Ei.span,{...t,ref:n,style:{...mRt,...t.style}})},"VisuallyHidden")),m0s=JJe,f0s=Object.defineProperty,bf=(s,t)=>f0s(s,"name",{value:t,configurable:!0}),fRt="ToastProvider",[eet,pRt,p0s]=EB("Toast"),[gRt,mkr]=tp("Toast",[p0s]),[g0s,zIe]=gRt(fRt),x0s=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 \`${fRt}\`. Expected non-empty \`string\`.`),e.jsx(eet.Provider,{scope:t,children:e.jsx(g0s,{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"),y0s="ToastViewport",v0s=["F8"],PVe="toast.viewportPause",IVe="toast.viewportResume",b0s=j.forwardRef(bf(function(t,n){const{__scopeToast:r,hotkey:a=v0s,label:i="Notifications ({hotkey})",...l}=t,o=zIe(y0s,r),c=pRt(r),d=j.useRef(null),u=j.useRef(null),h=j.useRef(null),m=j.useRef(null),f=Vo(n,m,o.onViewportChange),g=a.join("+").replace(/Key/g,"").replace(/Digit/g,""),x=o.toastCount>0;j.useEffect(()=>{const v=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",v),()=>document.removeEventListener("keydown",v)},[a]),j.useEffect(()=>{const v=d.current,b=m.current;if(x&&v&&b){const w=bf(()=>{if(!o.isClosePausedRef.current){const I=new CustomEvent(PVe);b.dispatchEvent(I),o.isClosePausedRef.current=!0}},"handlePause"),S=bf(()=>{if(o.isClosePausedRef.current){const I=new CustomEvent(IVe);b.dispatchEvent(I),o.isClosePausedRef.current=!1}},"handleResume"),A=bf(I=>{!v.contains(I.relatedTarget)&&S()},"handleFocusOutResume"),E=bf(()=>{v.contains(document.activeElement)||S()},"handlePointerLeaveResume");return v.addEventListener("focusin",w),v.addEventListener("focusout",A),v.addEventListener("pointermove",w),v.addEventListener("pointerleave",E),window.addEventListener("blur",w),window.addEventListener("focus",S),()=>{v.removeEventListener("focusin",w),v.removeEventListener("focusout",A),v.removeEventListener("pointermove",w),v.removeEventListener("pointerleave",E),window.removeEventListener("blur",w),window.removeEventListener("focus",S)}}},[x,o.isClosePausedRef]);const y=j.useCallback(({tabbingDirection:v})=>{const w=c().map(S=>{const A=S.ref.current,E=[A,..._Rt(A)];return v==="forwards"?E:E.reverse()});return(v==="forwards"?w.reverse():w).flat()},[c]);return j.useEffect(()=>{const v=m.current;if(v){const b=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===v&&D){(E=u.current)==null||E.focus();return}const W=y({tabbingDirection:D?"backwards":"forwards"}),V=W.findIndex(G=>G===R);gme(W.slice(V+1))?w.preventDefault():D?(I=u.current)==null||I.focus():(P=h.current)==null||P.focus()}},"handleKeyDown");return v.addEventListener("keydown",b),()=>v.removeEventListener("keydown",b)}},[c,y]),e.jsxs(s0s,{ref:d,role:"region","aria-label":i.replace("{hotkey}",g),tabIndex:-1,style:{pointerEvents:x?void 0:"none"},children:[x&&e.jsx(dgt,{ref:u,onFocusFromOutsideViewport:()=>{const v=y({tabbingDirection:"forwards"});gme(v)}}),e.jsx(eet.Slot,{scope:r,children:e.jsx(Ei.ol,{tabIndex:-1,...l,ref:f})}),x&&e.jsx(dgt,{ref:h,onFocusFromOutsideViewport:()=>{const v=y({tabbingDirection:"backwards"});gme(v)}})]})},"ToastViewport")),_0s="ToastFocusProxy",dgt=j.forwardRef(bf(function(t,n){const{__scopeToast:r,onFocusFromOutsideViewport:a,...i}=t,l=zIe(_0s,r);return e.jsx(JJe,{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")),BIe="Toast",w0s="toast.swipeStart",j0s="toast.swipeMove",N0s="toast.swipeCancel",k0s="toast.swipeEnd",S0s=j.forwardRef(bf(function(t,n){const{forceMount:r,open:a,defaultOpen:i,onOpenChange:l,...o}=t,[c,d]=hy({prop:a,defaultProp:i??!0,onChange:l,caller:BIe});return e.jsx(py,{present:r||c,children:e.jsx(E0s,{open:c,...o,ref:n,onClose:()=>d(!1),onPause:Zp(t.onPause),onResume:Zp(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")),[C0s,A0s]=gRt(BIe,{onClose(){}}),E0s=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,y=zIe(BIe,r),v=pRt(r),[b,w]=j.useState(null),S=Vo(n,w),A=j.useRef(null),E=j.useRef(null),I=i||y.duration,P=j.useRef(0),R=j.useRef(I),D=j.useRef(0),{onToastAdd:O,onToastRemove:U}=y,W=Zp(()=>{var X;(b==null?void 0:b.contains(document.activeElement))&&((X=y.viewport)==null||X.focus()),o()}),V=j.useCallback(Y=>{!Y||Y===1/0||(window.clearTimeout(D.current),P.current=new Date().getTime(),D.current=window.setTimeout(W,Y))},[W]);j.useEffect(()=>{const Y=y.viewport;if(Y){const X=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 Y.addEventListener(PVe,ae),Y.addEventListener(IVe,X),()=>{Y.removeEventListener(PVe,ae),Y.removeEventListener(IVe,X)}}},[y.viewport,I,d,u,V]),j.useEffect(()=>{l&&!y.isClosePausedRef.current&&V(I)},[l,I,y.isClosePausedRef,V]),j.useEffect(()=>()=>{window.clearTimeout(D.current)},[]),j.useEffect(()=>(O(),()=>U()),[O,U]);const G=j.useMemo(()=>b?tet(b):null,[b]);return y.viewport?e.jsxs(e.Fragment,{children:[G&&e.jsx(T0s,{__scopeToast:r,role:"status","aria-live":a==="foreground"?"assertive":"polite",children:G}),e.jsx(C0s,{scope:r,onClose:W,children:vv.createPortal(e.jsx(eet.ItemSlot,{scope:r,children:e.jsx(t0s,{asChild:!0,onEscapeKeyDown:Ra(c,Y=>{v().some(ae=>{var le;return(le=ae.ref.current)==null?void 0:le.contains(Y.target)})||W()}),children:e.jsx(Ei.li,{tabIndex:0,"data-state":l?"open":"closed","data-swipe-direction":y.swipeDirection,...x,ref:S,style:{userSelect:"none",touchAction:"none",...t.style},onKeyDown:Ra(t.onKeyDown,Y=>{Y.key==="Escape"&&(c==null||c(Y.nativeEvent),Y.nativeEvent.defaultPrevented||W())}),onPointerDown:Ra(t.onPointerDown,Y=>{Y.button===0&&(A.current={x:Y.clientX,y:Y.clientY})}),onPointerMove:Ra(t.onPointerMove,Y=>{if(!A.current)return;const X=Y.clientX-A.current.x,ae=Y.clientY-A.current.y,le=!!E.current,ne=["left","right"].includes(y.swipeDirection),te=["left","up"].includes(y.swipeDirection)?Math.min:Math.max,J=ne?te(0,X):0,ce=ne?0:te(0,ae),_e=Y.pointerType==="touch"?10:2,he={x:J,y:ce},ue={originalEvent:Y,delta:he};le?(E.current=he,eQ(j0s,m,ue,{discrete:!1})):ugt(he,y.swipeDirection,_e)?(E.current=he,eQ(w0s,h,ue,{discrete:!1}),Y.target.setPointerCapture(Y.pointerId)):(Math.abs(X)>_e||Math.abs(ae)>_e)&&(A.current=null)}),onPointerUp:Ra(t.onPointerUp,Y=>{const X=E.current,ae=Y.target;if(ae.hasPointerCapture(Y.pointerId)&&ae.releasePointerCapture(Y.pointerId),E.current=null,A.current=null,X){const le=Y.currentTarget,ne={originalEvent:Y,delta:X};ugt(X,y.swipeDirection,y.swipeThreshold)?eQ(k0s,g,ne,{discrete:!0}):eQ(N0s,f,ne,{discrete:!0}),le.addEventListener("click",te=>te.preventDefault(),{once:!0})}})})})}),y.viewport)})]}):null},"ToastImpl")),T0s=bf(s=>{const{__scopeToast:t,children:n,...r}=s,a=zIe(BIe,t),[i,l]=j.useState(!1),[o,c]=j.useState(!1);return vRt(()=>l(!0)),j.useEffect(()=>{const d=window.setTimeout(()=>c(!0),1e3);return()=>window.clearTimeout(d)},[]),o?null:e.jsx(gae,{asChild:!0,container:a.announcerContainer||void 0,children:e.jsx(JJe,{...r,children:i&&e.jsxs(e.Fragment,{children:[a.label," ",n]})})})},"ToastAnnounce"),M0s=j.forwardRef(bf(function(t,n){const{__scopeToast:r,...a}=t;return e.jsx(Ei.div,{...a,ref:n})},"ToastTitle")),P0s=j.forwardRef(bf(function(t,n){const{__scopeToast:r,...a}=t;return e.jsx(Ei.div,{...a,ref:n})},"ToastDescription")),I0s="ToastAction",L0s=j.forwardRef(bf(function(t,n){const{altText:r,...a}=t;return r.trim()?e.jsx(yRt,{altText:r,asChild:!0,children:e.jsx(xRt,{...a,ref:n})}):(console.error(`Invalid prop \`altText\` supplied to \`${I0s}\`. Expected non-empty \`string\`.`),null)},"ToastAction")),R0s="ToastClose",xRt=j.forwardRef(bf(function(t,n){const{__scopeToast:r,...a}=t,i=A0s(R0s,r);return e.jsx(yRt,{asChild:!0,children:e.jsx(Ei.button,{type:"button",...a,ref:n,onClick:Ra(t.onClick,i.onClose)})})},"ToastClose")),yRt=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 tet(s){const t=[];return Array.from(s.childNodes).forEach(r=>{if(r.nodeType===r.TEXT_NODE&&r.textContent&&t.push(r.textContent),bRt(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(...tet(r))}}),t}bf(tet,"getAnnounceTextContent");function eQ(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?OIe(a,i):a.dispatchEvent(i)}bf(eQ,"handleAndDispatchCustomEvent");var ugt=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 vRt(s=()=>{}){const t=Zp(s);Af(()=>{let n=0,r=0;return n=window.requestAnimationFrame(()=>r=window.requestAnimationFrame(t)),()=>{window.cancelAnimationFrame(n),window.cancelAnimationFrame(r)}},[t])}bf(vRt,"useNextFrame");function bRt(s){return s.nodeType===s.ELEMENT_NODE}bf(bRt,"isHTMLElement");function _Rt(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(_Rt,"getTabbableCandidates");function gme(s){const t=document.activeElement;return s.some(n=>n===t?!0:(n.focus(),document.activeElement!==t))}bf(gme,"focusFirst");var D0s=x0s,wRt=b0s,jRt=S0s,NRt=M0s,kRt=P0s,SRt=L0s,CRt=xRt;function ARt(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,mgt=sd,MB=(s,t)=>n=>{var r;if((t==null?void 0:t.variants)==null)return mgt(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=hgt(u)||hgt(h);return a[d][m]}),o=n&&Object.entries(n).reduce((d,u)=>{let[h,m]=u;return m===void 0||(d[h]=m),d},{}),c=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((d,u)=>{let{class:h,className:m,...f}=u;return Object.entries(f).every(g=>{let[x,y]=g;return Array.isArray(y)?y.includes({...i,...o}[x]):{...i,...o}[x]===y})?[...d,h,m]:d},[]);return mgt(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 F0s=s=>s.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),ERt=(...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 O0s={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 TRt=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,...O0s,width:t,height:t,stroke:s,strokeWidth:r?Number(n)*24/Number(t):n,className:ERt("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(TRt,{ref:i,iconNode:t,className:ERt(`lucide-${F0s(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 xme=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 yme=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 vme=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 bme=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 _me=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 wme=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 PR=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 IR=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 jme=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 LR=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 Nme=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 kme=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 Sme=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 Cme=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 Ame=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 DI=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 Eme=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 Tme=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 Mme=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 Pme=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 Ime=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 Lme=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 Rme=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 Dme=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 Fme=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 Ome=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 zme=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 FI=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 OI=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 Bme=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 $me=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 Ume=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 qme=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 Vme=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 Hme=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 Gme=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 Wme=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 Kme=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 Yme=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 Zme=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 Xme=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 Qme=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 Jme=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 efe=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 tfe=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 sfe=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 nfe=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 rfe=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 afe=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 ife=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 ofe=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 lfe=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 zI=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 cfe=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 jv=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 dfe=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 ufe=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 hfe=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 mfe=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 ffe=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 pfe=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 gfe=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 xfe=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 yfe=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 vfe=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 bfe=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 RR=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 _fe=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 wfe=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 jfe=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 dJ=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 Nfe=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 kfe=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 Sfe=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 DR=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 FR=ge("ArrowDownZA",[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 4v16",key:"1glfcx"}],["path",{d:"M15 4h5l-5 6h5",key:"8asdl1"}],["path",{d:"M15 20v-3.5a2.5 2.5 0 0 1 5 0V20",key:"r6l5cz"}],["path",{d:"M20 18h-5",key:"18j1r2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Dg=ge("ArrowDown",[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Cfe=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 uJ=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 Afe=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 Efe=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 C4=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 Tfe=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 Mfe=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 Pfe=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 OR=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 zy=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 Ife=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 Lfe=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 Rfe=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 zR=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 Lz=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 Dfe=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 Ffe=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 BR=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 Ofe=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 zfe=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 Bfe=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 $fe=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 Ufe=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 qfe=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 Vfe=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 $R=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 Hfe=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 Gfe=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 Wfe=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 Kfe=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 IA=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 Yfe=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 Zfe=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 Xfe=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 Qfe=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 Jfe=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 epe=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 tpe=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 spe=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 npe=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 rpe=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 ape=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 ipe=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 ope=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 lpe=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 cpe=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 Rz=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 dpe=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 upe=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 hpe=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 mpe=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 fpe=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 A0=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 ppe=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 gpe=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 xpe=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 ype=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 vpe=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 bpe=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 hJ=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 _pe=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 wpe=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 A4=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 jpe=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 r2=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 Npe=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 kpe=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 Spe=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 Cpe=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 Ape=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 Epe=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 YS=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 Tpe=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 ZS=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 Uy=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 UR=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 qR=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 Mpe=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 Ppe=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 Ipe=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 Lpe=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 Rpe=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 Dpe=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 Fpe=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 Ope=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 zpe=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 Bpe=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 $pe=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 Upe=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 qpe=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 Vpe=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 Hpe=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 Gpe=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 SE=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 Wpe=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 Kpe=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 Ype=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 Zpe=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 Xpe=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 Qpe=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 Jpe=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 VR=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 ege=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 tge=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 sge=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 nge=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 rge=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 age=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 ige=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 oge=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 lge=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 cge=ge("BookOpenText",[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M16 12h2",key:"7q9ll5"}],["path",{d:"M16 8h2",key:"msurwy"}],["path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",key:"ruj8y"}],["path",{d:"M6 12h2",key:"32wvfc"}],["path",{d:"M6 8h2",key:"30oboj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Xf=ge("BookOpen",[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",key:"ruj8y"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const dge=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 uge=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 hge=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 mge=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 fge=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 pge=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 gge=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 xge=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 yge=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 vge=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 BI=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 bge=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 E0=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 _ge=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 wge=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 jge=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 E4=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 mJ=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 Nge=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 sP=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 kge=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 Sge=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 Cge=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 fJ=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 Age=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 Ege=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 Tge=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 Mge=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 kx=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 Pge=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 Ige=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 Lge=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 Rge=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 Dge=ge("Bug",[["path",{d:"m8 2 1.88 1.88",key:"fmnt4t"}],["path",{d:"M14.12 3.88 16 2",key:"qol33r"}],["path",{d:"M9 7.13v-1a3.003 3.003 0 1 1 6 0v1",key:"d7y7pr"}],["path",{d:"M12 20c-3.3 0-6-2.7-6-6v-3a4 4 0 0 1 4-4h4a4 4 0 0 1 4 4v3c0 3.3-2.7 6-6 6",key:"xs1cw7"}],["path",{d:"M12 20v-9",key:"1qisl0"}],["path",{d:"M6.53 9C4.6 8.8 3 7.1 3 5",key:"32zzws"}],["path",{d:"M6 13H2",key:"82j7cp"}],["path",{d:"M3 21c0-2.1 1.7-3.9 3.8-4",key:"4p0ekp"}],["path",{d:"M20.97 5c0 2.1-1.6 3.8-3.5 4",key:"18gb23"}],["path",{d:"M22 13h-4",key:"1jl80f"}],["path",{d:"M17.2 17c2.1.1 3.8 1.9 3.8 4",key:"k3fwyw"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ji=ge("Building2",[["path",{d:"M6 22V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v18Z",key:"1b4qmf"}],["path",{d:"M6 12H4a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h2",key:"i71pzd"}],["path",{d:"M18 9h2a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2",key:"10jefs"}],["path",{d:"M10 6h4",key:"1itunk"}],["path",{d:"M10 10h4",key:"tcdvrf"}],["path",{d:"M10 14h4",key:"kelpxr"}],["path",{d:"M10 18h4",key:"1ulq68"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $I=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 Fge=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 Oge=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 zge=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 Bge=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 $ge=ge("CakeSlice",[["circle",{cx:"9",cy:"7",r:"2",key:"1305pl"}],["path",{d:"M7.2 7.9 3 11v9c0 .6.4 1 1 1h16c.6 0 1-.4 1-1v-9c0-2-3-6-7-8l-3.6 2.6",key:"xle13f"}],["path",{d:"M16 13H3",key:"1wpj08"}],["path",{d:"M16 17H3",key:"3lvfcd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Fg=ge("Cake",[["path",{d:"M20 21v-8a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v8",key:"1w3rig"}],["path",{d:"M4 16s.5-1 2-1 2.5 2 4 2 2.5-2 4-2 2.5 2 4 2 2-1 2-1",key:"n2jgmb"}],["path",{d:"M2 21h20",key:"1nyx9w"}],["path",{d:"M7 8v3",key:"1qtyvj"}],["path",{d:"M12 8v3",key:"hwp4zt"}],["path",{d:"M17 8v3",key:"1i6e5u"}],["path",{d:"M7 4h.01",key:"1bh4kh"}],["path",{d:"M12 4h.01",key:"1ujb9j"}],["path",{d:"M17 4h.01",key:"1upcoc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const a2=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 Uge=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 qge=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 Vge=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 Hge=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 xb=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 Cu=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 Gge=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 Wge=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 XS=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 Kge=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 Yge=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 kq=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 Zge=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 bv=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 Xge=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 Qge=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 Jge=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 exe=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 pJ=ge("CalendarX",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"m14 14-4 4",key:"rymu2i"}],["path",{d:"m10 14 4 4",key:"3sz06r"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ta=ge("Calendar",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const txe=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 Sx=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 sxe=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 nxe=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 rxe=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 axe=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 ixe=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 HR=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 oxe=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 lxe=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 cxe=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 dxe=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 uxe=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 hxe=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 mxe=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 fxe=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 pxe=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 gxe=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 xxe=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 yxe=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 vxe=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 GR=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 WR=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 bxe=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 _xe=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 wxe=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 KR=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 YR=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 ZR=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 jxe=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 XR=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 Nxe=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 kxe=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 QR=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 Sxe=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 Cxe=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 JR=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 eD=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 Axe=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 tD=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 sD=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 nD=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 Exe=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 Dz=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 ca=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 Txe=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 Mxe=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 Pxe=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 Ixe=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 yb=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 Lxe=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 Rxe=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 Dxe=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 Fxe=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 Oxe=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 zxe=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 Bxe=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 Sw=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 $xe=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 Fz=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 Uxe=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 qxe=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 Vxe=ge("Cigarette",[["path",{d:"M17 12H3a1 1 0 0 0-1 1v2a1 1 0 0 0 1 1h14",key:"1mb5g1"}],["path",{d:"M18 8c0-2.5-2-2.5-2-5",key:"1il607"}],["path",{d:"M21 16a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1",key:"1yl5r7"}],["path",{d:"M22 8c0-2.5-2-2.5-2-5",key:"1gah44"}],["path",{d:"M7 12v4",key:"jqww69"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ll=ge("CircleAlert",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rD=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 aD=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 iD=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 oD=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 lD=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 cD=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 dD=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 uD=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 hD=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 mD=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 fD=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 pD=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 Hxe=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 gD=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 Gxe=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 Wxe=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 Kxe=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 Yxe=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 Zxe=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 Xxe=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 Qxe=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 xD=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 e4=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 yD=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 Jxe=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 vD=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 bD=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 _D=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 wD=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 jD=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 ND=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 kD=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 eye=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 SD=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 CD=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 AD=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 Nu=ge("CircleX",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Og=ge("Circle",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tye=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 sye=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 Sq=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 KN=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 nye=ge("ClipboardCopy",[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M8 4H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2",key:"4jdomd"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v4",key:"3hqy98"}],["path",{d:"M21 14H11",key:"1bme5i"}],["path",{d:"m15 10-4 4 4 4",key:"5dvupr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const zg=ge("ClipboardList",[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2",key:"116196"}],["path",{d:"M12 11h4",key:"1jrz19"}],["path",{d:"M12 16h4",key:"n85exb"}],["path",{d:"M8 11h.01",key:"1dfujw"}],["path",{d:"M8 16h.01",key:"18s6g9"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rye=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 aye=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 ED=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 TD=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 iye=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 oye=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 lye=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 cye=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 dye=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 uye=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 hye=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 mye=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 fye=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 Cq=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 pye=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 gye=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 xye=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 yye=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 vye=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 bye=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 _ye=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 wye=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 jye=ge("ClockArrowUp",[["path",{d:"M13.228 21.925A10 10 0 1 1 21.994 12.338",key:"1fzlyi"}],["path",{d:"M12 6v6l1.562.781",key:"1ujuk9"}],["path",{d:"m14 18 4-4 4 4",key:"ftkppy"}],["path",{d:"M18 22v-8",key:"su0gjh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const da=ge("Clock",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 16 14",key:"68esgv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Nye=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 kye=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 MD=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 Sye=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 Cye=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 Aye=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 Eye=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 Tye=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 Mye=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 Pye=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 Iye=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 Lye=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 Rye=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 Dye=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 Fye=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 nP=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 Oye=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 zye=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 gE=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 Bye=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 t4=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 CE=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 $ye=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 Uye=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 T4=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 qye=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 gJ=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 PD=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 rP=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 Vye=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 Hye=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 Gye=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 Oz=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 Wye=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 Kye=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 Yye=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 Zye=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 Xye=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 ID=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 UI=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 Qye=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 Jye=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 e0e=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 t0e=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 s0e=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 n0e=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 r0e=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 a0e=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 i0e=ge("CopyX",[["line",{x1:"12",x2:"18",y1:"12",y2:"18",key:"1rg63v"}],["line",{x1:"12",x2:"18",y1:"18",y2:"12",key:"ebkxgr"}],["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ha=ge("Copy",[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const o0e=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 l0e=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 c0e=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 xJ=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 d0e=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 u0e=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 h0e=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 m0e=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 f0e=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 p0e=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 g0e=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 x0e=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 Nv=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 y0e=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 v0e=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 b0e=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 _0e=ge("Crosshair",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"22",x2:"18",y1:"12",y2:"12",key:"l9bcsi"}],["line",{x1:"6",x2:"2",y1:"12",y2:"12",key:"13hhkx"}],["line",{x1:"12",x2:"12",y1:"6",y2:"2",key:"10w3f3"}],["line",{x1:"12",x2:"12",y1:"22",y2:"18",key:"15g9kq"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Bg=ge("Crown",[["path",{d:"M11.562 3.266a.5.5 0 0 1 .876 0L15.39 8.87a1 1 0 0 0 1.516.294L21.183 5.5a.5.5 0 0 1 .798.519l-2.834 10.246a1 1 0 0 1-.956.734H5.81a1 1 0 0 1-.957-.734L2.02 6.02a.5.5 0 0 1 .798-.519l4.276 3.664a1 1 0 0 0 1.516-.294z",key:"1vdc57"}],["path",{d:"M5 21h14",key:"11awu3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const w0e=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 j0e=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 N0e=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 k0e=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 S0e=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 C0e=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 A0e=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 Aq=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 E0e=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 T0e=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 M0e=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 P0e=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 LD=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 I0e=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 L0e=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 R0e=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 D0e=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 F0e=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 O0e=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 z0e=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 B0e=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 $0e=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 U0e=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 q0e=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 V0e=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 H0e=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 G0e=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 W0e=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 K0e=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 Y0e=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 Z0e=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 X0e=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 nu=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 Q0e=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 J0e=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 i2=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 eve=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 xi=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 tve=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 sve=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 nve=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 rve=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 ave=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 g1=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 ive=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 ove=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 lve=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 cve=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 dve=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 uve=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 CN=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 hve=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 mve=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 fve=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 Eq=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 Jx=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 l_=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 pve=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 gve=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 xve=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 Tq=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 yve=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 vve=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 bve=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 Fr=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 _ve=ge("EyeClosed",[["path",{d:"m15 18-.722-3.25",key:"1j64jw"}],["path",{d:"M2 8a10.645 10.645 0 0 0 20 0",key:"1e7gxb"}],["path",{d:"m20 15-1.726-2.05",key:"1cnuld"}],["path",{d:"m4 15 1.726-2.05",key:"1dsqqd"}],["path",{d:"m9 18 .722-3.25",key:"ypw2yx"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $g=ge("EyeOff",[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",key:"ct8e1f"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242",key:"151rxh"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",key:"13bj9a"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ca=ge("Eye",[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Qp=ge("Facebook",[["path",{d:"M18 2h-3a5 5 0 0 0-5 5v3H7v4h3v8h4v-8h3l1-4h-4V7a1 1 0 0 1 1-1h3z",key:"1jg4f8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wve=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 jve=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 Nve=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 kve=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 Sve=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 Cve=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 Ave=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 Eve=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 Tve=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 Mve=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 RD=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 Pve=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 Ive=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 Lve=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 DD=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 FD=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 OD=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 zD=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 zz=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 yJ=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 Rve=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 Dve=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 Fve=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 BD=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 Ove=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 zve=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 o2=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 Bve=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 qI=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 $ve=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 Uve=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 qve=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 Vve=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 Hve=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 Gve=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 Wve=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 Kve=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 Yve=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 Zve=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 Xve=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 c_=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 $D=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 Mq=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 Qve=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 Jve=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 ebe=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 tbe=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 vJ=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 sbe=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 YN=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 bJ=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 nbe=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 rbe=ge("FileTerminal",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m8 16 2-2-2-2",key:"10vzyd"}],["path",{d:"M12 18h4",key:"1wd2n7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Jr=ge("FileText",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const abe=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 ibe=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 _J=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 obe=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 lbe=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 wJ=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 cbe=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 dbe=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 ube=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 hbe=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 mbe=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 Pq=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 fbe=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 pbe=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 Cw=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 gbe=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 xbe=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 ybe=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 vbe=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 bbe=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 _be=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 wbe=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 jbe=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 AE=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 Nbe=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 kbe=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 Sbe=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 Cbe=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 VI=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 Abe=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 Ebe=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 jJ=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 Tbe=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 Mbe=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 qS=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 Pbe=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 Ibe=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 Lbe=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 Rbe=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 Dbe=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 Fbe=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 Obe=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 zbe=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 Bbe=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 UD=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 $be=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 Ube=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 qbe=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 Vbe=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 Hbe=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 Gbe=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 Wbe=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 Kbe=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 Ybe=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 Zbe=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 Xbe=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 kv=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 Qbe=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 qD=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 NJ=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 Jbe=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 e1e=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 t1e=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 s1e=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 n1e=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 r1e=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 a1e=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 i1e=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 Iq=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 o1e=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 l1e=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 c1e=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 d1e=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 u1e=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 h1e=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 m1e=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 f1e=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 p1e=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 g1e=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 x1e=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 y1e=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 v1e=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 b1e=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 _1e=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 w1e=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 j1e=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 N1e=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 k1e=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 Bz=ge("Ghost",[["path",{d:"M9 10h.01",key:"qbtxuw"}],["path",{d:"M15 10h.01",key:"1qmjsl"}],["path",{d:"M12 2a8 8 0 0 0-8 8v12l3-3 2.5 2.5L12 19l2.5 2.5L17 19l3 3V10a8 8 0 0 0-8-8z",key:"uwwb07"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ul=ge("Gift",[["rect",{x:"3",y:"8",width:"18",height:"4",rx:"1",key:"bkv52"}],["path",{d:"M12 8v13",key:"1c76mn"}],["path",{d:"M19 12v7a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2v-7",key:"6wjy6b"}],["path",{d:"M7.5 8a2.5 2.5 0 0 1 0-5A4.8 8 0 0 1 12 8a4.8 8 0 0 1 4.5-5 2.5 2.5 0 0 1 0 5",key:"1ihvrl"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const S1e=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 C1e=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 VD=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 A1e=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 E1e=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 T1e=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 M1e=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 P1e=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 I1e=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 L1e=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 R1e=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 D1e=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 F1e=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 O1e=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 z1e=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 B1e=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 $1e=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 U1e=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 q1e=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 V1e=ge("GlobeLock",[["path",{d:"M15.686 15A14.5 14.5 0 0 1 12 22a14.5 14.5 0 0 1 0-20 10 10 0 1 0 9.542 13",key:"qkt0x6"}],["path",{d:"M2 12h8.5",key:"ovaggd"}],["path",{d:"M20 6V4a2 2 0 1 0-4 0v2",key:"1of5e8"}],["rect",{width:"8",height:"5",x:"14",y:"6",rx:"1",key:"1fmf51"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const dl=ge("Globe",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const H1e=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 G1e=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 W1e=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 K1e=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 HD=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 Y1e=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 GD=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 Fj=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 Z1e=ge("GripHorizontal",[["circle",{cx:"12",cy:"9",r:"1",key:"124mty"}],["circle",{cx:"19",cy:"9",r:"1",key:"1ruzo2"}],["circle",{cx:"5",cy:"9",r:"1",key:"1a8b28"}],["circle",{cx:"12",cy:"15",r:"1",key:"1e56xg"}],["circle",{cx:"19",cy:"15",r:"1",key:"1a92ep"}],["circle",{cx:"5",cy:"15",r:"1",key:"5r1jwy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ug=ge("GripVertical",[["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}],["circle",{cx:"9",cy:"5",r:"1",key:"hp0tcf"}],["circle",{cx:"9",cy:"19",r:"1",key:"fkjjf6"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"15",cy:"5",r:"1",key:"19l28e"}],["circle",{cx:"15",cy:"19",r:"1",key:"f4zoj3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const X1e=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 Q1e=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 J1e=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 e_e=ge("Ham",[["path",{d:"M13.144 21.144A7.274 10.445 45 1 0 2.856 10.856",key:"1k1t7q"}],["path",{d:"M13.144 21.144A7.274 4.365 45 0 0 2.856 10.856a7.274 4.365 45 0 0 10.288 10.288",key:"153t1g"}],["path",{d:"M16.565 10.435 18.6 8.4a2.501 2.501 0 1 0 1.65-4.65 2.5 2.5 0 1 0-4.66 1.66l-2.024 2.025",key:"gzrt0n"}],["path",{d:"m8.5 16.5-1-1",key:"otr954"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const kJ=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 t_e=ge("HandCoins",[["path",{d:"M11 15h2a2 2 0 1 0 0-4h-3c-.6 0-1.1.2-1.4.6L3 17",key:"geh8rc"}],["path",{d:"m7 21 1.6-1.4c.3-.4.8-.6 1.4-.6h4c1.1 0 2.1-.4 2.8-1.2l4.6-4.4a2 2 0 0 0-2.75-2.91l-4.2 3.9",key:"1fto5m"}],["path",{d:"m2 16 6 6",key:"1pfhp9"}],["circle",{cx:"16",cy:"9",r:"2.9",key:"1n0dlu"}],["circle",{cx:"6",cy:"5",r:"3",key:"151irh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const SJ=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 s4=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 s_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 n_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 Lq=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 vb=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 r_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 a_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 CJ=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 i_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 HI=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 o_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 l_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 Rq=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 $z=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 Dq=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 c_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 d_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 u_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 h_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 m_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 f_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 p_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 g_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 AJ=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 x_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 y_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 v_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 b_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 __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 Aw=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 w_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 j_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 N_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 k_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 EJ=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 S_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 C_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 WD=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 KD=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 TJ=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 A_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 E_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 T_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 M_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 Sv=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 P_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 I_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 L_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 R_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 Uz=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 YD=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 ZD=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 D_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 Fq=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 QS=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 F_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 EE=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 O_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 z_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 B_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 $_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 l2=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 GI=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 U_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 w_=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 q_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 V_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 H_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 G_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 W_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 K_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 Y_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 Z_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 X_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 Q_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 Oq=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 J_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 ewe=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 XD=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 twe=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 swe=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 nwe=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 rwe=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 awe=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 iwe=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 M4=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 WI=ge("LayoutDashboard",[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Qf=ge("LayoutGrid",[["rect",{width:"7",height:"7",x:"3",y:"3",rx:"1",key:"1g98yp"}],["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["rect",{width:"7",height:"7",x:"14",y:"14",rx:"1",key:"nxv5o0"}],["rect",{width:"7",height:"7",x:"3",y:"14",rx:"1",key:"1bb6yr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const owe=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 lwe=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 cwe=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 c2=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 dwe=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 uwe=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 hwe=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 mwe=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 fwe=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 d2=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 zq=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 pwe=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 gwe=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 JS=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 xwe=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 Wd=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 dy=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 ywe=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 Cv=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 vwe=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 bwe=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 MJ=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 _we=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 wwe=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 u2=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 PJ=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 jwe=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 Nwe=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 kwe=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 Swe=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 Cwe=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 Awe=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 T0=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 Ewe=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 Twe=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 Mwe=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 Pwe=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 Bq=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 QD=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 IJ=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 JD=ge("LockOpen",[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 9.9-1",key:"1mm8w8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pc=ge("Lock",[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const KI=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 qz=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 Iwe=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 Lwe=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 Rwe=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 Dwe=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 Vz=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 Fwe=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 $q=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 Uq=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 Owe=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 zwe=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 Bwe=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 YI=ge("MailX",[["path",{d:"M22 13V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v12c0 1.1.9 2 2 2h9",key:"1j9vog"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}],["path",{d:"m17 17 4 4",key:"1b3523"}],["path",{d:"m21 17-4 4",key:"uinynz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mn=ge("Mail",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $we=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 Uwe=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 qwe=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 Vwe=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 Hwe=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 Gwe=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 Wwe=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 Kwe=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 Ywe=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 Zwe=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 Xwe=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 Qwe=ge("MapPinX",[["path",{d:"M19.752 11.901A7.78 7.78 0 0 0 20 10a8 8 0 0 0-16 0c0 4.993 5.539 10.193 7.399 11.799a1 1 0 0 0 1.202 0 19 19 0 0 0 .09-.077",key:"y0ewhp"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}],["path",{d:"m21.5 15.5-5 5",key:"11iqnx"}],["path",{d:"m21.5 20.5-5-5",key:"1bylgx"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ci=ge("MapPin",[["path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0",key:"1r0f0z"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const LJ=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 Hz=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 Jwe=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 RJ=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 Gz=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 TE=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 eje=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 tje=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 sje=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 ME=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 Wz=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 nje=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 rje=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 qq=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 aje=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 ije=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 oje=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 DJ=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 lje=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 cje=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 dje=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 uje=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 hje=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 mje=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 fje=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 pje=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 gje=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 FJ=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 xje=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 m4=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 PE=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 OJ=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 yje=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 vje=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 zJ=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 bje=ge("MessageSquareX",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}],["path",{d:"m14.5 7.5-5 5",key:"3lb6iw"}],["path",{d:"m9.5 7.5 5 5",key:"ko136h"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const eo=ge("MessageSquare",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const BJ=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 _je=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 eF=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 Kz=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 wje=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 jje=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 Nje=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 kje=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 Sje=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 Cje=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 Aje=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 Eje=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 ZN=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 Tje=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 Mje=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 Pje=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 Ije=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 Lje=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 Rje=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 Vq=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 Dje=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 Fje=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 Oje=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 Yz=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 zje=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 XN=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 Bje=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 $je=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 Uje=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 qje=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 Vje=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 $J=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 Hje=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 cb=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 Gje=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 tF=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 Wje=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 Kje=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 Yje=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 Zje=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 Xje=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 Qje=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 Jje=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 e2e=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 t2e=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 s2e=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 n2e=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 r2e=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 UJ=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 a2e=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 i2e=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 o2e=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 Hq=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 l2e=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 c2e=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 d2e=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 qJ=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 u2e=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 QN=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 h2e=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 m2e=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 f2e=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 p2e=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 g2e=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 x2e=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 y2e=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 v2e=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 b2e=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 OS=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 _2e=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 sF=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 nF=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 w2e=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 j2e=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 N2e=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 k2e=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 S2e=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 C2e=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 A2e=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 E2e=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 T2e=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 M2e=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 P2e=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 I2e=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 L2e=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 R2e=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 rF=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 D2e=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 F2e=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 aF=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 O2e=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 z2e=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 iF=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 oF=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 lF=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 cF=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 B2e=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 dF=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 $2e=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 U2e=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 q2e=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 uF=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 V2e=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 H2e=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 G2e=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 W2e=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 LA=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 ZI=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 K2e=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 Y2e=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 Cx=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 Av=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 Z2e=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 X2e=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 Q2e=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 IE=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 AN=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 Gq=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 J2e=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 eNe=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 tNe=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 Ew=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 sNe=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 nNe=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 VJ=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 rNe=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 aNe=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 iNe=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 oNe=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 lNe=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 cNe=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 dNe=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 uNe=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 hNe=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 mNe=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 HJ=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 fNe=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 pNe=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 gNe=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 xNe=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 yNe=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 GJ=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 LE=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 vNe=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 bNe=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 _Ne=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 wNe=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 WJ=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 zu=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 jNe=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 hF=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 JN=ge("Plug",[["path",{d:"M12 22v-5",key:"1ega77"}],["path",{d:"M9 8V2",key:"14iosj"}],["path",{d:"M15 8V2",key:"18g5xt"}],["path",{d:"M18 8v5a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V8Z",key:"osxo6l"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const dn=ge("Plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const NNe=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 kNe=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 SNe=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 CNe=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 ANe=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 ENe=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 TNe=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 MNe=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 PNe=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 KJ=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 bb=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 INe=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 RE=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 LNe=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 RNe=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 DNe=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 FNe=ge("Pyramid",[["path",{d:"M2.5 16.88a1 1 0 0 1-.32-1.43l9-13.02a1 1 0 0 1 1.64 0l9 13.01a1 1 0 0 1-.32 1.44l-8.51 4.86a2 2 0 0 1-1.98 0Z",key:"aenxs0"}],["path",{d:"M12 2v20",key:"t6zp3m"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Jp=ge("QrCode",[["rect",{width:"5",height:"5",x:"3",y:"3",rx:"1",key:"1tu5fj"}],["rect",{width:"5",height:"5",x:"16",y:"3",rx:"1",key:"1v8r4q"}],["rect",{width:"5",height:"5",x:"3",y:"16",rx:"1",key:"1x03jg"}],["path",{d:"M21 16h-3a2 2 0 0 0-2 2v3",key:"177gqh"}],["path",{d:"M21 21v.01",key:"ents32"}],["path",{d:"M12 7v3a2 2 0 0 1-2 2H7",key:"8crl2c"}],["path",{d:"M3 12h.01",key:"nlz23k"}],["path",{d:"M12 3h.01",key:"n36tog"}],["path",{d:"M12 16v.01",key:"133mhm"}],["path",{d:"M16 12h1",key:"1slzba"}],["path",{d:"M21 12v.01",key:"1lwtk9"}],["path",{d:"M12 21v-1",key:"1880an"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const h2=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 ONe=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 Wq=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 zNe=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 BNe=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 $Ne=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 UNe=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 _b=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 qNe=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 VNe=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 HNe=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 GNe=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 WNe=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 KNe=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 YNe=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 ZNe=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 XNe=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 QNe=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 JNe=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 eke=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 tke=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 Kq=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 mF=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 ske=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 nke=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 rke=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 ake=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 ike=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 DE=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 oke=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 Yq=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 lke=ge("RefreshCwOff",[["path",{d:"M21 8L18.74 5.74A9.75 9.75 0 0 0 12 3C11 3 10.03 3.16 9.13 3.47",key:"1krf6h"}],["path",{d:"M8 16H3v5",key:"1cv678"}],["path",{d:"M3 12C3 9.51 4 7.26 5.64 5.64",key:"ruvoct"}],["path",{d:"m3 16 2.26 2.26A9.75 9.75 0 0 0 12 21c2.49 0 4.74-1 6.36-2.64",key:"19q130"}],["path",{d:"M21 12c0 1-.16 1.97-.47 2.87",key:"4w8emr"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M22 22 2 2",key:"1r8tn9"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ro=ge("RefreshCw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const cke=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 dke=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 uke=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 hke=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 YJ=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 FE=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 mke=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 fke=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 pke=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 Zq=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 gke=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 xke=ge("Ribbon",[["path",{d:"M12 11.22C11 9.997 10 9 10 8a2 2 0 0 1 4 0c0 1-.998 2.002-2.01 3.22",key:"1rnhq3"}],["path",{d:"m12 18 2.57-3.5",key:"116vt7"}],["path",{d:"M6.243 9.016a7 7 0 0 1 11.507-.009",key:"10dq0b"}],["path",{d:"M9.35 14.53 12 11.22",key:"tdsyp2"}],["path",{d:"M9.35 14.53C7.728 12.246 6 10.221 6 7a6 5 0 0 1 12 0c-.005 3.22-1.778 5.235-3.43 7.5l3.557 4.527a1 1 0 0 1-.203 1.43l-1.894 1.36a1 1 0 0 1-1.384-.215L12 18l-2.679 3.593a1 1 0 0 1-1.39.213l-1.865-1.353a1 1 0 0 1-.203-1.422z",key:"nmifey"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const qg=ge("Rocket",[["path",{d:"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09z",key:"m3kijz"}],["path",{d:"m12 15-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 0 1-4 2z",key:"1fmvmk"}],["path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0",key:"1f8sc4"}],["path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5",key:"qeys4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yke=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 vke=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 fF=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 bke=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 Ax=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 _ke=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 Zz=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 wke=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 Xq=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 jke=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 pF=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 gF=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 Nke=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 kke=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 P4=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 Ske=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 Cke=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 Ake=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 Eke=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 Tke=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 Mke=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 Pke=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 Ike=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 xF=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 Lke=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 Rke=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 Dke=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 Fke=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 Oke=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 zke=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 Bke=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 $ke=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 Uke=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 qke=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 Vke=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 Hke=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 Gke=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 Wke=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 Kke=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 Qq=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 Yke=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 Zke=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 Xke=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 Qke=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 Jq=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 Zr=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 Jke=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 yF=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 eSe=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 Kr=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 tSe=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 sSe=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 nSe=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 rSe=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 aSe=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 iSe=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 eC=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 oSe=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 Fd=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 ZJ=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 lSe=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 cSe=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 eV=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 dSe=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 uSe=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 hSe=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 mSe=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 Xz=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 fSe=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 Qz=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 vF=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 pSe=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 gSe=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 xSe=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 I4=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 ySe=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 tC=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 vSe=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 bSe=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 _Se=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 wSe=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 Jz=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 jSe=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 NSe=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 kSe=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 SSe=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 CSe=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 ASe=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 ESe=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 TSe=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 XJ=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 MSe=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 PSe=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 QJ=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 ISe=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 LSe=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 RSe=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 DSe=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 XI=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 bF=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 FSe=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 OSe=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 x1=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 zSe=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 BSe=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 $Se=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 Xj=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 tV=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 USe=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 qSe=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 VSe=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 QI=ge("Sparkle",[["path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z",key:"4pj2yx"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Nn=ge("Sparkles",[["path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z",key:"4pj2yx"}],["path",{d:"M20 3v4",key:"1olli1"}],["path",{d:"M22 5h-4",key:"1gvqau"}],["path",{d:"M4 17v2",key:"vumght"}],["path",{d:"M5 18H3",key:"zchphs"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const HSe=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 GSe=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 WSe=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 KSe=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 YSe=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 ZSe=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 XSe=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 JI=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 _F=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 wF=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 jF=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 NF=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 kF=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 SF=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 CF=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 AF=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 EF=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 TF=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 MF=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 PF=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 IF=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 LF=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 RF=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 p5=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 Vj=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 DF=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 FF=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 OF=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 zF=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 BF=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 $F=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 QSe=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 JSe=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 UF=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 qF=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 VF=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 HF=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 GF=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 WF=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 KF=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 YF=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 ZF=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 XF=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 QF=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 JF=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 eO=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 tO=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 sO=ge("SquareParking",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 17V7h4a3 3 0 0 1 0 6H9",key:"1dfk2c"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _p=ge("SquarePen",[["path",{d:"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7",key:"1m0v6g"}],["path",{d:"M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z",key:"ohrbg2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nO=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 rO=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 aO=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 iO=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 oO=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 lO=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 eCe=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 cO=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 dO=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 uO=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 hO=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 mO=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 tCe=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 sCe=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 fO=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 pO=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 gO=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 xO=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 j_=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 nCe=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 rCe=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 aCe=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 iCe=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 oCe=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 lCe=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 cCe=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 dCe=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 uCe=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 e7=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 sV=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 hCe=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 mCe=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 JJ=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 fCe=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 pCe=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 gCe=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 xCe=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 yCe=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 ek=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 vCe=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 bCe=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 _Ce=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 wCe=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 jCe=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 NCe=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 kCe=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 SCe=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 CCe=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 nV=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 ACe=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 ECe=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 TCe=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 MCe=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 PCe=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 ICe=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 rV=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 LCe=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 aV=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 RCe=ge("Tablets",[["circle",{cx:"7",cy:"7",r:"5",key:"x29byf"}],["circle",{cx:"17",cy:"17",r:"5",key:"1op1d2"}],["path",{d:"M12 17h10",key:"ls21zv"}],["path",{d:"m3.46 10.54 7.08-7.08",key:"1rehiu"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ap=ge("Tag",[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z",key:"vktsd0"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor",key:"kqv944"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const eee=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 DCe=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 FCe=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 OCe=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 zCe=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 BCe=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 $Ce=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 nh=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 UCe=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 qCe=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 VCe=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 HCe=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 yO=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 GCe=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 WCe=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 iV=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 KCe=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 YCe=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 ZCe=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 vO=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 XCe=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 QCe=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 JCe=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 e5e=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 t5e=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 tee=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 qy=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 s5e=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 n5e=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 r5e=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 a5e=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 i5e=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 o5e=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 t7=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 l5e=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 c5e=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 d5e=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 u5e=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 h5e=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 m5e=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 f5e=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 p5e=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 g5e=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 x5e=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 y5e=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 v5e=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 b5e=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 _5e=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 w5e=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 j5e=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 N5e=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 k5e=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 S5e=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 bO=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 Hn=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 C5e=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 A5e=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 _O=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 eL=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 E5e=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 T5e=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 sC=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 M5e=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 P5e=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 I5e=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 see=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 L5e=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 R5e=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 wO=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 D5e=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 F5e=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 nee=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 O5e=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 oV=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 z5e=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 B5e=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 s7=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 ree=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 $5e=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 OE=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 U5e=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 q5e=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 V5e=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 jO=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 H5e=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 n7=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 lV=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 G5e=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 m2=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 aee=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 cV=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 W5e=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 aP=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 NO=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 kO=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 K5e=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 SO=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 dV=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 CO=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 iP=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 Y5e=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 uV=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 y0=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 AO=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 EO=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 Z5e=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 hV=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 X5e=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 Q5e=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 J5e=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 e4e=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 t4e=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 s4e=ge("VideoOff",[["path",{d:"M10.66 6H14a2 2 0 0 1 2 2v2.5l5.248-3.062A.5.5 0 0 1 22 7.87v8.196",key:"w8jjjt"}],["path",{d:"M16 16a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h2",key:"1xawa7"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ua=ge("Video",[["path",{d:"m16 13 5.223 3.482a.5.5 0 0 0 .777-.416V7.87a.5.5 0 0 0-.752-.432L16 10.5",key:"ftymec"}],["rect",{x:"2",y:"6",width:"14",height:"12",rx:"2",key:"158x01"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const n4e=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 r4e=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 a4e=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 i4e=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 o4e=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 iee=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 l4e=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 oee=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 c4e=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 d4e=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 u4e=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 TO=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 r7=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 h4e=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 ey=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 m4e=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 f4e=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 p4e=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 g4e=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 x4e=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 y4e=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 v4e=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 b4e=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 _4e=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 w4e=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 j4e=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 N4e=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 k4e=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 S4e=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 C4e=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 A4e=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 E4e=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 T4e=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 M4e=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 P4e=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 I4e=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 L4e=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 a7=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 R4e=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 D4e=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 L4=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 pr=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 mV=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 F4e=ge("ZapOff",[["path",{d:"M10.513 4.856 13.12 2.17a.5.5 0 0 1 .86.46l-1.377 4.317",key:"193nxd"}],["path",{d:"M15.656 10H20a1 1 0 0 1 .78 1.63l-1.72 1.773",key:"27a7lr"}],["path",{d:"M16.273 16.273 10.88 21.83a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14H4a1 1 0 0 1-.78-1.63l4.507-4.643",key:"1e0qe9"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const eg=ge("Zap",[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tL=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 fV=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 z0s=Object.freeze(Object.defineProperty({__proto__:null,AArrowDown:xme,AArrowUp:yme,ALargeSmall:vme,Accessibility:bme,Activity:rf,AirVent:_me,Airplay:wme,AlarmClock:Nme,AlarmClockCheck:PR,AlarmClockMinus:IR,AlarmClockOff:jme,AlarmClockPlus:LR,AlarmSmoke:kme,Album:Sme,AlignCenter:DI,AlignCenterHorizontal:Cme,AlignCenterVertical:Ame,AlignEndHorizontal:Eme,AlignEndVertical:Tme,AlignHorizontalDistributeCenter:Mme,AlignHorizontalDistributeEnd:Pme,AlignHorizontalDistributeStart:Ime,AlignHorizontalJustifyCenter:Lme,AlignHorizontalJustifyEnd:Rme,AlignHorizontalJustifyStart:Dme,AlignHorizontalSpaceAround:Fme,AlignHorizontalSpaceBetween:Ome,AlignJustify:zme,AlignLeft:FI,AlignRight:OI,AlignStartHorizontal:Bme,AlignStartVertical:$me,AlignVerticalDistributeCenter:Ume,AlignVerticalDistributeEnd:qme,AlignVerticalDistributeStart:Vme,AlignVerticalJustifyCenter:Hme,AlignVerticalJustifyEnd:Gme,AlignVerticalJustifyStart:Wme,AlignVerticalSpaceAround:Kme,AlignVerticalSpaceBetween:Yme,Ambulance:Zme,Ampersand:Xme,Ampersands:Qme,Amphora:Jme,Anchor:efe,Angry:tfe,Annoyed:sfe,Antenna:nfe,Anvil:rfe,Aperture:afe,AppWindow:ofe,AppWindowMac:ife,Apple:lfe,Archive:jv,ArchiveRestore:zI,ArchiveX:cfe,Armchair:dfe,ArrowBigDown:hfe,ArrowBigDownDash:ufe,ArrowBigLeft:ffe,ArrowBigLeftDash:mfe,ArrowBigRight:gfe,ArrowBigRightDash:pfe,ArrowBigUp:yfe,ArrowBigUpDash:xfe,ArrowDown:Dg,ArrowDown01:vfe,ArrowDown10:bfe,ArrowDownAZ:RR,ArrowDownFromLine:_fe,ArrowDownLeft:wfe,ArrowDownNarrowWide:jfe,ArrowDownRight:dJ,ArrowDownToDot:Nfe,ArrowDownToLine:kfe,ArrowDownUp:Sfe,ArrowDownWideNarrow:DR,ArrowDownZA:FR,ArrowLeft:Va,ArrowLeftFromLine:Cfe,ArrowLeftRight:uJ,ArrowLeftToLine:Afe,ArrowRight:Qa,ArrowRightFromLine:Efe,ArrowRightLeft:C4,ArrowRightToLine:Tfe,ArrowUp:Zf,ArrowUp01:Mfe,ArrowUp10:Pfe,ArrowUpAZ:OR,ArrowUpDown:zy,ArrowUpFromDot:Ife,ArrowUpFromLine:Lfe,ArrowUpLeft:Rfe,ArrowUpNarrowWide:zR,ArrowUpRight:Lz,ArrowUpToLine:Dfe,ArrowUpWideNarrow:Ffe,ArrowUpZA:BR,ArrowsUpFromLine:Ofe,Asterisk:zfe,AtSign:Bfe,Atom:$fe,AudioLines:Ufe,AudioWaveform:qfe,Award:Im,Axe:Vfe,Axis3d:$R,Baby:Hfe,Backpack:Gfe,Badge:lpe,BadgeAlert:Wfe,BadgeCent:Kfe,BadgeCheck:IA,BadgeDollarSign:Yfe,BadgeEuro:Zfe,BadgeHelp:Xfe,BadgeIndianRupee:Qfe,BadgeInfo:Jfe,BadgeJapaneseYen:epe,BadgeMinus:tpe,BadgePercent:spe,BadgePlus:npe,BadgePoundSterling:rpe,BadgeRussianRuble:ape,BadgeSwissFranc:ipe,BadgeX:ope,BaggageClaim:cpe,Ban:Rz,Banana:dpe,Bandage:upe,Banknote:hpe,Barcode:mpe,Baseline:fpe,Bath:A0,Battery:bpe,BatteryCharging:ppe,BatteryFull:gpe,BatteryLow:xpe,BatteryMedium:ype,BatteryWarning:vpe,Beaker:hJ,Bean:wpe,BeanOff:_pe,Bed:r2,BedDouble:A4,BedSingle:jpe,Beef:Npe,Beer:Spe,BeerOff:kpe,Bell:Uy,BellDot:Cpe,BellElectric:Ape,BellMinus:Epe,BellOff:YS,BellPlus:Tpe,BellRing:ZS,BetweenHorizontalEnd:UR,BetweenHorizontalStart:qR,BetweenVerticalEnd:Mpe,BetweenVerticalStart:Ppe,BicepsFlexed:Ipe,Bike:Lpe,Binary:Rpe,Binoculars:Dpe,Biohazard:Fpe,Bird:Ope,Bitcoin:zpe,Blend:Bpe,Blinds:$pe,Blocks:Upe,Bluetooth:Gpe,BluetoothConnected:qpe,BluetoothOff:Vpe,BluetoothSearching:Hpe,Bold:SE,Bolt:Wpe,Bomb:Kpe,Bone:Ype,Book:xge,BookA:Zpe,BookAudio:Xpe,BookCheck:Qpe,BookCopy:Jpe,BookDashed:VR,BookDown:ege,BookHeadphones:tge,BookHeart:sge,BookImage:nge,BookKey:rge,BookLock:age,BookMarked:ige,BookMinus:oge,BookOpen:Xf,BookOpenCheck:lge,BookOpenText:cge,BookPlus:dge,BookText:uge,BookType:hge,BookUp:fge,BookUp2:mge,BookUser:pge,BookX:gge,Bookmark:E0,BookmarkCheck:yge,BookmarkMinus:vge,BookmarkPlus:BI,BookmarkX:bge,BoomBox:_ge,Bot:E4,BotMessageSquare:wge,BotOff:jge,Box:mJ,Boxes:Nge,Braces:sP,Brackets:kge,Brain:fJ,BrainCircuit:Sge,BrainCog:Cge,BrickWall:Age,Briefcase:kx,BriefcaseBusiness:Ege,BriefcaseConveyorBelt:Tge,BriefcaseMedical:Mge,BringToFront:Pge,Brush:Ige,Bug:Dge,BugOff:Lge,BugPlay:Rge,Building:$I,Building2:ji,Bus:Oge,BusFront:Fge,Cable:Bge,CableCar:zge,Cake:Fg,CakeSlice:$ge,Calculator:a2,Calendar:Ta,Calendar1:Uge,CalendarArrowDown:qge,CalendarArrowUp:Vge,CalendarCheck:xb,CalendarCheck2:Hge,CalendarClock:Cu,CalendarCog:Gge,CalendarDays:Wc,CalendarFold:Wge,CalendarHeart:XS,CalendarMinus:Yge,CalendarMinus2:Kge,CalendarOff:kq,CalendarPlus:bv,CalendarPlus2:Zge,CalendarRange:Xge,CalendarSearch:Qge,CalendarSync:Jge,CalendarX:pJ,CalendarX2:exe,Camera:Sx,CameraOff:txe,Candy:rxe,CandyCane:sxe,CandyOff:nxe,Cannabis:axe,Captions:HR,CaptionsOff:ixe,Car:cxe,CarFront:oxe,CarTaxiFront:lxe,Caravan:dxe,Carrot:uxe,CaseLower:hxe,CaseSensitive:mxe,CaseUpper:fxe,CassetteTape:pxe,Cast:gxe,Castle:xxe,Cat:yxe,Cctv:vxe,ChartArea:GR,ChartBar:KR,ChartBarBig:WR,ChartBarDecreasing:bxe,ChartBarIncreasing:_xe,ChartBarStacked:wxe,ChartCandlestick:YR,ChartColumn:Gl,ChartColumnBig:ZR,ChartColumnDecreasing:jxe,ChartColumnIncreasing:XR,ChartColumnStacked:Nxe,ChartGantt:kxe,ChartLine:QR,ChartNetwork:Sxe,ChartNoAxesColumn:eD,ChartNoAxesColumnDecreasing:Cxe,ChartNoAxesColumnIncreasing:JR,ChartNoAxesCombined:Axe,ChartNoAxesGantt:tD,ChartPie:sD,ChartScatter:nD,ChartSpline:Exe,Check:ca,CheckCheck:Dz,ChefHat:Txe,Cherry:Mxe,ChevronDown:wl,ChevronFirst:Pxe,ChevronLast:Ixe,ChevronLeft:kd,ChevronRight:Di,ChevronUp:yb,ChevronsDown:Rxe,ChevronsDownUp:Lxe,ChevronsLeft:Oxe,ChevronsLeftRight:Fxe,ChevronsLeftRightEllipsis:Dxe,ChevronsRight:Bxe,ChevronsRightLeft:zxe,ChevronsUp:$xe,ChevronsUpDown:Sw,Chrome:Fz,Church:Uxe,Cigarette:Vxe,CigaretteOff:qxe,Circle:Og,CircleAlert:ll,CircleArrowDown:rD,CircleArrowLeft:aD,CircleArrowOutDownLeft:iD,CircleArrowOutDownRight:oD,CircleArrowOutUpLeft:lD,CircleArrowOutUpRight:cD,CircleArrowRight:dD,CircleArrowUp:uD,CircleCheck:Vr,CircleCheckBig:Wl,CircleChevronDown:hD,CircleChevronLeft:mD,CircleChevronRight:fD,CircleChevronUp:pD,CircleDashed:Hxe,CircleDivide:gD,CircleDollarSign:Gxe,CircleDot:Kxe,CircleDotDashed:Wxe,CircleEllipsis:Yxe,CircleEqual:Zxe,CircleFadingArrowUp:Xxe,CircleFadingPlus:Qxe,CircleGauge:xD,CircleHelp:e4,CircleMinus:yD,CircleOff:Jxe,CircleParking:bD,CircleParkingOff:vD,CirclePause:_D,CirclePercent:wD,CirclePlay:ef,CirclePlus:jD,CirclePower:ND,CircleSlash:eye,CircleSlash2:kD,CircleStop:SD,CircleUser:AD,CircleUserRound:CD,CircleX:Nu,CircuitBoard:tye,Citrus:sye,Clapperboard:Sq,Clipboard:cye,ClipboardCheck:KN,ClipboardCopy:nye,ClipboardList:zg,ClipboardMinus:rye,ClipboardPaste:aye,ClipboardPen:TD,ClipboardPenLine:ED,ClipboardPlus:iye,ClipboardType:oye,ClipboardX:lye,Clock:da,Clock1:dye,Clock10:uye,Clock11:hye,Clock12:mye,Clock2:fye,Clock3:Cq,Clock4:pye,Clock5:gye,Clock6:xye,Clock7:yye,Clock8:vye,Clock9:bye,ClockAlert:_ye,ClockArrowDown:wye,ClockArrowUp:jye,Cloud:Oye,CloudAlert:Nye,CloudCog:kye,CloudDownload:MD,CloudDrizzle:Sye,CloudFog:Cye,CloudHail:Aye,CloudLightning:Eye,CloudMoon:Mye,CloudMoonRain:Tye,CloudOff:Pye,CloudRain:Lye,CloudRainWind:Iye,CloudSnow:Rye,CloudSun:Fye,CloudSunRain:Dye,CloudUpload:nP,Cloudy:zye,Clover:gE,Club:Bye,Code:CE,CodeXml:t4,Codepen:$ye,Codesandbox:Uye,Coffee:T4,Cog:qye,Coins:gJ,Columns2:PD,Columns3:rP,Columns4:Vye,Combine:Hye,Command:Gye,Compass:Oz,Component:Wye,Computer:Kye,ConciergeBell:Yye,Cone:Zye,Construction:Xye,Contact:UI,ContactRound:ID,Container:Qye,Contrast:Jye,Cookie:e0e,CookingPot:t0e,Copy:Ha,CopyCheck:s0e,CopyMinus:n0e,CopyPlus:r0e,CopySlash:a0e,CopyX:i0e,Copyleft:o0e,Copyright:l0e,CornerDownLeft:c0e,CornerDownRight:xJ,CornerLeftDown:d0e,CornerLeftUp:u0e,CornerRightDown:h0e,CornerRightUp:m0e,CornerUpLeft:f0e,CornerUpRight:p0e,Cpu:g0e,CreativeCommons:x0e,CreditCard:Nv,Croissant:y0e,Crop:v0e,Cross:b0e,Crosshair:_0e,Crown:Bg,Cuboid:w0e,CupSoda:j0e,Currency:N0e,Cylinder:k0e,Dam:S0e,Database:Aq,DatabaseBackup:C0e,DatabaseZap:A0e,Delete:E0e,Dessert:T0e,Diameter:M0e,Diamond:L0e,DiamondMinus:P0e,DiamondPercent:LD,DiamondPlus:I0e,Dice1:R0e,Dice2:D0e,Dice3:F0e,Dice4:O0e,Dice5:z0e,Dice6:B0e,Dices:$0e,Diff:U0e,Disc:G0e,Disc2:q0e,Disc3:V0e,DiscAlbum:H0e,Divide:W0e,Dna:Y0e,DnaOff:K0e,Dock:Z0e,Dog:X0e,DollarSign:nu,Donut:Q0e,DoorClosed:J0e,DoorOpen:i2,Dot:eve,Download:xi,DraftingCompass:tve,Drama:sve,Dribbble:nve,Drill:rve,Droplet:ave,Droplets:g1,Drum:ive,Drumstick:ove,Dumbbell:lve,Ear:dve,EarOff:cve,Earth:CN,EarthLock:uve,Eclipse:hve,Egg:Eq,EggFried:mve,EggOff:fve,Ellipsis:l_,EllipsisVertical:Jx,Equal:xve,EqualApproximately:pve,EqualNot:gve,Eraser:Tq,EthernetPort:yve,Euro:vve,Expand:bve,ExternalLink:Fr,Eye:Ca,EyeClosed:_ve,EyeOff:$g,Facebook:Qp,Factory:wve,Fan:jve,FastForward:Nve,Feather:kve,Fence:Sve,FerrisWheel:Cve,Figma:Ave,File:Pq,FileArchive:Eve,FileAudio:Mve,FileAudio2:Tve,FileAxis3d:RD,FileBadge:Ive,FileBadge2:Pve,FileBox:Lve,FileChartColumn:FD,FileChartColumnIncreasing:DD,FileChartLine:OD,FileChartPie:zD,FileCheck:yJ,FileCheck2:zz,FileClock:Rve,FileCode:Fve,FileCode2:Dve,FileCog:BD,FileDiff:Ove,FileDigit:zve,FileDown:o2,FileHeart:Bve,FileImage:qI,FileInput:$ve,FileJson:qve,FileJson2:Uve,FileKey:Hve,FileKey2:Vve,FileLock:Wve,FileLock2:Gve,FileMinus:Yve,FileMinus2:Kve,FileMusic:Zve,FileOutput:Xve,FilePen:$D,FilePenLine:c_,FilePlus:Qve,FilePlus2:Mq,FileQuestion:Jve,FileScan:ebe,FileSearch:vJ,FileSearch2:tbe,FileSliders:sbe,FileSpreadsheet:YN,FileStack:bJ,FileSymlink:nbe,FileTerminal:rbe,FileText:Jr,FileType:ibe,FileType2:abe,FileUp:_J,FileUser:obe,FileVideo:wJ,FileVideo2:lbe,FileVolume:dbe,FileVolume2:cbe,FileWarning:ube,FileX:mbe,FileX2:hbe,Files:fbe,Film:nf,Filter:Cw,FilterX:pbe,Fingerprint:gbe,FireExtinguisher:xbe,Fish:bbe,FishOff:ybe,FishSymbol:vbe,Flag:AE,FlagOff:_be,FlagTriangleLeft:wbe,FlagTriangleRight:jbe,Flame:sh,FlameKindling:Nbe,Flashlight:Sbe,FlashlightOff:kbe,FlaskConical:VI,FlaskConicalOff:Cbe,FlaskRound:Abe,FlipHorizontal:jJ,FlipHorizontal2:Ebe,FlipVertical:Mbe,FlipVertical2:Tbe,Flower:Pbe,Flower2:qS,Focus:Ibe,FoldHorizontal:Lbe,FoldVertical:Rbe,Folder:Iq,FolderArchive:Dbe,FolderCheck:Fbe,FolderClock:Obe,FolderClosed:zbe,FolderCode:Bbe,FolderCog:UD,FolderDot:$be,FolderDown:Ube,FolderGit:Vbe,FolderGit2:qbe,FolderHeart:Hbe,FolderInput:Gbe,FolderKanban:Wbe,FolderKey:Kbe,FolderLock:Ybe,FolderMinus:Zbe,FolderOpen:kv,FolderOpenDot:Xbe,FolderOutput:Qbe,FolderPen:qD,FolderPlus:NJ,FolderRoot:Jbe,FolderSearch:t1e,FolderSearch2:e1e,FolderSymlink:s1e,FolderSync:n1e,FolderTree:r1e,FolderUp:a1e,FolderX:i1e,Folders:o1e,Footprints:l1e,Forklift:c1e,Forward:d1e,Frame:u1e,Framer:h1e,Frown:m1e,Fuel:f1e,Fullscreen:p1e,GalleryHorizontal:x1e,GalleryHorizontalEnd:g1e,GalleryThumbnails:y1e,GalleryVertical:b1e,GalleryVerticalEnd:v1e,Gamepad:w1e,Gamepad2:_1e,Gauge:j1e,Gavel:N1e,Gem:k1e,Ghost:Bz,Gift:ul,GitBranch:C1e,GitBranchPlus:S1e,GitCommitHorizontal:VD,GitCommitVertical:A1e,GitCompare:T1e,GitCompareArrows:E1e,GitFork:M1e,GitGraph:P1e,GitMerge:I1e,GitPullRequest:z1e,GitPullRequestArrow:L1e,GitPullRequestClosed:R1e,GitPullRequestCreate:F1e,GitPullRequestCreateArrow:D1e,GitPullRequestDraft:O1e,Github:B1e,Gitlab:$1e,GlassWater:U1e,Glasses:q1e,Globe:dl,GlobeLock:V1e,Goal:H1e,Grab:G1e,GraduationCap:af,Grape:W1e,Grid2x2:GD,Grid2x2Check:K1e,Grid2x2Plus:HD,Grid2x2X:Y1e,Grid3x3:Fj,Grip:X1e,GripHorizontal:Z1e,GripVertical:Ug,Group:Q1e,Guitar:J1e,Ham:e_e,Hammer:kJ,Hand:Lq,HandCoins:t_e,HandHeart:SJ,HandHelping:s4,HandMetal:s_e,HandPlatter:n_e,Handshake:vb,HardDrive:CJ,HardDriveDownload:r_e,HardDriveUpload:a_e,HardHat:i_e,Hash:HI,Haze:o_e,HdmiPort:l_e,Heading:h_e,Heading1:Rq,Heading2:$z,Heading3:Dq,Heading4:c_e,Heading5:d_e,Heading6:u_e,HeadphoneOff:m_e,Headphones:f_e,Headset:p_e,Heart:Jo,HeartCrack:g_e,HeartHandshake:AJ,HeartOff:x_e,HeartPulse:y_e,Heater:v_e,Hexagon:b_e,Highlighter:__e,History:Aw,Hop:j_e,HopOff:w_e,Hospital:N_e,Hotel:k_e,Hourglass:EJ,House:va,HousePlug:S_e,HousePlus:C_e,IceCreamBowl:WD,IceCreamCone:KD,IdCard:TJ,Image:Hc,ImageDown:A_e,ImageMinus:E_e,ImageOff:T_e,ImagePlay:M_e,ImagePlus:Sv,ImageUp:P_e,ImageUpscale:I_e,Images:L_e,Import:R_e,Inbox:Uz,IndentDecrease:YD,IndentIncrease:ZD,IndianRupee:D_e,Infinity:Fq,Info:QS,InspectionPanel:F_e,Instagram:Ef,Italic:EE,IterationCcw:O_e,IterationCw:z_e,JapaneseYen:B_e,Joystick:$_e,Kanban:l2,Key:w_,KeyRound:GI,KeySquare:U_e,Keyboard:H_e,KeyboardMusic:q_e,KeyboardOff:V_e,Lamp:X_e,LampCeiling:G_e,LampDesk:W_e,LampFloor:K_e,LampWallDown:Y_e,LampWallUp:Z_e,LandPlot:Q_e,Landmark:Oq,Languages:J_e,Laptop:twe,LaptopMinimal:XD,LaptopMinimalCheck:ewe,Lasso:nwe,LassoSelect:swe,Laugh:rwe,Layers:M4,Layers2:awe,Layers3:iwe,LayoutDashboard:WI,LayoutGrid:Qf,LayoutList:owe,LayoutPanelLeft:lwe,LayoutPanelTop:cwe,LayoutTemplate:c2,Leaf:dwe,LeafyGreen:uwe,Lectern:hwe,LetterText:mwe,Library:d2,LibraryBig:fwe,LifeBuoy:zq,Ligature:pwe,Lightbulb:JS,LightbulbOff:gwe,Link:Sd,Link2:Wd,Link2Off:xwe,Linkedin:dy,List:T0,ListCheck:ywe,ListChecks:Cv,ListCollapse:vwe,ListEnd:bwe,ListFilter:MJ,ListMinus:_we,ListMusic:wwe,ListOrdered:u2,ListPlus:PJ,ListRestart:jwe,ListStart:Nwe,ListTodo:kwe,ListTree:Swe,ListVideo:Cwe,ListX:Awe,Loader:Twe,LoaderCircle:Ct,LoaderPinwheel:Ewe,Locate:Bq,LocateFixed:Mwe,LocateOff:Pwe,Lock:pc,LockKeyhole:IJ,LockKeyholeOpen:QD,LockOpen:JD,LogIn:KI,LogOut:qz,Logs:Iwe,Lollipop:Lwe,Luggage:Rwe,Magnet:Dwe,Mail:mn,MailCheck:Vz,MailMinus:Fwe,MailOpen:$q,MailPlus:Uq,MailQuestion:Owe,MailSearch:zwe,MailWarning:Bwe,MailX:YI,Mailbox:$we,Mails:Uwe,Map:Hz,MapPin:ci,MapPinCheck:Vwe,MapPinCheckInside:qwe,MapPinHouse:Hwe,MapPinMinus:Wwe,MapPinMinusInside:Gwe,MapPinOff:Kwe,MapPinPlus:Zwe,MapPinPlusInside:Ywe,MapPinX:Qwe,MapPinXInside:Xwe,MapPinned:LJ,Martini:Jwe,Maximize:Gz,Maximize2:RJ,Medal:TE,Megaphone:gm,MegaphoneOff:eje,Meh:tje,MemoryStick:sje,Menu:ME,Merge:Wz,MessageCircle:Ah,MessageCircleCode:nje,MessageCircleDashed:rje,MessageCircleHeart:qq,MessageCircleMore:aje,MessageCircleOff:ije,MessageCirclePlus:oje,MessageCircleQuestion:DJ,MessageCircleReply:lje,MessageCircleWarning:cje,MessageCircleX:dje,MessageSquare:eo,MessageSquareCode:uje,MessageSquareDashed:hje,MessageSquareDiff:mje,MessageSquareDot:fje,MessageSquareHeart:pje,MessageSquareLock:gje,MessageSquareMore:FJ,MessageSquareOff:xje,MessageSquarePlus:m4,MessageSquareQuote:PE,MessageSquareReply:OJ,MessageSquareShare:yje,MessageSquareText:vje,MessageSquareWarning:zJ,MessageSquareX:bje,MessagesSquare:BJ,Mic:Kz,MicOff:_je,MicVocal:eF,Microchip:wje,Microscope:jje,Microwave:Nje,Milestone:kje,Milk:Cje,MilkOff:Sje,Minimize:Eje,Minimize2:Aje,Minus:ZN,Monitor:XN,MonitorCheck:Tje,MonitorCog:Mje,MonitorDot:Pje,MonitorDown:Ije,MonitorOff:Lje,MonitorPause:Rje,MonitorPlay:Vq,MonitorSmartphone:Dje,MonitorSpeaker:Fje,MonitorStop:Oje,MonitorUp:Yz,MonitorX:zje,Moon:$je,MoonStar:Bje,Mountain:qje,MountainSnow:Uje,Mouse:Gje,MouseOff:Vje,MousePointer:cb,MousePointer2:$J,MousePointerBan:Hje,MousePointerClick:Pm,Move:UJ,Move3d:tF,MoveDiagonal:Kje,MoveDiagonal2:Wje,MoveDown:Xje,MoveDownLeft:Yje,MoveDownRight:Zje,MoveHorizontal:Qje,MoveLeft:Jje,MoveRight:e2e,MoveUp:n2e,MoveUpLeft:t2e,MoveUpRight:s2e,MoveVertical:r2e,Music:Hq,Music2:a2e,Music3:i2e,Music4:o2e,Navigation:qJ,Navigation2:c2e,Navigation2Off:l2e,NavigationOff:d2e,Network:u2e,Newspaper:QN,Nfc:h2e,Notebook:g2e,NotebookPen:m2e,NotebookTabs:f2e,NotebookText:p2e,NotepadText:y2e,NotepadTextDashed:x2e,Nut:b2e,NutOff:v2e,Octagon:w2e,OctagonAlert:OS,OctagonMinus:_2e,OctagonPause:sF,OctagonX:nF,Omega:j2e,Option:N2e,Orbit:k2e,Origami:S2e,Package:ym,Package2:C2e,PackageCheck:A2e,PackageMinus:E2e,PackageOpen:T2e,PackagePlus:M2e,PackageSearch:P2e,PackageX:I2e,PaintBucket:L2e,PaintRoller:R2e,Paintbrush:D2e,PaintbrushVertical:rF,Palette:yd,PanelBottom:z2e,PanelBottomClose:F2e,PanelBottomDashed:aF,PanelBottomOpen:O2e,PanelLeft:cF,PanelLeftClose:iF,PanelLeftDashed:oF,PanelLeftOpen:lF,PanelRight:U2e,PanelRightClose:B2e,PanelRightDashed:dF,PanelRightOpen:$2e,PanelTop:H2e,PanelTopClose:q2e,PanelTopDashed:uF,PanelTopOpen:V2e,PanelsLeftBottom:G2e,PanelsRightBottom:W2e,PanelsTopLeft:LA,Paperclip:ZI,Parentheses:K2e,ParkingMeter:Y2e,PartyPopper:Cx,Pause:Av,PawPrint:Z2e,PcCase:X2e,Pen:AN,PenLine:_f,PenOff:Q2e,PenTool:IE,Pencil:pi,PencilLine:Gq,PencilOff:J2e,PencilRuler:eNe,Pentagon:tNe,Percent:Ew,PersonStanding:sNe,PhilippinePeso:nNe,Phone:Da,PhoneCall:VJ,PhoneForwarded:rNe,PhoneIncoming:aNe,PhoneMissed:iNe,PhoneOff:oNe,PhoneOutgoing:lNe,Pi:cNe,Piano:dNe,Pickaxe:uNe,PictureInPicture:mNe,PictureInPicture2:hNe,PiggyBank:HJ,Pilcrow:gNe,PilcrowLeft:fNe,PilcrowRight:pNe,Pill:yNe,PillBottle:xNe,Pin:LE,PinOff:GJ,Pipette:vNe,Pizza:bNe,Plane:WJ,PlaneLanding:_Ne,PlaneTakeoff:wNe,Play:zu,Plug:JN,Plug2:jNe,PlugZap:hF,Plus:dn,Pocket:kNe,PocketKnife:NNe,Podcast:SNe,Pointer:ANe,PointerOff:CNe,Popcorn:ENe,Popsicle:TNe,PoundSterling:MNe,Power:KJ,PowerOff:PNe,Presentation:bb,Printer:RE,PrinterCheck:INe,Projector:LNe,Proportions:RNe,Puzzle:DNe,Pyramid:FNe,QrCode:Jp,Quote:h2,Rabbit:ONe,Radar:Wq,Radiation:zNe,Radical:BNe,Radio:_b,RadioReceiver:$Ne,RadioTower:UNe,Radius:qNe,RailSymbol:VNe,Rainbow:HNe,Rat:GNe,Ratio:WNe,Receipt:Kq,ReceiptCent:KNe,ReceiptEuro:YNe,ReceiptIndianRupee:ZNe,ReceiptJapaneseYen:XNe,ReceiptPoundSterling:QNe,ReceiptRussianRuble:JNe,ReceiptSwissFranc:eke,ReceiptText:tke,RectangleEllipsis:mF,RectangleHorizontal:ske,RectangleVertical:nke,Recycle:rke,Redo:DE,Redo2:ake,RedoDot:ike,RefreshCcw:Yq,RefreshCcwDot:oke,RefreshCw:ro,RefreshCwOff:lke,Refrigerator:cke,Regex:dke,RemoveFormatting:uke,Repeat:FE,Repeat1:hke,Repeat2:YJ,Replace:fke,ReplaceAll:mke,Reply:Zq,ReplyAll:pke,Rewind:gke,Ribbon:xke,Rocket:qg,RockingChair:yke,RollerCoaster:vke,Rotate3d:fF,RotateCcw:Ax,RotateCcwSquare:bke,RotateCw:Zz,RotateCwSquare:_ke,Route:Xq,RouteOff:wke,Router:jke,Rows2:pF,Rows3:gF,Rows4:Nke,Rss:kke,Ruler:P4,RussianRuble:Ske,Sailboat:Cke,Salad:Ake,Sandwich:Eke,Satellite:Mke,SatelliteDish:Tke,Save:tl,SaveAll:Pke,SaveOff:Ike,Scale:Lke,Scale3d:xF,Scaling:Rke,Scan:qke,ScanBarcode:Dke,ScanEye:Fke,ScanFace:Oke,ScanLine:zke,ScanQrCode:Bke,ScanSearch:$ke,ScanText:Uke,School:Vke,Scissors:Gke,ScissorsLineDashed:Hke,ScreenShare:Kke,ScreenShareOff:Wke,Scroll:Yke,ScrollText:Qq,Search:Zr,SearchCheck:Zke,SearchCode:Xke,SearchSlash:Qke,SearchX:Jq,Section:Jke,Send:Kr,SendHorizontal:yF,SendToBack:eSe,SeparatorHorizontal:tSe,SeparatorVertical:sSe,Server:iSe,ServerCog:nSe,ServerCrash:rSe,ServerOff:aSe,Settings:Nd,Settings2:eC,Shapes:oSe,Share:ZJ,Share2:Fd,Sheet:lSe,Shell:cSe,Shield:Tf,ShieldAlert:eV,ShieldBan:dSe,ShieldCheck:Rm,ShieldEllipsis:uSe,ShieldHalf:hSe,ShieldMinus:mSe,ShieldOff:Xz,ShieldPlus:fSe,ShieldQuestion:Qz,ShieldX:vF,Ship:gSe,ShipWheel:pSe,Shirt:xSe,ShoppingBag:I4,ShoppingBasket:ySe,ShoppingCart:tC,Shovel:vSe,ShowerHead:bSe,Shrink:_Se,Shrub:wSe,Shuffle:Jz,Sigma:jSe,Signal:ASe,SignalHigh:NSe,SignalLow:kSe,SignalMedium:SSe,SignalZero:CSe,Signature:ESe,Signpost:XJ,SignpostBig:TSe,Siren:MSe,SkipBack:PSe,SkipForward:QJ,Skull:ISe,Slack:LSe,Slash:RSe,Slice:DSe,SlidersHorizontal:XI,SlidersVertical:bF,Smartphone:x1,SmartphoneCharging:FSe,SmartphoneNfc:OSe,Smile:BSe,SmilePlus:zSe,Snail:$Se,Snowflake:Xj,Sofa:tV,Soup:USe,Space:qSe,Spade:VSe,Sparkle:QI,Sparkles:Nn,Speaker:HSe,Speech:GSe,SpellCheck:KSe,SpellCheck2:WSe,Spline:YSe,Split:ZSe,SprayCan:XSe,Sprout:JI,Square:j_,SquareActivity:_F,SquareArrowDown:NF,SquareArrowDownLeft:wF,SquareArrowDownRight:jF,SquareArrowLeft:kF,SquareArrowOutDownLeft:SF,SquareArrowOutDownRight:CF,SquareArrowOutUpLeft:AF,SquareArrowOutUpRight:EF,SquareArrowRight:TF,SquareArrowUp:IF,SquareArrowUpLeft:MF,SquareArrowUpRight:PF,SquareAsterisk:LF,SquareBottomDashedScissors:RF,SquareChartGantt:p5,SquareCheck:DF,SquareCheckBig:Vj,SquareChevronDown:FF,SquareChevronLeft:OF,SquareChevronRight:zF,SquareChevronUp:BF,SquareCode:$F,SquareDashed:VF,SquareDashedBottom:JSe,SquareDashedBottomCode:QSe,SquareDashedKanban:UF,SquareDashedMousePointer:qF,SquareDivide:HF,SquareDot:GF,SquareEqual:WF,SquareFunction:KF,SquareKanban:YF,SquareLibrary:ZF,SquareM:XF,SquareMenu:QF,SquareMinus:JF,SquareMousePointer:eO,SquareParking:sO,SquareParkingOff:tO,SquarePen:_p,SquarePercent:nO,SquarePi:rO,SquarePilcrow:aO,SquarePlay:iO,SquarePlus:oO,SquarePower:lO,SquareRadical:eCe,SquareScissors:cO,SquareSigma:dO,SquareSlash:uO,SquareSplitHorizontal:hO,SquareSplitVertical:mO,SquareSquare:tCe,SquareStack:sCe,SquareTerminal:fO,SquareUser:gO,SquareUserRound:pO,SquareX:xO,Squircle:nCe,Squirrel:rCe,Stamp:aCe,Star:ei,StarHalf:iCe,StarOff:oCe,StepBack:lCe,StepForward:cCe,Stethoscope:dCe,Sticker:uCe,StickyNote:e7,Store:sV,StretchHorizontal:hCe,StretchVertical:mCe,Strikethrough:JJ,Subscript:fCe,Sun:ek,SunDim:pCe,SunMedium:gCe,SunMoon:xCe,SunSnow:yCe,Sunrise:vCe,Sunset:bCe,Superscript:_Ce,SwatchBook:wCe,SwissFranc:jCe,SwitchCamera:NCe,Sword:kCe,Swords:SCe,Syringe:CCe,Table:rV,Table2:nV,TableCellsMerge:ACe,TableCellsSplit:ECe,TableColumnsSplit:TCe,TableOfContents:MCe,TableProperties:PCe,TableRowsSplit:ICe,Tablet:aV,TabletSmartphone:LCe,Tablets:RCe,Tag:Ap,Tags:eee,Tally1:DCe,Tally2:FCe,Tally3:OCe,Tally4:zCe,Tally5:BCe,Tangent:$Ce,Target:nh,Telescope:UCe,Tent:VCe,TentTree:qCe,Terminal:HCe,TestTube:GCe,TestTubeDiagonal:yO,TestTubes:WCe,Text:XCe,TextCursor:KCe,TextCursorInput:iV,TextQuote:YCe,TextSearch:ZCe,TextSelect:vO,Theater:QCe,Thermometer:t5e,ThermometerSnowflake:JCe,ThermometerSun:e5e,ThumbsDown:tee,ThumbsUp:qy,Ticket:t7,TicketCheck:s5e,TicketMinus:n5e,TicketPercent:r5e,TicketPlus:a5e,TicketSlash:i5e,TicketX:o5e,Tickets:c5e,TicketsPlane:l5e,Timer:h5e,TimerOff:d5e,TimerReset:u5e,ToggleLeft:m5e,ToggleRight:f5e,Toilet:p5e,Tornado:g5e,Torus:x5e,Touchpad:v5e,TouchpadOff:y5e,TowerControl:b5e,ToyBrick:_5e,Tractor:w5e,TrafficCone:j5e,TrainFront:k5e,TrainFrontTunnel:N5e,TrainTrack:S5e,TramFront:bO,Trash:C5e,Trash2:Hn,TreeDeciduous:A5e,TreePalm:_O,TreePine:eL,Trees:E5e,Trello:T5e,TrendingDown:sC,TrendingUp:Zl,TrendingUpDown:M5e,Triangle:I5e,TriangleAlert:Al,TriangleRight:P5e,Trophy:Kl,Truck:see,Turtle:L5e,Tv:D5e,TvMinimal:wO,TvMinimalPlay:R5e,Twitch:F5e,Twitter:nee,Type:oV,TypeOutline:O5e,Umbrella:B5e,UmbrellaOff:z5e,Underline:s7,Undo:OE,Undo2:ree,UndoDot:$5e,UnfoldHorizontal:U5e,UnfoldVertical:q5e,Ungroup:V5e,University:jO,Unlink:n7,Unlink2:H5e,Unplug:lV,Upload:ni,Usb:G5e,User:sl,UserCheck:m2,UserCog:aee,UserMinus:cV,UserPen:W5e,UserPlus:lc,UserRound:iP,UserRoundCheck:aP,UserRoundCog:NO,UserRoundMinus:kO,UserRoundPen:K5e,UserRoundPlus:SO,UserRoundSearch:dV,UserRoundX:CO,UserSearch:Y5e,UserX:uV,Users:Yn,UsersRound:y0,Utensils:EO,UtensilsCrossed:AO,UtilityPole:Z5e,Variable:hV,Vault:X5e,Vegan:Q5e,VenetianMask:J5e,Vibrate:t4e,VibrateOff:e4e,Video:ua,VideoOff:s4e,Videotape:n4e,View:r4e,Voicemail:a4e,Volleyball:i4e,Volume:c4e,Volume1:o4e,Volume2:iee,VolumeOff:l4e,VolumeX:oee,Vote:d4e,Wallet:r7,WalletCards:u4e,WalletMinimal:TO,Wallpaper:h4e,Wand:m4e,WandSparkles:ey,Warehouse:f4e,WashingMachine:p4e,Watch:g4e,Waves:x4e,Waypoints:y4e,Webcam:v4e,Webhook:_4e,WebhookOff:b4e,Weight:w4e,Wheat:N4e,WheatOff:j4e,WholeWord:k4e,Wifi:T4e,WifiHigh:S4e,WifiLow:C4e,WifiOff:A4e,WifiZero:E4e,Wind:P4e,WindArrowDown:M4e,Wine:L4e,WineOff:I4e,Workflow:a7,Worm:R4e,WrapText:D4e,Wrench:L4,X:pr,Youtube:mV,Zap:eg,ZapOff:F4e,ZoomIn:tL,ZoomOut:fV},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 $Ie=Object.freeze(Object.defineProperty({__proto__:null,AArrowDown:xme,AArrowDownIcon:xme,AArrowUp:yme,AArrowUpIcon:yme,ALargeSmall:vme,ALargeSmallIcon:vme,Accessibility:bme,AccessibilityIcon:bme,Activity:rf,ActivityIcon:rf,ActivitySquare:_F,ActivitySquareIcon:_F,AirVent:_me,AirVentIcon:_me,Airplay:wme,AirplayIcon:wme,AlarmCheck:PR,AlarmCheckIcon:PR,AlarmClock:Nme,AlarmClockCheck:PR,AlarmClockCheckIcon:PR,AlarmClockIcon:Nme,AlarmClockMinus:IR,AlarmClockMinusIcon:IR,AlarmClockOff:jme,AlarmClockOffIcon:jme,AlarmClockPlus:LR,AlarmClockPlusIcon:LR,AlarmMinus:IR,AlarmMinusIcon:IR,AlarmPlus:LR,AlarmPlusIcon:LR,AlarmSmoke:kme,AlarmSmokeIcon:kme,Album:Sme,AlbumIcon:Sme,AlertCircle:ll,AlertCircleIcon:ll,AlertOctagon:OS,AlertOctagonIcon:OS,AlertTriangle:Al,AlertTriangleIcon:Al,AlignCenter:DI,AlignCenterHorizontal:Cme,AlignCenterHorizontalIcon:Cme,AlignCenterIcon:DI,AlignCenterVertical:Ame,AlignCenterVerticalIcon:Ame,AlignEndHorizontal:Eme,AlignEndHorizontalIcon:Eme,AlignEndVertical:Tme,AlignEndVerticalIcon:Tme,AlignHorizontalDistributeCenter:Mme,AlignHorizontalDistributeCenterIcon:Mme,AlignHorizontalDistributeEnd:Pme,AlignHorizontalDistributeEndIcon:Pme,AlignHorizontalDistributeStart:Ime,AlignHorizontalDistributeStartIcon:Ime,AlignHorizontalJustifyCenter:Lme,AlignHorizontalJustifyCenterIcon:Lme,AlignHorizontalJustifyEnd:Rme,AlignHorizontalJustifyEndIcon:Rme,AlignHorizontalJustifyStart:Dme,AlignHorizontalJustifyStartIcon:Dme,AlignHorizontalSpaceAround:Fme,AlignHorizontalSpaceAroundIcon:Fme,AlignHorizontalSpaceBetween:Ome,AlignHorizontalSpaceBetweenIcon:Ome,AlignJustify:zme,AlignJustifyIcon:zme,AlignLeft:FI,AlignLeftIcon:FI,AlignRight:OI,AlignRightIcon:OI,AlignStartHorizontal:Bme,AlignStartHorizontalIcon:Bme,AlignStartVertical:$me,AlignStartVerticalIcon:$me,AlignVerticalDistributeCenter:Ume,AlignVerticalDistributeCenterIcon:Ume,AlignVerticalDistributeEnd:qme,AlignVerticalDistributeEndIcon:qme,AlignVerticalDistributeStart:Vme,AlignVerticalDistributeStartIcon:Vme,AlignVerticalJustifyCenter:Hme,AlignVerticalJustifyCenterIcon:Hme,AlignVerticalJustifyEnd:Gme,AlignVerticalJustifyEndIcon:Gme,AlignVerticalJustifyStart:Wme,AlignVerticalJustifyStartIcon:Wme,AlignVerticalSpaceAround:Kme,AlignVerticalSpaceAroundIcon:Kme,AlignVerticalSpaceBetween:Yme,AlignVerticalSpaceBetweenIcon:Yme,Ambulance:Zme,AmbulanceIcon:Zme,Ampersand:Xme,AmpersandIcon:Xme,Ampersands:Qme,AmpersandsIcon:Qme,Amphora:Jme,AmphoraIcon:Jme,Anchor:efe,AnchorIcon:efe,Angry:tfe,AngryIcon:tfe,Annoyed:sfe,AnnoyedIcon:sfe,Antenna:nfe,AntennaIcon:nfe,Anvil:rfe,AnvilIcon:rfe,Aperture:afe,ApertureIcon:afe,AppWindow:ofe,AppWindowIcon:ofe,AppWindowMac:ife,AppWindowMacIcon:ife,Apple:lfe,AppleIcon:lfe,Archive:jv,ArchiveIcon:jv,ArchiveRestore:zI,ArchiveRestoreIcon:zI,ArchiveX:cfe,ArchiveXIcon:cfe,AreaChart:GR,AreaChartIcon:GR,Armchair:dfe,ArmchairIcon:dfe,ArrowBigDown:hfe,ArrowBigDownDash:ufe,ArrowBigDownDashIcon:ufe,ArrowBigDownIcon:hfe,ArrowBigLeft:ffe,ArrowBigLeftDash:mfe,ArrowBigLeftDashIcon:mfe,ArrowBigLeftIcon:ffe,ArrowBigRight:gfe,ArrowBigRightDash:pfe,ArrowBigRightDashIcon:pfe,ArrowBigRightIcon:gfe,ArrowBigUp:yfe,ArrowBigUpDash:xfe,ArrowBigUpDashIcon:xfe,ArrowBigUpIcon:yfe,ArrowDown:Dg,ArrowDown01:vfe,ArrowDown01Icon:vfe,ArrowDown10:bfe,ArrowDown10Icon:bfe,ArrowDownAZ:RR,ArrowDownAZIcon:RR,ArrowDownAz:RR,ArrowDownAzIcon:RR,ArrowDownCircle:rD,ArrowDownCircleIcon:rD,ArrowDownFromLine:_fe,ArrowDownFromLineIcon:_fe,ArrowDownIcon:Dg,ArrowDownLeft:wfe,ArrowDownLeftFromCircle:iD,ArrowDownLeftFromCircleIcon:iD,ArrowDownLeftFromSquare:SF,ArrowDownLeftFromSquareIcon:SF,ArrowDownLeftIcon:wfe,ArrowDownLeftSquare:wF,ArrowDownLeftSquareIcon:wF,ArrowDownNarrowWide:jfe,ArrowDownNarrowWideIcon:jfe,ArrowDownRight:dJ,ArrowDownRightFromCircle:oD,ArrowDownRightFromCircleIcon:oD,ArrowDownRightFromSquare:CF,ArrowDownRightFromSquareIcon:CF,ArrowDownRightIcon:dJ,ArrowDownRightSquare:jF,ArrowDownRightSquareIcon:jF,ArrowDownSquare:NF,ArrowDownSquareIcon:NF,ArrowDownToDot:Nfe,ArrowDownToDotIcon:Nfe,ArrowDownToLine:kfe,ArrowDownToLineIcon:kfe,ArrowDownUp:Sfe,ArrowDownUpIcon:Sfe,ArrowDownWideNarrow:DR,ArrowDownWideNarrowIcon:DR,ArrowDownZA:FR,ArrowDownZAIcon:FR,ArrowDownZa:FR,ArrowDownZaIcon:FR,ArrowLeft:Va,ArrowLeftCircle:aD,ArrowLeftCircleIcon:aD,ArrowLeftFromLine:Cfe,ArrowLeftFromLineIcon:Cfe,ArrowLeftIcon:Va,ArrowLeftRight:uJ,ArrowLeftRightIcon:uJ,ArrowLeftSquare:kF,ArrowLeftSquareIcon:kF,ArrowLeftToLine:Afe,ArrowLeftToLineIcon:Afe,ArrowRight:Qa,ArrowRightCircle:dD,ArrowRightCircleIcon:dD,ArrowRightFromLine:Efe,ArrowRightFromLineIcon:Efe,ArrowRightIcon:Qa,ArrowRightLeft:C4,ArrowRightLeftIcon:C4,ArrowRightSquare:TF,ArrowRightSquareIcon:TF,ArrowRightToLine:Tfe,ArrowRightToLineIcon:Tfe,ArrowUp:Zf,ArrowUp01:Mfe,ArrowUp01Icon:Mfe,ArrowUp10:Pfe,ArrowUp10Icon:Pfe,ArrowUpAZ:OR,ArrowUpAZIcon:OR,ArrowUpAz:OR,ArrowUpAzIcon:OR,ArrowUpCircle:uD,ArrowUpCircleIcon:uD,ArrowUpDown:zy,ArrowUpDownIcon:zy,ArrowUpFromDot:Ife,ArrowUpFromDotIcon:Ife,ArrowUpFromLine:Lfe,ArrowUpFromLineIcon:Lfe,ArrowUpIcon:Zf,ArrowUpLeft:Rfe,ArrowUpLeftFromCircle:lD,ArrowUpLeftFromCircleIcon:lD,ArrowUpLeftFromSquare:AF,ArrowUpLeftFromSquareIcon:AF,ArrowUpLeftIcon:Rfe,ArrowUpLeftSquare:MF,ArrowUpLeftSquareIcon:MF,ArrowUpNarrowWide:zR,ArrowUpNarrowWideIcon:zR,ArrowUpRight:Lz,ArrowUpRightFromCircle:cD,ArrowUpRightFromCircleIcon:cD,ArrowUpRightFromSquare:EF,ArrowUpRightFromSquareIcon:EF,ArrowUpRightIcon:Lz,ArrowUpRightSquare:PF,ArrowUpRightSquareIcon:PF,ArrowUpSquare:IF,ArrowUpSquareIcon:IF,ArrowUpToLine:Dfe,ArrowUpToLineIcon:Dfe,ArrowUpWideNarrow:Ffe,ArrowUpWideNarrowIcon:Ffe,ArrowUpZA:BR,ArrowUpZAIcon:BR,ArrowUpZa:BR,ArrowUpZaIcon:BR,ArrowsUpFromLine:Ofe,ArrowsUpFromLineIcon:Ofe,Asterisk:zfe,AsteriskIcon:zfe,AsteriskSquare:LF,AsteriskSquareIcon:LF,AtSign:Bfe,AtSignIcon:Bfe,Atom:$fe,AtomIcon:$fe,AudioLines:Ufe,AudioLinesIcon:Ufe,AudioWaveform:qfe,AudioWaveformIcon:qfe,Award:Im,AwardIcon:Im,Axe:Vfe,AxeIcon:Vfe,Axis3D:$R,Axis3DIcon:$R,Axis3d:$R,Axis3dIcon:$R,Baby:Hfe,BabyIcon:Hfe,Backpack:Gfe,BackpackIcon:Gfe,Badge:lpe,BadgeAlert:Wfe,BadgeAlertIcon:Wfe,BadgeCent:Kfe,BadgeCentIcon:Kfe,BadgeCheck:IA,BadgeCheckIcon:IA,BadgeDollarSign:Yfe,BadgeDollarSignIcon:Yfe,BadgeEuro:Zfe,BadgeEuroIcon:Zfe,BadgeHelp:Xfe,BadgeHelpIcon:Xfe,BadgeIcon:lpe,BadgeIndianRupee:Qfe,BadgeIndianRupeeIcon:Qfe,BadgeInfo:Jfe,BadgeInfoIcon:Jfe,BadgeJapaneseYen:epe,BadgeJapaneseYenIcon:epe,BadgeMinus:tpe,BadgeMinusIcon:tpe,BadgePercent:spe,BadgePercentIcon:spe,BadgePlus:npe,BadgePlusIcon:npe,BadgePoundSterling:rpe,BadgePoundSterlingIcon:rpe,BadgeRussianRuble:ape,BadgeRussianRubleIcon:ape,BadgeSwissFranc:ipe,BadgeSwissFrancIcon:ipe,BadgeX:ope,BadgeXIcon:ope,BaggageClaim:cpe,BaggageClaimIcon:cpe,Ban:Rz,BanIcon:Rz,Banana:dpe,BananaIcon:dpe,Bandage:upe,BandageIcon:upe,Banknote:hpe,BanknoteIcon:hpe,BarChart:JR,BarChart2:eD,BarChart2Icon:eD,BarChart3:Gl,BarChart3Icon:Gl,BarChart4:XR,BarChart4Icon:XR,BarChartBig:ZR,BarChartBigIcon:ZR,BarChartHorizontal:KR,BarChartHorizontalBig:WR,BarChartHorizontalBigIcon:WR,BarChartHorizontalIcon:KR,BarChartIcon:JR,Barcode:mpe,BarcodeIcon:mpe,Baseline:fpe,BaselineIcon:fpe,Bath:A0,BathIcon:A0,Battery:bpe,BatteryCharging:ppe,BatteryChargingIcon:ppe,BatteryFull:gpe,BatteryFullIcon:gpe,BatteryIcon:bpe,BatteryLow:xpe,BatteryLowIcon:xpe,BatteryMedium:ype,BatteryMediumIcon:ype,BatteryWarning:vpe,BatteryWarningIcon:vpe,Beaker:hJ,BeakerIcon:hJ,Bean:wpe,BeanIcon:wpe,BeanOff:_pe,BeanOffIcon:_pe,Bed:r2,BedDouble:A4,BedDoubleIcon:A4,BedIcon:r2,BedSingle:jpe,BedSingleIcon:jpe,Beef:Npe,BeefIcon:Npe,Beer:Spe,BeerIcon:Spe,BeerOff:kpe,BeerOffIcon:kpe,Bell:Uy,BellDot:Cpe,BellDotIcon:Cpe,BellElectric:Ape,BellElectricIcon:Ape,BellIcon:Uy,BellMinus:Epe,BellMinusIcon:Epe,BellOff:YS,BellOffIcon:YS,BellPlus:Tpe,BellPlusIcon:Tpe,BellRing:ZS,BellRingIcon:ZS,BetweenHorizonalEnd:UR,BetweenHorizonalEndIcon:UR,BetweenHorizonalStart:qR,BetweenHorizonalStartIcon:qR,BetweenHorizontalEnd:UR,BetweenHorizontalEndIcon:UR,BetweenHorizontalStart:qR,BetweenHorizontalStartIcon:qR,BetweenVerticalEnd:Mpe,BetweenVerticalEndIcon:Mpe,BetweenVerticalStart:Ppe,BetweenVerticalStartIcon:Ppe,BicepsFlexed:Ipe,BicepsFlexedIcon:Ipe,Bike:Lpe,BikeIcon:Lpe,Binary:Rpe,BinaryIcon:Rpe,Binoculars:Dpe,BinocularsIcon:Dpe,Biohazard:Fpe,BiohazardIcon:Fpe,Bird:Ope,BirdIcon:Ope,Bitcoin:zpe,BitcoinIcon:zpe,Blend:Bpe,BlendIcon:Bpe,Blinds:$pe,BlindsIcon:$pe,Blocks:Upe,BlocksIcon:Upe,Bluetooth:Gpe,BluetoothConnected:qpe,BluetoothConnectedIcon:qpe,BluetoothIcon:Gpe,BluetoothOff:Vpe,BluetoothOffIcon:Vpe,BluetoothSearching:Hpe,BluetoothSearchingIcon:Hpe,Bold:SE,BoldIcon:SE,Bolt:Wpe,BoltIcon:Wpe,Bomb:Kpe,BombIcon:Kpe,Bone:Ype,BoneIcon:Ype,Book:xge,BookA:Zpe,BookAIcon:Zpe,BookAudio:Xpe,BookAudioIcon:Xpe,BookCheck:Qpe,BookCheckIcon:Qpe,BookCopy:Jpe,BookCopyIcon:Jpe,BookDashed:VR,BookDashedIcon:VR,BookDown:ege,BookDownIcon:ege,BookHeadphones:tge,BookHeadphonesIcon:tge,BookHeart:sge,BookHeartIcon:sge,BookIcon:xge,BookImage:nge,BookImageIcon:nge,BookKey:rge,BookKeyIcon:rge,BookLock:age,BookLockIcon:age,BookMarked:ige,BookMarkedIcon:ige,BookMinus:oge,BookMinusIcon:oge,BookOpen:Xf,BookOpenCheck:lge,BookOpenCheckIcon:lge,BookOpenIcon:Xf,BookOpenText:cge,BookOpenTextIcon:cge,BookPlus:dge,BookPlusIcon:dge,BookTemplate:VR,BookTemplateIcon:VR,BookText:uge,BookTextIcon:uge,BookType:hge,BookTypeIcon:hge,BookUp:fge,BookUp2:mge,BookUp2Icon:mge,BookUpIcon:fge,BookUser:pge,BookUserIcon:pge,BookX:gge,BookXIcon:gge,Bookmark:E0,BookmarkCheck:yge,BookmarkCheckIcon:yge,BookmarkIcon:E0,BookmarkMinus:vge,BookmarkMinusIcon:vge,BookmarkPlus:BI,BookmarkPlusIcon:BI,BookmarkX:bge,BookmarkXIcon:bge,BoomBox:_ge,BoomBoxIcon:_ge,Bot:E4,BotIcon:E4,BotMessageSquare:wge,BotMessageSquareIcon:wge,BotOff:jge,BotOffIcon:jge,Box:mJ,BoxIcon:mJ,BoxSelect:VF,BoxSelectIcon:VF,Boxes:Nge,BoxesIcon:Nge,Braces:sP,BracesIcon:sP,Brackets:kge,BracketsIcon:kge,Brain:fJ,BrainCircuit:Sge,BrainCircuitIcon:Sge,BrainCog:Cge,BrainCogIcon:Cge,BrainIcon:fJ,BrickWall:Age,BrickWallIcon:Age,Briefcase:kx,BriefcaseBusiness:Ege,BriefcaseBusinessIcon:Ege,BriefcaseConveyorBelt:Tge,BriefcaseConveyorBeltIcon:Tge,BriefcaseIcon:kx,BriefcaseMedical:Mge,BriefcaseMedicalIcon:Mge,BringToFront:Pge,BringToFrontIcon:Pge,Brush:Ige,BrushIcon:Ige,Bug:Dge,BugIcon:Dge,BugOff:Lge,BugOffIcon:Lge,BugPlay:Rge,BugPlayIcon:Rge,Building:$I,Building2:ji,Building2Icon:ji,BuildingIcon:$I,Bus:Oge,BusFront:Fge,BusFrontIcon:Fge,BusIcon:Oge,Cable:Bge,CableCar:zge,CableCarIcon:zge,CableIcon:Bge,Cake:Fg,CakeIcon:Fg,CakeSlice:$ge,CakeSliceIcon:$ge,Calculator:a2,CalculatorIcon:a2,Calendar:Ta,Calendar1:Uge,Calendar1Icon:Uge,CalendarArrowDown:qge,CalendarArrowDownIcon:qge,CalendarArrowUp:Vge,CalendarArrowUpIcon:Vge,CalendarCheck:xb,CalendarCheck2:Hge,CalendarCheck2Icon:Hge,CalendarCheckIcon:xb,CalendarClock:Cu,CalendarClockIcon:Cu,CalendarCog:Gge,CalendarCogIcon:Gge,CalendarDays:Wc,CalendarDaysIcon:Wc,CalendarFold:Wge,CalendarFoldIcon:Wge,CalendarHeart:XS,CalendarHeartIcon:XS,CalendarIcon:Ta,CalendarMinus:Yge,CalendarMinus2:Kge,CalendarMinus2Icon:Kge,CalendarMinusIcon:Yge,CalendarOff:kq,CalendarOffIcon:kq,CalendarPlus:bv,CalendarPlus2:Zge,CalendarPlus2Icon:Zge,CalendarPlusIcon:bv,CalendarRange:Xge,CalendarRangeIcon:Xge,CalendarSearch:Qge,CalendarSearchIcon:Qge,CalendarSync:Jge,CalendarSyncIcon:Jge,CalendarX:pJ,CalendarX2:exe,CalendarX2Icon:exe,CalendarXIcon:pJ,Camera:Sx,CameraIcon:Sx,CameraOff:txe,CameraOffIcon:txe,CandlestickChart:YR,CandlestickChartIcon:YR,Candy:rxe,CandyCane:sxe,CandyCaneIcon:sxe,CandyIcon:rxe,CandyOff:nxe,CandyOffIcon:nxe,Cannabis:axe,CannabisIcon:axe,Captions:HR,CaptionsIcon:HR,CaptionsOff:ixe,CaptionsOffIcon:ixe,Car:cxe,CarFront:oxe,CarFrontIcon:oxe,CarIcon:cxe,CarTaxiFront:lxe,CarTaxiFrontIcon:lxe,Caravan:dxe,CaravanIcon:dxe,Carrot:uxe,CarrotIcon:uxe,CaseLower:hxe,CaseLowerIcon:hxe,CaseSensitive:mxe,CaseSensitiveIcon:mxe,CaseUpper:fxe,CaseUpperIcon:fxe,CassetteTape:pxe,CassetteTapeIcon:pxe,Cast:gxe,CastIcon:gxe,Castle:xxe,CastleIcon:xxe,Cat:yxe,CatIcon:yxe,Cctv:vxe,CctvIcon:vxe,ChartArea:GR,ChartAreaIcon:GR,ChartBar:KR,ChartBarBig:WR,ChartBarBigIcon:WR,ChartBarDecreasing:bxe,ChartBarDecreasingIcon:bxe,ChartBarIcon:KR,ChartBarIncreasing:_xe,ChartBarIncreasingIcon:_xe,ChartBarStacked:wxe,ChartBarStackedIcon:wxe,ChartCandlestick:YR,ChartCandlestickIcon:YR,ChartColumn:Gl,ChartColumnBig:ZR,ChartColumnBigIcon:ZR,ChartColumnDecreasing:jxe,ChartColumnDecreasingIcon:jxe,ChartColumnIcon:Gl,ChartColumnIncreasing:XR,ChartColumnIncreasingIcon:XR,ChartColumnStacked:Nxe,ChartColumnStackedIcon:Nxe,ChartGantt:kxe,ChartGanttIcon:kxe,ChartLine:QR,ChartLineIcon:QR,ChartNetwork:Sxe,ChartNetworkIcon:Sxe,ChartNoAxesColumn:eD,ChartNoAxesColumnDecreasing:Cxe,ChartNoAxesColumnDecreasingIcon:Cxe,ChartNoAxesColumnIcon:eD,ChartNoAxesColumnIncreasing:JR,ChartNoAxesColumnIncreasingIcon:JR,ChartNoAxesCombined:Axe,ChartNoAxesCombinedIcon:Axe,ChartNoAxesGantt:tD,ChartNoAxesGanttIcon:tD,ChartPie:sD,ChartPieIcon:sD,ChartScatter:nD,ChartScatterIcon:nD,ChartSpline:Exe,ChartSplineIcon:Exe,Check:ca,CheckCheck:Dz,CheckCheckIcon:Dz,CheckCircle:Wl,CheckCircle2:Vr,CheckCircle2Icon:Vr,CheckCircleIcon:Wl,CheckIcon:ca,CheckSquare:Vj,CheckSquare2:DF,CheckSquare2Icon:DF,CheckSquareIcon:Vj,ChefHat:Txe,ChefHatIcon:Txe,Cherry:Mxe,CherryIcon:Mxe,ChevronDown:wl,ChevronDownCircle:hD,ChevronDownCircleIcon:hD,ChevronDownIcon:wl,ChevronDownSquare:FF,ChevronDownSquareIcon:FF,ChevronFirst:Pxe,ChevronFirstIcon:Pxe,ChevronLast:Ixe,ChevronLastIcon:Ixe,ChevronLeft:kd,ChevronLeftCircle:mD,ChevronLeftCircleIcon:mD,ChevronLeftIcon:kd,ChevronLeftSquare:OF,ChevronLeftSquareIcon:OF,ChevronRight:Di,ChevronRightCircle:fD,ChevronRightCircleIcon:fD,ChevronRightIcon:Di,ChevronRightSquare:zF,ChevronRightSquareIcon:zF,ChevronUp:yb,ChevronUpCircle:pD,ChevronUpCircleIcon:pD,ChevronUpIcon:yb,ChevronUpSquare:BF,ChevronUpSquareIcon:BF,ChevronsDown:Rxe,ChevronsDownIcon:Rxe,ChevronsDownUp:Lxe,ChevronsDownUpIcon:Lxe,ChevronsLeft:Oxe,ChevronsLeftIcon:Oxe,ChevronsLeftRight:Fxe,ChevronsLeftRightEllipsis:Dxe,ChevronsLeftRightEllipsisIcon:Dxe,ChevronsLeftRightIcon:Fxe,ChevronsRight:Bxe,ChevronsRightIcon:Bxe,ChevronsRightLeft:zxe,ChevronsRightLeftIcon:zxe,ChevronsUp:$xe,ChevronsUpDown:Sw,ChevronsUpDownIcon:Sw,ChevronsUpIcon:$xe,Chrome:Fz,ChromeIcon:Fz,Church:Uxe,ChurchIcon:Uxe,Cigarette:Vxe,CigaretteIcon:Vxe,CigaretteOff:qxe,CigaretteOffIcon:qxe,Circle:Og,CircleAlert:ll,CircleAlertIcon:ll,CircleArrowDown:rD,CircleArrowDownIcon:rD,CircleArrowLeft:aD,CircleArrowLeftIcon:aD,CircleArrowOutDownLeft:iD,CircleArrowOutDownLeftIcon:iD,CircleArrowOutDownRight:oD,CircleArrowOutDownRightIcon:oD,CircleArrowOutUpLeft:lD,CircleArrowOutUpLeftIcon:lD,CircleArrowOutUpRight:cD,CircleArrowOutUpRightIcon:cD,CircleArrowRight:dD,CircleArrowRightIcon:dD,CircleArrowUp:uD,CircleArrowUpIcon:uD,CircleCheck:Vr,CircleCheckBig:Wl,CircleCheckBigIcon:Wl,CircleCheckIcon:Vr,CircleChevronDown:hD,CircleChevronDownIcon:hD,CircleChevronLeft:mD,CircleChevronLeftIcon:mD,CircleChevronRight:fD,CircleChevronRightIcon:fD,CircleChevronUp:pD,CircleChevronUpIcon:pD,CircleDashed:Hxe,CircleDashedIcon:Hxe,CircleDivide:gD,CircleDivideIcon:gD,CircleDollarSign:Gxe,CircleDollarSignIcon:Gxe,CircleDot:Kxe,CircleDotDashed:Wxe,CircleDotDashedIcon:Wxe,CircleDotIcon:Kxe,CircleEllipsis:Yxe,CircleEllipsisIcon:Yxe,CircleEqual:Zxe,CircleEqualIcon:Zxe,CircleFadingArrowUp:Xxe,CircleFadingArrowUpIcon:Xxe,CircleFadingPlus:Qxe,CircleFadingPlusIcon:Qxe,CircleGauge:xD,CircleGaugeIcon:xD,CircleHelp:e4,CircleHelpIcon:e4,CircleIcon:Og,CircleMinus:yD,CircleMinusIcon:yD,CircleOff:Jxe,CircleOffIcon:Jxe,CircleParking:bD,CircleParkingIcon:bD,CircleParkingOff:vD,CircleParkingOffIcon:vD,CirclePause:_D,CirclePauseIcon:_D,CirclePercent:wD,CirclePercentIcon:wD,CirclePlay:ef,CirclePlayIcon:ef,CirclePlus:jD,CirclePlusIcon:jD,CirclePower:ND,CirclePowerIcon:ND,CircleSlash:eye,CircleSlash2:kD,CircleSlash2Icon:kD,CircleSlashIcon:eye,CircleSlashed:kD,CircleSlashedIcon:kD,CircleStop:SD,CircleStopIcon:SD,CircleUser:AD,CircleUserIcon:AD,CircleUserRound:CD,CircleUserRoundIcon:CD,CircleX:Nu,CircleXIcon:Nu,CircuitBoard:tye,CircuitBoardIcon:tye,Citrus:sye,CitrusIcon:sye,Clapperboard:Sq,ClapperboardIcon:Sq,Clipboard:cye,ClipboardCheck:KN,ClipboardCheckIcon:KN,ClipboardCopy:nye,ClipboardCopyIcon:nye,ClipboardEdit:TD,ClipboardEditIcon:TD,ClipboardIcon:cye,ClipboardList:zg,ClipboardListIcon:zg,ClipboardMinus:rye,ClipboardMinusIcon:rye,ClipboardPaste:aye,ClipboardPasteIcon:aye,ClipboardPen:TD,ClipboardPenIcon:TD,ClipboardPenLine:ED,ClipboardPenLineIcon:ED,ClipboardPlus:iye,ClipboardPlusIcon:iye,ClipboardSignature:ED,ClipboardSignatureIcon:ED,ClipboardType:oye,ClipboardTypeIcon:oye,ClipboardX:lye,ClipboardXIcon:lye,Clock:da,Clock1:dye,Clock10:uye,Clock10Icon:uye,Clock11:hye,Clock11Icon:hye,Clock12:mye,Clock12Icon:mye,Clock1Icon:dye,Clock2:fye,Clock2Icon:fye,Clock3:Cq,Clock3Icon:Cq,Clock4:pye,Clock4Icon:pye,Clock5:gye,Clock5Icon:gye,Clock6:xye,Clock6Icon:xye,Clock7:yye,Clock7Icon:yye,Clock8:vye,Clock8Icon:vye,Clock9:bye,Clock9Icon:bye,ClockAlert:_ye,ClockAlertIcon:_ye,ClockArrowDown:wye,ClockArrowDownIcon:wye,ClockArrowUp:jye,ClockArrowUpIcon:jye,ClockIcon:da,Cloud:Oye,CloudAlert:Nye,CloudAlertIcon:Nye,CloudCog:kye,CloudCogIcon:kye,CloudDownload:MD,CloudDownloadIcon:MD,CloudDrizzle:Sye,CloudDrizzleIcon:Sye,CloudFog:Cye,CloudFogIcon:Cye,CloudHail:Aye,CloudHailIcon:Aye,CloudIcon:Oye,CloudLightning:Eye,CloudLightningIcon:Eye,CloudMoon:Mye,CloudMoonIcon:Mye,CloudMoonRain:Tye,CloudMoonRainIcon:Tye,CloudOff:Pye,CloudOffIcon:Pye,CloudRain:Lye,CloudRainIcon:Lye,CloudRainWind:Iye,CloudRainWindIcon:Iye,CloudSnow:Rye,CloudSnowIcon:Rye,CloudSun:Fye,CloudSunIcon:Fye,CloudSunRain:Dye,CloudSunRainIcon:Dye,CloudUpload:nP,CloudUploadIcon:nP,Cloudy:zye,CloudyIcon:zye,Clover:gE,CloverIcon:gE,Club:Bye,ClubIcon:Bye,Code:CE,Code2:t4,Code2Icon:t4,CodeIcon:CE,CodeSquare:$F,CodeSquareIcon:$F,CodeXml:t4,CodeXmlIcon:t4,Codepen:$ye,CodepenIcon:$ye,Codesandbox:Uye,CodesandboxIcon:Uye,Coffee:T4,CoffeeIcon:T4,Cog:qye,CogIcon:qye,Coins:gJ,CoinsIcon:gJ,Columns:PD,Columns2:PD,Columns2Icon:PD,Columns3:rP,Columns3Icon:rP,Columns4:Vye,Columns4Icon:Vye,ColumnsIcon:PD,Combine:Hye,CombineIcon:Hye,Command:Gye,CommandIcon:Gye,Compass:Oz,CompassIcon:Oz,Component:Wye,ComponentIcon:Wye,Computer:Kye,ComputerIcon:Kye,ConciergeBell:Yye,ConciergeBellIcon:Yye,Cone:Zye,ConeIcon:Zye,Construction:Xye,ConstructionIcon:Xye,Contact:UI,Contact2:ID,Contact2Icon:ID,ContactIcon:UI,ContactRound:ID,ContactRoundIcon:ID,Container:Qye,ContainerIcon:Qye,Contrast:Jye,ContrastIcon:Jye,Cookie:e0e,CookieIcon:e0e,CookingPot:t0e,CookingPotIcon:t0e,Copy:Ha,CopyCheck:s0e,CopyCheckIcon:s0e,CopyIcon:Ha,CopyMinus:n0e,CopyMinusIcon:n0e,CopyPlus:r0e,CopyPlusIcon:r0e,CopySlash:a0e,CopySlashIcon:a0e,CopyX:i0e,CopyXIcon:i0e,Copyleft:o0e,CopyleftIcon:o0e,Copyright:l0e,CopyrightIcon:l0e,CornerDownLeft:c0e,CornerDownLeftIcon:c0e,CornerDownRight:xJ,CornerDownRightIcon:xJ,CornerLeftDown:d0e,CornerLeftDownIcon:d0e,CornerLeftUp:u0e,CornerLeftUpIcon:u0e,CornerRightDown:h0e,CornerRightDownIcon:h0e,CornerRightUp:m0e,CornerRightUpIcon:m0e,CornerUpLeft:f0e,CornerUpLeftIcon:f0e,CornerUpRight:p0e,CornerUpRightIcon:p0e,Cpu:g0e,CpuIcon:g0e,CreativeCommons:x0e,CreativeCommonsIcon:x0e,CreditCard:Nv,CreditCardIcon:Nv,Croissant:y0e,CroissantIcon:y0e,Crop:v0e,CropIcon:v0e,Cross:b0e,CrossIcon:b0e,Crosshair:_0e,CrosshairIcon:_0e,Crown:Bg,CrownIcon:Bg,Cuboid:w0e,CuboidIcon:w0e,CupSoda:j0e,CupSodaIcon:j0e,CurlyBraces:sP,CurlyBracesIcon:sP,Currency:N0e,CurrencyIcon:N0e,Cylinder:k0e,CylinderIcon:k0e,Dam:S0e,DamIcon:S0e,Database:Aq,DatabaseBackup:C0e,DatabaseBackupIcon:C0e,DatabaseIcon:Aq,DatabaseZap:A0e,DatabaseZapIcon:A0e,Delete:E0e,DeleteIcon:E0e,Dessert:T0e,DessertIcon:T0e,Diameter:M0e,DiameterIcon:M0e,Diamond:L0e,DiamondIcon:L0e,DiamondMinus:P0e,DiamondMinusIcon:P0e,DiamondPercent:LD,DiamondPercentIcon:LD,DiamondPlus:I0e,DiamondPlusIcon:I0e,Dice1:R0e,Dice1Icon:R0e,Dice2:D0e,Dice2Icon:D0e,Dice3:F0e,Dice3Icon:F0e,Dice4:O0e,Dice4Icon:O0e,Dice5:z0e,Dice5Icon:z0e,Dice6:B0e,Dice6Icon:B0e,Dices:$0e,DicesIcon:$0e,Diff:U0e,DiffIcon:U0e,Disc:G0e,Disc2:q0e,Disc2Icon:q0e,Disc3:V0e,Disc3Icon:V0e,DiscAlbum:H0e,DiscAlbumIcon:H0e,DiscIcon:G0e,Divide:W0e,DivideCircle:gD,DivideCircleIcon:gD,DivideIcon:W0e,DivideSquare:HF,DivideSquareIcon:HF,Dna:Y0e,DnaIcon:Y0e,DnaOff:K0e,DnaOffIcon:K0e,Dock:Z0e,DockIcon:Z0e,Dog:X0e,DogIcon:X0e,DollarSign:nu,DollarSignIcon:nu,Donut:Q0e,DonutIcon:Q0e,DoorClosed:J0e,DoorClosedIcon:J0e,DoorOpen:i2,DoorOpenIcon:i2,Dot:eve,DotIcon:eve,DotSquare:GF,DotSquareIcon:GF,Download:xi,DownloadCloud:MD,DownloadCloudIcon:MD,DownloadIcon:xi,DraftingCompass:tve,DraftingCompassIcon:tve,Drama:sve,DramaIcon:sve,Dribbble:nve,DribbbleIcon:nve,Drill:rve,DrillIcon:rve,Droplet:ave,DropletIcon:ave,Droplets:g1,DropletsIcon:g1,Drum:ive,DrumIcon:ive,Drumstick:ove,DrumstickIcon:ove,Dumbbell:lve,DumbbellIcon:lve,Ear:dve,EarIcon:dve,EarOff:cve,EarOffIcon:cve,Earth:CN,EarthIcon:CN,EarthLock:uve,EarthLockIcon:uve,Eclipse:hve,EclipseIcon:hve,Edit:_p,Edit2:AN,Edit2Icon:AN,Edit3:_f,Edit3Icon:_f,EditIcon:_p,Egg:Eq,EggFried:mve,EggFriedIcon:mve,EggIcon:Eq,EggOff:fve,EggOffIcon:fve,Ellipsis:l_,EllipsisIcon:l_,EllipsisVertical:Jx,EllipsisVerticalIcon:Jx,Equal:xve,EqualApproximately:pve,EqualApproximatelyIcon:pve,EqualIcon:xve,EqualNot:gve,EqualNotIcon:gve,EqualSquare:WF,EqualSquareIcon:WF,Eraser:Tq,EraserIcon:Tq,EthernetPort:yve,EthernetPortIcon:yve,Euro:vve,EuroIcon:vve,Expand:bve,ExpandIcon:bve,ExternalLink:Fr,ExternalLinkIcon:Fr,Eye:Ca,EyeClosed:_ve,EyeClosedIcon:_ve,EyeIcon:Ca,EyeOff:$g,EyeOffIcon:$g,Facebook:Qp,FacebookIcon:Qp,Factory:wve,FactoryIcon:wve,Fan:jve,FanIcon:jve,FastForward:Nve,FastForwardIcon:Nve,Feather:kve,FeatherIcon:kve,Fence:Sve,FenceIcon:Sve,FerrisWheel:Cve,FerrisWheelIcon:Cve,Figma:Ave,FigmaIcon:Ave,File:Pq,FileArchive:Eve,FileArchiveIcon:Eve,FileAudio:Mve,FileAudio2:Tve,FileAudio2Icon:Tve,FileAudioIcon:Mve,FileAxis3D:RD,FileAxis3DIcon:RD,FileAxis3d:RD,FileAxis3dIcon:RD,FileBadge:Ive,FileBadge2:Pve,FileBadge2Icon:Pve,FileBadgeIcon:Ive,FileBarChart:DD,FileBarChart2:FD,FileBarChart2Icon:FD,FileBarChartIcon:DD,FileBox:Lve,FileBoxIcon:Lve,FileChartColumn:FD,FileChartColumnIcon:FD,FileChartColumnIncreasing:DD,FileChartColumnIncreasingIcon:DD,FileChartLine:OD,FileChartLineIcon:OD,FileChartPie:zD,FileChartPieIcon:zD,FileCheck:yJ,FileCheck2:zz,FileCheck2Icon:zz,FileCheckIcon:yJ,FileClock:Rve,FileClockIcon:Rve,FileCode:Fve,FileCode2:Dve,FileCode2Icon:Dve,FileCodeIcon:Fve,FileCog:BD,FileCog2:BD,FileCog2Icon:BD,FileCogIcon:BD,FileDiff:Ove,FileDiffIcon:Ove,FileDigit:zve,FileDigitIcon:zve,FileDown:o2,FileDownIcon:o2,FileEdit:$D,FileEditIcon:$D,FileHeart:Bve,FileHeartIcon:Bve,FileIcon:Pq,FileImage:qI,FileImageIcon:qI,FileInput:$ve,FileInputIcon:$ve,FileJson:qve,FileJson2:Uve,FileJson2Icon:Uve,FileJsonIcon:qve,FileKey:Hve,FileKey2:Vve,FileKey2Icon:Vve,FileKeyIcon:Hve,FileLineChart:OD,FileLineChartIcon:OD,FileLock:Wve,FileLock2:Gve,FileLock2Icon:Gve,FileLockIcon:Wve,FileMinus:Yve,FileMinus2:Kve,FileMinus2Icon:Kve,FileMinusIcon:Yve,FileMusic:Zve,FileMusicIcon:Zve,FileOutput:Xve,FileOutputIcon:Xve,FilePen:$D,FilePenIcon:$D,FilePenLine:c_,FilePenLineIcon:c_,FilePieChart:zD,FilePieChartIcon:zD,FilePlus:Qve,FilePlus2:Mq,FilePlus2Icon:Mq,FilePlusIcon:Qve,FileQuestion:Jve,FileQuestionIcon:Jve,FileScan:ebe,FileScanIcon:ebe,FileSearch:vJ,FileSearch2:tbe,FileSearch2Icon:tbe,FileSearchIcon:vJ,FileSignature:c_,FileSignatureIcon:c_,FileSliders:sbe,FileSlidersIcon:sbe,FileSpreadsheet:YN,FileSpreadsheetIcon:YN,FileStack:bJ,FileStackIcon:bJ,FileSymlink:nbe,FileSymlinkIcon:nbe,FileTerminal:rbe,FileTerminalIcon:rbe,FileText:Jr,FileTextIcon:Jr,FileType:ibe,FileType2:abe,FileType2Icon:abe,FileTypeIcon:ibe,FileUp:_J,FileUpIcon:_J,FileUser:obe,FileUserIcon:obe,FileVideo:wJ,FileVideo2:lbe,FileVideo2Icon:lbe,FileVideoIcon:wJ,FileVolume:dbe,FileVolume2:cbe,FileVolume2Icon:cbe,FileVolumeIcon:dbe,FileWarning:ube,FileWarningIcon:ube,FileX:mbe,FileX2:hbe,FileX2Icon:hbe,FileXIcon:mbe,Files:fbe,FilesIcon:fbe,Film:nf,FilmIcon:nf,Filter:Cw,FilterIcon:Cw,FilterX:pbe,FilterXIcon:pbe,Fingerprint:gbe,FingerprintIcon:gbe,FireExtinguisher:xbe,FireExtinguisherIcon:xbe,Fish:bbe,FishIcon:bbe,FishOff:ybe,FishOffIcon:ybe,FishSymbol:vbe,FishSymbolIcon:vbe,Flag:AE,FlagIcon:AE,FlagOff:_be,FlagOffIcon:_be,FlagTriangleLeft:wbe,FlagTriangleLeftIcon:wbe,FlagTriangleRight:jbe,FlagTriangleRightIcon:jbe,Flame:sh,FlameIcon:sh,FlameKindling:Nbe,FlameKindlingIcon:Nbe,Flashlight:Sbe,FlashlightIcon:Sbe,FlashlightOff:kbe,FlashlightOffIcon:kbe,FlaskConical:VI,FlaskConicalIcon:VI,FlaskConicalOff:Cbe,FlaskConicalOffIcon:Cbe,FlaskRound:Abe,FlaskRoundIcon:Abe,FlipHorizontal:jJ,FlipHorizontal2:Ebe,FlipHorizontal2Icon:Ebe,FlipHorizontalIcon:jJ,FlipVertical:Mbe,FlipVertical2:Tbe,FlipVertical2Icon:Tbe,FlipVerticalIcon:Mbe,Flower:Pbe,Flower2:qS,Flower2Icon:qS,FlowerIcon:Pbe,Focus:Ibe,FocusIcon:Ibe,FoldHorizontal:Lbe,FoldHorizontalIcon:Lbe,FoldVertical:Rbe,FoldVerticalIcon:Rbe,Folder:Iq,FolderArchive:Dbe,FolderArchiveIcon:Dbe,FolderCheck:Fbe,FolderCheckIcon:Fbe,FolderClock:Obe,FolderClockIcon:Obe,FolderClosed:zbe,FolderClosedIcon:zbe,FolderCode:Bbe,FolderCodeIcon:Bbe,FolderCog:UD,FolderCog2:UD,FolderCog2Icon:UD,FolderCogIcon:UD,FolderDot:$be,FolderDotIcon:$be,FolderDown:Ube,FolderDownIcon:Ube,FolderEdit:qD,FolderEditIcon:qD,FolderGit:Vbe,FolderGit2:qbe,FolderGit2Icon:qbe,FolderGitIcon:Vbe,FolderHeart:Hbe,FolderHeartIcon:Hbe,FolderIcon:Iq,FolderInput:Gbe,FolderInputIcon:Gbe,FolderKanban:Wbe,FolderKanbanIcon:Wbe,FolderKey:Kbe,FolderKeyIcon:Kbe,FolderLock:Ybe,FolderLockIcon:Ybe,FolderMinus:Zbe,FolderMinusIcon:Zbe,FolderOpen:kv,FolderOpenDot:Xbe,FolderOpenDotIcon:Xbe,FolderOpenIcon:kv,FolderOutput:Qbe,FolderOutputIcon:Qbe,FolderPen:qD,FolderPenIcon:qD,FolderPlus:NJ,FolderPlusIcon:NJ,FolderRoot:Jbe,FolderRootIcon:Jbe,FolderSearch:t1e,FolderSearch2:e1e,FolderSearch2Icon:e1e,FolderSearchIcon:t1e,FolderSymlink:s1e,FolderSymlinkIcon:s1e,FolderSync:n1e,FolderSyncIcon:n1e,FolderTree:r1e,FolderTreeIcon:r1e,FolderUp:a1e,FolderUpIcon:a1e,FolderX:i1e,FolderXIcon:i1e,Folders:o1e,FoldersIcon:o1e,Footprints:l1e,FootprintsIcon:l1e,ForkKnife:EO,ForkKnifeCrossed:AO,ForkKnifeCrossedIcon:AO,ForkKnifeIcon:EO,Forklift:c1e,ForkliftIcon:c1e,FormInput:mF,FormInputIcon:mF,Forward:d1e,ForwardIcon:d1e,Frame:u1e,FrameIcon:u1e,Framer:h1e,FramerIcon:h1e,Frown:m1e,FrownIcon:m1e,Fuel:f1e,FuelIcon:f1e,Fullscreen:p1e,FullscreenIcon:p1e,FunctionSquare:KF,FunctionSquareIcon:KF,GalleryHorizontal:x1e,GalleryHorizontalEnd:g1e,GalleryHorizontalEndIcon:g1e,GalleryHorizontalIcon:x1e,GalleryThumbnails:y1e,GalleryThumbnailsIcon:y1e,GalleryVertical:b1e,GalleryVerticalEnd:v1e,GalleryVerticalEndIcon:v1e,GalleryVerticalIcon:b1e,Gamepad:w1e,Gamepad2:_1e,Gamepad2Icon:_1e,GamepadIcon:w1e,GanttChart:tD,GanttChartIcon:tD,GanttChartSquare:p5,GanttChartSquareIcon:p5,Gauge:j1e,GaugeCircle:xD,GaugeCircleIcon:xD,GaugeIcon:j1e,Gavel:N1e,GavelIcon:N1e,Gem:k1e,GemIcon:k1e,Ghost:Bz,GhostIcon:Bz,Gift:ul,GiftIcon:ul,GitBranch:C1e,GitBranchIcon:C1e,GitBranchPlus:S1e,GitBranchPlusIcon:S1e,GitCommit:VD,GitCommitHorizontal:VD,GitCommitHorizontalIcon:VD,GitCommitIcon:VD,GitCommitVertical:A1e,GitCommitVerticalIcon:A1e,GitCompare:T1e,GitCompareArrows:E1e,GitCompareArrowsIcon:E1e,GitCompareIcon:T1e,GitFork:M1e,GitForkIcon:M1e,GitGraph:P1e,GitGraphIcon:P1e,GitMerge:I1e,GitMergeIcon:I1e,GitPullRequest:z1e,GitPullRequestArrow:L1e,GitPullRequestArrowIcon:L1e,GitPullRequestClosed:R1e,GitPullRequestClosedIcon:R1e,GitPullRequestCreate:F1e,GitPullRequestCreateArrow:D1e,GitPullRequestCreateArrowIcon:D1e,GitPullRequestCreateIcon:F1e,GitPullRequestDraft:O1e,GitPullRequestDraftIcon:O1e,GitPullRequestIcon:z1e,Github:B1e,GithubIcon:B1e,Gitlab:$1e,GitlabIcon:$1e,GlassWater:U1e,GlassWaterIcon:U1e,Glasses:q1e,GlassesIcon:q1e,Globe:dl,Globe2:CN,Globe2Icon:CN,GlobeIcon:dl,GlobeLock:V1e,GlobeLockIcon:V1e,Goal:H1e,GoalIcon:H1e,Grab:G1e,GrabIcon:G1e,GraduationCap:af,GraduationCapIcon:af,Grape:W1e,GrapeIcon:W1e,Grid:Fj,Grid2X2:GD,Grid2X2Icon:GD,Grid2X2Plus:HD,Grid2X2PlusIcon:HD,Grid2x2:GD,Grid2x2Check:K1e,Grid2x2CheckIcon:K1e,Grid2x2Icon:GD,Grid2x2Plus:HD,Grid2x2PlusIcon:HD,Grid2x2X:Y1e,Grid2x2XIcon:Y1e,Grid3X3:Fj,Grid3X3Icon:Fj,Grid3x3:Fj,Grid3x3Icon:Fj,GridIcon:Fj,Grip:X1e,GripHorizontal:Z1e,GripHorizontalIcon:Z1e,GripIcon:X1e,GripVertical:Ug,GripVerticalIcon:Ug,Group:Q1e,GroupIcon:Q1e,Guitar:J1e,GuitarIcon:J1e,Ham:e_e,HamIcon:e_e,Hammer:kJ,HammerIcon:kJ,Hand:Lq,HandCoins:t_e,HandCoinsIcon:t_e,HandHeart:SJ,HandHeartIcon:SJ,HandHelping:s4,HandHelpingIcon:s4,HandIcon:Lq,HandMetal:s_e,HandMetalIcon:s_e,HandPlatter:n_e,HandPlatterIcon:n_e,Handshake:vb,HandshakeIcon:vb,HardDrive:CJ,HardDriveDownload:r_e,HardDriveDownloadIcon:r_e,HardDriveIcon:CJ,HardDriveUpload:a_e,HardDriveUploadIcon:a_e,HardHat:i_e,HardHatIcon:i_e,Hash:HI,HashIcon:HI,Haze:o_e,HazeIcon:o_e,HdmiPort:l_e,HdmiPortIcon:l_e,Heading:h_e,Heading1:Rq,Heading1Icon:Rq,Heading2:$z,Heading2Icon:$z,Heading3:Dq,Heading3Icon:Dq,Heading4:c_e,Heading4Icon:c_e,Heading5:d_e,Heading5Icon:d_e,Heading6:u_e,Heading6Icon:u_e,HeadingIcon:h_e,HeadphoneOff:m_e,HeadphoneOffIcon:m_e,Headphones:f_e,HeadphonesIcon:f_e,Headset:p_e,HeadsetIcon:p_e,Heart:Jo,HeartCrack:g_e,HeartCrackIcon:g_e,HeartHandshake:AJ,HeartHandshakeIcon:AJ,HeartIcon:Jo,HeartOff:x_e,HeartOffIcon:x_e,HeartPulse:y_e,HeartPulseIcon:y_e,Heater:v_e,HeaterIcon:v_e,HelpCircle:e4,HelpCircleIcon:e4,HelpingHand:s4,HelpingHandIcon:s4,Hexagon:b_e,HexagonIcon:b_e,Highlighter:__e,HighlighterIcon:__e,History:Aw,HistoryIcon:Aw,Home:va,HomeIcon:va,Hop:j_e,HopIcon:j_e,HopOff:w_e,HopOffIcon:w_e,Hospital:N_e,HospitalIcon:N_e,Hotel:k_e,HotelIcon:k_e,Hourglass:EJ,HourglassIcon:EJ,House:va,HouseIcon:va,HousePlug:S_e,HousePlugIcon:S_e,HousePlus:C_e,HousePlusIcon:C_e,IceCream:KD,IceCream2:WD,IceCream2Icon:WD,IceCreamBowl:WD,IceCreamBowlIcon:WD,IceCreamCone:KD,IceCreamConeIcon:KD,IceCreamIcon:KD,Icon:TRt,IdCard:TJ,IdCardIcon:TJ,Image:Hc,ImageDown:A_e,ImageDownIcon:A_e,ImageIcon:Hc,ImageMinus:E_e,ImageMinusIcon:E_e,ImageOff:T_e,ImageOffIcon:T_e,ImagePlay:M_e,ImagePlayIcon:M_e,ImagePlus:Sv,ImagePlusIcon:Sv,ImageUp:P_e,ImageUpIcon:P_e,ImageUpscale:I_e,ImageUpscaleIcon:I_e,Images:L_e,ImagesIcon:L_e,Import:R_e,ImportIcon:R_e,Inbox:Uz,InboxIcon:Uz,Indent:ZD,IndentDecrease:YD,IndentDecreaseIcon:YD,IndentIcon:ZD,IndentIncrease:ZD,IndentIncreaseIcon:ZD,IndianRupee:D_e,IndianRupeeIcon:D_e,Infinity:Fq,InfinityIcon:Fq,Info:QS,InfoIcon:QS,Inspect:eO,InspectIcon:eO,InspectionPanel:F_e,InspectionPanelIcon:F_e,Instagram:Ef,InstagramIcon:Ef,Italic:EE,ItalicIcon:EE,IterationCcw:O_e,IterationCcwIcon:O_e,IterationCw:z_e,IterationCwIcon:z_e,JapaneseYen:B_e,JapaneseYenIcon:B_e,Joystick:$_e,JoystickIcon:$_e,Kanban:l2,KanbanIcon:l2,KanbanSquare:YF,KanbanSquareDashed:UF,KanbanSquareDashedIcon:UF,KanbanSquareIcon:YF,Key:w_,KeyIcon:w_,KeyRound:GI,KeyRoundIcon:GI,KeySquare:U_e,KeySquareIcon:U_e,Keyboard:H_e,KeyboardIcon:H_e,KeyboardMusic:q_e,KeyboardMusicIcon:q_e,KeyboardOff:V_e,KeyboardOffIcon:V_e,Lamp:X_e,LampCeiling:G_e,LampCeilingIcon:G_e,LampDesk:W_e,LampDeskIcon:W_e,LampFloor:K_e,LampFloorIcon:K_e,LampIcon:X_e,LampWallDown:Y_e,LampWallDownIcon:Y_e,LampWallUp:Z_e,LampWallUpIcon:Z_e,LandPlot:Q_e,LandPlotIcon:Q_e,Landmark:Oq,LandmarkIcon:Oq,Languages:J_e,LanguagesIcon:J_e,Laptop:twe,Laptop2:XD,Laptop2Icon:XD,LaptopIcon:twe,LaptopMinimal:XD,LaptopMinimalCheck:ewe,LaptopMinimalCheckIcon:ewe,LaptopMinimalIcon:XD,Lasso:nwe,LassoIcon:nwe,LassoSelect:swe,LassoSelectIcon:swe,Laugh:rwe,LaughIcon:rwe,Layers:M4,Layers2:awe,Layers2Icon:awe,Layers3:iwe,Layers3Icon:iwe,LayersIcon:M4,Layout:LA,LayoutDashboard:WI,LayoutDashboardIcon:WI,LayoutGrid:Qf,LayoutGridIcon:Qf,LayoutIcon:LA,LayoutList:owe,LayoutListIcon:owe,LayoutPanelLeft:lwe,LayoutPanelLeftIcon:lwe,LayoutPanelTop:cwe,LayoutPanelTopIcon:cwe,LayoutTemplate:c2,LayoutTemplateIcon:c2,Leaf:dwe,LeafIcon:dwe,LeafyGreen:uwe,LeafyGreenIcon:uwe,Lectern:hwe,LecternIcon:hwe,LetterText:mwe,LetterTextIcon:mwe,Library:d2,LibraryBig:fwe,LibraryBigIcon:fwe,LibraryIcon:d2,LibrarySquare:ZF,LibrarySquareIcon:ZF,LifeBuoy:zq,LifeBuoyIcon:zq,Ligature:pwe,LigatureIcon:pwe,Lightbulb:JS,LightbulbIcon:JS,LightbulbOff:gwe,LightbulbOffIcon:gwe,LineChart:QR,LineChartIcon:QR,Link:Sd,Link2:Wd,Link2Icon:Wd,Link2Off:xwe,Link2OffIcon:xwe,LinkIcon:Sd,Linkedin:dy,LinkedinIcon:dy,List:T0,ListCheck:ywe,ListCheckIcon:ywe,ListChecks:Cv,ListChecksIcon:Cv,ListCollapse:vwe,ListCollapseIcon:vwe,ListEnd:bwe,ListEndIcon:bwe,ListFilter:MJ,ListFilterIcon:MJ,ListIcon:T0,ListMinus:_we,ListMinusIcon:_we,ListMusic:wwe,ListMusicIcon:wwe,ListOrdered:u2,ListOrderedIcon:u2,ListPlus:PJ,ListPlusIcon:PJ,ListRestart:jwe,ListRestartIcon:jwe,ListStart:Nwe,ListStartIcon:Nwe,ListTodo:kwe,ListTodoIcon:kwe,ListTree:Swe,ListTreeIcon:Swe,ListVideo:Cwe,ListVideoIcon:Cwe,ListX:Awe,ListXIcon:Awe,Loader:Twe,Loader2:Ct,Loader2Icon:Ct,LoaderCircle:Ct,LoaderCircleIcon:Ct,LoaderIcon:Twe,LoaderPinwheel:Ewe,LoaderPinwheelIcon:Ewe,Locate:Bq,LocateFixed:Mwe,LocateFixedIcon:Mwe,LocateIcon:Bq,LocateOff:Pwe,LocateOffIcon:Pwe,Lock:pc,LockIcon:pc,LockKeyhole:IJ,LockKeyholeIcon:IJ,LockKeyholeOpen:QD,LockKeyholeOpenIcon:QD,LockOpen:JD,LockOpenIcon:JD,LogIn:KI,LogInIcon:KI,LogOut:qz,LogOutIcon:qz,Logs:Iwe,LogsIcon:Iwe,Lollipop:Lwe,LollipopIcon:Lwe,LucideAArrowDown:xme,LucideAArrowUp:yme,LucideALargeSmall:vme,LucideAccessibility:bme,LucideActivity:rf,LucideActivitySquare:_F,LucideAirVent:_me,LucideAirplay:wme,LucideAlarmCheck:PR,LucideAlarmClock:Nme,LucideAlarmClockCheck:PR,LucideAlarmClockMinus:IR,LucideAlarmClockOff:jme,LucideAlarmClockPlus:LR,LucideAlarmMinus:IR,LucideAlarmPlus:LR,LucideAlarmSmoke:kme,LucideAlbum:Sme,LucideAlertCircle:ll,LucideAlertOctagon:OS,LucideAlertTriangle:Al,LucideAlignCenter:DI,LucideAlignCenterHorizontal:Cme,LucideAlignCenterVertical:Ame,LucideAlignEndHorizontal:Eme,LucideAlignEndVertical:Tme,LucideAlignHorizontalDistributeCenter:Mme,LucideAlignHorizontalDistributeEnd:Pme,LucideAlignHorizontalDistributeStart:Ime,LucideAlignHorizontalJustifyCenter:Lme,LucideAlignHorizontalJustifyEnd:Rme,LucideAlignHorizontalJustifyStart:Dme,LucideAlignHorizontalSpaceAround:Fme,LucideAlignHorizontalSpaceBetween:Ome,LucideAlignJustify:zme,LucideAlignLeft:FI,LucideAlignRight:OI,LucideAlignStartHorizontal:Bme,LucideAlignStartVertical:$me,LucideAlignVerticalDistributeCenter:Ume,LucideAlignVerticalDistributeEnd:qme,LucideAlignVerticalDistributeStart:Vme,LucideAlignVerticalJustifyCenter:Hme,LucideAlignVerticalJustifyEnd:Gme,LucideAlignVerticalJustifyStart:Wme,LucideAlignVerticalSpaceAround:Kme,LucideAlignVerticalSpaceBetween:Yme,LucideAmbulance:Zme,LucideAmpersand:Xme,LucideAmpersands:Qme,LucideAmphora:Jme,LucideAnchor:efe,LucideAngry:tfe,LucideAnnoyed:sfe,LucideAntenna:nfe,LucideAnvil:rfe,LucideAperture:afe,LucideAppWindow:ofe,LucideAppWindowMac:ife,LucideApple:lfe,LucideArchive:jv,LucideArchiveRestore:zI,LucideArchiveX:cfe,LucideAreaChart:GR,LucideArmchair:dfe,LucideArrowBigDown:hfe,LucideArrowBigDownDash:ufe,LucideArrowBigLeft:ffe,LucideArrowBigLeftDash:mfe,LucideArrowBigRight:gfe,LucideArrowBigRightDash:pfe,LucideArrowBigUp:yfe,LucideArrowBigUpDash:xfe,LucideArrowDown:Dg,LucideArrowDown01:vfe,LucideArrowDown10:bfe,LucideArrowDownAZ:RR,LucideArrowDownAz:RR,LucideArrowDownCircle:rD,LucideArrowDownFromLine:_fe,LucideArrowDownLeft:wfe,LucideArrowDownLeftFromCircle:iD,LucideArrowDownLeftFromSquare:SF,LucideArrowDownLeftSquare:wF,LucideArrowDownNarrowWide:jfe,LucideArrowDownRight:dJ,LucideArrowDownRightFromCircle:oD,LucideArrowDownRightFromSquare:CF,LucideArrowDownRightSquare:jF,LucideArrowDownSquare:NF,LucideArrowDownToDot:Nfe,LucideArrowDownToLine:kfe,LucideArrowDownUp:Sfe,LucideArrowDownWideNarrow:DR,LucideArrowDownZA:FR,LucideArrowDownZa:FR,LucideArrowLeft:Va,LucideArrowLeftCircle:aD,LucideArrowLeftFromLine:Cfe,LucideArrowLeftRight:uJ,LucideArrowLeftSquare:kF,LucideArrowLeftToLine:Afe,LucideArrowRight:Qa,LucideArrowRightCircle:dD,LucideArrowRightFromLine:Efe,LucideArrowRightLeft:C4,LucideArrowRightSquare:TF,LucideArrowRightToLine:Tfe,LucideArrowUp:Zf,LucideArrowUp01:Mfe,LucideArrowUp10:Pfe,LucideArrowUpAZ:OR,LucideArrowUpAz:OR,LucideArrowUpCircle:uD,LucideArrowUpDown:zy,LucideArrowUpFromDot:Ife,LucideArrowUpFromLine:Lfe,LucideArrowUpLeft:Rfe,LucideArrowUpLeftFromCircle:lD,LucideArrowUpLeftFromSquare:AF,LucideArrowUpLeftSquare:MF,LucideArrowUpNarrowWide:zR,LucideArrowUpRight:Lz,LucideArrowUpRightFromCircle:cD,LucideArrowUpRightFromSquare:EF,LucideArrowUpRightSquare:PF,LucideArrowUpSquare:IF,LucideArrowUpToLine:Dfe,LucideArrowUpWideNarrow:Ffe,LucideArrowUpZA:BR,LucideArrowUpZa:BR,LucideArrowsUpFromLine:Ofe,LucideAsterisk:zfe,LucideAsteriskSquare:LF,LucideAtSign:Bfe,LucideAtom:$fe,LucideAudioLines:Ufe,LucideAudioWaveform:qfe,LucideAward:Im,LucideAxe:Vfe,LucideAxis3D:$R,LucideAxis3d:$R,LucideBaby:Hfe,LucideBackpack:Gfe,LucideBadge:lpe,LucideBadgeAlert:Wfe,LucideBadgeCent:Kfe,LucideBadgeCheck:IA,LucideBadgeDollarSign:Yfe,LucideBadgeEuro:Zfe,LucideBadgeHelp:Xfe,LucideBadgeIndianRupee:Qfe,LucideBadgeInfo:Jfe,LucideBadgeJapaneseYen:epe,LucideBadgeMinus:tpe,LucideBadgePercent:spe,LucideBadgePlus:npe,LucideBadgePoundSterling:rpe,LucideBadgeRussianRuble:ape,LucideBadgeSwissFranc:ipe,LucideBadgeX:ope,LucideBaggageClaim:cpe,LucideBan:Rz,LucideBanana:dpe,LucideBandage:upe,LucideBanknote:hpe,LucideBarChart:JR,LucideBarChart2:eD,LucideBarChart3:Gl,LucideBarChart4:XR,LucideBarChartBig:ZR,LucideBarChartHorizontal:KR,LucideBarChartHorizontalBig:WR,LucideBarcode:mpe,LucideBaseline:fpe,LucideBath:A0,LucideBattery:bpe,LucideBatteryCharging:ppe,LucideBatteryFull:gpe,LucideBatteryLow:xpe,LucideBatteryMedium:ype,LucideBatteryWarning:vpe,LucideBeaker:hJ,LucideBean:wpe,LucideBeanOff:_pe,LucideBed:r2,LucideBedDouble:A4,LucideBedSingle:jpe,LucideBeef:Npe,LucideBeer:Spe,LucideBeerOff:kpe,LucideBell:Uy,LucideBellDot:Cpe,LucideBellElectric:Ape,LucideBellMinus:Epe,LucideBellOff:YS,LucideBellPlus:Tpe,LucideBellRing:ZS,LucideBetweenHorizonalEnd:UR,LucideBetweenHorizonalStart:qR,LucideBetweenHorizontalEnd:UR,LucideBetweenHorizontalStart:qR,LucideBetweenVerticalEnd:Mpe,LucideBetweenVerticalStart:Ppe,LucideBicepsFlexed:Ipe,LucideBike:Lpe,LucideBinary:Rpe,LucideBinoculars:Dpe,LucideBiohazard:Fpe,LucideBird:Ope,LucideBitcoin:zpe,LucideBlend:Bpe,LucideBlinds:$pe,LucideBlocks:Upe,LucideBluetooth:Gpe,LucideBluetoothConnected:qpe,LucideBluetoothOff:Vpe,LucideBluetoothSearching:Hpe,LucideBold:SE,LucideBolt:Wpe,LucideBomb:Kpe,LucideBone:Ype,LucideBook:xge,LucideBookA:Zpe,LucideBookAudio:Xpe,LucideBookCheck:Qpe,LucideBookCopy:Jpe,LucideBookDashed:VR,LucideBookDown:ege,LucideBookHeadphones:tge,LucideBookHeart:sge,LucideBookImage:nge,LucideBookKey:rge,LucideBookLock:age,LucideBookMarked:ige,LucideBookMinus:oge,LucideBookOpen:Xf,LucideBookOpenCheck:lge,LucideBookOpenText:cge,LucideBookPlus:dge,LucideBookTemplate:VR,LucideBookText:uge,LucideBookType:hge,LucideBookUp:fge,LucideBookUp2:mge,LucideBookUser:pge,LucideBookX:gge,LucideBookmark:E0,LucideBookmarkCheck:yge,LucideBookmarkMinus:vge,LucideBookmarkPlus:BI,LucideBookmarkX:bge,LucideBoomBox:_ge,LucideBot:E4,LucideBotMessageSquare:wge,LucideBotOff:jge,LucideBox:mJ,LucideBoxSelect:VF,LucideBoxes:Nge,LucideBraces:sP,LucideBrackets:kge,LucideBrain:fJ,LucideBrainCircuit:Sge,LucideBrainCog:Cge,LucideBrickWall:Age,LucideBriefcase:kx,LucideBriefcaseBusiness:Ege,LucideBriefcaseConveyorBelt:Tge,LucideBriefcaseMedical:Mge,LucideBringToFront:Pge,LucideBrush:Ige,LucideBug:Dge,LucideBugOff:Lge,LucideBugPlay:Rge,LucideBuilding:$I,LucideBuilding2:ji,LucideBus:Oge,LucideBusFront:Fge,LucideCable:Bge,LucideCableCar:zge,LucideCake:Fg,LucideCakeSlice:$ge,LucideCalculator:a2,LucideCalendar:Ta,LucideCalendar1:Uge,LucideCalendarArrowDown:qge,LucideCalendarArrowUp:Vge,LucideCalendarCheck:xb,LucideCalendarCheck2:Hge,LucideCalendarClock:Cu,LucideCalendarCog:Gge,LucideCalendarDays:Wc,LucideCalendarFold:Wge,LucideCalendarHeart:XS,LucideCalendarMinus:Yge,LucideCalendarMinus2:Kge,LucideCalendarOff:kq,LucideCalendarPlus:bv,LucideCalendarPlus2:Zge,LucideCalendarRange:Xge,LucideCalendarSearch:Qge,LucideCalendarSync:Jge,LucideCalendarX:pJ,LucideCalendarX2:exe,LucideCamera:Sx,LucideCameraOff:txe,LucideCandlestickChart:YR,LucideCandy:rxe,LucideCandyCane:sxe,LucideCandyOff:nxe,LucideCannabis:axe,LucideCaptions:HR,LucideCaptionsOff:ixe,LucideCar:cxe,LucideCarFront:oxe,LucideCarTaxiFront:lxe,LucideCaravan:dxe,LucideCarrot:uxe,LucideCaseLower:hxe,LucideCaseSensitive:mxe,LucideCaseUpper:fxe,LucideCassetteTape:pxe,LucideCast:gxe,LucideCastle:xxe,LucideCat:yxe,LucideCctv:vxe,LucideChartArea:GR,LucideChartBar:KR,LucideChartBarBig:WR,LucideChartBarDecreasing:bxe,LucideChartBarIncreasing:_xe,LucideChartBarStacked:wxe,LucideChartCandlestick:YR,LucideChartColumn:Gl,LucideChartColumnBig:ZR,LucideChartColumnDecreasing:jxe,LucideChartColumnIncreasing:XR,LucideChartColumnStacked:Nxe,LucideChartGantt:kxe,LucideChartLine:QR,LucideChartNetwork:Sxe,LucideChartNoAxesColumn:eD,LucideChartNoAxesColumnDecreasing:Cxe,LucideChartNoAxesColumnIncreasing:JR,LucideChartNoAxesCombined:Axe,LucideChartNoAxesGantt:tD,LucideChartPie:sD,LucideChartScatter:nD,LucideChartSpline:Exe,LucideCheck:ca,LucideCheckCheck:Dz,LucideCheckCircle:Wl,LucideCheckCircle2:Vr,LucideCheckSquare:Vj,LucideCheckSquare2:DF,LucideChefHat:Txe,LucideCherry:Mxe,LucideChevronDown:wl,LucideChevronDownCircle:hD,LucideChevronDownSquare:FF,LucideChevronFirst:Pxe,LucideChevronLast:Ixe,LucideChevronLeft:kd,LucideChevronLeftCircle:mD,LucideChevronLeftSquare:OF,LucideChevronRight:Di,LucideChevronRightCircle:fD,LucideChevronRightSquare:zF,LucideChevronUp:yb,LucideChevronUpCircle:pD,LucideChevronUpSquare:BF,LucideChevronsDown:Rxe,LucideChevronsDownUp:Lxe,LucideChevronsLeft:Oxe,LucideChevronsLeftRight:Fxe,LucideChevronsLeftRightEllipsis:Dxe,LucideChevronsRight:Bxe,LucideChevronsRightLeft:zxe,LucideChevronsUp:$xe,LucideChevronsUpDown:Sw,LucideChrome:Fz,LucideChurch:Uxe,LucideCigarette:Vxe,LucideCigaretteOff:qxe,LucideCircle:Og,LucideCircleAlert:ll,LucideCircleArrowDown:rD,LucideCircleArrowLeft:aD,LucideCircleArrowOutDownLeft:iD,LucideCircleArrowOutDownRight:oD,LucideCircleArrowOutUpLeft:lD,LucideCircleArrowOutUpRight:cD,LucideCircleArrowRight:dD,LucideCircleArrowUp:uD,LucideCircleCheck:Vr,LucideCircleCheckBig:Wl,LucideCircleChevronDown:hD,LucideCircleChevronLeft:mD,LucideCircleChevronRight:fD,LucideCircleChevronUp:pD,LucideCircleDashed:Hxe,LucideCircleDivide:gD,LucideCircleDollarSign:Gxe,LucideCircleDot:Kxe,LucideCircleDotDashed:Wxe,LucideCircleEllipsis:Yxe,LucideCircleEqual:Zxe,LucideCircleFadingArrowUp:Xxe,LucideCircleFadingPlus:Qxe,LucideCircleGauge:xD,LucideCircleHelp:e4,LucideCircleMinus:yD,LucideCircleOff:Jxe,LucideCircleParking:bD,LucideCircleParkingOff:vD,LucideCirclePause:_D,LucideCirclePercent:wD,LucideCirclePlay:ef,LucideCirclePlus:jD,LucideCirclePower:ND,LucideCircleSlash:eye,LucideCircleSlash2:kD,LucideCircleSlashed:kD,LucideCircleStop:SD,LucideCircleUser:AD,LucideCircleUserRound:CD,LucideCircleX:Nu,LucideCircuitBoard:tye,LucideCitrus:sye,LucideClapperboard:Sq,LucideClipboard:cye,LucideClipboardCheck:KN,LucideClipboardCopy:nye,LucideClipboardEdit:TD,LucideClipboardList:zg,LucideClipboardMinus:rye,LucideClipboardPaste:aye,LucideClipboardPen:TD,LucideClipboardPenLine:ED,LucideClipboardPlus:iye,LucideClipboardSignature:ED,LucideClipboardType:oye,LucideClipboardX:lye,LucideClock:da,LucideClock1:dye,LucideClock10:uye,LucideClock11:hye,LucideClock12:mye,LucideClock2:fye,LucideClock3:Cq,LucideClock4:pye,LucideClock5:gye,LucideClock6:xye,LucideClock7:yye,LucideClock8:vye,LucideClock9:bye,LucideClockAlert:_ye,LucideClockArrowDown:wye,LucideClockArrowUp:jye,LucideCloud:Oye,LucideCloudAlert:Nye,LucideCloudCog:kye,LucideCloudDownload:MD,LucideCloudDrizzle:Sye,LucideCloudFog:Cye,LucideCloudHail:Aye,LucideCloudLightning:Eye,LucideCloudMoon:Mye,LucideCloudMoonRain:Tye,LucideCloudOff:Pye,LucideCloudRain:Lye,LucideCloudRainWind:Iye,LucideCloudSnow:Rye,LucideCloudSun:Fye,LucideCloudSunRain:Dye,LucideCloudUpload:nP,LucideCloudy:zye,LucideClover:gE,LucideClub:Bye,LucideCode:CE,LucideCode2:t4,LucideCodeSquare:$F,LucideCodeXml:t4,LucideCodepen:$ye,LucideCodesandbox:Uye,LucideCoffee:T4,LucideCog:qye,LucideCoins:gJ,LucideColumns:PD,LucideColumns2:PD,LucideColumns3:rP,LucideColumns4:Vye,LucideCombine:Hye,LucideCommand:Gye,LucideCompass:Oz,LucideComponent:Wye,LucideComputer:Kye,LucideConciergeBell:Yye,LucideCone:Zye,LucideConstruction:Xye,LucideContact:UI,LucideContact2:ID,LucideContactRound:ID,LucideContainer:Qye,LucideContrast:Jye,LucideCookie:e0e,LucideCookingPot:t0e,LucideCopy:Ha,LucideCopyCheck:s0e,LucideCopyMinus:n0e,LucideCopyPlus:r0e,LucideCopySlash:a0e,LucideCopyX:i0e,LucideCopyleft:o0e,LucideCopyright:l0e,LucideCornerDownLeft:c0e,LucideCornerDownRight:xJ,LucideCornerLeftDown:d0e,LucideCornerLeftUp:u0e,LucideCornerRightDown:h0e,LucideCornerRightUp:m0e,LucideCornerUpLeft:f0e,LucideCornerUpRight:p0e,LucideCpu:g0e,LucideCreativeCommons:x0e,LucideCreditCard:Nv,LucideCroissant:y0e,LucideCrop:v0e,LucideCross:b0e,LucideCrosshair:_0e,LucideCrown:Bg,LucideCuboid:w0e,LucideCupSoda:j0e,LucideCurlyBraces:sP,LucideCurrency:N0e,LucideCylinder:k0e,LucideDam:S0e,LucideDatabase:Aq,LucideDatabaseBackup:C0e,LucideDatabaseZap:A0e,LucideDelete:E0e,LucideDessert:T0e,LucideDiameter:M0e,LucideDiamond:L0e,LucideDiamondMinus:P0e,LucideDiamondPercent:LD,LucideDiamondPlus:I0e,LucideDice1:R0e,LucideDice2:D0e,LucideDice3:F0e,LucideDice4:O0e,LucideDice5:z0e,LucideDice6:B0e,LucideDices:$0e,LucideDiff:U0e,LucideDisc:G0e,LucideDisc2:q0e,LucideDisc3:V0e,LucideDiscAlbum:H0e,LucideDivide:W0e,LucideDivideCircle:gD,LucideDivideSquare:HF,LucideDna:Y0e,LucideDnaOff:K0e,LucideDock:Z0e,LucideDog:X0e,LucideDollarSign:nu,LucideDonut:Q0e,LucideDoorClosed:J0e,LucideDoorOpen:i2,LucideDot:eve,LucideDotSquare:GF,LucideDownload:xi,LucideDownloadCloud:MD,LucideDraftingCompass:tve,LucideDrama:sve,LucideDribbble:nve,LucideDrill:rve,LucideDroplet:ave,LucideDroplets:g1,LucideDrum:ive,LucideDrumstick:ove,LucideDumbbell:lve,LucideEar:dve,LucideEarOff:cve,LucideEarth:CN,LucideEarthLock:uve,LucideEclipse:hve,LucideEdit:_p,LucideEdit2:AN,LucideEdit3:_f,LucideEgg:Eq,LucideEggFried:mve,LucideEggOff:fve,LucideEllipsis:l_,LucideEllipsisVertical:Jx,LucideEqual:xve,LucideEqualApproximately:pve,LucideEqualNot:gve,LucideEqualSquare:WF,LucideEraser:Tq,LucideEthernetPort:yve,LucideEuro:vve,LucideExpand:bve,LucideExternalLink:Fr,LucideEye:Ca,LucideEyeClosed:_ve,LucideEyeOff:$g,LucideFacebook:Qp,LucideFactory:wve,LucideFan:jve,LucideFastForward:Nve,LucideFeather:kve,LucideFence:Sve,LucideFerrisWheel:Cve,LucideFigma:Ave,LucideFile:Pq,LucideFileArchive:Eve,LucideFileAudio:Mve,LucideFileAudio2:Tve,LucideFileAxis3D:RD,LucideFileAxis3d:RD,LucideFileBadge:Ive,LucideFileBadge2:Pve,LucideFileBarChart:DD,LucideFileBarChart2:FD,LucideFileBox:Lve,LucideFileChartColumn:FD,LucideFileChartColumnIncreasing:DD,LucideFileChartLine:OD,LucideFileChartPie:zD,LucideFileCheck:yJ,LucideFileCheck2:zz,LucideFileClock:Rve,LucideFileCode:Fve,LucideFileCode2:Dve,LucideFileCog:BD,LucideFileCog2:BD,LucideFileDiff:Ove,LucideFileDigit:zve,LucideFileDown:o2,LucideFileEdit:$D,LucideFileHeart:Bve,LucideFileImage:qI,LucideFileInput:$ve,LucideFileJson:qve,LucideFileJson2:Uve,LucideFileKey:Hve,LucideFileKey2:Vve,LucideFileLineChart:OD,LucideFileLock:Wve,LucideFileLock2:Gve,LucideFileMinus:Yve,LucideFileMinus2:Kve,LucideFileMusic:Zve,LucideFileOutput:Xve,LucideFilePen:$D,LucideFilePenLine:c_,LucideFilePieChart:zD,LucideFilePlus:Qve,LucideFilePlus2:Mq,LucideFileQuestion:Jve,LucideFileScan:ebe,LucideFileSearch:vJ,LucideFileSearch2:tbe,LucideFileSignature:c_,LucideFileSliders:sbe,LucideFileSpreadsheet:YN,LucideFileStack:bJ,LucideFileSymlink:nbe,LucideFileTerminal:rbe,LucideFileText:Jr,LucideFileType:ibe,LucideFileType2:abe,LucideFileUp:_J,LucideFileUser:obe,LucideFileVideo:wJ,LucideFileVideo2:lbe,LucideFileVolume:dbe,LucideFileVolume2:cbe,LucideFileWarning:ube,LucideFileX:mbe,LucideFileX2:hbe,LucideFiles:fbe,LucideFilm:nf,LucideFilter:Cw,LucideFilterX:pbe,LucideFingerprint:gbe,LucideFireExtinguisher:xbe,LucideFish:bbe,LucideFishOff:ybe,LucideFishSymbol:vbe,LucideFlag:AE,LucideFlagOff:_be,LucideFlagTriangleLeft:wbe,LucideFlagTriangleRight:jbe,LucideFlame:sh,LucideFlameKindling:Nbe,LucideFlashlight:Sbe,LucideFlashlightOff:kbe,LucideFlaskConical:VI,LucideFlaskConicalOff:Cbe,LucideFlaskRound:Abe,LucideFlipHorizontal:jJ,LucideFlipHorizontal2:Ebe,LucideFlipVertical:Mbe,LucideFlipVertical2:Tbe,LucideFlower:Pbe,LucideFlower2:qS,LucideFocus:Ibe,LucideFoldHorizontal:Lbe,LucideFoldVertical:Rbe,LucideFolder:Iq,LucideFolderArchive:Dbe,LucideFolderCheck:Fbe,LucideFolderClock:Obe,LucideFolderClosed:zbe,LucideFolderCode:Bbe,LucideFolderCog:UD,LucideFolderCog2:UD,LucideFolderDot:$be,LucideFolderDown:Ube,LucideFolderEdit:qD,LucideFolderGit:Vbe,LucideFolderGit2:qbe,LucideFolderHeart:Hbe,LucideFolderInput:Gbe,LucideFolderKanban:Wbe,LucideFolderKey:Kbe,LucideFolderLock:Ybe,LucideFolderMinus:Zbe,LucideFolderOpen:kv,LucideFolderOpenDot:Xbe,LucideFolderOutput:Qbe,LucideFolderPen:qD,LucideFolderPlus:NJ,LucideFolderRoot:Jbe,LucideFolderSearch:t1e,LucideFolderSearch2:e1e,LucideFolderSymlink:s1e,LucideFolderSync:n1e,LucideFolderTree:r1e,LucideFolderUp:a1e,LucideFolderX:i1e,LucideFolders:o1e,LucideFootprints:l1e,LucideForkKnife:EO,LucideForkKnifeCrossed:AO,LucideForklift:c1e,LucideFormInput:mF,LucideForward:d1e,LucideFrame:u1e,LucideFramer:h1e,LucideFrown:m1e,LucideFuel:f1e,LucideFullscreen:p1e,LucideFunctionSquare:KF,LucideGalleryHorizontal:x1e,LucideGalleryHorizontalEnd:g1e,LucideGalleryThumbnails:y1e,LucideGalleryVertical:b1e,LucideGalleryVerticalEnd:v1e,LucideGamepad:w1e,LucideGamepad2:_1e,LucideGanttChart:tD,LucideGanttChartSquare:p5,LucideGauge:j1e,LucideGaugeCircle:xD,LucideGavel:N1e,LucideGem:k1e,LucideGhost:Bz,LucideGift:ul,LucideGitBranch:C1e,LucideGitBranchPlus:S1e,LucideGitCommit:VD,LucideGitCommitHorizontal:VD,LucideGitCommitVertical:A1e,LucideGitCompare:T1e,LucideGitCompareArrows:E1e,LucideGitFork:M1e,LucideGitGraph:P1e,LucideGitMerge:I1e,LucideGitPullRequest:z1e,LucideGitPullRequestArrow:L1e,LucideGitPullRequestClosed:R1e,LucideGitPullRequestCreate:F1e,LucideGitPullRequestCreateArrow:D1e,LucideGitPullRequestDraft:O1e,LucideGithub:B1e,LucideGitlab:$1e,LucideGlassWater:U1e,LucideGlasses:q1e,LucideGlobe:dl,LucideGlobe2:CN,LucideGlobeLock:V1e,LucideGoal:H1e,LucideGrab:G1e,LucideGraduationCap:af,LucideGrape:W1e,LucideGrid:Fj,LucideGrid2X2:GD,LucideGrid2X2Plus:HD,LucideGrid2x2:GD,LucideGrid2x2Check:K1e,LucideGrid2x2Plus:HD,LucideGrid2x2X:Y1e,LucideGrid3X3:Fj,LucideGrid3x3:Fj,LucideGrip:X1e,LucideGripHorizontal:Z1e,LucideGripVertical:Ug,LucideGroup:Q1e,LucideGuitar:J1e,LucideHam:e_e,LucideHammer:kJ,LucideHand:Lq,LucideHandCoins:t_e,LucideHandHeart:SJ,LucideHandHelping:s4,LucideHandMetal:s_e,LucideHandPlatter:n_e,LucideHandshake:vb,LucideHardDrive:CJ,LucideHardDriveDownload:r_e,LucideHardDriveUpload:a_e,LucideHardHat:i_e,LucideHash:HI,LucideHaze:o_e,LucideHdmiPort:l_e,LucideHeading:h_e,LucideHeading1:Rq,LucideHeading2:$z,LucideHeading3:Dq,LucideHeading4:c_e,LucideHeading5:d_e,LucideHeading6:u_e,LucideHeadphoneOff:m_e,LucideHeadphones:f_e,LucideHeadset:p_e,LucideHeart:Jo,LucideHeartCrack:g_e,LucideHeartHandshake:AJ,LucideHeartOff:x_e,LucideHeartPulse:y_e,LucideHeater:v_e,LucideHelpCircle:e4,LucideHelpingHand:s4,LucideHexagon:b_e,LucideHighlighter:__e,LucideHistory:Aw,LucideHome:va,LucideHop:j_e,LucideHopOff:w_e,LucideHospital:N_e,LucideHotel:k_e,LucideHourglass:EJ,LucideHouse:va,LucideHousePlug:S_e,LucideHousePlus:C_e,LucideIceCream:KD,LucideIceCream2:WD,LucideIceCreamBowl:WD,LucideIceCreamCone:KD,LucideIdCard:TJ,LucideImage:Hc,LucideImageDown:A_e,LucideImageMinus:E_e,LucideImageOff:T_e,LucideImagePlay:M_e,LucideImagePlus:Sv,LucideImageUp:P_e,LucideImageUpscale:I_e,LucideImages:L_e,LucideImport:R_e,LucideInbox:Uz,LucideIndent:ZD,LucideIndentDecrease:YD,LucideIndentIncrease:ZD,LucideIndianRupee:D_e,LucideInfinity:Fq,LucideInfo:QS,LucideInspect:eO,LucideInspectionPanel:F_e,LucideInstagram:Ef,LucideItalic:EE,LucideIterationCcw:O_e,LucideIterationCw:z_e,LucideJapaneseYen:B_e,LucideJoystick:$_e,LucideKanban:l2,LucideKanbanSquare:YF,LucideKanbanSquareDashed:UF,LucideKey:w_,LucideKeyRound:GI,LucideKeySquare:U_e,LucideKeyboard:H_e,LucideKeyboardMusic:q_e,LucideKeyboardOff:V_e,LucideLamp:X_e,LucideLampCeiling:G_e,LucideLampDesk:W_e,LucideLampFloor:K_e,LucideLampWallDown:Y_e,LucideLampWallUp:Z_e,LucideLandPlot:Q_e,LucideLandmark:Oq,LucideLanguages:J_e,LucideLaptop:twe,LucideLaptop2:XD,LucideLaptopMinimal:XD,LucideLaptopMinimalCheck:ewe,LucideLasso:nwe,LucideLassoSelect:swe,LucideLaugh:rwe,LucideLayers:M4,LucideLayers2:awe,LucideLayers3:iwe,LucideLayout:LA,LucideLayoutDashboard:WI,LucideLayoutGrid:Qf,LucideLayoutList:owe,LucideLayoutPanelLeft:lwe,LucideLayoutPanelTop:cwe,LucideLayoutTemplate:c2,LucideLeaf:dwe,LucideLeafyGreen:uwe,LucideLectern:hwe,LucideLetterText:mwe,LucideLibrary:d2,LucideLibraryBig:fwe,LucideLibrarySquare:ZF,LucideLifeBuoy:zq,LucideLigature:pwe,LucideLightbulb:JS,LucideLightbulbOff:gwe,LucideLineChart:QR,LucideLink:Sd,LucideLink2:Wd,LucideLink2Off:xwe,LucideLinkedin:dy,LucideList:T0,LucideListCheck:ywe,LucideListChecks:Cv,LucideListCollapse:vwe,LucideListEnd:bwe,LucideListFilter:MJ,LucideListMinus:_we,LucideListMusic:wwe,LucideListOrdered:u2,LucideListPlus:PJ,LucideListRestart:jwe,LucideListStart:Nwe,LucideListTodo:kwe,LucideListTree:Swe,LucideListVideo:Cwe,LucideListX:Awe,LucideLoader:Twe,LucideLoader2:Ct,LucideLoaderCircle:Ct,LucideLoaderPinwheel:Ewe,LucideLocate:Bq,LucideLocateFixed:Mwe,LucideLocateOff:Pwe,LucideLock:pc,LucideLockKeyhole:IJ,LucideLockKeyholeOpen:QD,LucideLockOpen:JD,LucideLogIn:KI,LucideLogOut:qz,LucideLogs:Iwe,LucideLollipop:Lwe,LucideLuggage:Rwe,LucideMSquare:XF,LucideMagnet:Dwe,LucideMail:mn,LucideMailCheck:Vz,LucideMailMinus:Fwe,LucideMailOpen:$q,LucideMailPlus:Uq,LucideMailQuestion:Owe,LucideMailSearch:zwe,LucideMailWarning:Bwe,LucideMailX:YI,LucideMailbox:$we,LucideMails:Uwe,LucideMap:Hz,LucideMapPin:ci,LucideMapPinCheck:Vwe,LucideMapPinCheckInside:qwe,LucideMapPinHouse:Hwe,LucideMapPinMinus:Wwe,LucideMapPinMinusInside:Gwe,LucideMapPinOff:Kwe,LucideMapPinPlus:Zwe,LucideMapPinPlusInside:Ywe,LucideMapPinX:Qwe,LucideMapPinXInside:Xwe,LucideMapPinned:LJ,LucideMartini:Jwe,LucideMaximize:Gz,LucideMaximize2:RJ,LucideMedal:TE,LucideMegaphone:gm,LucideMegaphoneOff:eje,LucideMeh:tje,LucideMemoryStick:sje,LucideMenu:ME,LucideMenuSquare:QF,LucideMerge:Wz,LucideMessageCircle:Ah,LucideMessageCircleCode:nje,LucideMessageCircleDashed:rje,LucideMessageCircleHeart:qq,LucideMessageCircleMore:aje,LucideMessageCircleOff:ije,LucideMessageCirclePlus:oje,LucideMessageCircleQuestion:DJ,LucideMessageCircleReply:lje,LucideMessageCircleWarning:cje,LucideMessageCircleX:dje,LucideMessageSquare:eo,LucideMessageSquareCode:uje,LucideMessageSquareDashed:hje,LucideMessageSquareDiff:mje,LucideMessageSquareDot:fje,LucideMessageSquareHeart:pje,LucideMessageSquareLock:gje,LucideMessageSquareMore:FJ,LucideMessageSquareOff:xje,LucideMessageSquarePlus:m4,LucideMessageSquareQuote:PE,LucideMessageSquareReply:OJ,LucideMessageSquareShare:yje,LucideMessageSquareText:vje,LucideMessageSquareWarning:zJ,LucideMessageSquareX:bje,LucideMessagesSquare:BJ,LucideMic:Kz,LucideMic2:eF,LucideMicOff:_je,LucideMicVocal:eF,LucideMicrochip:wje,LucideMicroscope:jje,LucideMicrowave:Nje,LucideMilestone:kje,LucideMilk:Cje,LucideMilkOff:Sje,LucideMinimize:Eje,LucideMinimize2:Aje,LucideMinus:ZN,LucideMinusCircle:yD,LucideMinusSquare:JF,LucideMonitor:XN,LucideMonitorCheck:Tje,LucideMonitorCog:Mje,LucideMonitorDot:Pje,LucideMonitorDown:Ije,LucideMonitorOff:Lje,LucideMonitorPause:Rje,LucideMonitorPlay:Vq,LucideMonitorSmartphone:Dje,LucideMonitorSpeaker:Fje,LucideMonitorStop:Oje,LucideMonitorUp:Yz,LucideMonitorX:zje,LucideMoon:$je,LucideMoonStar:Bje,LucideMoreHorizontal:l_,LucideMoreVertical:Jx,LucideMountain:qje,LucideMountainSnow:Uje,LucideMouse:Gje,LucideMouseOff:Vje,LucideMousePointer:cb,LucideMousePointer2:$J,LucideMousePointerBan:Hje,LucideMousePointerClick:Pm,LucideMousePointerSquareDashed:qF,LucideMove:UJ,LucideMove3D:tF,LucideMove3d:tF,LucideMoveDiagonal:Kje,LucideMoveDiagonal2:Wje,LucideMoveDown:Xje,LucideMoveDownLeft:Yje,LucideMoveDownRight:Zje,LucideMoveHorizontal:Qje,LucideMoveLeft:Jje,LucideMoveRight:e2e,LucideMoveUp:n2e,LucideMoveUpLeft:t2e,LucideMoveUpRight:s2e,LucideMoveVertical:r2e,LucideMusic:Hq,LucideMusic2:a2e,LucideMusic3:i2e,LucideMusic4:o2e,LucideNavigation:qJ,LucideNavigation2:c2e,LucideNavigation2Off:l2e,LucideNavigationOff:d2e,LucideNetwork:u2e,LucideNewspaper:QN,LucideNfc:h2e,LucideNotebook:g2e,LucideNotebookPen:m2e,LucideNotebookTabs:f2e,LucideNotebookText:p2e,LucideNotepadText:y2e,LucideNotepadTextDashed:x2e,LucideNut:b2e,LucideNutOff:v2e,LucideOctagon:w2e,LucideOctagonAlert:OS,LucideOctagonMinus:_2e,LucideOctagonPause:sF,LucideOctagonX:nF,LucideOmega:j2e,LucideOption:N2e,LucideOrbit:k2e,LucideOrigami:S2e,LucideOutdent:YD,LucidePackage:ym,LucidePackage2:C2e,LucidePackageCheck:A2e,LucidePackageMinus:E2e,LucidePackageOpen:T2e,LucidePackagePlus:M2e,LucidePackageSearch:P2e,LucidePackageX:I2e,LucidePaintBucket:L2e,LucidePaintRoller:R2e,LucidePaintbrush:D2e,LucidePaintbrush2:rF,LucidePaintbrushVertical:rF,LucidePalette:yd,LucidePalmtree:_O,LucidePanelBottom:z2e,LucidePanelBottomClose:F2e,LucidePanelBottomDashed:aF,LucidePanelBottomInactive:aF,LucidePanelBottomOpen:O2e,LucidePanelLeft:cF,LucidePanelLeftClose:iF,LucidePanelLeftDashed:oF,LucidePanelLeftInactive:oF,LucidePanelLeftOpen:lF,LucidePanelRight:U2e,LucidePanelRightClose:B2e,LucidePanelRightDashed:dF,LucidePanelRightInactive:dF,LucidePanelRightOpen:$2e,LucidePanelTop:H2e,LucidePanelTopClose:q2e,LucidePanelTopDashed:uF,LucidePanelTopInactive:uF,LucidePanelTopOpen:V2e,LucidePanelsLeftBottom:G2e,LucidePanelsLeftRight:rP,LucidePanelsRightBottom:W2e,LucidePanelsTopBottom:gF,LucidePanelsTopLeft:LA,LucidePaperclip:ZI,LucideParentheses:K2e,LucideParkingCircle:bD,LucideParkingCircleOff:vD,LucideParkingMeter:Y2e,LucideParkingSquare:sO,LucideParkingSquareOff:tO,LucidePartyPopper:Cx,LucidePause:Av,LucidePauseCircle:_D,LucidePauseOctagon:sF,LucidePawPrint:Z2e,LucidePcCase:X2e,LucidePen:AN,LucidePenBox:_p,LucidePenLine:_f,LucidePenOff:Q2e,LucidePenSquare:_p,LucidePenTool:IE,LucidePencil:pi,LucidePencilLine:Gq,LucidePencilOff:J2e,LucidePencilRuler:eNe,LucidePentagon:tNe,LucidePercent:Ew,LucidePercentCircle:wD,LucidePercentDiamond:LD,LucidePercentSquare:nO,LucidePersonStanding:sNe,LucidePhilippinePeso:nNe,LucidePhone:Da,LucidePhoneCall:VJ,LucidePhoneForwarded:rNe,LucidePhoneIncoming:aNe,LucidePhoneMissed:iNe,LucidePhoneOff:oNe,LucidePhoneOutgoing:lNe,LucidePi:cNe,LucidePiSquare:rO,LucidePiano:dNe,LucidePickaxe:uNe,LucidePictureInPicture:mNe,LucidePictureInPicture2:hNe,LucidePieChart:sD,LucidePiggyBank:HJ,LucidePilcrow:gNe,LucidePilcrowLeft:fNe,LucidePilcrowRight:pNe,LucidePilcrowSquare:aO,LucidePill:yNe,LucidePillBottle:xNe,LucidePin:LE,LucidePinOff:GJ,LucidePipette:vNe,LucidePizza:bNe,LucidePlane:WJ,LucidePlaneLanding:_Ne,LucidePlaneTakeoff:wNe,LucidePlay:zu,LucidePlayCircle:ef,LucidePlaySquare:iO,LucidePlug:JN,LucidePlug2:jNe,LucidePlugZap:hF,LucidePlugZap2:hF,LucidePlus:dn,LucidePlusCircle:jD,LucidePlusSquare:oO,LucidePocket:kNe,LucidePocketKnife:NNe,LucidePodcast:SNe,LucidePointer:ANe,LucidePointerOff:CNe,LucidePopcorn:ENe,LucidePopsicle:TNe,LucidePoundSterling:MNe,LucidePower:KJ,LucidePowerCircle:ND,LucidePowerOff:PNe,LucidePowerSquare:lO,LucidePresentation:bb,LucidePrinter:RE,LucidePrinterCheck:INe,LucideProjector:LNe,LucideProportions:RNe,LucidePuzzle:DNe,LucidePyramid:FNe,LucideQrCode:Jp,LucideQuote:h2,LucideRabbit:ONe,LucideRadar:Wq,LucideRadiation:zNe,LucideRadical:BNe,LucideRadio:_b,LucideRadioReceiver:$Ne,LucideRadioTower:UNe,LucideRadius:qNe,LucideRailSymbol:VNe,LucideRainbow:HNe,LucideRat:GNe,LucideRatio:WNe,LucideReceipt:Kq,LucideReceiptCent:KNe,LucideReceiptEuro:YNe,LucideReceiptIndianRupee:ZNe,LucideReceiptJapaneseYen:XNe,LucideReceiptPoundSterling:QNe,LucideReceiptRussianRuble:JNe,LucideReceiptSwissFranc:eke,LucideReceiptText:tke,LucideRectangleEllipsis:mF,LucideRectangleHorizontal:ske,LucideRectangleVertical:nke,LucideRecycle:rke,LucideRedo:DE,LucideRedo2:ake,LucideRedoDot:ike,LucideRefreshCcw:Yq,LucideRefreshCcwDot:oke,LucideRefreshCw:ro,LucideRefreshCwOff:lke,LucideRefrigerator:cke,LucideRegex:dke,LucideRemoveFormatting:uke,LucideRepeat:FE,LucideRepeat1:hke,LucideRepeat2:YJ,LucideReplace:fke,LucideReplaceAll:mke,LucideReply:Zq,LucideReplyAll:pke,LucideRewind:gke,LucideRibbon:xke,LucideRocket:qg,LucideRockingChair:yke,LucideRollerCoaster:vke,LucideRotate3D:fF,LucideRotate3d:fF,LucideRotateCcw:Ax,LucideRotateCcwSquare:bke,LucideRotateCw:Zz,LucideRotateCwSquare:_ke,LucideRoute:Xq,LucideRouteOff:wke,LucideRouter:jke,LucideRows:pF,LucideRows2:pF,LucideRows3:gF,LucideRows4:Nke,LucideRss:kke,LucideRuler:P4,LucideRussianRuble:Ske,LucideSailboat:Cke,LucideSalad:Ake,LucideSandwich:Eke,LucideSatellite:Mke,LucideSatelliteDish:Tke,LucideSave:tl,LucideSaveAll:Pke,LucideSaveOff:Ike,LucideScale:Lke,LucideScale3D:xF,LucideScale3d:xF,LucideScaling:Rke,LucideScan:qke,LucideScanBarcode:Dke,LucideScanEye:Fke,LucideScanFace:Oke,LucideScanLine:zke,LucideScanQrCode:Bke,LucideScanSearch:$ke,LucideScanText:Uke,LucideScatterChart:nD,LucideSchool:Vke,LucideSchool2:jO,LucideScissors:Gke,LucideScissorsLineDashed:Hke,LucideScissorsSquare:cO,LucideScissorsSquareDashedBottom:RF,LucideScreenShare:Kke,LucideScreenShareOff:Wke,LucideScroll:Yke,LucideScrollText:Qq,LucideSearch:Zr,LucideSearchCheck:Zke,LucideSearchCode:Xke,LucideSearchSlash:Qke,LucideSearchX:Jq,LucideSection:Jke,LucideSend:Kr,LucideSendHorizonal:yF,LucideSendHorizontal:yF,LucideSendToBack:eSe,LucideSeparatorHorizontal:tSe,LucideSeparatorVertical:sSe,LucideServer:iSe,LucideServerCog:nSe,LucideServerCrash:rSe,LucideServerOff:aSe,LucideSettings:Nd,LucideSettings2:eC,LucideShapes:oSe,LucideShare:ZJ,LucideShare2:Fd,LucideSheet:lSe,LucideShell:cSe,LucideShield:Tf,LucideShieldAlert:eV,LucideShieldBan:dSe,LucideShieldCheck:Rm,LucideShieldClose:vF,LucideShieldEllipsis:uSe,LucideShieldHalf:hSe,LucideShieldMinus:mSe,LucideShieldOff:Xz,LucideShieldPlus:fSe,LucideShieldQuestion:Qz,LucideShieldX:vF,LucideShip:gSe,LucideShipWheel:pSe,LucideShirt:xSe,LucideShoppingBag:I4,LucideShoppingBasket:ySe,LucideShoppingCart:tC,LucideShovel:vSe,LucideShowerHead:bSe,LucideShrink:_Se,LucideShrub:wSe,LucideShuffle:Jz,LucideSidebar:cF,LucideSidebarClose:iF,LucideSidebarOpen:lF,LucideSigma:jSe,LucideSigmaSquare:dO,LucideSignal:ASe,LucideSignalHigh:NSe,LucideSignalLow:kSe,LucideSignalMedium:SSe,LucideSignalZero:CSe,LucideSignature:ESe,LucideSignpost:XJ,LucideSignpostBig:TSe,LucideSiren:MSe,LucideSkipBack:PSe,LucideSkipForward:QJ,LucideSkull:ISe,LucideSlack:LSe,LucideSlash:RSe,LucideSlashSquare:uO,LucideSlice:DSe,LucideSliders:bF,LucideSlidersHorizontal:XI,LucideSlidersVertical:bF,LucideSmartphone:x1,LucideSmartphoneCharging:FSe,LucideSmartphoneNfc:OSe,LucideSmile:BSe,LucideSmilePlus:zSe,LucideSnail:$Se,LucideSnowflake:Xj,LucideSofa:tV,LucideSortAsc:zR,LucideSortDesc:DR,LucideSoup:USe,LucideSpace:qSe,LucideSpade:VSe,LucideSparkle:QI,LucideSparkles:Nn,LucideSpeaker:HSe,LucideSpeech:GSe,LucideSpellCheck:KSe,LucideSpellCheck2:WSe,LucideSpline:YSe,LucideSplit:ZSe,LucideSplitSquareHorizontal:hO,LucideSplitSquareVertical:mO,LucideSprayCan:XSe,LucideSprout:JI,LucideSquare:j_,LucideSquareActivity:_F,LucideSquareArrowDown:NF,LucideSquareArrowDownLeft:wF,LucideSquareArrowDownRight:jF,LucideSquareArrowLeft:kF,LucideSquareArrowOutDownLeft:SF,LucideSquareArrowOutDownRight:CF,LucideSquareArrowOutUpLeft:AF,LucideSquareArrowOutUpRight:EF,LucideSquareArrowRight:TF,LucideSquareArrowUp:IF,LucideSquareArrowUpLeft:MF,LucideSquareArrowUpRight:PF,LucideSquareAsterisk:LF,LucideSquareBottomDashedScissors:RF,LucideSquareChartGantt:p5,LucideSquareCheck:DF,LucideSquareCheckBig:Vj,LucideSquareChevronDown:FF,LucideSquareChevronLeft:OF,LucideSquareChevronRight:zF,LucideSquareChevronUp:BF,LucideSquareCode:$F,LucideSquareDashed:VF,LucideSquareDashedBottom:JSe,LucideSquareDashedBottomCode:QSe,LucideSquareDashedKanban:UF,LucideSquareDashedMousePointer:qF,LucideSquareDivide:HF,LucideSquareDot:GF,LucideSquareEqual:WF,LucideSquareFunction:KF,LucideSquareGanttChart:p5,LucideSquareKanban:YF,LucideSquareLibrary:ZF,LucideSquareM:XF,LucideSquareMenu:QF,LucideSquareMinus:JF,LucideSquareMousePointer:eO,LucideSquareParking:sO,LucideSquareParkingOff:tO,LucideSquarePen:_p,LucideSquarePercent:nO,LucideSquarePi:rO,LucideSquarePilcrow:aO,LucideSquarePlay:iO,LucideSquarePlus:oO,LucideSquarePower:lO,LucideSquareRadical:eCe,LucideSquareScissors:cO,LucideSquareSigma:dO,LucideSquareSlash:uO,LucideSquareSplitHorizontal:hO,LucideSquareSplitVertical:mO,LucideSquareSquare:tCe,LucideSquareStack:sCe,LucideSquareTerminal:fO,LucideSquareUser:gO,LucideSquareUserRound:pO,LucideSquareX:xO,LucideSquircle:nCe,LucideSquirrel:rCe,LucideStamp:aCe,LucideStar:ei,LucideStarHalf:iCe,LucideStarOff:oCe,LucideStars:Nn,LucideStepBack:lCe,LucideStepForward:cCe,LucideStethoscope:dCe,LucideSticker:uCe,LucideStickyNote:e7,LucideStopCircle:SD,LucideStore:sV,LucideStretchHorizontal:hCe,LucideStretchVertical:mCe,LucideStrikethrough:JJ,LucideSubscript:fCe,LucideSubtitles:HR,LucideSun:ek,LucideSunDim:pCe,LucideSunMedium:gCe,LucideSunMoon:xCe,LucideSunSnow:yCe,LucideSunrise:vCe,LucideSunset:bCe,LucideSuperscript:_Ce,LucideSwatchBook:wCe,LucideSwissFranc:jCe,LucideSwitchCamera:NCe,LucideSword:kCe,LucideSwords:SCe,LucideSyringe:CCe,LucideTable:rV,LucideTable2:nV,LucideTableCellsMerge:ACe,LucideTableCellsSplit:ECe,LucideTableColumnsSplit:TCe,LucideTableOfContents:MCe,LucideTableProperties:PCe,LucideTableRowsSplit:ICe,LucideTablet:aV,LucideTabletSmartphone:LCe,LucideTablets:RCe,LucideTag:Ap,LucideTags:eee,LucideTally1:DCe,LucideTally2:FCe,LucideTally3:OCe,LucideTally4:zCe,LucideTally5:BCe,LucideTangent:$Ce,LucideTarget:nh,LucideTelescope:UCe,LucideTent:VCe,LucideTentTree:qCe,LucideTerminal:HCe,LucideTerminalSquare:fO,LucideTestTube:GCe,LucideTestTube2:yO,LucideTestTubeDiagonal:yO,LucideTestTubes:WCe,LucideText:XCe,LucideTextCursor:KCe,LucideTextCursorInput:iV,LucideTextQuote:YCe,LucideTextSearch:ZCe,LucideTextSelect:vO,LucideTextSelection:vO,LucideTheater:QCe,LucideThermometer:t5e,LucideThermometerSnowflake:JCe,LucideThermometerSun:e5e,LucideThumbsDown:tee,LucideThumbsUp:qy,LucideTicket:t7,LucideTicketCheck:s5e,LucideTicketMinus:n5e,LucideTicketPercent:r5e,LucideTicketPlus:a5e,LucideTicketSlash:i5e,LucideTicketX:o5e,LucideTickets:c5e,LucideTicketsPlane:l5e,LucideTimer:h5e,LucideTimerOff:d5e,LucideTimerReset:u5e,LucideToggleLeft:m5e,LucideToggleRight:f5e,LucideToilet:p5e,LucideTornado:g5e,LucideTorus:x5e,LucideTouchpad:v5e,LucideTouchpadOff:y5e,LucideTowerControl:b5e,LucideToyBrick:_5e,LucideTractor:w5e,LucideTrafficCone:j5e,LucideTrain:bO,LucideTrainFront:k5e,LucideTrainFrontTunnel:N5e,LucideTrainTrack:S5e,LucideTramFront:bO,LucideTrash:C5e,LucideTrash2:Hn,LucideTreeDeciduous:A5e,LucideTreePalm:_O,LucideTreePine:eL,LucideTrees:E5e,LucideTrello:T5e,LucideTrendingDown:sC,LucideTrendingUp:Zl,LucideTrendingUpDown:M5e,LucideTriangle:I5e,LucideTriangleAlert:Al,LucideTriangleRight:P5e,LucideTrophy:Kl,LucideTruck:see,LucideTurtle:L5e,LucideTv:D5e,LucideTv2:wO,LucideTvMinimal:wO,LucideTvMinimalPlay:R5e,LucideTwitch:F5e,LucideTwitter:nee,LucideType:oV,LucideTypeOutline:O5e,LucideUmbrella:B5e,LucideUmbrellaOff:z5e,LucideUnderline:s7,LucideUndo:OE,LucideUndo2:ree,LucideUndoDot:$5e,LucideUnfoldHorizontal:U5e,LucideUnfoldVertical:q5e,LucideUngroup:V5e,LucideUniversity:jO,LucideUnlink:n7,LucideUnlink2:H5e,LucideUnlock:JD,LucideUnlockKeyhole:QD,LucideUnplug:lV,LucideUpload:ni,LucideUploadCloud:nP,LucideUsb:G5e,LucideUser:sl,LucideUser2:iP,LucideUserCheck:m2,LucideUserCheck2:aP,LucideUserCircle:AD,LucideUserCircle2:CD,LucideUserCog:aee,LucideUserCog2:NO,LucideUserMinus:cV,LucideUserMinus2:kO,LucideUserPen:W5e,LucideUserPlus:lc,LucideUserPlus2:SO,LucideUserRound:iP,LucideUserRoundCheck:aP,LucideUserRoundCog:NO,LucideUserRoundMinus:kO,LucideUserRoundPen:K5e,LucideUserRoundPlus:SO,LucideUserRoundSearch:dV,LucideUserRoundX:CO,LucideUserSearch:Y5e,LucideUserSquare:gO,LucideUserSquare2:pO,LucideUserX:uV,LucideUserX2:CO,LucideUsers:Yn,LucideUsers2:y0,LucideUsersRound:y0,LucideUtensils:EO,LucideUtensilsCrossed:AO,LucideUtilityPole:Z5e,LucideVariable:hV,LucideVault:X5e,LucideVegan:Q5e,LucideVenetianMask:J5e,LucideVerified:IA,LucideVibrate:t4e,LucideVibrateOff:e4e,LucideVideo:ua,LucideVideoOff:s4e,LucideVideotape:n4e,LucideView:r4e,LucideVoicemail:a4e,LucideVolleyball:i4e,LucideVolume:c4e,LucideVolume1:o4e,LucideVolume2:iee,LucideVolumeOff:l4e,LucideVolumeX:oee,LucideVote:d4e,LucideWallet:r7,LucideWallet2:TO,LucideWalletCards:u4e,LucideWalletMinimal:TO,LucideWallpaper:h4e,LucideWand:m4e,LucideWand2:ey,LucideWandSparkles:ey,LucideWarehouse:f4e,LucideWashingMachine:p4e,LucideWatch:g4e,LucideWaves:x4e,LucideWaypoints:y4e,LucideWebcam:v4e,LucideWebhook:_4e,LucideWebhookOff:b4e,LucideWeight:w4e,LucideWheat:N4e,LucideWheatOff:j4e,LucideWholeWord:k4e,LucideWifi:T4e,LucideWifiHigh:S4e,LucideWifiLow:C4e,LucideWifiOff:A4e,LucideWifiZero:E4e,LucideWind:P4e,LucideWindArrowDown:M4e,LucideWine:L4e,LucideWineOff:I4e,LucideWorkflow:a7,LucideWorm:R4e,LucideWrapText:D4e,LucideWrench:L4,LucideX:pr,LucideXCircle:Nu,LucideXOctagon:nF,LucideXSquare:xO,LucideYoutube:mV,LucideZap:eg,LucideZapOff:F4e,LucideZoomIn:tL,LucideZoomOut:fV,Luggage:Rwe,LuggageIcon:Rwe,MSquare:XF,MSquareIcon:XF,Magnet:Dwe,MagnetIcon:Dwe,Mail:mn,MailCheck:Vz,MailCheckIcon:Vz,MailIcon:mn,MailMinus:Fwe,MailMinusIcon:Fwe,MailOpen:$q,MailOpenIcon:$q,MailPlus:Uq,MailPlusIcon:Uq,MailQuestion:Owe,MailQuestionIcon:Owe,MailSearch:zwe,MailSearchIcon:zwe,MailWarning:Bwe,MailWarningIcon:Bwe,MailX:YI,MailXIcon:YI,Mailbox:$we,MailboxIcon:$we,Mails:Uwe,MailsIcon:Uwe,Map:Hz,MapIcon:Hz,MapPin:ci,MapPinCheck:Vwe,MapPinCheckIcon:Vwe,MapPinCheckInside:qwe,MapPinCheckInsideIcon:qwe,MapPinHouse:Hwe,MapPinHouseIcon:Hwe,MapPinIcon:ci,MapPinMinus:Wwe,MapPinMinusIcon:Wwe,MapPinMinusInside:Gwe,MapPinMinusInsideIcon:Gwe,MapPinOff:Kwe,MapPinOffIcon:Kwe,MapPinPlus:Zwe,MapPinPlusIcon:Zwe,MapPinPlusInside:Ywe,MapPinPlusInsideIcon:Ywe,MapPinX:Qwe,MapPinXIcon:Qwe,MapPinXInside:Xwe,MapPinXInsideIcon:Xwe,MapPinned:LJ,MapPinnedIcon:LJ,Martini:Jwe,MartiniIcon:Jwe,Maximize:Gz,Maximize2:RJ,Maximize2Icon:RJ,MaximizeIcon:Gz,Medal:TE,MedalIcon:TE,Megaphone:gm,MegaphoneIcon:gm,MegaphoneOff:eje,MegaphoneOffIcon:eje,Meh:tje,MehIcon:tje,MemoryStick:sje,MemoryStickIcon:sje,Menu:ME,MenuIcon:ME,MenuSquare:QF,MenuSquareIcon:QF,Merge:Wz,MergeIcon:Wz,MessageCircle:Ah,MessageCircleCode:nje,MessageCircleCodeIcon:nje,MessageCircleDashed:rje,MessageCircleDashedIcon:rje,MessageCircleHeart:qq,MessageCircleHeartIcon:qq,MessageCircleIcon:Ah,MessageCircleMore:aje,MessageCircleMoreIcon:aje,MessageCircleOff:ije,MessageCircleOffIcon:ije,MessageCirclePlus:oje,MessageCirclePlusIcon:oje,MessageCircleQuestion:DJ,MessageCircleQuestionIcon:DJ,MessageCircleReply:lje,MessageCircleReplyIcon:lje,MessageCircleWarning:cje,MessageCircleWarningIcon:cje,MessageCircleX:dje,MessageCircleXIcon:dje,MessageSquare:eo,MessageSquareCode:uje,MessageSquareCodeIcon:uje,MessageSquareDashed:hje,MessageSquareDashedIcon:hje,MessageSquareDiff:mje,MessageSquareDiffIcon:mje,MessageSquareDot:fje,MessageSquareDotIcon:fje,MessageSquareHeart:pje,MessageSquareHeartIcon:pje,MessageSquareIcon:eo,MessageSquareLock:gje,MessageSquareLockIcon:gje,MessageSquareMore:FJ,MessageSquareMoreIcon:FJ,MessageSquareOff:xje,MessageSquareOffIcon:xje,MessageSquarePlus:m4,MessageSquarePlusIcon:m4,MessageSquareQuote:PE,MessageSquareQuoteIcon:PE,MessageSquareReply:OJ,MessageSquareReplyIcon:OJ,MessageSquareShare:yje,MessageSquareShareIcon:yje,MessageSquareText:vje,MessageSquareTextIcon:vje,MessageSquareWarning:zJ,MessageSquareWarningIcon:zJ,MessageSquareX:bje,MessageSquareXIcon:bje,MessagesSquare:BJ,MessagesSquareIcon:BJ,Mic:Kz,Mic2:eF,Mic2Icon:eF,MicIcon:Kz,MicOff:_je,MicOffIcon:_je,MicVocal:eF,MicVocalIcon:eF,Microchip:wje,MicrochipIcon:wje,Microscope:jje,MicroscopeIcon:jje,Microwave:Nje,MicrowaveIcon:Nje,Milestone:kje,MilestoneIcon:kje,Milk:Cje,MilkIcon:Cje,MilkOff:Sje,MilkOffIcon:Sje,Minimize:Eje,Minimize2:Aje,Minimize2Icon:Aje,MinimizeIcon:Eje,Minus:ZN,MinusCircle:yD,MinusCircleIcon:yD,MinusIcon:ZN,MinusSquare:JF,MinusSquareIcon:JF,Monitor:XN,MonitorCheck:Tje,MonitorCheckIcon:Tje,MonitorCog:Mje,MonitorCogIcon:Mje,MonitorDot:Pje,MonitorDotIcon:Pje,MonitorDown:Ije,MonitorDownIcon:Ije,MonitorIcon:XN,MonitorOff:Lje,MonitorOffIcon:Lje,MonitorPause:Rje,MonitorPauseIcon:Rje,MonitorPlay:Vq,MonitorPlayIcon:Vq,MonitorSmartphone:Dje,MonitorSmartphoneIcon:Dje,MonitorSpeaker:Fje,MonitorSpeakerIcon:Fje,MonitorStop:Oje,MonitorStopIcon:Oje,MonitorUp:Yz,MonitorUpIcon:Yz,MonitorX:zje,MonitorXIcon:zje,Moon:$je,MoonIcon:$je,MoonStar:Bje,MoonStarIcon:Bje,MoreHorizontal:l_,MoreHorizontalIcon:l_,MoreVertical:Jx,MoreVerticalIcon:Jx,Mountain:qje,MountainIcon:qje,MountainSnow:Uje,MountainSnowIcon:Uje,Mouse:Gje,MouseIcon:Gje,MouseOff:Vje,MouseOffIcon:Vje,MousePointer:cb,MousePointer2:$J,MousePointer2Icon:$J,MousePointerBan:Hje,MousePointerBanIcon:Hje,MousePointerClick:Pm,MousePointerClickIcon:Pm,MousePointerIcon:cb,MousePointerSquareDashed:qF,MousePointerSquareDashedIcon:qF,Move:UJ,Move3D:tF,Move3DIcon:tF,Move3d:tF,Move3dIcon:tF,MoveDiagonal:Kje,MoveDiagonal2:Wje,MoveDiagonal2Icon:Wje,MoveDiagonalIcon:Kje,MoveDown:Xje,MoveDownIcon:Xje,MoveDownLeft:Yje,MoveDownLeftIcon:Yje,MoveDownRight:Zje,MoveDownRightIcon:Zje,MoveHorizontal:Qje,MoveHorizontalIcon:Qje,MoveIcon:UJ,MoveLeft:Jje,MoveLeftIcon:Jje,MoveRight:e2e,MoveRightIcon:e2e,MoveUp:n2e,MoveUpIcon:n2e,MoveUpLeft:t2e,MoveUpLeftIcon:t2e,MoveUpRight:s2e,MoveUpRightIcon:s2e,MoveVertical:r2e,MoveVerticalIcon:r2e,Music:Hq,Music2:a2e,Music2Icon:a2e,Music3:i2e,Music3Icon:i2e,Music4:o2e,Music4Icon:o2e,MusicIcon:Hq,Navigation:qJ,Navigation2:c2e,Navigation2Icon:c2e,Navigation2Off:l2e,Navigation2OffIcon:l2e,NavigationIcon:qJ,NavigationOff:d2e,NavigationOffIcon:d2e,Network:u2e,NetworkIcon:u2e,Newspaper:QN,NewspaperIcon:QN,Nfc:h2e,NfcIcon:h2e,Notebook:g2e,NotebookIcon:g2e,NotebookPen:m2e,NotebookPenIcon:m2e,NotebookTabs:f2e,NotebookTabsIcon:f2e,NotebookText:p2e,NotebookTextIcon:p2e,NotepadText:y2e,NotepadTextDashed:x2e,NotepadTextDashedIcon:x2e,NotepadTextIcon:y2e,Nut:b2e,NutIcon:b2e,NutOff:v2e,NutOffIcon:v2e,Octagon:w2e,OctagonAlert:OS,OctagonAlertIcon:OS,OctagonIcon:w2e,OctagonMinus:_2e,OctagonMinusIcon:_2e,OctagonPause:sF,OctagonPauseIcon:sF,OctagonX:nF,OctagonXIcon:nF,Omega:j2e,OmegaIcon:j2e,Option:N2e,OptionIcon:N2e,Orbit:k2e,OrbitIcon:k2e,Origami:S2e,OrigamiIcon:S2e,Outdent:YD,OutdentIcon:YD,Package:ym,Package2:C2e,Package2Icon:C2e,PackageCheck:A2e,PackageCheckIcon:A2e,PackageIcon:ym,PackageMinus:E2e,PackageMinusIcon:E2e,PackageOpen:T2e,PackageOpenIcon:T2e,PackagePlus:M2e,PackagePlusIcon:M2e,PackageSearch:P2e,PackageSearchIcon:P2e,PackageX:I2e,PackageXIcon:I2e,PaintBucket:L2e,PaintBucketIcon:L2e,PaintRoller:R2e,PaintRollerIcon:R2e,Paintbrush:D2e,Paintbrush2:rF,Paintbrush2Icon:rF,PaintbrushIcon:D2e,PaintbrushVertical:rF,PaintbrushVerticalIcon:rF,Palette:yd,PaletteIcon:yd,Palmtree:_O,PalmtreeIcon:_O,PanelBottom:z2e,PanelBottomClose:F2e,PanelBottomCloseIcon:F2e,PanelBottomDashed:aF,PanelBottomDashedIcon:aF,PanelBottomIcon:z2e,PanelBottomInactive:aF,PanelBottomInactiveIcon:aF,PanelBottomOpen:O2e,PanelBottomOpenIcon:O2e,PanelLeft:cF,PanelLeftClose:iF,PanelLeftCloseIcon:iF,PanelLeftDashed:oF,PanelLeftDashedIcon:oF,PanelLeftIcon:cF,PanelLeftInactive:oF,PanelLeftInactiveIcon:oF,PanelLeftOpen:lF,PanelLeftOpenIcon:lF,PanelRight:U2e,PanelRightClose:B2e,PanelRightCloseIcon:B2e,PanelRightDashed:dF,PanelRightDashedIcon:dF,PanelRightIcon:U2e,PanelRightInactive:dF,PanelRightInactiveIcon:dF,PanelRightOpen:$2e,PanelRightOpenIcon:$2e,PanelTop:H2e,PanelTopClose:q2e,PanelTopCloseIcon:q2e,PanelTopDashed:uF,PanelTopDashedIcon:uF,PanelTopIcon:H2e,PanelTopInactive:uF,PanelTopInactiveIcon:uF,PanelTopOpen:V2e,PanelTopOpenIcon:V2e,PanelsLeftBottom:G2e,PanelsLeftBottomIcon:G2e,PanelsLeftRight:rP,PanelsLeftRightIcon:rP,PanelsRightBottom:W2e,PanelsRightBottomIcon:W2e,PanelsTopBottom:gF,PanelsTopBottomIcon:gF,PanelsTopLeft:LA,PanelsTopLeftIcon:LA,Paperclip:ZI,PaperclipIcon:ZI,Parentheses:K2e,ParenthesesIcon:K2e,ParkingCircle:bD,ParkingCircleIcon:bD,ParkingCircleOff:vD,ParkingCircleOffIcon:vD,ParkingMeter:Y2e,ParkingMeterIcon:Y2e,ParkingSquare:sO,ParkingSquareIcon:sO,ParkingSquareOff:tO,ParkingSquareOffIcon:tO,PartyPopper:Cx,PartyPopperIcon:Cx,Pause:Av,PauseCircle:_D,PauseCircleIcon:_D,PauseIcon:Av,PauseOctagon:sF,PauseOctagonIcon:sF,PawPrint:Z2e,PawPrintIcon:Z2e,PcCase:X2e,PcCaseIcon:X2e,Pen:AN,PenBox:_p,PenBoxIcon:_p,PenIcon:AN,PenLine:_f,PenLineIcon:_f,PenOff:Q2e,PenOffIcon:Q2e,PenSquare:_p,PenSquareIcon:_p,PenTool:IE,PenToolIcon:IE,Pencil:pi,PencilIcon:pi,PencilLine:Gq,PencilLineIcon:Gq,PencilOff:J2e,PencilOffIcon:J2e,PencilRuler:eNe,PencilRulerIcon:eNe,Pentagon:tNe,PentagonIcon:tNe,Percent:Ew,PercentCircle:wD,PercentCircleIcon:wD,PercentDiamond:LD,PercentDiamondIcon:LD,PercentIcon:Ew,PercentSquare:nO,PercentSquareIcon:nO,PersonStanding:sNe,PersonStandingIcon:sNe,PhilippinePeso:nNe,PhilippinePesoIcon:nNe,Phone:Da,PhoneCall:VJ,PhoneCallIcon:VJ,PhoneForwarded:rNe,PhoneForwardedIcon:rNe,PhoneIcon:Da,PhoneIncoming:aNe,PhoneIncomingIcon:aNe,PhoneMissed:iNe,PhoneMissedIcon:iNe,PhoneOff:oNe,PhoneOffIcon:oNe,PhoneOutgoing:lNe,PhoneOutgoingIcon:lNe,Pi:cNe,PiIcon:cNe,PiSquare:rO,PiSquareIcon:rO,Piano:dNe,PianoIcon:dNe,Pickaxe:uNe,PickaxeIcon:uNe,PictureInPicture:mNe,PictureInPicture2:hNe,PictureInPicture2Icon:hNe,PictureInPictureIcon:mNe,PieChart:sD,PieChartIcon:sD,PiggyBank:HJ,PiggyBankIcon:HJ,Pilcrow:gNe,PilcrowIcon:gNe,PilcrowLeft:fNe,PilcrowLeftIcon:fNe,PilcrowRight:pNe,PilcrowRightIcon:pNe,PilcrowSquare:aO,PilcrowSquareIcon:aO,Pill:yNe,PillBottle:xNe,PillBottleIcon:xNe,PillIcon:yNe,Pin:LE,PinIcon:LE,PinOff:GJ,PinOffIcon:GJ,Pipette:vNe,PipetteIcon:vNe,Pizza:bNe,PizzaIcon:bNe,Plane:WJ,PlaneIcon:WJ,PlaneLanding:_Ne,PlaneLandingIcon:_Ne,PlaneTakeoff:wNe,PlaneTakeoffIcon:wNe,Play:zu,PlayCircle:ef,PlayCircleIcon:ef,PlayIcon:zu,PlaySquare:iO,PlaySquareIcon:iO,Plug:JN,Plug2:jNe,Plug2Icon:jNe,PlugIcon:JN,PlugZap:hF,PlugZap2:hF,PlugZap2Icon:hF,PlugZapIcon:hF,Plus:dn,PlusCircle:jD,PlusCircleIcon:jD,PlusIcon:dn,PlusSquare:oO,PlusSquareIcon:oO,Pocket:kNe,PocketIcon:kNe,PocketKnife:NNe,PocketKnifeIcon:NNe,Podcast:SNe,PodcastIcon:SNe,Pointer:ANe,PointerIcon:ANe,PointerOff:CNe,PointerOffIcon:CNe,Popcorn:ENe,PopcornIcon:ENe,Popsicle:TNe,PopsicleIcon:TNe,PoundSterling:MNe,PoundSterlingIcon:MNe,Power:KJ,PowerCircle:ND,PowerCircleIcon:ND,PowerIcon:KJ,PowerOff:PNe,PowerOffIcon:PNe,PowerSquare:lO,PowerSquareIcon:lO,Presentation:bb,PresentationIcon:bb,Printer:RE,PrinterCheck:INe,PrinterCheckIcon:INe,PrinterIcon:RE,Projector:LNe,ProjectorIcon:LNe,Proportions:RNe,ProportionsIcon:RNe,Puzzle:DNe,PuzzleIcon:DNe,Pyramid:FNe,PyramidIcon:FNe,QrCode:Jp,QrCodeIcon:Jp,Quote:h2,QuoteIcon:h2,Rabbit:ONe,RabbitIcon:ONe,Radar:Wq,RadarIcon:Wq,Radiation:zNe,RadiationIcon:zNe,Radical:BNe,RadicalIcon:BNe,Radio:_b,RadioIcon:_b,RadioReceiver:$Ne,RadioReceiverIcon:$Ne,RadioTower:UNe,RadioTowerIcon:UNe,Radius:qNe,RadiusIcon:qNe,RailSymbol:VNe,RailSymbolIcon:VNe,Rainbow:HNe,RainbowIcon:HNe,Rat:GNe,RatIcon:GNe,Ratio:WNe,RatioIcon:WNe,Receipt:Kq,ReceiptCent:KNe,ReceiptCentIcon:KNe,ReceiptEuro:YNe,ReceiptEuroIcon:YNe,ReceiptIcon:Kq,ReceiptIndianRupee:ZNe,ReceiptIndianRupeeIcon:ZNe,ReceiptJapaneseYen:XNe,ReceiptJapaneseYenIcon:XNe,ReceiptPoundSterling:QNe,ReceiptPoundSterlingIcon:QNe,ReceiptRussianRuble:JNe,ReceiptRussianRubleIcon:JNe,ReceiptSwissFranc:eke,ReceiptSwissFrancIcon:eke,ReceiptText:tke,ReceiptTextIcon:tke,RectangleEllipsis:mF,RectangleEllipsisIcon:mF,RectangleHorizontal:ske,RectangleHorizontalIcon:ske,RectangleVertical:nke,RectangleVerticalIcon:nke,Recycle:rke,RecycleIcon:rke,Redo:DE,Redo2:ake,Redo2Icon:ake,RedoDot:ike,RedoDotIcon:ike,RedoIcon:DE,RefreshCcw:Yq,RefreshCcwDot:oke,RefreshCcwDotIcon:oke,RefreshCcwIcon:Yq,RefreshCw:ro,RefreshCwIcon:ro,RefreshCwOff:lke,RefreshCwOffIcon:lke,Refrigerator:cke,RefrigeratorIcon:cke,Regex:dke,RegexIcon:dke,RemoveFormatting:uke,RemoveFormattingIcon:uke,Repeat:FE,Repeat1:hke,Repeat1Icon:hke,Repeat2:YJ,Repeat2Icon:YJ,RepeatIcon:FE,Replace:fke,ReplaceAll:mke,ReplaceAllIcon:mke,ReplaceIcon:fke,Reply:Zq,ReplyAll:pke,ReplyAllIcon:pke,ReplyIcon:Zq,Rewind:gke,RewindIcon:gke,Ribbon:xke,RibbonIcon:xke,Rocket:qg,RocketIcon:qg,RockingChair:yke,RockingChairIcon:yke,RollerCoaster:vke,RollerCoasterIcon:vke,Rotate3D:fF,Rotate3DIcon:fF,Rotate3d:fF,Rotate3dIcon:fF,RotateCcw:Ax,RotateCcwIcon:Ax,RotateCcwSquare:bke,RotateCcwSquareIcon:bke,RotateCw:Zz,RotateCwIcon:Zz,RotateCwSquare:_ke,RotateCwSquareIcon:_ke,Route:Xq,RouteIcon:Xq,RouteOff:wke,RouteOffIcon:wke,Router:jke,RouterIcon:jke,Rows:pF,Rows2:pF,Rows2Icon:pF,Rows3:gF,Rows3Icon:gF,Rows4:Nke,Rows4Icon:Nke,RowsIcon:pF,Rss:kke,RssIcon:kke,Ruler:P4,RulerIcon:P4,RussianRuble:Ske,RussianRubleIcon:Ske,Sailboat:Cke,SailboatIcon:Cke,Salad:Ake,SaladIcon:Ake,Sandwich:Eke,SandwichIcon:Eke,Satellite:Mke,SatelliteDish:Tke,SatelliteDishIcon:Tke,SatelliteIcon:Mke,Save:tl,SaveAll:Pke,SaveAllIcon:Pke,SaveIcon:tl,SaveOff:Ike,SaveOffIcon:Ike,Scale:Lke,Scale3D:xF,Scale3DIcon:xF,Scale3d:xF,Scale3dIcon:xF,ScaleIcon:Lke,Scaling:Rke,ScalingIcon:Rke,Scan:qke,ScanBarcode:Dke,ScanBarcodeIcon:Dke,ScanEye:Fke,ScanEyeIcon:Fke,ScanFace:Oke,ScanFaceIcon:Oke,ScanIcon:qke,ScanLine:zke,ScanLineIcon:zke,ScanQrCode:Bke,ScanQrCodeIcon:Bke,ScanSearch:$ke,ScanSearchIcon:$ke,ScanText:Uke,ScanTextIcon:Uke,ScatterChart:nD,ScatterChartIcon:nD,School:Vke,School2:jO,School2Icon:jO,SchoolIcon:Vke,Scissors:Gke,ScissorsIcon:Gke,ScissorsLineDashed:Hke,ScissorsLineDashedIcon:Hke,ScissorsSquare:cO,ScissorsSquareDashedBottom:RF,ScissorsSquareDashedBottomIcon:RF,ScissorsSquareIcon:cO,ScreenShare:Kke,ScreenShareIcon:Kke,ScreenShareOff:Wke,ScreenShareOffIcon:Wke,Scroll:Yke,ScrollIcon:Yke,ScrollText:Qq,ScrollTextIcon:Qq,Search:Zr,SearchCheck:Zke,SearchCheckIcon:Zke,SearchCode:Xke,SearchCodeIcon:Xke,SearchIcon:Zr,SearchSlash:Qke,SearchSlashIcon:Qke,SearchX:Jq,SearchXIcon:Jq,Section:Jke,SectionIcon:Jke,Send:Kr,SendHorizonal:yF,SendHorizonalIcon:yF,SendHorizontal:yF,SendHorizontalIcon:yF,SendIcon:Kr,SendToBack:eSe,SendToBackIcon:eSe,SeparatorHorizontal:tSe,SeparatorHorizontalIcon:tSe,SeparatorVertical:sSe,SeparatorVerticalIcon:sSe,Server:iSe,ServerCog:nSe,ServerCogIcon:nSe,ServerCrash:rSe,ServerCrashIcon:rSe,ServerIcon:iSe,ServerOff:aSe,ServerOffIcon:aSe,Settings:Nd,Settings2:eC,Settings2Icon:eC,SettingsIcon:Nd,Shapes:oSe,ShapesIcon:oSe,Share:ZJ,Share2:Fd,Share2Icon:Fd,ShareIcon:ZJ,Sheet:lSe,SheetIcon:lSe,Shell:cSe,ShellIcon:cSe,Shield:Tf,ShieldAlert:eV,ShieldAlertIcon:eV,ShieldBan:dSe,ShieldBanIcon:dSe,ShieldCheck:Rm,ShieldCheckIcon:Rm,ShieldClose:vF,ShieldCloseIcon:vF,ShieldEllipsis:uSe,ShieldEllipsisIcon:uSe,ShieldHalf:hSe,ShieldHalfIcon:hSe,ShieldIcon:Tf,ShieldMinus:mSe,ShieldMinusIcon:mSe,ShieldOff:Xz,ShieldOffIcon:Xz,ShieldPlus:fSe,ShieldPlusIcon:fSe,ShieldQuestion:Qz,ShieldQuestionIcon:Qz,ShieldX:vF,ShieldXIcon:vF,Ship:gSe,ShipIcon:gSe,ShipWheel:pSe,ShipWheelIcon:pSe,Shirt:xSe,ShirtIcon:xSe,ShoppingBag:I4,ShoppingBagIcon:I4,ShoppingBasket:ySe,ShoppingBasketIcon:ySe,ShoppingCart:tC,ShoppingCartIcon:tC,Shovel:vSe,ShovelIcon:vSe,ShowerHead:bSe,ShowerHeadIcon:bSe,Shrink:_Se,ShrinkIcon:_Se,Shrub:wSe,ShrubIcon:wSe,Shuffle:Jz,ShuffleIcon:Jz,Sidebar:cF,SidebarClose:iF,SidebarCloseIcon:iF,SidebarIcon:cF,SidebarOpen:lF,SidebarOpenIcon:lF,Sigma:jSe,SigmaIcon:jSe,SigmaSquare:dO,SigmaSquareIcon:dO,Signal:ASe,SignalHigh:NSe,SignalHighIcon:NSe,SignalIcon:ASe,SignalLow:kSe,SignalLowIcon:kSe,SignalMedium:SSe,SignalMediumIcon:SSe,SignalZero:CSe,SignalZeroIcon:CSe,Signature:ESe,SignatureIcon:ESe,Signpost:XJ,SignpostBig:TSe,SignpostBigIcon:TSe,SignpostIcon:XJ,Siren:MSe,SirenIcon:MSe,SkipBack:PSe,SkipBackIcon:PSe,SkipForward:QJ,SkipForwardIcon:QJ,Skull:ISe,SkullIcon:ISe,Slack:LSe,SlackIcon:LSe,Slash:RSe,SlashIcon:RSe,SlashSquare:uO,SlashSquareIcon:uO,Slice:DSe,SliceIcon:DSe,Sliders:bF,SlidersHorizontal:XI,SlidersHorizontalIcon:XI,SlidersIcon:bF,SlidersVertical:bF,SlidersVerticalIcon:bF,Smartphone:x1,SmartphoneCharging:FSe,SmartphoneChargingIcon:FSe,SmartphoneIcon:x1,SmartphoneNfc:OSe,SmartphoneNfcIcon:OSe,Smile:BSe,SmileIcon:BSe,SmilePlus:zSe,SmilePlusIcon:zSe,Snail:$Se,SnailIcon:$Se,Snowflake:Xj,SnowflakeIcon:Xj,Sofa:tV,SofaIcon:tV,SortAsc:zR,SortAscIcon:zR,SortDesc:DR,SortDescIcon:DR,Soup:USe,SoupIcon:USe,Space:qSe,SpaceIcon:qSe,Spade:VSe,SpadeIcon:VSe,Sparkle:QI,SparkleIcon:QI,Sparkles:Nn,SparklesIcon:Nn,Speaker:HSe,SpeakerIcon:HSe,Speech:GSe,SpeechIcon:GSe,SpellCheck:KSe,SpellCheck2:WSe,SpellCheck2Icon:WSe,SpellCheckIcon:KSe,Spline:YSe,SplineIcon:YSe,Split:ZSe,SplitIcon:ZSe,SplitSquareHorizontal:hO,SplitSquareHorizontalIcon:hO,SplitSquareVertical:mO,SplitSquareVerticalIcon:mO,SprayCan:XSe,SprayCanIcon:XSe,Sprout:JI,SproutIcon:JI,Square:j_,SquareActivity:_F,SquareActivityIcon:_F,SquareArrowDown:NF,SquareArrowDownIcon:NF,SquareArrowDownLeft:wF,SquareArrowDownLeftIcon:wF,SquareArrowDownRight:jF,SquareArrowDownRightIcon:jF,SquareArrowLeft:kF,SquareArrowLeftIcon:kF,SquareArrowOutDownLeft:SF,SquareArrowOutDownLeftIcon:SF,SquareArrowOutDownRight:CF,SquareArrowOutDownRightIcon:CF,SquareArrowOutUpLeft:AF,SquareArrowOutUpLeftIcon:AF,SquareArrowOutUpRight:EF,SquareArrowOutUpRightIcon:EF,SquareArrowRight:TF,SquareArrowRightIcon:TF,SquareArrowUp:IF,SquareArrowUpIcon:IF,SquareArrowUpLeft:MF,SquareArrowUpLeftIcon:MF,SquareArrowUpRight:PF,SquareArrowUpRightIcon:PF,SquareAsterisk:LF,SquareAsteriskIcon:LF,SquareBottomDashedScissors:RF,SquareBottomDashedScissorsIcon:RF,SquareChartGantt:p5,SquareChartGanttIcon:p5,SquareCheck:DF,SquareCheckBig:Vj,SquareCheckBigIcon:Vj,SquareCheckIcon:DF,SquareChevronDown:FF,SquareChevronDownIcon:FF,SquareChevronLeft:OF,SquareChevronLeftIcon:OF,SquareChevronRight:zF,SquareChevronRightIcon:zF,SquareChevronUp:BF,SquareChevronUpIcon:BF,SquareCode:$F,SquareCodeIcon:$F,SquareDashed:VF,SquareDashedBottom:JSe,SquareDashedBottomCode:QSe,SquareDashedBottomCodeIcon:QSe,SquareDashedBottomIcon:JSe,SquareDashedIcon:VF,SquareDashedKanban:UF,SquareDashedKanbanIcon:UF,SquareDashedMousePointer:qF,SquareDashedMousePointerIcon:qF,SquareDivide:HF,SquareDivideIcon:HF,SquareDot:GF,SquareDotIcon:GF,SquareEqual:WF,SquareEqualIcon:WF,SquareFunction:KF,SquareFunctionIcon:KF,SquareGanttChart:p5,SquareGanttChartIcon:p5,SquareIcon:j_,SquareKanban:YF,SquareKanbanIcon:YF,SquareLibrary:ZF,SquareLibraryIcon:ZF,SquareM:XF,SquareMIcon:XF,SquareMenu:QF,SquareMenuIcon:QF,SquareMinus:JF,SquareMinusIcon:JF,SquareMousePointer:eO,SquareMousePointerIcon:eO,SquareParking:sO,SquareParkingIcon:sO,SquareParkingOff:tO,SquareParkingOffIcon:tO,SquarePen:_p,SquarePenIcon:_p,SquarePercent:nO,SquarePercentIcon:nO,SquarePi:rO,SquarePiIcon:rO,SquarePilcrow:aO,SquarePilcrowIcon:aO,SquarePlay:iO,SquarePlayIcon:iO,SquarePlus:oO,SquarePlusIcon:oO,SquarePower:lO,SquarePowerIcon:lO,SquareRadical:eCe,SquareRadicalIcon:eCe,SquareScissors:cO,SquareScissorsIcon:cO,SquareSigma:dO,SquareSigmaIcon:dO,SquareSlash:uO,SquareSlashIcon:uO,SquareSplitHorizontal:hO,SquareSplitHorizontalIcon:hO,SquareSplitVertical:mO,SquareSplitVerticalIcon:mO,SquareSquare:tCe,SquareSquareIcon:tCe,SquareStack:sCe,SquareStackIcon:sCe,SquareTerminal:fO,SquareTerminalIcon:fO,SquareUser:gO,SquareUserIcon:gO,SquareUserRound:pO,SquareUserRoundIcon:pO,SquareX:xO,SquareXIcon:xO,Squircle:nCe,SquircleIcon:nCe,Squirrel:rCe,SquirrelIcon:rCe,Stamp:aCe,StampIcon:aCe,Star:ei,StarHalf:iCe,StarHalfIcon:iCe,StarIcon:ei,StarOff:oCe,StarOffIcon:oCe,Stars:Nn,StarsIcon:Nn,StepBack:lCe,StepBackIcon:lCe,StepForward:cCe,StepForwardIcon:cCe,Stethoscope:dCe,StethoscopeIcon:dCe,Sticker:uCe,StickerIcon:uCe,StickyNote:e7,StickyNoteIcon:e7,StopCircle:SD,StopCircleIcon:SD,Store:sV,StoreIcon:sV,StretchHorizontal:hCe,StretchHorizontalIcon:hCe,StretchVertical:mCe,StretchVerticalIcon:mCe,Strikethrough:JJ,StrikethroughIcon:JJ,Subscript:fCe,SubscriptIcon:fCe,Subtitles:HR,SubtitlesIcon:HR,Sun:ek,SunDim:pCe,SunDimIcon:pCe,SunIcon:ek,SunMedium:gCe,SunMediumIcon:gCe,SunMoon:xCe,SunMoonIcon:xCe,SunSnow:yCe,SunSnowIcon:yCe,Sunrise:vCe,SunriseIcon:vCe,Sunset:bCe,SunsetIcon:bCe,Superscript:_Ce,SuperscriptIcon:_Ce,SwatchBook:wCe,SwatchBookIcon:wCe,SwissFranc:jCe,SwissFrancIcon:jCe,SwitchCamera:NCe,SwitchCameraIcon:NCe,Sword:kCe,SwordIcon:kCe,Swords:SCe,SwordsIcon:SCe,Syringe:CCe,SyringeIcon:CCe,Table:rV,Table2:nV,Table2Icon:nV,TableCellsMerge:ACe,TableCellsMergeIcon:ACe,TableCellsSplit:ECe,TableCellsSplitIcon:ECe,TableColumnsSplit:TCe,TableColumnsSplitIcon:TCe,TableIcon:rV,TableOfContents:MCe,TableOfContentsIcon:MCe,TableProperties:PCe,TablePropertiesIcon:PCe,TableRowsSplit:ICe,TableRowsSplitIcon:ICe,Tablet:aV,TabletIcon:aV,TabletSmartphone:LCe,TabletSmartphoneIcon:LCe,Tablets:RCe,TabletsIcon:RCe,Tag:Ap,TagIcon:Ap,Tags:eee,TagsIcon:eee,Tally1:DCe,Tally1Icon:DCe,Tally2:FCe,Tally2Icon:FCe,Tally3:OCe,Tally3Icon:OCe,Tally4:zCe,Tally4Icon:zCe,Tally5:BCe,Tally5Icon:BCe,Tangent:$Ce,TangentIcon:$Ce,Target:nh,TargetIcon:nh,Telescope:UCe,TelescopeIcon:UCe,Tent:VCe,TentIcon:VCe,TentTree:qCe,TentTreeIcon:qCe,Terminal:HCe,TerminalIcon:HCe,TerminalSquare:fO,TerminalSquareIcon:fO,TestTube:GCe,TestTube2:yO,TestTube2Icon:yO,TestTubeDiagonal:yO,TestTubeDiagonalIcon:yO,TestTubeIcon:GCe,TestTubes:WCe,TestTubesIcon:WCe,Text:XCe,TextCursor:KCe,TextCursorIcon:KCe,TextCursorInput:iV,TextCursorInputIcon:iV,TextIcon:XCe,TextQuote:YCe,TextQuoteIcon:YCe,TextSearch:ZCe,TextSearchIcon:ZCe,TextSelect:vO,TextSelectIcon:vO,TextSelection:vO,TextSelectionIcon:vO,Theater:QCe,TheaterIcon:QCe,Thermometer:t5e,ThermometerIcon:t5e,ThermometerSnowflake:JCe,ThermometerSnowflakeIcon:JCe,ThermometerSun:e5e,ThermometerSunIcon:e5e,ThumbsDown:tee,ThumbsDownIcon:tee,ThumbsUp:qy,ThumbsUpIcon:qy,Ticket:t7,TicketCheck:s5e,TicketCheckIcon:s5e,TicketIcon:t7,TicketMinus:n5e,TicketMinusIcon:n5e,TicketPercent:r5e,TicketPercentIcon:r5e,TicketPlus:a5e,TicketPlusIcon:a5e,TicketSlash:i5e,TicketSlashIcon:i5e,TicketX:o5e,TicketXIcon:o5e,Tickets:c5e,TicketsIcon:c5e,TicketsPlane:l5e,TicketsPlaneIcon:l5e,Timer:h5e,TimerIcon:h5e,TimerOff:d5e,TimerOffIcon:d5e,TimerReset:u5e,TimerResetIcon:u5e,ToggleLeft:m5e,ToggleLeftIcon:m5e,ToggleRight:f5e,ToggleRightIcon:f5e,Toilet:p5e,ToiletIcon:p5e,Tornado:g5e,TornadoIcon:g5e,Torus:x5e,TorusIcon:x5e,Touchpad:v5e,TouchpadIcon:v5e,TouchpadOff:y5e,TouchpadOffIcon:y5e,TowerControl:b5e,TowerControlIcon:b5e,ToyBrick:_5e,ToyBrickIcon:_5e,Tractor:w5e,TractorIcon:w5e,TrafficCone:j5e,TrafficConeIcon:j5e,Train:bO,TrainFront:k5e,TrainFrontIcon:k5e,TrainFrontTunnel:N5e,TrainFrontTunnelIcon:N5e,TrainIcon:bO,TrainTrack:S5e,TrainTrackIcon:S5e,TramFront:bO,TramFrontIcon:bO,Trash:C5e,Trash2:Hn,Trash2Icon:Hn,TrashIcon:C5e,TreeDeciduous:A5e,TreeDeciduousIcon:A5e,TreePalm:_O,TreePalmIcon:_O,TreePine:eL,TreePineIcon:eL,Trees:E5e,TreesIcon:E5e,Trello:T5e,TrelloIcon:T5e,TrendingDown:sC,TrendingDownIcon:sC,TrendingUp:Zl,TrendingUpDown:M5e,TrendingUpDownIcon:M5e,TrendingUpIcon:Zl,Triangle:I5e,TriangleAlert:Al,TriangleAlertIcon:Al,TriangleIcon:I5e,TriangleRight:P5e,TriangleRightIcon:P5e,Trophy:Kl,TrophyIcon:Kl,Truck:see,TruckIcon:see,Turtle:L5e,TurtleIcon:L5e,Tv:D5e,Tv2:wO,Tv2Icon:wO,TvIcon:D5e,TvMinimal:wO,TvMinimalIcon:wO,TvMinimalPlay:R5e,TvMinimalPlayIcon:R5e,Twitch:F5e,TwitchIcon:F5e,Twitter:nee,TwitterIcon:nee,Type:oV,TypeIcon:oV,TypeOutline:O5e,TypeOutlineIcon:O5e,Umbrella:B5e,UmbrellaIcon:B5e,UmbrellaOff:z5e,UmbrellaOffIcon:z5e,Underline:s7,UnderlineIcon:s7,Undo:OE,Undo2:ree,Undo2Icon:ree,UndoDot:$5e,UndoDotIcon:$5e,UndoIcon:OE,UnfoldHorizontal:U5e,UnfoldHorizontalIcon:U5e,UnfoldVertical:q5e,UnfoldVerticalIcon:q5e,Ungroup:V5e,UngroupIcon:V5e,University:jO,UniversityIcon:jO,Unlink:n7,Unlink2:H5e,Unlink2Icon:H5e,UnlinkIcon:n7,Unlock:JD,UnlockIcon:JD,UnlockKeyhole:QD,UnlockKeyholeIcon:QD,Unplug:lV,UnplugIcon:lV,Upload:ni,UploadCloud:nP,UploadCloudIcon:nP,UploadIcon:ni,Usb:G5e,UsbIcon:G5e,User:sl,User2:iP,User2Icon:iP,UserCheck:m2,UserCheck2:aP,UserCheck2Icon:aP,UserCheckIcon:m2,UserCircle:AD,UserCircle2:CD,UserCircle2Icon:CD,UserCircleIcon:AD,UserCog:aee,UserCog2:NO,UserCog2Icon:NO,UserCogIcon:aee,UserIcon:sl,UserMinus:cV,UserMinus2:kO,UserMinus2Icon:kO,UserMinusIcon:cV,UserPen:W5e,UserPenIcon:W5e,UserPlus:lc,UserPlus2:SO,UserPlus2Icon:SO,UserPlusIcon:lc,UserRound:iP,UserRoundCheck:aP,UserRoundCheckIcon:aP,UserRoundCog:NO,UserRoundCogIcon:NO,UserRoundIcon:iP,UserRoundMinus:kO,UserRoundMinusIcon:kO,UserRoundPen:K5e,UserRoundPenIcon:K5e,UserRoundPlus:SO,UserRoundPlusIcon:SO,UserRoundSearch:dV,UserRoundSearchIcon:dV,UserRoundX:CO,UserRoundXIcon:CO,UserSearch:Y5e,UserSearchIcon:Y5e,UserSquare:gO,UserSquare2:pO,UserSquare2Icon:pO,UserSquareIcon:gO,UserX:uV,UserX2:CO,UserX2Icon:CO,UserXIcon:uV,Users:Yn,Users2:y0,Users2Icon:y0,UsersIcon:Yn,UsersRound:y0,UsersRoundIcon:y0,Utensils:EO,UtensilsCrossed:AO,UtensilsCrossedIcon:AO,UtensilsIcon:EO,UtilityPole:Z5e,UtilityPoleIcon:Z5e,Variable:hV,VariableIcon:hV,Vault:X5e,VaultIcon:X5e,Vegan:Q5e,VeganIcon:Q5e,VenetianMask:J5e,VenetianMaskIcon:J5e,Verified:IA,VerifiedIcon:IA,Vibrate:t4e,VibrateIcon:t4e,VibrateOff:e4e,VibrateOffIcon:e4e,Video:ua,VideoIcon:ua,VideoOff:s4e,VideoOffIcon:s4e,Videotape:n4e,VideotapeIcon:n4e,View:r4e,ViewIcon:r4e,Voicemail:a4e,VoicemailIcon:a4e,Volleyball:i4e,VolleyballIcon:i4e,Volume:c4e,Volume1:o4e,Volume1Icon:o4e,Volume2:iee,Volume2Icon:iee,VolumeIcon:c4e,VolumeOff:l4e,VolumeOffIcon:l4e,VolumeX:oee,VolumeXIcon:oee,Vote:d4e,VoteIcon:d4e,Wallet:r7,Wallet2:TO,Wallet2Icon:TO,WalletCards:u4e,WalletCardsIcon:u4e,WalletIcon:r7,WalletMinimal:TO,WalletMinimalIcon:TO,Wallpaper:h4e,WallpaperIcon:h4e,Wand:m4e,Wand2:ey,Wand2Icon:ey,WandIcon:m4e,WandSparkles:ey,WandSparklesIcon:ey,Warehouse:f4e,WarehouseIcon:f4e,WashingMachine:p4e,WashingMachineIcon:p4e,Watch:g4e,WatchIcon:g4e,Waves:x4e,WavesIcon:x4e,Waypoints:y4e,WaypointsIcon:y4e,Webcam:v4e,WebcamIcon:v4e,Webhook:_4e,WebhookIcon:_4e,WebhookOff:b4e,WebhookOffIcon:b4e,Weight:w4e,WeightIcon:w4e,Wheat:N4e,WheatIcon:N4e,WheatOff:j4e,WheatOffIcon:j4e,WholeWord:k4e,WholeWordIcon:k4e,Wifi:T4e,WifiHigh:S4e,WifiHighIcon:S4e,WifiIcon:T4e,WifiLow:C4e,WifiLowIcon:C4e,WifiOff:A4e,WifiOffIcon:A4e,WifiZero:E4e,WifiZeroIcon:E4e,Wind:P4e,WindArrowDown:M4e,WindArrowDownIcon:M4e,WindIcon:P4e,Wine:L4e,WineIcon:L4e,WineOff:I4e,WineOffIcon:I4e,Workflow:a7,WorkflowIcon:a7,Worm:R4e,WormIcon:R4e,WrapText:D4e,WrapTextIcon:D4e,Wrench:L4,WrenchIcon:L4,X:pr,XCircle:Nu,XCircleIcon:Nu,XIcon:pr,XOctagon:nF,XOctagonIcon:nF,XSquare:xO,XSquareIcon:xO,Youtube:mV,YoutubeIcon:mV,Zap:eg,ZapIcon:eg,ZapOff:F4e,ZapOffIcon:F4e,ZoomIn:tL,ZoomInIcon:tL,ZoomOut:fV,ZoomOutIcon:fV,createLucideIcon:ge,icons:z0s},Symbol.toStringTag,{value:"Module"})),set="-",B0s=s=>{const t=U0s(s),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=s;return{getClassGroupId:l=>{const o=l.split(set);return o[0]===""&&o.length!==1&&o.shift(),MRt(o,t)||$0s(l)},getConflictingClassGroupIds:(l,o)=>{const c=n[l]||[];return o&&r[l]?[...c,...r[l]]:c}}},MRt=(s,t)=>{var l;if(s.length===0)return t.classGroupId;const n=s[0],r=t.nextPart.get(n),a=r?MRt(s.slice(1),r):void 0;if(a)return a;if(t.validators.length===0)return;const i=s.join(set);return(l=t.validators.find(({validator:o})=>o(i)))==null?void 0:l.classGroupId},fgt=/^\[(.+)\]$/,$0s=s=>{if(fgt.test(s)){const t=fgt.exec(s)[1],n=t==null?void 0:t.substring(0,t.indexOf(":"));if(n)return"arbitrary.."+n}},U0s=s=>{const{theme:t,prefix:n}=s,r={nextPart:new Map,validators:[]};return V0s(Object.entries(s.classGroups),n).forEach(([i,l])=>{LVe(l,r,i,t)}),r},LVe=(s,t,n,r)=>{s.forEach(a=>{if(typeof a=="string"){const i=a===""?t:pgt(t,a);i.classGroupId=n;return}if(typeof a=="function"){if(q0s(a)){LVe(a(r),t,n,r);return}t.validators.push({validator:a,classGroupId:n});return}Object.entries(a).forEach(([i,l])=>{LVe(l,pgt(t,i),n,r)})})},pgt=(s,t)=>{let n=s;return t.split(set).forEach(r=>{n.nextPart.has(r)||n.nextPart.set(r,{nextPart:new Map,validators:[]}),n=n.nextPart.get(r)}),n},q0s=s=>s.isThemeGetter,V0s=(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,H0s=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)}}},PRt="!",G0s=s=>{const{separator:t,experimentalParseClassName:n}=s,r=t.length===1,a=t[0],i=t.length,l=o=>{const c=[];let d=0,u=0,h;for(let y=0;yu?h-u:void 0;return{modifiers:c,hasImportantModifier:f,baseClassName:g,maybePostfixModifierPosition:x}};return n?o=>n({className:o,parseClassName:l}):l},W0s=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},K0s=s=>({cache:H0s(s.cacheSize),parseClassName:G0s(s),...B0s(s)}),Y0s=/\s+/,Z0s=(s,t)=>{const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:a}=t,i=[],l=s.trim().split(Y0s);let o="";for(let c=l.length-1;c>=0;c-=1){const d=l[c],{modifiers:u,hasImportantModifier:h,baseClassName:m,maybePostfixModifierPosition:f}=n(d);let g=!!f,x=r(g?m.substring(0,f):m);if(!x){if(!g){o=d+(o.length>0?" "+o:o);continue}if(x=r(m),!x){o=d+(o.length>0?" "+o:o);continue}g=!1}const y=W0s(u).join(":"),v=h?y+PRt:y,b=v+x;if(i.includes(b))continue;i.push(b);const w=a(x,g);for(let S=0;S0?" "+o:o)}return o};function X0s(){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=K0s(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=Z0s(c,n);return a(c,u),u}return function(){return i(X0s.apply(null,arguments))}}const pp=s=>{const t=n=>n[s]||[];return t.isThemeGetter=!0,t},LRt=/^\[(?:([a-z-]+):)?(.+)\]$/i,J0s=/^\d+\/\d+$/,evs=new Set(["px","full","screen"]),tvs=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,svs=/\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$/,nvs=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,rvs=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,avs=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Z3=s=>pV(s)||evs.has(s)||J0s.test(s),pM=s=>$W(s,"length",mvs),pV=s=>!!s&&!Number.isNaN(Number(s)),vze=s=>$W(s,"number",pV),pZ=s=>!!s&&Number.isInteger(Number(s)),ivs=s=>s.endsWith("%")&&pV(s.slice(0,-1)),Id=s=>LRt.test(s),gM=s=>tvs.test(s),ovs=new Set(["length","size","percentage"]),lvs=s=>$W(s,ovs,RRt),cvs=s=>$W(s,"position",RRt),dvs=new Set(["image","url"]),uvs=s=>$W(s,dvs,pvs),hvs=s=>$W(s,"",fvs),gZ=()=>!0,$W=(s,t,n)=>{const r=LRt.exec(s);return r?r[1]?typeof t=="string"?r[1]===t:t.has(r[1]):n(r[2]):!1},mvs=s=>svs.test(s)&&!nvs.test(s),RRt=()=>!1,fvs=s=>rvs.test(s),pvs=s=>avs.test(s),gvs=()=>{const s=pp("colors"),t=pp("spacing"),n=pp("blur"),r=pp("brightness"),a=pp("borderColor"),i=pp("borderRadius"),l=pp("borderSpacing"),o=pp("borderWidth"),c=pp("contrast"),d=pp("grayscale"),u=pp("hueRotate"),h=pp("invert"),m=pp("gap"),f=pp("gradientColorStops"),g=pp("gradientColorStopPositions"),x=pp("inset"),y=pp("margin"),v=pp("opacity"),b=pp("padding"),w=pp("saturate"),S=pp("scale"),A=pp("sepia"),E=pp("skew"),I=pp("space"),P=pp("translate"),R=()=>["auto","contain","none"],D=()=>["auto","hidden","clip","visible","scroll"],O=()=>["auto",Id,t],U=()=>[Id,t],W=()=>["",Z3,pM],V=()=>["auto",pV,Id],G=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],Y=()=>["solid","dashed","dotted","double","none"],X=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],ae=()=>["start","end","center","between","around","evenly","stretch"],le=()=>["","0",Id],ne=()=>["auto","avoid","all","avoid-page","page","left","right","column"],te=()=>[pV,Id];return{cacheSize:500,separator:":",theme:{colors:[gZ],spacing:[Z3,pM],blur:["none","",gM,Id],brightness:te(),borderColor:[s],borderRadius:["none","","full",gM,Id],borderSpacing:U(),borderWidth:W(),contrast:te(),grayscale:le(),hueRotate:te(),invert:le(),gap:U(),gradientColorStops:[s],gradientColorStopPositions:[ivs,pM],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:[gM]}],"break-after":[{"break-after":ne()}],"break-before":[{"break-before":ne()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...G(),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",pZ,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",pZ,Id]}],"grid-cols":[{"grid-cols":[gZ]}],"col-start-end":[{col:["auto",{span:["full",pZ,Id]},Id]}],"col-start":[{"col-start":V()}],"col-end":[{"col-end":V()}],"grid-rows":[{"grid-rows":[gZ]}],"row-start-end":[{row:["auto",{span:[pZ,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:[y]}],mx:[{mx:[y]}],my:[{my:[y]}],ms:[{ms:[y]}],me:[{me:[y]}],mt:[{mt:[y]}],mr:[{mr:[y]}],mb:[{mb:[y]}],ml:[{ml:[y]}],"space-x":[{"space-x":[I]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[I]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",Id,t]}],"min-w":[{"min-w":[Id,t,"min","max","fit"]}],"max-w":[{"max-w":[Id,t,"none","full","min","max","fit","prose",{screen:[gM]},gM]}],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",gM,pM]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",vze]}],"font-family":[{font:[gZ]}],"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",pV,vze]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",Z3,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":[v]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[s]}],"text-opacity":[{"text-opacity":[v]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...Y(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",Z3,pM]}],"underline-offset":[{"underline-offset":["auto",Z3,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":[v]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...G(),cvs]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",lvs]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},uvs]}],"bg-color":[{bg:[s]}],"gradient-from-pos":[{from:[g]}],"gradient-via-pos":[{via:[g]}],"gradient-to-pos":[{to:[g]}],"gradient-from":[{from:[f]}],"gradient-via":[{via:[f]}],"gradient-to":[{to:[f]}],rounded:[{rounded:[i]}],"rounded-s":[{"rounded-s":[i]}],"rounded-e":[{"rounded-e":[i]}],"rounded-t":[{"rounded-t":[i]}],"rounded-r":[{"rounded-r":[i]}],"rounded-b":[{"rounded-b":[i]}],"rounded-l":[{"rounded-l":[i]}],"rounded-ss":[{"rounded-ss":[i]}],"rounded-se":[{"rounded-se":[i]}],"rounded-ee":[{"rounded-ee":[i]}],"rounded-es":[{"rounded-es":[i]}],"rounded-tl":[{"rounded-tl":[i]}],"rounded-tr":[{"rounded-tr":[i]}],"rounded-br":[{"rounded-br":[i]}],"rounded-bl":[{"rounded-bl":[i]}],"border-w":[{border:[o]}],"border-w-x":[{"border-x":[o]}],"border-w-y":[{"border-y":[o]}],"border-w-s":[{"border-s":[o]}],"border-w-e":[{"border-e":[o]}],"border-w-t":[{"border-t":[o]}],"border-w-r":[{"border-r":[o]}],"border-w-b":[{"border-b":[o]}],"border-w-l":[{"border-l":[o]}],"border-opacity":[{"border-opacity":[v]}],"border-style":[{border:[...Y(),"hidden"]}],"divide-x":[{"divide-x":[o]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[o]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[v]}],"divide-style":[{divide:Y()}],"border-color":[{border:[a]}],"border-color-x":[{"border-x":[a]}],"border-color-y":[{"border-y":[a]}],"border-color-s":[{"border-s":[a]}],"border-color-e":[{"border-e":[a]}],"border-color-t":[{"border-t":[a]}],"border-color-r":[{"border-r":[a]}],"border-color-b":[{"border-b":[a]}],"border-color-l":[{"border-l":[a]}],"divide-color":[{divide:[a]}],"outline-style":[{outline:["",...Y()]}],"outline-offset":[{"outline-offset":[Z3,Id]}],"outline-w":[{outline:[Z3,pM]}],"outline-color":[{outline:[s]}],"ring-w":[{ring:W()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[s]}],"ring-opacity":[{"ring-opacity":[v]}],"ring-offset-w":[{"ring-offset":[Z3,pM]}],"ring-offset-color":[{"ring-offset":[s]}],shadow:[{shadow:["","inner","none",gM,hvs]}],"shadow-color":[{shadow:[gZ]}],opacity:[{opacity:[v]}],"mix-blend":[{"mix-blend":[...X(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":X()}],filter:[{filter:["","none"]}],blur:[{blur:[n]}],brightness:[{brightness:[r]}],contrast:[{contrast:[c]}],"drop-shadow":[{"drop-shadow":["","none",gM,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":[v]}],"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:[pZ,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:[Z3,pM,vze]}],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"]}}},xvs=Q0s(gvs);function Pt(...s){return xvs(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 ggt(s){const t=new Date(s);return new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric"}).format(t)}function zte(s){return s?s.replace(/<[^>]*>/g,""):""}const yvs=D0s,DRt=j.forwardRef(({className:s,...t},n)=>e.jsx(wRt,{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}));DRt.displayName=wRt.displayName;const vvs=MB("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"}}),FRt=j.forwardRef(({className:s,variant:t,...n},r)=>e.jsx(jRt,{ref:r,className:Pt(vvs({variant:t}),s),...n}));FRt.displayName=jRt.displayName;const bvs=j.forwardRef(({className:s,...t},n)=>e.jsx(SRt,{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}));bvs.displayName=SRt.displayName;const ORt=j.forwardRef(({className:s,...t},n)=>e.jsx(CRt,{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(pr,{className:"h-4 w-4"})}));ORt.displayName=CRt.displayName;const zRt=j.forwardRef(({className:s,...t},n)=>e.jsx(NRt,{ref:n,className:Pt("text-sm font-semibold",s),...t}));zRt.displayName=NRt.displayName;const BRt=j.forwardRef(({className:s,...t},n)=>e.jsx(kRt,{ref:n,className:Pt("text-sm opacity-90",s),...t}));BRt.displayName=kRt.displayName;function _vs(){const{toasts:s}=Bi();return e.jsxs(yvs,{children:[s.map(function({id:t,title:n,description:r,action:a,...i}){return e.jsxs(FRt,{...i,children:[e.jsxs("div",{className:"grid gap-1",children:[n&&e.jsx(zRt,{children:n}),r&&e.jsx(BRt,{children:r})]}),a,e.jsx(ORt,{})]},t)}),e.jsx(DRt,{})]})}var xgt=["light","dark"],wvs="(prefers-color-scheme: dark)",jvs=j.createContext(void 0),Nvs={setTheme:s=>{},themes:[]},kvs=()=>{var s;return(s=j.useContext(jvs))!=null?s:Nvs};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?xgt.includes(i)&&i?`if(e==='light'||e==='dark'||!e)d.style.colorScheme=e||'${i}'`:"if(e==='light'||e==='dark')d.style.colorScheme=e":"",m=(g,x=!1,y=!0)=>{let v=l?l[g]:g,b=x?g+"|| ''":`'${v}'`,w="";return a&&y&&!x&&xgt.includes(g)&&(w+=`d.style.colorScheme = '${g}';`),n==="class"?x||v?w+=`c.add(${b})`:w+="null":v&&(w+=`d[s](n,${b})`),w},f=s?`!function(){${u}${m(s)}}()`:r?`!function(){try{${u}var e=localStorage.getItem('${t}');if('system'===e||(!e&&${d})){var t='${wvs}',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 Svs=s=>{switch(s){case"success":return Evs;case"info":return Mvs;case"warning":return Tvs;case"error":return Pvs;default:return null}},Cvs=Array(12).fill(0),Avs=({visible:s,className:t})=>Gt.createElement("div",{className:["sonner-loading-wrapper",t].filter(Boolean).join(" "),"data-visible":s},Gt.createElement("div",{className:"sonner-spinner"},Cvs.map((n,r)=>Gt.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${r}`})))),Evs=Gt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Gt.createElement("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z",clipRule:"evenodd"})),Tvs=Gt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},Gt.createElement("path",{fillRule:"evenodd",d:"M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z",clipRule:"evenodd"})),Mvs=Gt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Gt.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z",clipRule:"evenodd"})),Pvs=Gt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Gt.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})),Ivs=Gt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},Gt.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),Gt.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),Lvs=()=>{let[s,t]=Gt.useState(document.hidden);return Gt.useEffect(()=>{let n=()=>{t(document.hidden)};return document.addEventListener("visibilitychange",n),()=>window.removeEventListener("visibilitychange",n)},[]),s},RVe=1,Rvs=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:RVe++,l=this.toasts.find(c=>c.id===i),o=t.dismissible===void 0?!0:t.dismissible;return this.dismissedToasts.has(i)&&this.dismissedToasts.delete(i),l?this.toasts=this.toasts.map(c=>c.id===i?(this.publish({...c,...t,id:i,title:r}),{...c,...t,id:i,dismissible:o,title:r}):c):this.addToast({title:r,...a,dismissible:o,id:i}),i},this.dismiss=t=>(this.dismissedToasts.add(t),t||this.toasts.forEach(n=>{this.subscribers.forEach(r=>r({id:n.id,dismiss:!0}))}),this.subscribers.forEach(n=>n({id:t,dismiss:!0})),t),this.message=(t,n)=>this.create({...n,message:t}),this.error=(t,n)=>this.create({...n,message:t,type:"error"}),this.success=(t,n)=>this.create({...n,type:"success",message:t}),this.info=(t,n)=>this.create({...n,type:"info",message:t}),this.warning=(t,n)=>this.create({...n,type:"warning",message:t}),this.loading=(t,n)=>this.create({...n,type:"loading",message:t}),this.promise=(t,n)=>{if(!n)return;let r;n.loading!==void 0&&(r=this.create({...n,promise:t,type:"loading",message:n.loading,description:typeof n.description!="function"?n.description:void 0}));let a=t instanceof Promise?t:t(),i=r!==void 0,l,o=a.then(async d=>{if(l=["resolve",d],Gt.isValidElement(d))i=!1,this.create({id:r,type:"default",message:d});else if(Fvs(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)||RVe++;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}},lw=new Rvs,Dvs=(s,t)=>{let n=(t==null?void 0:t.id)||RVe++;return lw.addToast({title:s,...t,id:n}),n},Fvs=s=>s&&typeof s=="object"&&"ok"in s&&typeof s.ok=="boolean"&&"status"in s&&typeof s.status=="number",Ovs=Dvs,zvs=()=>lw.toasts,Bvs=()=>lw.getActiveToasts(),re=Object.assign(Ovs,{success:lw.success,info:lw.info,warning:lw.warning,error:lw.error,custom:lw.custom,message:lw.message,promise:lw.promise,dismiss:lw.dismiss,loading:lw.loading},{getHistory:zvs,getToasts:Bvs});function $vs(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))}$vs(`: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 uce(s){return s.label!==void 0}var Uvs=3,qvs="32px",Vvs="16px",ygt=4e3,Hvs=356,Gvs=14,Wvs=20,Kvs=200;function Qk(...s){return s.filter(Boolean).join(" ")}function Yvs(s){let[t,n]=s.split("-"),r=[];return t&&r.push(t),n&&r.push(n),r}var Zvs=s=>{var t,n,r,a,i,l,o,c,d,u,h;let{invert:m,toast:f,unstyled:g,interacting:x,setHeights:y,visibleToasts:v,heights:b,index:w,toasts:S,expanded:A,removeToast:E,defaultRichColors:I,closeButton:P,style:R,cancelButtonStyle:D,actionButtonStyle:O,className:U="",descriptionClassName:W="",duration:V,position:G,gap:Y,loadingIcon:X,expandByDefault:ae,classNames:le,icons:ne,closeButtonAriaLabel:te="Close toast",pauseWhenPageIsHidden:J}=s,[ce,_e]=Gt.useState(null),[he,ue]=Gt.useState(null),[ve,Ee]=Gt.useState(!1),[Se,Le]=Gt.useState(!1),[Fe,ke]=Gt.useState(!1),[Be,Ne]=Gt.useState(!1),[Ae,Ce]=Gt.useState(!1),[Ve,ze]=Gt.useState(0),[qe,dt]=Gt.useState(0),Xe=Gt.useRef(f.duration||V||ygt),at=Gt.useRef(null),rt=Gt.useRef(null),Ke=w===0,Je=w+1<=v,pt=f.type,gt=f.dismissible!==!1,ss=f.className||"",Yt=f.descriptionClassName||"",ts=Gt.useMemo(()=>b.findIndex(Js=>Js.toastId===f.id)||0,[b,f.id]),ys=Gt.useMemo(()=>{var Js;return(Js=f.closeButton)!=null?Js:P},[f.closeButton,P]),Bt=Gt.useMemo(()=>f.duration||V||ygt,[f.duration,V]),Ft=Gt.useRef(0),as=Gt.useRef(0),kt=Gt.useRef(0),Ks=Gt.useRef(null),[wt,gs]=G.split("-"),ks=Gt.useMemo(()=>b.reduce((Js,Ut,hn)=>hn>=ts?Js:Js+Ut.height,0),[b,ts]),Is=Lvs(),Xs=f.invert||m,ds=pt==="loading";as.current=Gt.useMemo(()=>ts*Y+ks,[ts,ks]),Gt.useEffect(()=>{Xe.current=Bt},[Bt]),Gt.useEffect(()=>{Ee(!0)},[]),Gt.useEffect(()=>{let Js=rt.current;if(Js){let Ut=Js.getBoundingClientRect().height;return dt(Ut),y(hn=>[{toastId:f.id,height:Ut,position:f.position},...hn]),()=>y(hn=>hn.filter(hr=>hr.toastId!==f.id))}},[y,f.id]),Gt.useLayoutEffect(()=>{if(!ve)return;let Js=rt.current,Ut=Js.style.height;Js.style.height="auto";let hn=Js.getBoundingClientRect().height;Js.style.height=Ut,dt(hn),y(hr=>hr.find(Rs=>Rs.toastId===f.id)?hr.map(Rs=>Rs.toastId===f.id?{...Rs,height:hn}:Rs):[{toastId:f.id,height:hn,position:f.position},...hr])},[ve,f.title,f.description,y,f.id]);let Ss=Gt.useCallback(()=>{Le(!0),ze(as.current),y(Js=>Js.filter(Ut=>Ut.toastId!==f.id)),setTimeout(()=>{E(f)},Kvs)},[f,E,y,as]);Gt.useEffect(()=>{if(f.promise&&pt==="loading"||f.duration===1/0||f.type==="loading")return;let Js;return A||x||J&&Is?(()=>{if(kt.current{var Ut;(Ut=f.onAutoClose)==null||Ut.call(f,f),Ss()},Xe.current)),()=>clearTimeout(Js)},[A,x,f,pt,J,Is,Ss]),Gt.useEffect(()=>{f.delete&&Ss()},[Ss,f.delete]);function yn(){var Js,Ut,hn;return ne!=null&&ne.loading?Gt.createElement("div",{className:Qk(le==null?void 0:le.loader,(Js=f==null?void 0:f.classNames)==null?void 0:Js.loader,"sonner-loader"),"data-visible":pt==="loading"},ne.loading):X?Gt.createElement("div",{className:Qk(le==null?void 0:le.loader,(Ut=f==null?void 0:f.classNames)==null?void 0:Ut.loader,"sonner-loader"),"data-visible":pt==="loading"},X):Gt.createElement(Avs,{className:Qk(le==null?void 0:le.loader,(hn=f==null?void 0:f.classNames)==null?void 0:hn.loader),visible:pt==="loading"})}return Gt.createElement("li",{tabIndex:0,ref:rt,className:Qk(U,ss,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[pt],(n=f==null?void 0:f.classNames)==null?void 0:n[pt]),"data-sonner-toast":"","data-rich-colors":(r=f.richColors)!=null?r:I,"data-styled":!(f.jsx||f.unstyled||g),"data-mounted":ve,"data-promise":!!f.promise,"data-swiped":Ae,"data-removed":Se,"data-visible":Je,"data-y-position":wt,"data-x-position":gs,"data-index":w,"data-front":Ke,"data-swiping":Fe,"data-dismissible":gt,"data-type":pt,"data-invert":Xs,"data-swipe-out":Be,"data-swipe-direction":he,"data-expanded":!!(A||ae&&ve),style:{"--index":w,"--toasts-before":w,"--z-index":S.length-w,"--offset":`${Se?Ve:as.current}px`,"--initial-height":ae?"auto":`${qe}px`,...R,...f.style},onDragEnd:()=>{ke(!1),_e(null),Ks.current=null},onPointerDown:Js=>{ds||!gt||(at.current=new Date,ze(as.current),Js.target.setPointerCapture(Js.pointerId),Js.target.tagName!=="BUTTON"&&(ke(!0),Ks.current={x:Js.clientX,y:Js.clientY}))},onPointerUp:()=>{var Js,Ut,hn,hr;if(Be||!gt)return;Ks.current=null;let Rs=Number(((Js=rt.current)==null?void 0:Js.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),jr=Number(((Ut=rt.current)==null?void 0:Ut.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),kr=new Date().getTime()-((hn=at.current)==null?void 0:hn.getTime()),$n=ce==="x"?Rs:jr,kn=Math.abs($n)/kr;if(Math.abs($n)>=Wvs||kn>.11){ze(as.current),(hr=f.onDismiss)==null||hr.call(f,f),ue(ce==="x"?Rs>0?"right":"left":jr>0?"down":"up"),Ss(),Ne(!0),Ce(!1);return}ke(!1),_e(null)},onPointerMove:Js=>{var Ut,hn,hr,Rs;if(!Ks.current||!gt||((Ut=window.getSelection())==null?void 0:Ut.toString().length)>0)return;let jr=Js.clientY-Ks.current.y,kr=Js.clientX-Ks.current.x,$n=(hn=s.swipeDirections)!=null?hn:Yvs(G);!ce&&(Math.abs(kr)>1||Math.abs(jr)>1)&&_e(Math.abs(kr)>Math.abs(jr)?"x":"y");let kn={x:0,y:0};ce==="y"?($n.includes("top")||$n.includes("bottom"))&&($n.includes("top")&&jr<0||$n.includes("bottom")&&jr>0)&&(kn.y=jr):ce==="x"&&($n.includes("left")||$n.includes("right"))&&($n.includes("left")&&kr<0||$n.includes("right")&&kr>0)&&(kn.x=kr),(Math.abs(kn.x)>0||Math.abs(kn.y)>0)&&Ce(!0),(hr=rt.current)==null||hr.style.setProperty("--swipe-amount-x",`${kn.x}px`),(Rs=rt.current)==null||Rs.style.setProperty("--swipe-amount-y",`${kn.y}px`)}},ys&&!f.jsx?Gt.createElement("button",{"aria-label":te,"data-disabled":ds,"data-close-button":!0,onClick:ds||!gt?()=>{}:()=>{var Js;Ss(),(Js=f.onDismiss)==null||Js.call(f,f)},className:Qk(le==null?void 0:le.closeButton,(a=f==null?void 0:f.classNames)==null?void 0:a.closeButton)},(i=ne==null?void 0:ne.close)!=null?i:Ivs):null,f.jsx||j.isValidElement(f.title)?f.jsx?f.jsx:typeof f.title=="function"?f.title():f.title:Gt.createElement(Gt.Fragment,null,pt||f.icon||f.promise?Gt.createElement("div",{"data-icon":"",className:Qk(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||yn():null,f.type!=="loading"?f.icon||(ne==null?void 0:ne[pt])||Svs(pt):null):null,Gt.createElement("div",{"data-content":"",className:Qk(le==null?void 0:le.content,(o=f==null?void 0:f.classNames)==null?void 0:o.content)},Gt.createElement("div",{"data-title":"",className:Qk(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?Gt.createElement("div",{"data-description":"",className:Qk(W,Yt,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&&uce(f.cancel)?Gt.createElement("button",{"data-button":!0,"data-cancel":!0,style:f.cancelButtonStyle||D,onClick:Js=>{var Ut,hn;uce(f.cancel)&>&&((hn=(Ut=f.cancel).onClick)==null||hn.call(Ut,Js),Ss())},className:Qk(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&&uce(f.action)?Gt.createElement("button",{"data-button":!0,"data-action":!0,style:f.actionButtonStyle||O,onClick:Js=>{var Ut,hn;uce(f.action)&&((hn=(Ut=f.action).onClick)==null||hn.call(Ut,Js),!Js.defaultPrevented&&Ss())},className:Qk(le==null?void 0:le.actionButton,(h=f==null?void 0:f.classNames)==null?void 0:h.actionButton)},f.action.label):null))};function vgt(){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 Xvs(s,t){let n={};return[s,t].forEach((r,a)=>{let i=a===1,l=i?"--mobile-offset":"--offset",o=i?Vvs:qvs;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 Qvs=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=Uvs,toastOptions:x,dir:y=vgt(),gap:v=Gvs,loadingIcon:b,icons:w,containerAriaLabel:S="Notifications",pauseWhenPageIsHidden:A}=s,[E,I]=Gt.useState([]),P=Gt.useMemo(()=>Array.from(new Set([r].concat(E.filter(J=>J.position).map(J=>J.position)))),[E,r]),[R,D]=Gt.useState([]),[O,U]=Gt.useState(!1),[W,V]=Gt.useState(!1),[G,Y]=Gt.useState(u!=="system"?u:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),X=Gt.useRef(null),ae=a.join("+").replace(/Key/g,"").replace(/Digit/g,""),le=Gt.useRef(null),ne=Gt.useRef(!1),te=Gt.useCallback(J=>{I(ce=>{var _e;return(_e=ce.find(he=>he.id===J.id))!=null&&_e.delete||lw.dismiss(J.id),ce.filter(({id:he})=>he!==J.id)})},[]);return Gt.useEffect(()=>lw.subscribe(J=>{if(J.dismiss){I(ce=>ce.map(_e=>_e.id===J.id?{..._e,delete:!0}:_e));return}setTimeout(()=>{z6t.flushSync(()=>{I(ce=>{let _e=ce.findIndex(he=>he.id===J.id);return _e!==-1?[...ce.slice(0,_e),{...ce[_e],...J},...ce.slice(_e+1)]:[J,...ce]})})})}),[]),Gt.useEffect(()=>{if(u!=="system"){Y(u);return}if(u==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?Y("dark"):Y("light")),typeof window>"u")return;let J=window.matchMedia("(prefers-color-scheme: dark)");try{J.addEventListener("change",({matches:ce})=>{Y(ce?"dark":"light")})}catch{J.addListener(({matches:_e})=>{try{Y(_e?"dark":"light")}catch(he){console.error(he)}})}},[u]),Gt.useEffect(()=>{E.length<=1&&U(!1)},[E]),Gt.useEffect(()=>{let J=ce=>{var _e,he;a.every(ue=>ce[ue]||ce.code===ue)&&(U(!0),(_e=X.current)==null||_e.focus()),ce.code==="Escape"&&(document.activeElement===X.current||(he=X.current)!=null&&he.contains(document.activeElement))&&U(!1)};return document.addEventListener("keydown",J),()=>document.removeEventListener("keydown",J)},[a]),Gt.useEffect(()=>{if(X.current)return()=>{le.current&&(le.current.focus({preventScroll:!0}),le.current=null,ne.current=!1)}},[X.current]),Gt.createElement("section",{ref:t,"aria-label":`${S} ${ae}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},P.map((J,ce)=>{var _e;let[he,ue]=J.split("-");return E.length?Gt.createElement("ol",{key:J,dir:y==="auto"?vgt():y,tabIndex:-1,ref:X,className:o,"data-sonner-toaster":!0,"data-theme":G,"data-y-position":he,"data-lifted":O&&E.length>1&&!i,"data-x-position":ue,style:{"--front-toast-height":`${((_e=R[0])==null?void 0:_e.height)||0}px`,"--width":`${Hvs}px`,"--gap":`${v}px`,...f,...Xvs(c,d)},onBlur:ve=>{ne.current&&!ve.currentTarget.contains(ve.relatedTarget)&&(ne.current=!1,le.current&&(le.current.focus({preventScroll:!0}),le.current=null))},onFocus:ve=>{ve.target instanceof HTMLElement&&ve.target.dataset.dismissible==="false"||ne.current||(ne.current=!0,le.current=ve.relatedTarget)},onMouseEnter:()=>U(!0),onMouseMove:()=>U(!0),onMouseLeave:()=>{W||U(!1)},onDragEnd:()=>U(!1),onPointerDown:ve=>{ve.target instanceof HTMLElement&&ve.target.dataset.dismissible==="false"||V(!0)},onPointerUp:()=>V(!1)},E.filter(ve=>!ve.position&&ce===0||ve.position===J).map((ve,Ee)=>{var Se,Le;return Gt.createElement(Zvs,{key:ve.id,icons:w,index:Ee,toast:ve,defaultRichColors:h,duration:(Se=x==null?void 0:x.duration)!=null?Se:m,className:x==null?void 0:x.className,descriptionClassName:x==null?void 0:x.descriptionClassName,invert:n,visibleToasts:g,closeButton:(Le=x==null?void 0:x.closeButton)!=null?Le:l,interacting:W,position:J,style:x==null?void 0:x.style,unstyled:x==null?void 0:x.unstyled,classNames:x==null?void 0:x.classNames,cancelButtonStyle:x==null?void 0:x.cancelButtonStyle,actionButtonStyle:x==null?void 0:x.actionButtonStyle,removeToast:te,toasts:E.filter(Fe=>Fe.position==ve.position),heights:R.filter(Fe=>Fe.position==ve.position),setHeights:D,expandByDefault:i,gap:v,loadingIcon:b,expanded:O,pauseWhenPageIsHidden:A,swipeDirections:s.swipeDirections})})):null}))});const Jvs=({...s})=>{const{theme:t="system"}=kvs();return e.jsx(Qvs,{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 ebs=Object.defineProperty,tbs=(s,t)=>ebs(s,"name",{value:t,configurable:!0}),sbs=SB[" useId ".trim().toString()]||(()=>{}),nbs=0;function uy(s){const[t,n]=j.useState(sbs());return Af(()=>{s||n(r=>r??String(nbs++))},[s]),s||(t?`radix-${t}`:"")}tbs(uy,"useId");var rbs=Object.defineProperty,m_=(s,t)=>rbs(s,"name",{value:t,configurable:!0}),bze="focusScope.autoFocusOnMount",_ze="focusScope.autoFocusOnUnmount",bgt={bubbles:!1,cancelable:!0},UIe=j.forwardRef(m_(function(t,n){const{loop:r=!1,trapped:a=!1,onMountAutoFocus:i,onUnmountAutoFocus:l,...o}=t,[c,d]=j.useState(null),u=Zp(i),h=Zp(l),m=j.useRef(null),f=Vo(n,d),g=j.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;j.useEffect(()=>{if(a){let y=function(S){if(g.paused||!c)return;const A=S.target;c.contains(A)?m.current=A:kA(m.current,{select:!0})},v=function(S){if(g.paused||!c)return;const A=S.relatedTarget;A!==null&&(c.contains(A)||kA(m.current,{select:!0}))},b=function(S){if(document.activeElement===document.body)for(const E of S)E.removedNodes.length>0&&kA(c)};m_(y,"handleFocusIn"),m_(v,"handleFocusOut"),m_(b,"handleMutations"),document.addEventListener("focusin",y),document.addEventListener("focusout",v);const w=new MutationObserver(b);return c&&w.observe(c,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",y),document.removeEventListener("focusout",v),w.disconnect()}}},[a,c,g.paused]),j.useEffect(()=>{if(c){_gt.add(g);const y=document.activeElement;if(!c.contains(y)){const b=new CustomEvent(bze,bgt);c.addEventListener(bze,u),c.dispatchEvent(b),b.defaultPrevented||($Rt(GRt(net(c)),{select:!0}),document.activeElement===y&&kA(c))}return()=>{c.removeEventListener(bze,u),setTimeout(()=>{const b=new CustomEvent(_ze,bgt);c.addEventListener(_ze,h),c.dispatchEvent(b),b.defaultPrevented||kA(y??document.body,{select:!0}),c.removeEventListener(_ze,h),_gt.remove(g)},0)}}},[c,u,h,g]);const x=j.useCallback(y=>{if(!r&&!a||g.paused)return;const v=y.key==="Tab"&&!y.altKey&&!y.ctrlKey&&!y.metaKey,b=document.activeElement;if(v&&b){const w=y.currentTarget,[S,A]=URt(w);S&&A?!y.shiftKey&&b===A?(y.preventDefault(),r&&kA(S,{select:!0})):y.shiftKey&&b===S&&(y.preventDefault(),r&&kA(A,{select:!0})):b===w&&y.preventDefault()}},[r,a,g.paused]);return e.jsx(Ei.div,{tabIndex:-1,...o,ref:f,onKeyDown:x})},"FocusScope"));function $Rt(s,{select:t=!1}={}){const n=document.activeElement;for(const r of s)if(kA(r,{select:t}),document.activeElement!==n)return}m_($Rt,"focusFirst");function URt(s){const t=net(s),n=DVe(t,s),r=DVe(t.reverse(),s);return[n,r]}m_(URt,"getTabbableEdges");function net(s){const t=[],n=document.createTreeWalker(s,NodeFilter.SHOW_ELEMENT,{acceptNode:m_(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}m_(net,"getTabbableCandidates");function DVe(s,t){const n=typeof t.checkVisibility=="function"&&t.checkVisibility({checkVisibilityCSS:!0});for(const r of s)if(!(n?!r.checkVisibility({checkVisibilityCSS:!0}):qRt(r,{upTo:t})))return r}m_(DVe,"findVisible");function qRt(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}m_(qRt,"isHidden");function VRt(s){return s instanceof HTMLInputElement&&"select"in s}m_(VRt,"isSelectableInput");function kA(s,{select:t=!1}={}){if(s&&s.focus){const n=document.activeElement;s.focus({preventScroll:!0}),s!==n&&VRt(s)&&t&&s.select()}}m_(kA,"focus");var _gt=HRt();function HRt(){let s=[];return{add(t){const n=s[0];t!==n&&(n==null||n.pause()),s=FVe(s,t),s.unshift(t)},remove(t){var n;s=FVe(s,t),(n=s[0])==null||n.resume()}}}m_(HRt,"createFocusScopesStack");function FVe(s,t){const n=[...s],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}m_(FVe,"arrayRemove");function GRt(s){return s.filter(t=>t.tagName!=="A")}m_(GRt,"removeLinks");var abs=Object.defineProperty,ret=(s,t)=>abs(s,"name",{value:t,configurable:!0}),hce=0,JC=null;function ibs(s){return UW(),s.children}ret(ibs,"FocusGuards");function UW(){j.useEffect(()=>{JC||(JC={start:OVe(),end:OVe()});const{start:s,end:t}=JC;return document.body.firstElementChild!==s&&document.body.insertAdjacentElement("afterbegin",s),document.body.lastElementChild!==t&&document.body.insertAdjacentElement("beforeend",t),hce++,()=>{hce===1&&(JC==null||JC.start.remove(),JC==null||JC.end.remove(),JC=null),hce=Math.max(0,hce-1)}},[])}ret(UW,"useFocusGuards");function OVe(){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}ret(OVe,"createFocusGuard");var o4=function(){return o4=Object.assign||function(t){for(var n,r=1,a=arguments.length;r"u")return jbs;var t=Nbs(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])}},Sbs=ZRt(),gV="data-scroll-locked",Cbs=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(lbs,` { overflow: hidden `).concat(r,`; padding-right: `).concat(o,"px ").concat(r,`; } body[`).concat(gV,`] { 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(O4e,` { right: `).concat(o,"px ").concat(r,`; } .`).concat(z4e,` { margin-right: `).concat(o,"px ").concat(r,`; } .`).concat(O4e," .").concat(O4e,` { right: 0 `).concat(r,`; } .`).concat(z4e," .").concat(z4e,` { margin-right: 0 `).concat(r,`; } body[`).concat(gV,`] { `).concat(cbs,": ").concat(o,`px; } `)},jgt=function(){var s=parseInt(document.body.getAttribute(gV)||"0",10);return isFinite(s)?s:0},Abs=function(){j.useEffect(function(){return document.body.setAttribute(gV,(jgt()+1).toString()),function(){var s=jgt()-1;s<=0?document.body.removeAttribute(gV):document.body.setAttribute(gV,s.toString())}},[])},Ebs=function(s){var t=s.noRelative,n=s.noImportant,r=s.gapMode,a=r===void 0?"margin":r;Abs();var i=j.useMemo(function(){return kbs(a)},[a]);return j.createElement(Sbs,{styles:Cbs(i,!t,a,n?"":"!important")})},zVe=!1;if(typeof window<"u")try{var mce=Object.defineProperty({},"passive",{get:function(){return zVe=!0,!0}});window.addEventListener("test",mce,mce),window.removeEventListener("test",mce,mce)}catch{zVe=!1}var l$=zVe?{passive:!1}:!1,Tbs=function(s){return s.tagName==="TEXTAREA"},XRt=function(s,t){if(!(s instanceof Element))return!1;var n=window.getComputedStyle(s);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!Tbs(s)&&n[t]==="visible")},Mbs=function(s){return XRt(s,"overflowY")},Pbs=function(s){return XRt(s,"overflowX")},Ngt=function(s,t){var n=t.ownerDocument,r=t;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var a=QRt(s,r);if(a){var i=JRt(s,r),l=i[1],o=i[2];if(l>o)return!0}r=r.parentNode}while(r&&r!==n.body);return!1},Ibs=function(s){var t=s.scrollTop,n=s.scrollHeight,r=s.clientHeight;return[t,n,r]},Lbs=function(s){var t=s.scrollLeft,n=s.scrollWidth,r=s.clientWidth;return[t,n,r]},QRt=function(s,t){return s==="v"?Mbs(t):Pbs(t)},JRt=function(s,t){return s==="v"?Ibs(t):Lbs(t)},Rbs=function(s,t){return s==="h"&&t==="rtl"?-1:1},Dbs=function(s,t,n,r,a){var i=Rbs(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=JRt(s,o),g=f[0],x=f[1],y=f[2],v=x-y-i*g;(g||v)&&QRt(s,o)&&(h+=v,m+=g);var b=o.parentNode;o=b&&b.nodeType===Node.DOCUMENT_FRAGMENT_NODE?b.host:b}while(!c&&o!==document.body||c&&(t.contains(o)||t===o));return(u&&Math.abs(h)<1||!u&&Math.abs(m)<1)&&(d=!0),d},fce=function(s){return"changedTouches"in s?[s.changedTouches[0].clientX,s.changedTouches[0].clientY]:[0,0]},kgt=function(s){return[s.deltaX,s.deltaY]},Sgt=function(s){return s&&"current"in s?s.current:s},Fbs=function(s,t){return s[0]===t[0]&&s[1]===t[1]},Obs=function(s){return` .block-interactivity-`.concat(s,` {pointer-events: none;} .allow-interactivity-`).concat(s,` {pointer-events: all;} `)},zbs=0,c$=[];function Bbs(s){var t=j.useRef([]),n=j.useRef([0,0]),r=j.useRef(),a=j.useState(zbs++)[0],i=j.useState(ZRt)[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=obs([s.lockRef.current],(s.shards||[]).map(Sgt),!0).filter(Boolean);return x.forEach(function(y){return y.classList.add("allow-interactivity-".concat(a))}),function(){document.body.classList.remove("block-interactivity-".concat(a)),x.forEach(function(y){return y.classList.remove("allow-interactivity-".concat(a))})}}},[s.inert,s.lockRef.current,s.shards]);var o=j.useCallback(function(x,y){if("touches"in x&&x.touches.length===2||x.type==="wheel"&&x.ctrlKey)return!l.current.allowPinchZoom;var v=fce(x),b=n.current,w="deltaX"in x?x.deltaX:b[0]-v[0],S="deltaY"in x?x.deltaY:b[1]-v[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=Ngt(I,E);if(!O)return!0;if(O?A=I:(A=I==="v"?"h":"v",O=Ngt(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 Dbs(U,y,x,U==="h"?w:S)},[]),c=j.useCallback(function(x){var y=x;if(!(!c$.length||c$[c$.length-1]!==i)){var v="deltaY"in y?kgt(y):fce(y),b=t.current.filter(function(A){return A.name===y.type&&(A.target===y.target||y.target===A.shadowParent)&&Fbs(A.delta,v)})[0];if(b&&b.should){y.cancelable&&y.preventDefault();return}if(!b){var w=(l.current.shards||[]).map(Sgt).filter(Boolean).filter(function(A){return A.contains(y.target)}),S=w.length>0?o(y,w[0]):!l.current.noIsolation;S&&y.cancelable&&y.preventDefault()}}},[]),d=j.useCallback(function(x,y,v,b){var w={name:x,delta:y,target:v,should:b,shadowParent:$bs(v)};t.current.push(w),setTimeout(function(){t.current=t.current.filter(function(S){return S!==w})},1)},[]),u=j.useCallback(function(x){n.current=fce(x),r.current=void 0},[]),h=j.useCallback(function(x){d(x.type,kgt(x),x.target,o(x,s.lockRef.current))},[]),m=j.useCallback(function(x){d(x.type,fce(x),x.target,o(x,s.lockRef.current))},[]);j.useEffect(function(){return c$.push(i),s.setCallbacks({onScrollCapture:h,onWheelCapture:h,onTouchMoveCapture:m}),document.addEventListener("wheel",c,l$),document.addEventListener("touchmove",c,l$),document.addEventListener("touchstart",u,l$),function(){c$=c$.filter(function(x){return x!==i}),document.removeEventListener("wheel",c,l$),document.removeEventListener("touchmove",c,l$),document.removeEventListener("touchstart",u,l$)}},[]);var f=s.removeScrollBar,g=s.inert;return j.createElement(j.Fragment,null,g?j.createElement(i,{styles:Obs(a)}):null,f?j.createElement(Ebs,{noRelative:s.noRelative,gapMode:s.gapMode}):null)}function $bs(s){for(var t=null;s!==null;)s instanceof ShadowRoot&&(t=s.host,s=s.host),s=s.parentNode;return t}const Ubs=gbs(YRt,Bbs);var yae=j.forwardRef(function(s,t){return j.createElement(qIe,o4({},s,{ref:t,sideCar:Ubs}))});yae.classNames=qIe.classNames;var qbs=function(s){if(typeof document>"u")return null;var t=Array.isArray(s)?s[0]:s;return t.ownerDocument.body},d$=new WeakMap,pce=new WeakMap,gce={},kze=0,eDt=function(s){return s&&(s.host||eDt(s.parentNode))},Vbs=function(s,t){return t.map(function(n){if(s.contains(n))return n;var r=eDt(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})},Hbs=function(s,t,n,r){var a=Vbs(t,Array.isArray(s)?s:[s]);gce[n]||(gce[n]=new WeakMap);var i=gce[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=(d$.get(m)||0)+1,y=(i.get(m)||0)+1;d$.set(m,x),i.set(m,y),l.push(m),x===1&&g&&pce.set(m,!0),y===1&&m.setAttribute(n,"true"),g||m.setAttribute(r,"true")}catch(v){console.error("aria-hidden: cannot operate on ",m,v)}})};return u(t),o.clear(),kze++,function(){l.forEach(function(h){var m=d$.get(h)-1,f=i.get(h)-1;d$.set(h,m),i.set(h,f),m||(pce.has(h)||h.removeAttribute(r),pce.delete(h)),f||h.removeAttribute(n)}),kze--,kze||(d$=new WeakMap,d$=new WeakMap,pce=new WeakMap,gce={})}},VIe=function(s,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(s)?s:[s]),a=qbs(s);return a?(r.push.apply(r,Array.from(a.querySelectorAll("[aria-live], script"))),Hbs(r,a,n,"aria-hidden")):function(){return null}},Gbs=Object.defineProperty,O2=(s,t)=>Gbs(s,"name",{value:t,configurable:!0}),aet="Dialog",[tDt,sDt]=tp(aet),[Wbs,bC]=tDt(aet),HIe=O2(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]=hy({prop:r,defaultProp:a??!1,onChange:i,caller:aet}),[h,m]=j.useState(0),[f,g]=j.useState(0);return e.jsx(Wbs,{scope:t,triggerRef:o,contentRef:c,contentId:uy(),titleId:uy(),descriptionId:uy(),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"),Kbs="DialogTrigger",iet=j.forwardRef(O2(function(t,n){const{__scopeDialog:r,...a}=t,i=bC(Kbs,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":WIe(i.open),...a,ref:l,onClick:Ra(t.onClick,i.onOpenToggle)})},"DialogTrigger")),nDt="DialogPortal",[Ybs,rDt]=tDt(nDt,{forceMount:void 0}),GIe=O2(s=>{const{__scopeDialog:t,forceMount:n,children:r,container:a}=s,i=bC(nDt,t);return e.jsx(Ybs,{scope:t,forceMount:n,children:j.Children.map(r,l=>e.jsx(py,{present:n||i.open,children:e.jsx(gae,{asChild:!0,container:a,children:l})}))})},"DialogPortal"),BVe="DialogOverlay",qW=j.forwardRef(O2(function(t,n){const r=rDt(BVe,t.__scopeDialog),{forceMount:a=r.forceMount,...i}=t,l=bC(BVe,t.__scopeDialog);return l.modal?e.jsx(py,{present:a||l.open,children:e.jsx(Xbs,{...i,ref:n})}):null},"DialogOverlay")),Zbs=mC("DialogOverlay.RemoveScroll"),Xbs=j.forwardRef(O2(function(t,n){const{__scopeDialog:r,...a}=t,i=bC(BVe,r),l=nRt(),o=Vo(n,l);return e.jsx(yae,{as:Zbs,allowPinchZoom:!0,shards:[i.contentRef],children:e.jsx(Ei.div,{"data-state":WIe(i.open),...a,ref:o,style:{pointerEvents:"auto",...a.style}})})},"DialogOverlayImpl")),Bte="DialogContent",VW=j.forwardRef(O2(function(t,n){const r=rDt(Bte,t.__scopeDialog),{forceMount:a=r.forceMount,...i}=t,l=bC(Bte,t.__scopeDialog);return e.jsx(py,{present:a||l.open,children:l.modal?e.jsx(Qbs,{...i,ref:n}):e.jsx(Jbs,{...i,ref:n})})},"DialogContent")),Qbs=j.forwardRef(O2(function(t,n){const r=bC(Bte,t.__scopeDialog),a=j.useRef(null),i=Vo(n,r.contentRef,a);return j.useEffect(()=>{const l=a.current;if(l)return VIe(l)},[]),e.jsx(aDt,{...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")),Jbs=j.forwardRef(O2(function(t,n){const r=bC(Bte,t.__scopeDialog),a=j.useRef(!1),i=j.useRef(!1);return e.jsx(aDt,{...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")),aDt=j.forwardRef(O2(function(t,n){const{__scopeDialog:r,trapFocus:a,onOpenAutoFocus:i,onCloseAutoFocus:l,...o}=t,c=bC(Bte,r);return UW(),e.jsx(e.Fragment,{children:e.jsx(UIe,{asChild:!0,loop:!0,trapped:a,onMountAutoFocus:i,onUnmountAutoFocus:l,children:e.jsx(TB,{role:"dialog",id:c.contentId,"aria-describedby":c.descriptionPresent?c.descriptionId:void 0,"aria-labelledby":c.titlePresent?c.titleId:void 0,"data-state":WIe(c.open),...o,ref:n,deferPointerDownOutside:!0,onDismiss:()=>c.onOpenChange(!1)})})})},"DialogContentImpl")),e1s="DialogTitle",vae=j.forwardRef(O2(function(t,n){const{__scopeDialog:r,...a}=t,i=bC(e1s,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")),t1s="DialogDescription",bae=j.forwardRef(O2(function(t,n){const{__scopeDialog:r,...a}=t,i=bC(t1s,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")),s1s="DialogClose",_ae=j.forwardRef(O2(function(t,n){const{__scopeDialog:r,...a}=t,i=bC(s1s,r);return e.jsx(Ei.button,{type:"button",...a,ref:n,onClick:Ra(t.onClick,()=>i.onOpenChange(!1))})},"DialogClose"));function WIe(s){return s?"open":"closed"}O2(WIe,"getState");var n1s=Object.defineProperty,kT=(s,t)=>n1s(s,"name",{value:t,configurable:!0}),r1s="AlertDialog",[a1s,pkr]=tp(r1s,[sDt]),ST=sDt(),i1s=kT(s=>{const{__scopeAlertDialog:t,...n}=s,r=ST(t);return e.jsx(HIe,{...r,...n,modal:!0})},"AlertDialog"),o1s=j.forwardRef(kT(function(t,n){const{__scopeAlertDialog:r,...a}=t,i=ST(r);return e.jsx(iet,{...i,...a,ref:n})},"AlertDialogTrigger")),l1s=kT(s=>{const{__scopeAlertDialog:t,...n}=s,r=ST(t);return e.jsx(GIe,{...r,...n})},"AlertDialogPortal"),c1s=j.forwardRef(kT(function(t,n){const{__scopeAlertDialog:r,...a}=t,i=ST(r);return e.jsx(qW,{...i,...a,ref:n})},"AlertDialogOverlay")),d1s="AlertDialogContent",[u1s,h1s]=a1s(d1s),m1s=j.forwardRef(kT(function(t,n){const{__scopeAlertDialog:r,children:a,...i}=t,l=ST(r),o=j.useRef(null),c=Vo(n,o),d=j.useRef(null);return e.jsx(u1s,{scope:r,cancelRef:d,children:e.jsx(VW,{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")),f1s=j.forwardRef(kT(function(t,n){const{__scopeAlertDialog:r,...a}=t,i=ST(r);return e.jsx(vae,{...i,...a,ref:n})},"AlertDialogTitle")),p1s=j.forwardRef(kT(function(t,n){const{__scopeAlertDialog:r,...a}=t,i=ST(r);return e.jsx(bae,{...i,...a,ref:n})},"AlertDialogDescription")),g1s=j.forwardRef(kT(function(t,n){const{__scopeAlertDialog:r,...a}=t,i=ST(r);return e.jsx(_ae,{...i,...a,ref:n})},"AlertDialogAction")),x1s="AlertDialogCancel",y1s=j.forwardRef(kT(function(t,n){const{__scopeAlertDialog:r,...a}=t,{cancelRef:i}=h1s(x1s,r),l=ST(r),o=Vo(n,i);return e.jsx(_ae,{...l,...a,ref:o})},"AlertDialogCancel")),v1s=i1s,b1s=o1s,_1s=l1s,iDt=c1s,oDt=m1s,lDt=g1s,cDt=y1s,dDt=f1s,uDt=p1s;const hG=MB("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?YJe:"button";return e.jsx(l,{className:Pt(hG({variant:t,size:n,className:s})),ref:i,...a})});$.displayName="Button";const fc=v1s,Tg=b1s,w1s=_1s,hDt=j.forwardRef(({className:s,...t},n)=>e.jsx(iDt,{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}));hDt.displayName=iDt.displayName;const sc=j.forwardRef(({className:s,...t},n)=>e.jsxs(w1s,{children:[e.jsx(hDt,{}),e.jsx(oDt,{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=oDt.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(dDt,{ref:n,className:Pt("text-lg font-semibold",s),...t}));ac.displayName=dDt.displayName;const ic=j.forwardRef(({className:s,...t},n)=>e.jsx(uDt,{ref:n,className:Pt("text-sm text-muted-foreground",s),...t}));ic.displayName=uDt.displayName;const Yl=j.forwardRef(({className:s,...t},n)=>e.jsx(lDt,{ref:n,className:Pt(hG(),s),...t}));Yl.displayName=lDt.displayName;const oc=j.forwardRef(({className:s,...t},n)=>e.jsx(cDt,{ref:n,className:Pt(hG({variant:"outline"}),"mt-2 sm:mt-0",s),...t}));oc.displayName=cDt.displayName;let cEe=null;const j1s=["delete","remove","revoke","cannot be undone","permanently"];function fo(s,t={}){const n=typeof s=="string"?{description:s,...t}:s,r=`${n.title??""} ${n.description??""}`.toLowerCase(),a=n.destructive??j1s.some(i=>r.includes(i));return new Promise(i=>{if(!cEe){i(window.confirm(n.description??n.title??"Are you sure?"));return}cEe({...n,destructive:a,resolve:i})})}function N1s(){const[s,t]=j.useState(null);j.useEffect(()=>(cEe=a=>t(a),()=>{cEe=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 k1s=["top","right","bottom","left"],_L=Math.min,zE=Math.max,dEe=Math.round,xce=Math.floor,BE=s=>({x:s,y:s}),S1s={left:"right",right:"left",bottom:"top",top:"bottom"};function mDt(s,t,n){return zE(s,_L(t,n))}function lT(s,t){return typeof s=="function"?s(t):s}function wL(s){return s.split("-")[0]}function HW(s){return s.split("-")[1]}function oet(s){return s==="x"?"y":"x"}function cet(s){return s==="y"?"height":"width"}function f4(s){const t=s[0];return t==="t"||t==="b"?"y":"x"}function det(s){return oet(f4(s))}function C1s(s,t,n){n===void 0&&(n=!1);const r=HW(s),a=det(s),i=cet(a);let l=a==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[i]>t.floating[i]&&(l=uEe(l)),[l,uEe(l)]}function A1s(s){const t=uEe(s);return[$Ve(s),t,$Ve(t)]}function $Ve(s){return s.includes("start")?s.replace("start","end"):s.replace("end","start")}const Cgt=["left","right"],Agt=["right","left"],E1s=["top","bottom"],T1s=["bottom","top"];function M1s(s,t,n){switch(s){case"top":case"bottom":return n?t?Agt:Cgt:t?Cgt:Agt;case"left":case"right":return t?E1s:T1s;default:return[]}}function P1s(s,t,n,r){const a=HW(s);let i=M1s(wL(s),n==="start",r);return a&&(i=i.map(l=>l+"-"+a),t&&(i=i.concat(i.map($Ve)))),i}function uEe(s){const t=wL(s);return S1s[t]+s.slice(t.length)}function I1s(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 fDt(s){return typeof s!="number"?I1s(s):{top:s,right:s,bottom:s,left:s}}function hEe(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 Egt(s,t,n){let{reference:r,floating:a}=s;const i=f4(t),l=det(t),o=cet(l),c=wL(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=HW(t);return g&&(f[l]+=m*(g==="end"?1:-1)*(n&&d?-1:1)),f}async function L1s(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}=lT(t,s),g=fDt(f),y=o[m?h==="floating"?"reference":"floating":h],v=hEe(await i.getClippingRect({element:(n=await(i.isElement==null?void 0:i.isElement(y)))==null||n?y:y.contextElement||await(i.getDocumentElement==null?void 0:i.getDocumentElement(o.floating)),boundary:d,rootBoundary:u,strategy:c})),b=h==="floating"?{x:r,y:a,width:l.floating.width,height:l.floating.height}:l.reference,w=await(i.getOffsetParent==null?void 0:i.getOffsetParent(o.floating)),S=await(i.isElement==null?void 0:i.isElement(w))&&await(i.getScale==null?void 0:i.getScale(w))||{x:1,y:1},A=hEe(i.convertOffsetParentRelativeRectToViewportRelativeRect?await i.convertOffsetParentRelativeRectToViewportRelativeRect({elements:o,rect:b,offsetParent:w,strategy:c}):b);return{top:(v.top-A.top+g.top)/S.y,bottom:(A.bottom-v.bottom+g.bottom)/S.y,left:(v.left-A.left+g.left)/S.x,right:(A.right-v.right+g.right)/S.x}}const R1s=50,D1s=async(s,t,n)=>{const{placement:r="bottom",strategy:a="absolute",middleware:i=[],platform:l}=n,o=l.detectOverflow?l:{...l,detectOverflow:L1s},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}=Egt(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}=lT(s,t)||{};if(d==null)return{};const h=fDt(u),m={x:n,y:r},f=det(a),g=cet(f),x=await l.getDimensions(d),y=f==="y",v=y?"top":"left",b=y?"bottom":"right",w=y?"clientHeight":"clientWidth",S=i.reference[g]+i.reference[f]-m[f]-i.floating[g],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=_L(h[v],R),O=_L(h[b],R),U=I-x[g]-O,W=I/2-x[g]/2+P,V=mDt(D,W,U),G=!c.arrow&&HW(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!==f4(G):!1)||D.every(ae=>f4(ae.placement)===b?ae.overflows[0]>0:!0)))return{data:{index:V,overflows:D},reset:{placement:G}};let Y=(U=D.filter(X=>X.overflows[0]<=0).sort((X,ae)=>X.overflows[1]-ae.overflows[1])[0])==null?void 0:U.placement;if(!Y)switch(f){case"bestFit":{var W;const X=(W=D.filter(ae=>{if(E){const le=f4(ae.placement);return le===b||le==="y"}return!0}).map(ae=>[ae.placement,ae.overflows.filter(le=>le>0).reduce((le,ne)=>le+ne,0)]).sort((ae,le)=>ae[1]-le[1])[0])==null?void 0:W[0];X&&(Y=X);break}case"initialPlacement":Y=o;break}if(a!==Y)return{reset:{placement:Y}}}return{}}}};function Tgt(s,t){return{top:s.top-t.height,right:s.right-t.width,bottom:s.bottom-t.height,left:s.left-t.width}}function Mgt(s){return k1s.some(t=>s[t]>=0)}const z1s=function(s){return s===void 0&&(s={}),{name:"hide",options:s,async fn(t){const{rects:n,platform:r}=t,{strategy:a="referenceHidden",...i}=lT(s,t);switch(a){case"referenceHidden":{const l=await r.detectOverflow(t,{...i,elementContext:"reference"}),o=Tgt(l,n.reference);return{data:{referenceHiddenOffsets:o,referenceHidden:Mgt(o)}}}case"escaped":{const l=await r.detectOverflow(t,{...i,altBoundary:!0}),o=Tgt(l,n.floating);return{data:{escapedOffsets:o,escaped:Mgt(o)}}}default:return{}}}}},pDt=new Set(["left","top"]);async function B1s(s,t){const{placement:n,platform:r,elements:a}=s,i=await(r.isRTL==null?void 0:r.isRTL(a.floating)),l=wL(n),o=HW(n),c=f4(n)==="y",d=pDt.has(l)?-1:1,u=i&&c?-1:1,h=lT(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 $1s=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 B1s(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}}}}},U1s=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}=lT(s,t),u={x:n,y:r},h=await i.detectOverflow(t,d),m=f4(a),f=oet(m);let g=u[f],x=u[m];const y=(b,w)=>mDt(w+h[b==="y"?"top":"left"],w,w-h[b==="y"?"bottom":"right"]);l&&(g=y(f,g)),o&&(x=y(m,x));const v=c.fn({...t,[f]:g,[m]:x});return{...v,data:{x:v.x-n,y:v.y-r,enabled:{[f]:l,[m]:o}}}}}},q1s=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}=lT(s,t),m={x:a,y:i},f=f4(l),g=oet(f);let x=m[g],y=m[f];const v=lT(d,t),b=typeof v=="number"?{mainAxis:v,crossAxis:0}:{mainAxis:(n=v.mainAxis)!=null?n:0,crossAxis:(r=v.crossAxis)!=null?r:0};if(u){const 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=pDt.has(wL(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);yP&&(y=P)}return{[g]:x,[f]:y}}}},V1s=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}=lT(s,t),c=await a.detectOverflow(t,o),d=wL(n),u=HW(n),h=f4(n)==="y",{width:m,height:f}=r.floating;let g,x;d==="top"||d==="bottom"?(g=d,x=u===(await(a.isRTL==null?void 0:a.isRTL(i.floating))?"start":"end")?"left":"right"):(x=d,g=u==="end"?"top":"bottom");const y=f-c.top-c.bottom,v=m-c.left-c.right,b=_L(f-c[g],y),w=_L(m-c[x],v),S=t.middlewareData.shift,A=!S;let E=b,I=w;S!=null&&S.enabled.x&&(I=v),S!=null&&S.enabled.y&&(E=y),A&&!u&&(h?I=m-2*zE(c.left,c.right):E=f-2*zE(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 KIe(){return typeof window<"u"}function GW(s){return gDt(s)?(s.nodeName||"").toLowerCase():"#document"}function Tw(s){var t;return(s==null||(t=s.ownerDocument)==null?void 0:t.defaultView)||window}function CT(s){var t;return(t=(gDt(s)?s.ownerDocument:s.document)||window.document)==null?void 0:t.documentElement}function gDt(s){return KIe()?s instanceof Node||s instanceof Tw(s).Node:!1}function q4(s){return KIe()?s instanceof Element||s instanceof Tw(s).Element:!1}function JL(s){return KIe()?s instanceof HTMLElement||s instanceof Tw(s).HTMLElement:!1}function Pgt(s){return!KIe()||typeof ShadowRoot>"u"?!1:s instanceof ShadowRoot||s instanceof Tw(s).ShadowRoot}function YIe(s){const{overflow:t,overflowX:n,overflowY:r,display:a}=V4(s);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&a!=="inline"&&a!=="contents"}function H1s(s){return/^(table|td|th)$/.test(GW(s))}function ZIe(s){try{if(s.matches(":popover-open"))return!0}catch{}try{return s.matches(":modal")}catch{return!1}}const G1s=/transform|translate|scale|rotate|perspective|filter/,W1s=/paint|layout|strict|content/,cR=s=>!!s&&s!=="none";let Sze;function uet(s){const t=q4(s)?V4(s):s;return cR(t.transform)||cR(t.translate)||cR(t.scale)||cR(t.rotate)||cR(t.perspective)||!het()&&(cR(t.backdropFilter)||cR(t.filter))||G1s.test(t.willChange||"")||W1s.test(t.contain||"")}function K1s(s){let t=F7(s);for(;JL(t)&&!$te(t);){if(uet(t))return t;if(ZIe(t))return null;t=F7(t)}return null}function het(){return Sze==null&&(Sze=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),Sze}function $te(s){return/^(html|body|#document)$/.test(GW(s))}function V4(s){return Tw(s).getComputedStyle(s)}function XIe(s){return q4(s)?{scrollLeft:s.scrollLeft,scrollTop:s.scrollTop}:{scrollLeft:s.scrollX,scrollTop:s.scrollY}}function F7(s){if(GW(s)==="html")return s;const t=s.assignedSlot||s.parentNode||Pgt(s)&&s.host||CT(s);return Pgt(t)?t.host:t}function xDt(s){const t=F7(s);return $te(t)?(s.ownerDocument||s).body:JL(t)&&YIe(t)?t:xDt(t)}function Ute(s,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const a=xDt(s),i=a===((r=s.ownerDocument)==null?void 0:r.body),l=Tw(a);if(i){const o=UVe(l);return t.concat(l,l.visualViewport||[],YIe(a)?a:[],o&&n?Ute(o):[])}else return t.concat(a,Ute(a,[],n))}function UVe(s){return s.parent&&Object.getPrototypeOf(s.parent)?s.frameElement:null}function yDt(s){const t=V4(s);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const a=JL(s),i=a?s.offsetWidth:n,l=a?s.offsetHeight:r,o=dEe(n)!==i||dEe(r)!==l;return o&&(n=i,r=l),{width:n,height:r,$:o}}function met(s){return q4(s)?s:s.contextElement}function xV(s){const t=met(s);if(!JL(t))return BE(1);const n=t.getBoundingClientRect(),{width:r,height:a,$:i}=yDt(t);let l=(i?dEe(n.width):n.width)/r,o=(i?dEe(n.height):n.height)/a;return(!l||!Number.isFinite(l))&&(l=1),(!o||!Number.isFinite(o))&&(o=1),{x:l,y:o}}const Y1s=BE(0);function vDt(s){const t=Tw(s);return!het()||!t.visualViewport?Y1s:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function Z1s(s,t,n){return t===void 0&&(t=!1),!!n&&t&&n===Tw(s)}function O7(s,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const a=s.getBoundingClientRect(),i=met(s);let l=BE(1);t&&(r?q4(r)&&(l=xV(r)):l=xV(s));const o=Z1s(i,n,r)?vDt(i):BE(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=Tw(i),f=q4(r)?Tw(r):r;let g=m,x=UVe(g);for(;x&&f!==g;){const y=xV(x),v=x.getBoundingClientRect(),b=V4(x),w=v.left+(x.clientLeft+parseFloat(b.paddingLeft))*y.x,S=v.top+(x.clientTop+parseFloat(b.paddingTop))*y.y;c*=y.x,d*=y.y,u*=y.x,h*=y.y,c+=w,d+=S,g=Tw(x),x=UVe(g)}}return hEe({width:u,height:h,x:c,y:d})}function QIe(s,t){const n=XIe(s).scrollLeft;return t?t.left+n:O7(CT(s)).left+n}function bDt(s,t){const n=s.getBoundingClientRect(),r=n.left+t.scrollLeft-QIe(s,n),a=n.top+t.scrollTop;return{x:r,y:a}}function X1s(s){let{elements:t,rect:n,offsetParent:r,strategy:a}=s;const i=a==="fixed",l=CT(r),o=t?ZIe(t.floating):!1;if(r===l||o&&i)return n;let c={scrollLeft:0,scrollTop:0},d=BE(1);const u=BE(0),h=JL(r);if((h||!i)&&((GW(r)!=="body"||YIe(l))&&(c=XIe(r)),h)){const f=O7(r);d=xV(r),u.x=f.x+r.clientLeft,u.y=f.y+r.clientTop}const m=l&&!h&&!i?bDt(l,c):BE(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 Q1s(s){return s.getClientRects?Array.from(s.getClientRects()):[]}function J1s(s){const t=XIe(s),n=s.ownerDocument.body,r=zE(s.scrollWidth,s.clientWidth,n.scrollWidth,n.clientWidth),a=zE(s.scrollHeight,s.clientHeight,n.scrollHeight,n.clientHeight);let i=-t.scrollLeft+QIe(s);const l=-t.scrollTop;return V4(n).direction==="rtl"&&(i+=zE(s.clientWidth,n.clientWidth)-r),{width:r,height:a,x:i,y:l}}const e_s=25;function t_s(s,t,n){n===void 0&&(n="viewport");const r=n==="layoutViewport",a=Tw(s),i=CT(s),l=a.visualViewport;let o=i.clientWidth,c=i.clientHeight,d=0,u=0;if(l){const m=!het()||t==="fixed";r?m||(d=-l.offsetLeft,u=-l.offsetTop):(o=l.width,c=l.height,m&&(d=l.offsetLeft,u=l.offsetTop))}if(QIe(i)<=0){const m=i.ownerDocument,f=m.body,g=getComputedStyle(f),x=m.compatMode==="CSS1Compat"&&parseFloat(g.marginLeft)+parseFloat(g.marginRight)||0,y=Math.abs(i.clientWidth-f.clientWidth-x),v=getComputedStyle(i).scrollbarGutter==="stable both-edges"?y/2:y;v<=e_s&&(o-=v)}return{width:o,height:c,x:d,y:u}}function s_s(s,t){const n=O7(s,!0,t==="fixed"),r=n.top+s.clientTop,a=n.left+s.clientLeft,i=xV(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 Igt(s,t,n){let r;if(t==="viewport"||t==="layoutViewport")r=t_s(s,n,t);else if(t==="document")r=J1s(CT(s));else if(q4(t))r=s_s(t,n);else{const a=vDt(s);r={x:t.x-a.x,y:t.y-a.y,width:t.width,height:t.height}}return hEe(r)}function n_s(s,t){const n=t.get(s);if(n)return n;let r=Ute(s,[],!1).filter(o=>q4(o)&&GW(o)!=="body"),a=null;const i=V4(s).position==="fixed";let l=i?F7(s):s;for(;q4(l)&&!$te(l);){const o=V4(l),c=uet(l),d=a?a.position:i?"fixed":"";!c&&(d==="fixed"||d==="absolute"&&o.position==="static")?r=r.filter(h=>h!==l):a=o,l=F7(l)}return t.set(s,r),r}function r_s(s){let{element:t,boundary:n,rootBoundary:r,strategy:a}=s;const l=[...n==="clippingAncestors"?ZIe(t)?[]:n_s(t,this._c):[].concat(n),r],o=Igt(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=Tw(s),d=()=>o(n);return c.addEventListener("resize",d),o(!0),()=>{c.removeEventListener("resize",d),l()}}function u_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=met(s),u=a||i?[...d?Ute(d):[],...t?Ute(t):[]]:[];u.forEach(v=>{a&&v.addEventListener("scroll",n),i&&v.addEventListener("resize",n)});const h=d&&o?d_s(d,n,i):null;let m=-1,f=null;l&&(f=new ResizeObserver(v=>{let[b]=v;b&&b.target===d&&f&&t&&(f.unobserve(t),cancelAnimationFrame(m),m=requestAnimationFrame(()=>{var w;(w=f)==null||w.observe(t)})),n()}),d&&!c&&f.observe(d),t&&f.observe(t));let g,x=c?O7(s):null;c&&y();function y(){const v=O7(s);x&&!wDt(x,v)&&n(),x=v,g=requestAnimationFrame(y)}return n(),()=>{var v;u.forEach(b=>{a&&b.removeEventListener("scroll",n),i&&b.removeEventListener("resize",n)}),h==null||h(),(v=f)==null||v.disconnect(),f=null,c&&cancelAnimationFrame(g)}}const h_s=$1s,m_s=U1s,f_s=O1s,p_s=V1s,g_s=z1s,Rgt=F1s,x_s=q1s,y_s=(s,t,n)=>{const r=new Map,a=n??{},i={...c_s,...a.platform,_c:r};return D1s(s,t,{...a,platform:i})};var v_s=typeof document<"u",b_s=function(){},B4e=v_s?j.useLayoutEffect:b_s;function mEe(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(!mEe(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)&&!mEe(s[i],t[i]))return!1}return!0}return s!==s&&t!==t}function jDt(s){return typeof window>"u"?1:(s.ownerDocument.defaultView||window).devicePixelRatio||1}function Dgt(s,t){const n=jDt(s);return Math.round(t*n)/n}function Aze(s){const t=j.useRef(s);return B4e(()=>{t.current=s}),t}function __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);mEe(m,r)||f(r);const[g,x]=j.useState(null),[y,v]=j.useState(null),b=j.useCallback(ae=>{ae!==E.current&&(E.current=ae,x(ae))},[]),w=j.useCallback(ae=>{ae!==I.current&&(I.current=ae,v(ae))},[]),S=i||g,A=l||y,E=j.useRef(null),I=j.useRef(null),P=j.useRef(u),R=c!=null,D=Aze(c),O=Aze(a),U=Aze(d),W=j.useCallback(()=>{if(!E.current||!I.current)return;const ae={placement:t,strategy:n,middleware:m};O.current&&(ae.platform=O.current),y_s(E.current,I.current,ae).then(le=>{const ne={...le,isPositioned:U.current!==!1};V.current&&!mEe(P.current,ne)&&(P.current=ne,vv.flushSync(()=>{h(ne)}))})},[m,t,n,O,U]);B4e(()=>{d===!1&&P.current.isPositioned&&(P.current.isPositioned=!1,h(ae=>({...ae,isPositioned:!1})))},[d]);const V=j.useRef(!1);B4e(()=>(V.current=!0,()=>{V.current=!1}),[]),B4e(()=>{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]),Y=j.useMemo(()=>({reference:S,floating:A}),[S,A]),X=j.useMemo(()=>{const ae={position:n,left:0,top:0};if(!Y.floating)return ae;const le=Dgt(Y.floating,u.x),ne=Dgt(Y.floating,u.y);return o?{...ae,transform:"translate("+le+"px, "+ne+"px)",...jDt(Y.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:le,top:ne}},[n,o,Y.floating,u.x,u.y]);return j.useMemo(()=>({...u,update:W,refs:G,elements:Y,floatingStyles:X}),[u,W,G,Y,X])}const w_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?Rgt({element:r.current,padding:a}).fn(n):{}:r?Rgt({element:r,padding:a}).fn(n):{}}}},j_s=(s,t)=>{const n=h_s(s);return{name:n.name,fn:n.fn,options:[s,t]}},N_s=(s,t)=>{const n=m_s(s);return{name:n.name,fn:n.fn,options:[s,t]}},k_s=(s,t)=>({fn:x_s(s).fn,options:[s,t]}),S_s=(s,t)=>{const n=f_s(s);return{name:n.name,fn:n.fn,options:[s,t]}},C_s=(s,t)=>{const n=p_s(s);return{name:n.name,fn:n.fn,options:[s,t]}},A_s=(s,t)=>{const n=g_s(s);return{name:n.name,fn:n.fn,options:[s,t]}},E_s=(s,t)=>{const n=w_s(s);return{name:n.name,fn:n.fn,options:[s,t]}};var T_s=Object.defineProperty,M_s=(s,t)=>T_s(s,"name",{value:t,configurable:!0});function WW(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}M_s(WW,"useSize");var P_s=Object.defineProperty,sL=(s,t)=>P_s(s,"name",{value:t,configurable:!0}),NDt="Popper",[kDt,r3]=tp(NDt),[I_s,SDt]=kDt(NDt),L_s=sL(s=>{const{__scopePopper:t,children:n}=s,[r,a]=j.useState(null),[i,l]=j.useState(void 0);return e.jsx(I_s,{scope:t,anchor:r,onAnchorChange:a,placementState:i,setPlacementState:l,children:n})},"Popper"),R_s="PopperAnchor",D_s=j.forwardRef(sL(function(t,n){const{__scopePopper:r,virtualRef:a,...i}=t,l=SDt(R_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&&JIe(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")),CDt="PopperContent",[F_s,gkr]=kDt(CDt),O_s=j.forwardRef(sL(function(t,n){var Se,Le,Fe,ke,Be,Ne,Ae;const{__scopePopper:r,side:a="bottom",sideOffset:i=0,align:l="center",alignOffset:o=0,arrowPadding:c=0,avoidCollisions:d=!0,collisionBoundary:u=[],collisionPadding:h=0,sticky:m="partial",hideWhenDetached:f=!1,updatePositionStrategy:g="optimized",onPlaced:x,...y}=t,v=SDt(CDt,r),[b,w]=j.useState(null),S=Vo(n,w),[A,E]=j.useState(null),I=WW(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(ADt),altBoundary:W},{refs:G,floatingStyles:Y,placement:X,isPositioned:ae,middlewareData:le}=__s({strategy:"fixed",placement:D,whileElementsMounted:sL((...Ce)=>u_s(...Ce,{animationFrame:g==="always"}),"whileElementsMounted"),elements:{reference:v.anchor},middleware:[j_s({mainAxis:i+R,alignmentAxis:o}),d&&N_s({mainAxis:!0,crossAxis:!1,limiter:m==="partial"?k_s():void 0,...V}),d&&S_s({...V}),C_s({...V,apply:sL(({elements:Ce,rects:Ve,availableWidth:ze,availableHeight:qe})=>{const{width:dt,height:Xe}=Ve.reference,at=Ce.floating.style;at.setProperty("--radix-popper-available-width",`${ze}px`),at.setProperty("--radix-popper-available-height",`${qe}px`),at.setProperty("--radix-popper-anchor-width",`${dt}px`),at.setProperty("--radix-popper-anchor-height",`${Xe}px`)},"apply")}),A&&E_s({element:A,padding:c}),z_s({arrowWidth:P,arrowHeight:R}),f&&A_s({strategy:"referenceHidden",...V,boundary:W?V.boundary:void 0})]}),ne=v.setPlacementState;Af(()=>(ne(X),()=>{ne(void 0)}),[X,ne]);const[te,J]=JIe(X),ce=Zp(x);Af(()=>{ae&&(ce==null||ce())},[ae,ce]);const _e=(Se=le.arrow)==null?void 0:Se.x,he=(Le=le.arrow)==null?void 0:Le.y,ue=((Fe=le.arrow)==null?void 0:Fe.centerOffset)!==0,[ve,Ee]=j.useState();return Af(()=>{b&&Ee(window.getComputedStyle(b).zIndex)},[b]),e.jsx("div",{ref:G.setFloating,"data-radix-popper-content-wrapper":"",style:{...Y,transform:ae?Y.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:ve,"--radix-popper-transform-origin":[(ke=le.transformOrigin)==null?void 0:ke.x,(Be=le.transformOrigin)==null?void 0:Be.y].join(" "),...((Ne=le.hide)==null?void 0:Ne.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:t.dir,children:e.jsx(F_s,{scope:r,placedSide:te,placedAlign:J,onArrowChange:E,arrowX:_e,arrowY:he,shouldHideArrow:ue,children:e.jsx(Ei.div,{"data-side":te,"data-align":J,...y,ref:S,style:{...y.style,animation:ae?(Ae=y.style)==null?void 0:Ae.animation:"none"}})})})},"PopperContent"));function ADt(s){return s!==null}sL(ADt,"isNotNull");var z_s=sL(s=>({name:"transformOrigin",options:s,fn(t){var y,v,b;const{placement:n,rects:r,middlewareData:a}=t,l=((y=a.arrow)==null?void 0:y.centerOffset)!==0,o=l?0:s.arrowWidth,c=l?0:s.arrowHeight,[d,u]=JIe(n),h={start:"0%",center:"50%",end:"100%"}[u],m=(((v=a.arrow)==null?void 0:v.x)??0)+o/2,f=(((b=a.arrow)==null?void 0:b.y)??0)+c/2;let g="",x="";return d==="bottom"?(g=l?h:`${m}px`,x=`${-c}px`):d==="top"?(g=l?h:`${m}px`,x=`${r.floating.height+c}px`):d==="right"?(g=`${-c}px`,x=l?h:`${f}px`):d==="left"&&(g=`${r.floating.width+c}px`,x=l?h:`${f}px`),{data:{x:g,y:x}}}}),"transformOrigin");function JIe(s){const[t,n="center"]=s.split("-");return[t,n]}sL(JIe,"getSideAndAlignFromPlacement");var wae=L_s,jae=D_s,Nae=O_s,B_s=Object.defineProperty,db=(s,t)=>B_s(s,"name",{value:t,configurable:!0}),[fet,xkr]=tp("Tooltip",[r3]),pet=r3(),$_s="TooltipProvider",U_s=700,qVe="tooltip.open",[q_s,get]=fet($_s),V_s=db(s=>{const{__scopeTooltip:t,delayDuration:n=U_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(q_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"),VVe="Tooltip",[H_s,eLe]=fet(VVe),G_s=db(s=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:a,onOpenChange:i,disableHoverableContent:l,delayDuration:o}=s,c=get(VVe,s.__scopeTooltip),d=pet(t),[u,h]=j.useState(null),[m,f]=j.useState(void 0),g=uy(),x=j.useRef(0),y=l??c.disableHoverableContent,v=o??c.delayDuration,b=j.useRef(!1),[w,S]=hy({prop:r,defaultProp:a??!1,onChange:db(D=>{D?(c.onOpen(),document.dispatchEvent(new CustomEvent(qVe))):c.onClose(),i==null||i(D)},"onChange"),caller:VVe}),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},v)},[v,S]);j.useEffect(()=>()=>{x.current&&(window.clearTimeout(x.current),x.current=0)},[]);const R=m??g;return e.jsx(wae,{...d,children:e.jsx(H_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(()=>{y?I():(window.clearTimeout(x.current),x.current=0)},[I,y]),onOpen:E,onClose:I,disableHoverableContent:y,children:n})})},"Tooltip"),Fgt="TooltipTrigger",W_s=j.forwardRef(db(function(t,n){const{__scopeTooltip:r,...a}=t,i=eLe(Fgt,r),l=get(Fgt,r),o=pet(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(jae,{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")),K_s="TooltipPortal",[ykr,Y_s]=fet(K_s,{forceMount:void 0}),qte="TooltipContent",Z_s=j.forwardRef(db(function(t,n){const r=Y_s(qte,t.__scopeTooltip),{forceMount:a=r.forceMount,side:i="top",...l}=t,o=eLe(qte,t.__scopeTooltip);return e.jsx(py,{present:a||o.open,children:o.disableHoverableContent?e.jsx(EDt,{side:i,...l,ref:n}):e.jsx(X_s,{side:i,...l,ref:n})})},"TooltipContent")),X_s=j.forwardRef(db(function(t,n){const r=eLe(qte,t.__scopeTooltip),a=get(qte,t.__scopeTooltip),i=j.useRef(null),l=Vo(n,i),[o,c]=j.useState(null),{trigger:d,onClose:u}=r,h=i.current,{onPointerInTransitChange:m}=a,f=j.useCallback(()=>{c(null),m(!1)},[m]),g=j.useCallback((x,y)=>{const v=x.currentTarget,b={x:x.clientX,y:x.clientY},w=TDt(b,v.getBoundingClientRect()),S=MDt(b,w),A=PDt(y.getBoundingClientRect()),E=LDt([...S,...A]);c(E),m(!0)},[m]);return j.useEffect(()=>()=>f(),[f]),j.useEffect(()=>{if(d&&h){const x=db(v=>g(v,h),"handleTriggerLeave"),y=db(v=>g(v,d),"handleContentLeave");return d.addEventListener("pointerleave",x),h.addEventListener("pointerleave",y),()=>{d.removeEventListener("pointerleave",x),h.removeEventListener("pointerleave",y)}}},[d,h,g,f]),j.useEffect(()=>{if(o){const x=db(y=>{const v=y.target,b={x:y.clientX,y:y.clientY},w=(d==null?void 0:d.contains(v))||(h==null?void 0:h.contains(v)),S=!IDt(b,o);w?f():S&&(f(),u())},"handleTrackPointerGrace");return document.addEventListener("pointermove",x),()=>document.removeEventListener("pointermove",x)}},[d,h,o,u,f]),e.jsx(EDt,{...t,ref:l})},"TooltipContentHoverable")),Q_s=K6t("TooltipContent"),EDt=j.forwardRef(db(function(t,n){const{__scopeTooltip:r,children:a,"aria-label":i,id:l,onEscapeKeyDown:o,onPointerDownOutside:c,...d}=t,u=eLe(qte,r),h=pet(r),{onClose:m}=u;j.useEffect(()=>(document.addEventListener(qVe,m),()=>document.removeEventListener(qVe,m)),[m]),j.useEffect(()=>{if(u.trigger){const g=db(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(TB,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:o,onPointerDownOutside:c,onFocusOutside:g=>g.preventDefault(),onDismiss:m,children:e.jsxs(Nae,{"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(Q_s,{children:a}),i?e.jsx(m0s,{id:u.contentId,role:"tooltip",children:i}):null]})})},"TooltipContentImpl"));function TDt(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")}}db(TDt,"getExitSideFromRect");function MDt(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}db(MDt,"getPaddedExitPoints");function PDt(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}]}db(PDt,"getPointsFromRect");function IDt(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}db(IDt,"isPointInPolygon");function LDt(s){const t=s.slice();return t.sort((n,r)=>n.xr.x?1:n.yr.y?1:0),RDt(t)}db(LDt,"getHull");function RDt(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)}db(RDt,"getHullPresorted");var J_s=V_s,ews=G_s,tws=W_s,DDt=Z_s;const bk=J_s,iy=ews,oy=tws,jx=j.forwardRef(({className:s,sideOffset:t=4,...n},r)=>e.jsx(DDt,{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}));jx.displayName=DDt.displayName;const FDt=j.createContext(void 0),Wt=s=>{const t=j.useContext(FDt);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},sws=({client:s,children:t})=>(j.useEffect(()=>(s.mount(),()=>{s.unmount()}),[s]),e.jsx(FDt.Provider,{value:s,children:t})),nws={setTimeout:(s,t)=>setTimeout(s,t),clearTimeout:s=>clearTimeout(s),setInterval:(s,t)=>setInterval(s,t),clearInterval:s=>clearInterval(s)};var MP,JQe,pIt,rws=(pIt=class{constructor(){vs(this,MP,nws);vs(this,JQe,!1)}setTimeoutProvider(s){Kt(this,MP,s)}setTimeout(s,t){return ye(this,MP).setTimeout(s,t)}clearTimeout(s){ye(this,MP).clearTimeout(s)}setInterval(s,t){return ye(this,MP).setInterval(s,t)}clearInterval(s){ye(this,MP).clearInterval(s)}},MP=new WeakMap,JQe=new WeakMap,pIt);const r8=new rws;function aws(s){setTimeout(s,0)}const iws=typeof window>"u"||"Deno"in globalThis;function i_(){}function ows(s,t){return typeof s=="function"?s(t):s}function ODt(s){return typeof s=="number"&&s>=0&&s!==1/0}function zDt(s,t){return Math.max(s+(t||0)-Date.now(),0)}function Hp(s,t){return typeof s=="function"?s(t):s}function Ogt(s,t){const{type:n="all",exact:r,fetchStatus:a,predicate:i,queryKey:l,stale:o}=s;if(l){if(r){if(t.queryHash!==xet(l,t.options))return!1}else if(!mG(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 zgt(s,t){const{exact:n,status:r,predicate:a,mutationKey:i}=s;if(i){if(!t.options.mutationKey)return!1;if(n){if(z7(t.options.mutationKey)!==z7(i))return!1}else if(!mG(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||a&&!a(t))}function xet(s,t){return((t==null?void 0:t.queryKeyHashFn)||z7)(s)}function z7(s){return JSON.stringify(s,(t,n)=>HVe(n)?Object.keys(n).sort().reduce((r,a)=>(r[a]=n[a],r),{}):n)}function mG(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=Bgt(s)&&Bgt(t);if(!r&&!(HVe(s)&&HVe(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{r8.setTimeout(t,s)})}function GVe(s,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(s,t):n.structuralSharing!==!1?BDt(s,t):t}function dws(s,t,n=0){const r=[...s,t];return n&&r.length>n?r.slice(1):r}function uws(s,t,n=0){const r=[t,...s];return n&&r.length>n?r.slice(0,-1):r}const yet=Symbol();function $Dt(s,t){return!s.queryFn&&(t!=null&&t.initialPromise)?()=>t.initialPromise:!s.queryFn||s.queryFn===yet?()=>Promise.reject(new Error(`Missing queryFn: '${s.queryHash}'`)):s.queryFn}function vet(s,t){return typeof s=="function"?s(...t):!!s}function hws(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 mws=()=>iws;const bet=()=>mws();var KW=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(){}},S8,PP,KV,gIt,fws=(gIt=class extends KW{constructor(){super();vs(this,S8);vs(this,PP);vs(this,KV);Kt(this,KV,t=>{if(typeof window<"u"&&window.addEventListener){const n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){ye(this,PP)||this.setEventListener(ye(this,KV))}onUnsubscribe(){var t;this.hasListeners()||((t=ye(this,PP))==null||t.call(this),Kt(this,PP,void 0))}setEventListener(t){var n;Kt(this,KV,t),(n=ye(this,PP))==null||n.call(this),Kt(this,PP,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){ye(this,S8)!==t&&(Kt(this,S8,t),this.onFocus())}onFocus(){const t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){var t;return typeof ye(this,S8)=="boolean"?ye(this,S8):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},S8=new WeakMap,PP=new WeakMap,KV=new WeakMap,gIt);const _et=new fws,pws=aws;function gws(){let s=[],t=0,n=o=>{o()},r=o=>{o()},a=pws;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 v0=gws();var YV,IP,ZV,xIt,xws=(xIt=class extends KW{constructor(){super();vs(this,YV,!0);vs(this,IP);vs(this,ZV);Kt(this,ZV,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,IP)||this.setEventListener(ye(this,ZV))}onUnsubscribe(){var t;this.hasListeners()||((t=ye(this,IP))==null||t.call(this),Kt(this,IP,void 0))}setEventListener(t){var n;Kt(this,ZV,t),(n=ye(this,IP))==null||n.call(this),Kt(this,IP,t(this.setOnline.bind(this)))}setOnline(t){ye(this,YV)!==t&&(Kt(this,YV,t),this.listeners.forEach(n=>{n(t)}))}isOnline(){return ye(this,YV)}},YV=new WeakMap,IP=new WeakMap,ZV=new WeakMap,xIt);const fEe=new xws;function yws(s){return Math.min(1e3*2**s,3e4)}function UDt(s){return(s??"online")==="online"?fEe.isOnline():!0}var WVe=class extends Error{constructor(s){super("CancelledError"),this.revert=s==null?void 0:s.revert,this.silent=s==null?void 0:s.silent}};function qDt(s){let t=!1,n=0,r,a="pending",i,l;const o=new Promise((b,w)=>{i=b,l=w});o.catch(i_);const c=()=>a!=="pending",d=b=>{var w;if(!c()){const S=new WVe(b);x(S),(w=s.onCancel)==null||w.call(s,S)}},u=()=>{t=!0},h=()=>{t=!1},m=()=>_et.isFocused()&&(s.networkMode==="always"||fEe.isOnline())&&s.canRun(),f=()=>UDt(s.networkMode)&&s.canRun(),g=b=>{c()||(r==null||r(),a="resolved",i(b))},x=b=>{c()||(r==null||r(),a="rejected",l(b))},y=()=>new Promise(b=>{var w;r=S=>{(c()||m())&&b(S)},(w=s.onPause)==null||w.call(s)}).then(()=>{var b;r=void 0,c()||(b=s.onContinue)==null||b.call(s)}),v=()=>{if(c())return;let b;const w=n===0?s.initialPromise:void 0;try{b=w??s.fn()}catch(S){b=Promise.reject(S)}Promise.resolve(b).then(g).catch(S=>{var R;if(c())return;const A=s.retry??(bet()?0:3),E=s.retryDelay??yws,I=typeof E=="function"?E(n,S):E,P=A===!0||typeof A=="number"&&nm()?void 0:y()).then(()=>{t?x(S):v()})})};return{promise:o,status:()=>a,cancel:d,continue:()=>(r==null||r(),o),cancelRetry:u,continueRetry:h,canStart:f,start:()=>(f()?v():y().then(v),o)}}var C8,yIt,VDt=(yIt=class{constructor(){vs(this,C8)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),ODt(this.gcTime)&&Kt(this,C8,r8.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(s){this.gcTime=Math.max(this.gcTime||0,s??(bet()?1/0:3e5))}clearGcTimeout(){ye(this,C8)!==void 0&&(r8.clearTimeout(ye(this,C8)),Kt(this,C8,void 0))}},C8=new WeakMap,yIt);function vws(s){return{onFetch:(t,n)=>{var u,h,m,f,g;const r=t.options,a=(m=(h=(u=t.fetchOptions)==null?void 0:u.meta)==null?void 0:h.fetchMore)==null?void 0:m.direction,i=((f=t.state.data)==null?void 0:f.pages)||[],l=((g=t.state.data)==null?void 0:g.pageParams)||[];let o={pages:[],pageParams:[]},c=0;const d=async()=>{let x=!1;const y=w=>{hws(w,()=>t.signal,()=>x=!0)},v=$Dt(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 y(O),O})(),P=await v(I),{maxPages:R}=t.options,D=A?uws:dws;return{pages:D(w.pages,P,R),pageParams:D(w.pageParams,S,R)}};if(a&&i.length){const w=a==="backward",S=w?HDt:KVe,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:KVe(r,o);if(c>0&&S==null)break;o=await b(o,S),c++}while(c{var x,y;return(y=(x=t.options).persister)==null?void 0:y.call(x,d,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n)}:t.fetchFn=d}}}function KVe(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 HDt(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 bws(s,t){return t?KVe(s,t)!=null:!1}function _ws(s,t){return!t||!s.getPreviousPageParam?!1:HDt(s,t)!=null}var XV,A8,QV,xN,E8,o0,Hne,T8,gS,gA,vIt,wws=(vIt=class extends VDt{constructor(t){super();vs(this,gS);vs(this,XV);vs(this,A8);vs(this,QV);vs(this,xN);vs(this,E8);vs(this,o0);vs(this,Hne);vs(this,T8);Kt(this,T8,!1),Kt(this,Hne,t.defaultOptions),this.setOptions(t.options),this.observers=[],Kt(this,E8,t.client),Kt(this,xN,ye(this,E8).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,Kt(this,A8,qgt(this.options)),this.state=t.state??ye(this,A8),this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return ye(this,XV)}get promise(){var t;return(t=ye(this,o0))==null?void 0:t.promise}setOptions(t){if(this.options={...ye(this,Hne),...t},t!=null&&t._type&&Kt(this,XV,t._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const n=qgt(this.options);n.data!==void 0&&(this.setState(Ugt(n.data,n.dataUpdatedAt)),Kt(this,A8,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&ye(this,xN).remove(this)}setData(t,n){const r=GVe(this.state.data,t,this.options);return cs(this,gS,gA).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(t){cs(this,gS,gA).call(this,{type:"setState",state:t})}cancel(t){var r,a;const n=(r=ye(this,o0))==null?void 0:r.promise;return(a=ye(this,o0))==null||a.cancel(t),n?n.then(i_).catch(i_):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return ye(this,A8)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(t=>Hp(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===yet||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>Hp(t.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(t=>t.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(t=0){return this.state.data===void 0?!0:t==="static"?!1:this.state.isInvalidated?!0:!zDt(this.state.dataUpdatedAt,t)}onFocus(){var t,n;(t=this.observers.find(r=>r.shouldFetchOnWindowFocus()))==null||t.refetch({cancelRefetch:!1}),(n=ye(this,o0))==null||n.continue()}onOnline(){var t,n;(t=this.observers.find(r=>r.shouldFetchOnReconnect()))==null||t.refetch({cancelRefetch:!1}),(n=ye(this,o0))==null||n.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),ye(this,xN).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,o0)&&(ye(this,T8)||this.state.fetchStatus==="paused"&&this.state.status==="pending"?ye(this,o0).cancel({revert:!0}):ye(this,o0).cancelRetry()),this.scheduleGc()),ye(this,xN).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||cs(this,gS,gA).call(this,{type:"invalidate"})}async fetch(t,n){var d,u,h,m,f,g,x,y,v,b,w,S;if(this.state.fetchStatus!=="idle"&&((d=ye(this,o0))==null?void 0:d.status())!=="rejected"){if(this.state.data!==void 0&&(n!=null&&n.cancelRefetch))this.cancel({silent:!0});else if(ye(this,o0))return ye(this,o0).continueRetry(),ye(this,o0).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:()=>(Kt(this,T8,!0),r.signal)})},i=()=>{const A=$Dt(this.options,n),I=(()=>{const P={client:ye(this,E8),queryKey:this.queryKey,meta:this.meta};return a(P),P})();return Kt(this,T8,!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,E8),state:this.state,fetchFn:i};return a(A),A})();(u=ye(this,XV)==="infinite"?vws(this.options.pages):this.options.behavior)==null||u.onFetch(o,this),Kt(this,QV,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((h=o.fetchOptions)==null?void 0:h.meta))&&cs(this,gS,gA).call(this,{type:"fetch",meta:(m=o.fetchOptions)==null?void 0:m.meta});const c=Kt(this,o0,qDt({initialPromise:n==null?void 0:n.initialPromise,fn:o.fetchFn,onCancel:A=>{A instanceof WVe&&A.revert&&this.setState({...ye(this,QV),fetchStatus:"idle"}),r.abort()},onFail:(A,E)=>{cs(this,gS,gA).call(this,{type:"failed",failureCount:A,error:E})},onPause:()=>{cs(this,gS,gA).call(this,{type:"pause"})},onContinue:()=>{cs(this,gS,gA).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,xN).config).onSuccess)==null||g.call(f,A,this),(y=(x=ye(this,xN).config).onSettled)==null||y.call(x,A,this.state.error,this),A}catch(A){if(A instanceof WVe){if(A.silent)return ye(this,o0).promise;if(A.revert){if(this.state.data===void 0)throw A;return this.state.data}}throw cs(this,gS,gA).call(this,{type:"error",error:A}),(b=(v=ye(this,xN).config).onError)==null||b.call(v,A,this),(S=(w=ye(this,xN).config).onSettled)==null||S.call(w,this.state.data,A,this),A}finally{ye(this,o0)===c&&Kt(this,o0,void 0),this.scheduleGc()}}},XV=new WeakMap,A8=new WeakMap,QV=new WeakMap,xN=new WeakMap,E8=new WeakMap,o0=new WeakMap,Hne=new WeakMap,T8=new WeakMap,gS=new WeakSet,gA=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,...GDt(r.data,this.options),fetchMeta:t.meta??null};case"success":const a={...r,...Ugt(t.data,t.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return Kt(this,QV,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),v0.batch(()=>{this.observers.slice().forEach(r=>{r.onQueryUpdate()}),ye(this,xN).notify({query:this,type:"updated",action:t})})},vIt);function GDt(s,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:UDt(t.networkMode)?"fetching":"paused",...s===void 0&&{error:null,status:"pending"}}}function Ugt(s,t){return{data:s,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function qgt(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 n_,Zu,Gne,r_,M8,JV,FA,Wne,eH,tH,P8,I8,LP,sH,am,tQ,YVe,ZVe,XVe,QVe,JVe,eHe,tHe,sHe,bIt,WDt=(bIt=class extends KW{constructor(t,n){super();vs(this,am);vs(this,n_);vs(this,Zu);vs(this,Gne);vs(this,r_);vs(this,M8);vs(this,JV);vs(this,FA);vs(this,Wne);vs(this,eH);vs(this,tH);vs(this,P8);vs(this,I8);vs(this,LP);vs(this,sH,new Set);this.options=n,Kt(this,n_,t),Kt(this,FA,null),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(ye(this,Zu).addObserver(this),Vgt(ye(this,Zu),this.options)?cs(this,am,tQ).call(this):this.updateResult(),cs(this,am,JVe).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return nHe(ye(this,Zu),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return nHe(ye(this,Zu),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,cs(this,am,eHe).call(this),cs(this,am,tHe).call(this),ye(this,Zu).removeObserver(this)}setOptions(t){const n=this.options,r=ye(this,Zu);if(this.options=ye(this,n_).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof Hp(this.options.enabled,ye(this,Zu))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");cs(this,am,sHe).call(this),ye(this,Zu).setOptions(this.options),n._defaulted&&!$4e(this.options,n)&&ye(this,n_).getQueryCache().notify({type:"observerOptionsUpdated",query:ye(this,Zu),observer:this});const a=this.hasListeners();a&&Hgt(ye(this,Zu),r,this.options,n)&&cs(this,am,tQ).call(this),this.updateResult(),a&&(ye(this,Zu)!==r||Hp(this.options.enabled,ye(this,Zu))!==Hp(n.enabled,ye(this,Zu))||Hp(this.options.staleTime,ye(this,Zu))!==Hp(n.staleTime,ye(this,Zu)))&&cs(this,am,ZVe).call(this);const i=cs(this,am,XVe).call(this);a&&(ye(this,Zu)!==r||Hp(this.options.enabled,ye(this,Zu))!==Hp(n.enabled,ye(this,Zu))||i!==ye(this,LP))&&cs(this,am,QVe).call(this,i)}getOptimisticResult(t){const n=ye(this,n_).getQueryCache().build(ye(this,n_),t),r=this.createResult(n,t);return $4e(this.getCurrentResult(),r)||(Kt(this,r_,r),Kt(this,JV,this.options),Kt(this,M8,ye(this,Zu).state)),r}getCurrentResult(){return ye(this,r_)}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,sH).add(t)}getCurrentQuery(){return ye(this,Zu)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const n=ye(this,n_).defaultQueryOptions(t),r=ye(this,n_).getQueryCache().build(ye(this,n_),n);let a=()=>{},i;const l=new Promise(o=>{i=o,a=ye(this,n_).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 cs(this,am,tQ).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),ye(this,r_)))}createResult(t,n){var E;const r=ye(this,Zu),a=this.options,i=ye(this,r_),l=ye(this,M8),o=ye(this,JV),c=t!==r?t.state:ye(this,Gne),{state:d}=t;let u={...d},h=!1,m;if(n._optimisticResults){const I=this.hasListeners(),P=!I&&Vgt(t,n),R=I&&Hgt(t,r,n,a);(P||R)&&(u={...u,...GDt(d.data,t.options)}),n._optimisticResults==="isRestoring"&&(u.fetchStatus="idle")}let{error:f,errorUpdatedAt:g,status:x}=u;m=u.data;let y=!1;if(n.placeholderData!==void 0&&m===void 0&&x==="pending"){let I;i!=null&&i.isPlaceholderData&&n.placeholderData===(o==null?void 0:o.placeholderData)?(I=i.data,y=!0):I=typeof n.placeholderData=="function"?n.placeholderData((E=ye(this,tH))==null?void 0:E.state.data,ye(this,tH)):n.placeholderData,I!==void 0&&(x="success",m=GVe(i==null?void 0:i.data,I,n),h=!0)}if(n.select&&m!==void 0&&!y)if(i&&m===(l==null?void 0:l.data)&&n.select===ye(this,Wne))m=ye(this,eH);else try{Kt(this,Wne,n.select),m=n.select(m),m=GVe(i==null?void 0:i.data,m,n),Kt(this,eH,m),Kt(this,FA,null)}catch(I){Kt(this,FA,I)}else m===void 0&&Kt(this,FA,null);ye(this,FA)&&(f=ye(this,FA),m=ye(this,eH),g=Date.now(),x="error",h=!1);const v=u.fetchStatus==="fetching",b=x==="pending",w=x==="error",S=b&&v,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:v,isRefetching:v&&!b,isLoadingError:w&&!A,isPaused:u.fetchStatus==="paused",isPlaceholderData:h,isRefetchError:w&&A,isStale:wet(t,n),refetch:this.refetch,isEnabled:Hp(n.enabled,t)!==!1}}updateResult(){const t=ye(this,r_),n=this.createResult(ye(this,Zu),this.options);if(Kt(this,M8,ye(this,Zu).state),Kt(this,JV,this.options),ye(this,M8).data!==void 0&&Kt(this,tH,ye(this,Zu)),$4e(n,t))return;Kt(this,r_,n);const a=(()=>{if(!t)return!0;const{notifyOnChangeProps:i}=this.options,l=typeof i=="function"?i():i;if(l==="all"||!l&&!ye(this,sH).size)return!0;const o=new Set(l??ye(this,sH));return this.options.throwOnError&&o.add("error"),Object.keys(ye(this,r_)).some(c=>{const d=c;return ye(this,r_)[d]!==t[d]&&o.has(d)})})();v0.batch(()=>{a&&this.listeners.forEach(i=>{i(ye(this,r_))}),ye(this,n_).getQueryCache().notify({query:ye(this,Zu),type:"observerResultsUpdated"})})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&cs(this,am,JVe).call(this)}},n_=new WeakMap,Zu=new WeakMap,Gne=new WeakMap,r_=new WeakMap,M8=new WeakMap,JV=new WeakMap,FA=new WeakMap,Wne=new WeakMap,eH=new WeakMap,tH=new WeakMap,P8=new WeakMap,I8=new WeakMap,LP=new WeakMap,sH=new WeakMap,am=new WeakSet,tQ=function(t){cs(this,am,sHe).call(this);let n=ye(this,Zu).fetch(this.options,t);return t!=null&&t.throwOnError||(n=n.catch(i_)),n},YVe=function(t){return!bet()&&Hp(this.options.enabled,ye(this,Zu))!==!1&&ODt(t)},ZVe=function(){cs(this,am,eHe).call(this);const t=Hp(this.options.staleTime,ye(this,Zu));if(ye(this,r_).isStale||!cs(this,am,YVe).call(this,t))return;const n=zDt(ye(this,r_).dataUpdatedAt,t)+1;Kt(this,P8,r8.setTimeout(()=>{ye(this,r_).isStale||this.updateResult()},n))},XVe=function(){return Hp(this.options.refetchInterval,ye(this,Zu))??!1},QVe=function(t){cs(this,am,tHe).call(this),Kt(this,LP,t),!(ye(this,LP)===0||!cs(this,am,YVe).call(this,ye(this,LP)))&&Kt(this,I8,r8.setInterval(()=>{(this.options.refetchIntervalInBackground||_et.isFocused())&&cs(this,am,tQ).call(this)},ye(this,LP)))},JVe=function(){cs(this,am,ZVe).call(this),cs(this,am,QVe).call(this,cs(this,am,XVe).call(this))},eHe=function(){ye(this,P8)!==void 0&&(r8.clearTimeout(ye(this,P8)),Kt(this,P8,void 0))},tHe=function(){ye(this,I8)!==void 0&&(r8.clearInterval(ye(this,I8)),Kt(this,I8,void 0))},sHe=function(){const t=ye(this,n_).getQueryCache().build(ye(this,n_),this.options);if(t===ye(this,Zu))return;const n=ye(this,Zu);Kt(this,Zu,t),Kt(this,Gne,t.state),this.hasListeners()&&(n==null||n.removeObserver(this),t.addObserver(this))},bIt);function jws(s,t){return Hp(t.enabled,s)!==!1&&s.state.data===void 0&&!(s.state.status==="error"&&Hp(t.retryOnMount,s)===!1)}function Vgt(s,t){return jws(s,t)||s.state.data!==void 0&&nHe(s,t,t.refetchOnMount)}function nHe(s,t,n){if(Hp(t.enabled,s)!==!1&&Hp(t.staleTime,s)!=="static"){const r=Hp(n,s);return r==="always"||r!==!1&&wet(s,t)}return!1}function Hgt(s,t,n,r){return(s!==t||Hp(r.enabled,s)===!1)&&(!n.suspense||s.state.status!=="error")&&wet(s,n)}function wet(s,t){return Hp(t.enabled,s)!==!1&&s.isStaleByTime(Hp(t.staleTime,s))}var Nws=class extends WDt{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:bws(t,n.data),hasPreviousPage:_ws(t,n.data),isFetchNextPageError:d,isFetchingNextPage:u,isFetchPreviousPageError:h,isFetchingPreviousPage:m,isRefetchError:o&&!d&&!h,isRefetching:i&&!u&&!m}}},Kne,I5,t1,L8,L5,BM,_It,kws=(_It=class extends VDt{constructor(t){super();vs(this,L5);vs(this,Kne);vs(this,I5);vs(this,t1);vs(this,L8);Kt(this,Kne,t.client),this.mutationId=t.mutationId,Kt(this,t1,t.mutationCache),Kt(this,I5,[]),this.state=t.state||KDt(),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,I5).includes(t)||(ye(this,I5).push(t),this.clearGcTimeout(),ye(this,t1).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){Kt(this,I5,ye(this,I5).filter(n=>n!==t)),this.scheduleGc(),ye(this,t1).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){ye(this,I5).length||(this.state.status==="pending"?this.scheduleGc():ye(this,t1).remove(this))}continue(){var t;return((t=ye(this,L8))==null?void 0:t.continue())??(this.state.status==="pending"?this.execute(this.state.variables):Promise.resolve())}async execute(t){var o,c,d,u,h,m,f,g,x,y,v,b,w,S,A,E,I,P;const n=()=>{cs(this,L5,BM).call(this,{type:"continue"})},r={client:ye(this,Kne),meta:this.options.meta,mutationKey:this.options.mutationKey},a=Kt(this,L8,qDt({fn:()=>this.options.mutationFn?this.options.mutationFn(t,r):Promise.reject(new Error("No mutationFn found")),onFail:(R,D)=>{cs(this,L5,BM).call(this,{type:"failed",failureCount:R,error:D})},onPause:()=>{cs(this,L5,BM).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>ye(this,t1).canRun(this)})),i=this.state.status==="pending",l=!a.canStart();try{if(i)n();else{cs(this,L5,BM).call(this,{type:"pending",variables:t,isPaused:l}),ye(this,t1).config.onMutate&&await ye(this,t1).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&&cs(this,L5,BM).call(this,{type:"pending",context:D,variables:t,isPaused:l})}const R=await a.start();return await((u=(d=ye(this,t1).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,t1).config).onSettled)==null?void 0:g.call(f,R,null,this.state.variables,this.state.context,this,r)),await((y=(x=this.options).onSettled)==null?void 0:y.call(x,R,null,t,this.state.context,r)),cs(this,L5,BM).call(this,{type:"success",data:R}),R}catch(R){try{await((b=(v=ye(this,t1).config).onError)==null?void 0:b.call(v,R,t,this.state.context,this,r))}catch(D){Promise.reject(D)}try{await((S=(w=this.options).onError)==null?void 0:S.call(w,R,t,this.state.context,r))}catch(D){Promise.reject(D)}try{await((E=(A=ye(this,t1).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 cs(this,L5,BM).call(this,{type:"error",error:R}),R}finally{ye(this,L8)===a&&Kt(this,L8,void 0),ye(this,t1).runNext(this)}}},Kne=new WeakMap,I5=new WeakMap,t1=new WeakMap,L8=new WeakMap,L5=new WeakSet,BM=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),v0.batch(()=>{ye(this,I5).forEach(r=>{r.onMutationUpdate(t)}),ye(this,t1).notify({mutation:this,type:"updated",action:t})})},_It);function KDt(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var OA,xS,Yne,wIt,Sws=(wIt=class extends KW{constructor(t={}){super();vs(this,OA);vs(this,xS);vs(this,Yne);this.config=t,Kt(this,OA,new Set),Kt(this,xS,new Map),Kt(this,Yne,0)}build(t,n,r){const a=new kws({client:t,mutationCache:this,mutationId:++X0(this,Yne)._,options:t.defaultMutationOptions(n),state:r});return this.add(a),a}add(t){ye(this,OA).add(t);const n=yce(t);if(typeof n=="string"){const r=ye(this,xS).get(n);r?r.push(t):ye(this,xS).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(ye(this,OA).delete(t)){const n=yce(t);if(typeof n=="string"){const r=ye(this,xS).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,xS).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){var r;const n=yce(t);if(typeof n=="string"){const a=(r=ye(this,xS).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=yce(t);return typeof n=="string"?((a=(r=ye(this,xS).get(n))==null?void 0:r.find(i=>i!==t&&i.state.isPaused))==null?void 0:a.continue())??Promise.resolve():Promise.resolve()}clear(){v0.batch(()=>{ye(this,OA).forEach(t=>{this.notify({type:"removed",mutation:t})}),ye(this,OA).clear(),ye(this,xS).clear()})}getAll(){return Array.from(ye(this,OA))}find(t){const n={exact:!0,...t};return this.getAll().find(r=>zgt(n,r))}findAll(t={}){return this.getAll().filter(n=>zgt(t,n))}notify(t){v0.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){const t=this.getAll().filter(n=>n.state.isPaused);return v0.batch(()=>Promise.all(t.map(n=>n.continue().catch(i_))))}},OA=new WeakMap,xS=new WeakMap,Yne=new WeakMap,wIt);function yce(s){var t;return(t=s.options.scope)==null?void 0:t.id}var zA,RP,s1,BA,N4,sQ,rHe,jIt,Cws=(jIt=class extends KW{constructor(n,r){super();vs(this,N4);vs(this,zA);vs(this,RP);vs(this,s1);vs(this,BA);Kt(this,zA,n),this.setOptions(r),this.bindMethods(),cs(this,N4,sQ).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,zA).defaultMutationOptions(n),$4e(this.options,r)||ye(this,zA).getMutationCache().notify({type:"observerOptionsUpdated",mutation:ye(this,s1),observer:this}),r!=null&&r.mutationKey&&this.options.mutationKey&&z7(r.mutationKey)!==z7(this.options.mutationKey)?this.reset():((a=ye(this,s1))==null?void 0:a.state.status)==="pending"&&ye(this,s1).setOptions(this.options)}onSubscribe(){this.listeners.size===1&&ye(this,s1)&&(ye(this,s1).addObserver(this),cs(this,N4,sQ).call(this))}onUnsubscribe(){var n;this.hasListeners()||(n=ye(this,s1))==null||n.removeObserver(this)}onMutationUpdate(n){cs(this,N4,sQ).call(this),cs(this,N4,rHe).call(this,n)}getCurrentResult(){return ye(this,RP)}reset(){var n;(n=ye(this,s1))==null||n.removeObserver(this),Kt(this,s1,void 0),cs(this,N4,sQ).call(this),cs(this,N4,rHe).call(this)}mutate(n,r){var a;return Kt(this,BA,r),(a=ye(this,s1))==null||a.removeObserver(this),Kt(this,s1,ye(this,zA).getMutationCache().build(ye(this,zA),this.options)),ye(this,s1).addObserver(this),ye(this,s1).execute(n)}},zA=new WeakMap,RP=new WeakMap,s1=new WeakMap,BA=new WeakMap,N4=new WeakSet,sQ=function(){var r;const n=((r=ye(this,s1))==null?void 0:r.state)??KDt();Kt(this,RP,{...n,isPending:n.status==="pending",isSuccess:n.status==="success",isError:n.status==="error",isIdle:n.status==="idle",mutate:this.mutate,reset:this.reset})},rHe=function(n){v0.batch(()=>{var r,a,i,l,o,c,d,u;if(ye(this,BA)&&this.hasListeners()){const h=ye(this,RP).variables,m=ye(this,RP).context,f={client:ye(this,zA),meta:this.options.meta,mutationKey:this.options.mutationKey};if((n==null?void 0:n.type)==="success"){try{(a=(r=ye(this,BA)).onSuccess)==null||a.call(r,n.data,h,m,f)}catch(g){Promise.reject(g)}try{(l=(i=ye(this,BA)).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,BA)).onError)==null||c.call(o,n.error,h,m,f)}catch(g){Promise.reject(g)}try{(u=(d=ye(this,BA)).onSettled)==null||u.call(d,void 0,n.error,h,m,f)}catch(g){Promise.reject(g)}}}this.listeners.forEach(h=>{h(ye(this,RP))})})},jIt),R5,NIt,Aws=(NIt=class extends KW{constructor(t={}){super();vs(this,R5);this.config=t,Kt(this,R5,new Map)}build(t,n,r){const a=n.queryKey,i=n.queryHash??xet(a,n);let l=this.get(i);return l||(l=new wws({client:t,queryKey:a,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(a)}),this.add(l)),l}add(t){ye(this,R5).has(t.queryHash)||(ye(this,R5).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){ye(this,R5).get(t.queryHash)===t&&(t.destroy(),ye(this,R5).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){v0.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return ye(this,R5).get(t)}getAll(){return[...ye(this,R5).values()]}find(t){const n={exact:!0,...t};return this.getAll().find(r=>Ogt(n,r))}findAll(t={}){const n=this.getAll();return Object.keys(t).length>0?n.filter(r=>Ogt(t,r)):n}notify(t){v0.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){v0.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){v0.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},R5=new WeakMap,NIt),yg,DP,FP,nH,rH,OP,aH,iH,kIt,Ews=(kIt=class{constructor(s={}){vs(this,yg);vs(this,DP);vs(this,FP);vs(this,nH);vs(this,rH);vs(this,OP);vs(this,aH);vs(this,iH);Kt(this,yg,s.queryCache||new Aws),Kt(this,DP,s.mutationCache||new Sws),Kt(this,FP,s.defaultOptions||{}),Kt(this,nH,new Map),Kt(this,rH,new Map),Kt(this,OP,0)}mount(){X0(this,OP)._++,ye(this,OP)===1&&(Kt(this,aH,_et.subscribe(async s=>{s&&(await this.resumePausedMutations(),ye(this,yg).onFocus())})),Kt(this,iH,fEe.subscribe(async s=>{s&&(await this.resumePausedMutations(),ye(this,yg).onOnline())})))}unmount(){var s,t;X0(this,OP)._--,ye(this,OP)===0&&((s=ye(this,aH))==null||s.call(this),Kt(this,aH,void 0),(t=ye(this,iH))==null||t.call(this),Kt(this,iH,void 0))}isFetching(s){return ye(this,yg).findAll({...s,fetchStatus:"fetching"}).length}isMutating(s){return ye(this,DP).findAll({...s,status:"pending"}).length}getQueryData(s){var n;const t=this.defaultQueryOptions({queryKey:s});return(n=ye(this,yg).get(t.queryHash))==null?void 0:n.state.data}ensureQueryData(s){const t=this.defaultQueryOptions(s),n=ye(this,yg).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(s):(s.revalidateIfStale&&n.isStaleByTime(Hp(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(s){return ye(this,yg).findAll(s).map(({queryKey:t,state:n})=>[t,n.data])}setQueryData(s,t,n){var l;const r=this.defaultQueryOptions({queryKey:s}),a=(l=ye(this,yg).get(r.queryHash))==null?void 0:l.state.data,i=ows(t,a);if(i!==void 0)return ye(this,yg).build(this,r).setData(i,{...n,manual:!0})}setQueriesData(s,t,n){return v0.batch(()=>ye(this,yg).findAll(s).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(s){var n;const t=this.defaultQueryOptions({queryKey:s});return(n=ye(this,yg).get(t.queryHash))==null?void 0:n.state}removeQueries(s){const t=ye(this,yg);v0.batch(()=>{t.findAll(s).forEach(n=>{t.remove(n)})})}resetQueries(s,t){const n=ye(this,yg);return v0.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=v0.batch(()=>ye(this,yg).findAll(s).map(a=>a.cancel(n)));return Promise.all(r).then(i_).catch(i_)}invalidateQueries(s,t={}){return v0.batch(()=>(ye(this,yg).findAll(s).forEach(n=>{n.invalidate()}),(s==null?void 0:s.refetchType)==="none"?Promise.resolve():this.refetchQueries({...s,type:(s==null?void 0:s.refetchType)??(s==null?void 0:s.type)??"active"},t)))}refetchQueries(s,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},r=v0.batch(()=>ye(this,yg).findAll(s).filter(a=>!a.isDisabled()&&!a.isStatic()).map(a=>{let i=a.fetch(void 0,n);return n.throwOnError||(i=i.catch(i_)),a.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(i_)}async query(s){const t=this.defaultQueryOptions(s);t.retry===void 0&&(t.retry=!1);const n=ye(this,yg).build(this,t),r=n.isStaleByTime(Hp(t.staleTime,n))?await n.fetch(t):n.state.data,a=t.select;return a?a(r):r}fetchQuery(s){const t=this.defaultQueryOptions(s);t.retry===void 0&&(t.retry=!1);const n=ye(this,yg).build(this,t);return n.isStaleByTime(Hp(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(s){return this.fetchQuery(s).then(i_).catch(i_)}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(i_).catch(i_)}ensureInfiniteQueryData(s){return s._type="infinite",this.ensureQueryData(s)}resumePausedMutations(){return fEe.isOnline()?ye(this,DP).resumePausedMutations():Promise.resolve()}getQueryCache(){return ye(this,yg)}getMutationCache(){return ye(this,DP)}getDefaultOptions(){return ye(this,FP)}setDefaultOptions(s){Kt(this,FP,s)}setQueryDefaults(s,t){ye(this,nH).set(z7(s),{queryKey:s,defaultOptions:t})}getQueryDefaults(s){const t=[...ye(this,nH).values()],n={};return t.forEach(r=>{mG(s,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(s,t){ye(this,rH).set(z7(s),{mutationKey:s,defaultOptions:t})}getMutationDefaults(s){const t=[...ye(this,rH).values()],n={};return t.forEach(r=>{mG(s,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(s){if(s._defaulted)return s;const t={...ye(this,FP).queries,...this.getQueryDefaults(s.queryKey),...s,_defaulted:!0};return t.queryHash||(t.queryHash=xet(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===yet&&(t.enabled=!1),t}defaultMutationOptions(s){return s!=null&&s._defaulted?s:{...ye(this,FP).mutations,...(s==null?void 0:s.mutationKey)&&this.getMutationDefaults(s.mutationKey),...s,_defaulted:!0}}clear(){ye(this,yg).clear(),ye(this,DP).clear()}},yg=new WeakMap,DP=new WeakMap,FP=new WeakMap,nH=new WeakMap,rH=new WeakMap,OP=new WeakMap,aH=new WeakMap,iH=new WeakMap,kIt);const YDt=j.createContext(!1),Tws=()=>j.useContext(YDt);YDt.Provider;function Mws(){let s=!1;return{clearReset:()=>{s=!1},reset:()=>{s=!0},isReset:()=>s}}const Pws=j.createContext(Mws()),Iws=()=>j.useContext(Pws),Lws=(s,t,n)=>{const r=n!=null&&n.state.error&&typeof s.throwOnError=="function"?vet(s.throwOnError,[n.state.error,n]):s.throwOnError;(s.suspense||r)&&(t.isReset()||(s.retryOnMount=!1))},Rws=s=>{j.useEffect(()=>{s.clearReset()},[s])},Dws=({result:s,errorResetBoundary:t,throwOnError:n,query:r,suspense:a})=>s.isError&&!t.isReset()&&!s.isFetching&&r&&(a&&s.data===void 0||vet(n,[s.error,r])),Fws=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))}},Ows=(s,t)=>(s==null?void 0:s.suspense)&&t.isPending,zws=(s,t,n)=>t.fetchOptimistic(s).catch(()=>{n.clearReset()});function ZDt(s,t,n){const r=Tws(),a=Iws(),i=Wt(),l=i.defaultQueryOptions(s),o=i.getQueryCache().get(l.queryHash),c=s.subscribed!==!1;l._optimisticResults=r?"isRestoring":c?"optimistic":void 0,Fws(l),Lws(l,a,o),Rws(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(v0.batchCalls(m)):i_;return d.updateResult(),f},[d,h]),()=>d.getCurrentResult(),()=>d.getCurrentResult()),j.useEffect(()=>{d.setOptions(l)},[l,d]),Ows(l,u))throw zws(l,d,a);if(Dws({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 ZDt(s,WDt)}function mt(s,t){const n=Wt(),[r]=j.useState(()=>new Cws(n,s));j.useEffect(()=>{r.setOptions(s)},[r,s]);const a=j.useSyncExternalStore(j.useCallback(l=>r.subscribe(v0.batchCalls(l)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),i=j.useCallback((...l)=>{r.mutate(l[0],l[1]).catch(i_)},[r]);if(a.error&&vet(r.options.throwOnError,[a.error]))throw a.error;return{...a,mutate:i,mutateAsync:a.mutate}}function Bws(s,t){return ZDt(s,Nws)}/** * @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 Vte(){return Vte=Object.assign?Object.assign.bind():function(s){for(var t=1;t"u")throw new Error(t)}function XDt(s,t){if(!s){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function Uws(){return Math.random().toString(36).substr(2,8)}function Wgt(s,t){return{usr:s.state,key:s.key,idx:t}}function aHe(s,t,n,r){return n===void 0&&(n=null),Vte({pathname:typeof s=="string"?s:s.pathname,search:"",hash:""},typeof t=="string"?YW(t):t,{state:n,key:t&&t.key||r||Uws()})}function pEe(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 YW(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 qws(s,t,n,r){r===void 0&&(r={});let{window:a=document.defaultView,v5Compat:i=!1}=r,l=a.history,o=fI.Pop,c=null,d=u();d==null&&(d=0,l.replaceState(Vte({},l.state,{idx:d}),""));function u(){return(l.state||{idx:null}).idx}function h(){o=fI.Pop;let y=u(),v=y==null?null:y-d;d=y,c&&c({action:o,location:x.location,delta:v})}function m(y,v){o=fI.Push;let b=aHe(x.location,y,v);d=u()+1;let w=Wgt(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(y,v){o=fI.Replace;let b=aHe(x.location,y,v);d=u();let w=Wgt(b,d),S=x.createHref(b);l.replaceState(w,"",S),i&&c&&c({action:o,location:x.location,delta:0})}function g(y){let v=a.location.origin!=="null"?a.location.origin:a.location.href,b=typeof y=="string"?y:pEe(y);return b=b.replace(/ $/,"%20"),Vg(v,"No window.location.(origin|href) available to create URL for href: "+b),new URL(b,v)}let x={get action(){return o},get location(){return s(a,l)},listen(y){if(c)throw new Error("A history only accepts one active listener");return a.addEventListener(Ggt,h),c=y,()=>{a.removeEventListener(Ggt,h),c=null}},createHref(y){return t(a,y)},createURL:g,encodeLocation(y){let v=g(y);return{pathname:v.pathname,search:v.search,hash:v.hash}},push:m,replace:f,go(y){return l.go(y)}};return x}var Kgt;(function(s){s.data="data",s.deferred="deferred",s.redirect="redirect",s.error="error"})(Kgt||(Kgt={}));function Vws(s,t,n){return n===void 0&&(n="/"),Hws(s,t,n)}function Hws(s,t,n,r){let a=typeof t=="string"?YW(t):t,i=fG(a.pathname||"/",n);if(i==null)return null;let l=QDt(s);Gws(l);let o=null,c=njs(i);for(let d=0;o==null&&d{let c={relativePath:o===void 0?i.path||"":o,caseSensitive:i.caseSensitive===!0,childrenIndex:l,route:i};c.relativePath.startsWith("/")&&(Vg(c.relativePath.startsWith(r),'Absolute route path "'+c.relativePath+'" nested under path '+('"'+r+'" is not valid. An absolute child route path ')+"must start with the combined path of all its parent routes."),c.relativePath=c.relativePath.slice(r.length));let d=nL([r,c.relativePath]),u=n.concat(c);i.children&&i.children.length>0&&(Vg(i.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+d+'".')),QDt(i.children,t,u,d)),!(i.path==null&&!i.index)&&t.push({path:d,score:Jws(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 JDt(i.path))a(i,l,c)}),t}function JDt(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=JDt(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 Gws(s){s.sort((t,n)=>t.score!==n.score?n.score-t.score:ejs(t.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}const Wws=/^:[\w-]+$/,Kws=3,Yws=2,Zws=1,Xws=10,Qws=-2,Ygt=s=>s==="*";function Jws(s,t){let n=s.split("/"),r=n.length;return n.some(Ygt)&&(r+=Qws),t&&(r+=Yws),n.filter(a=>!Ygt(a)).reduce((a,i)=>a+(Wws.test(i)?Kws:i===""?Zws:Xws),r)}function ejs(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 tjs(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 sjs(s,t,n){t===void 0&&(t=!1),n===void 0&&(n=!0),XDt(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 njs(s){try{return s.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return XDt(!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 fG(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 rjs(s,t){t===void 0&&(t="/");let{pathname:n,search:r="",hash:a=""}=typeof s=="string"?YW(s):s,i;return n?(n=eFt(n),n.startsWith("/")?i=Zgt(n.substring(1),"/"):i=Zgt(n,t)):i=t,{pathname:i,search:ojs(r),hash:ljs(a)}}function Zgt(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 Eze(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 ajs(s){return s.filter((t,n)=>n===0||t.route.path&&t.route.path.length>0)}function jet(s,t){let n=ajs(s);return t?n.map((r,a)=>a===n.length-1?r.pathname:r.pathnameBase):n.map(r=>r.pathnameBase)}function Net(s,t,n,r){r===void 0&&(r=!1);let a;typeof s=="string"?a=YW(s):(a=Vte({},s),Vg(!a.pathname||!a.pathname.includes("?"),Eze("?","pathname","search",a)),Vg(!a.pathname||!a.pathname.includes("#"),Eze("#","pathname","hash",a)),Vg(!a.search||!a.search.includes("#"),Eze("#","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=rjs(a,o),d=l&&l!=="/"&&l.endsWith("/"),u=(i||l===".")&&n.endsWith("/");return!c.pathname.endsWith("/")&&(d||u)&&(c.pathname+="/"),c}const eFt=s=>s.replace(/\/\/+/g,"/"),nL=s=>eFt(s.join("/")),ijs=s=>s.replace(/\/+$/,"").replace(/^\/*/,"/"),ojs=s=>!s||s==="?"?"":s.startsWith("?")?s:"?"+s,ljs=s=>!s||s==="#"?"":s.startsWith("#")?s:"#"+s;function cjs(s){return s!=null&&typeof s.status=="number"&&typeof s.statusText=="string"&&typeof s.internal=="boolean"&&"data"in s}const tFt=["post","put","patch","delete"];new Set(tFt);const djs=["get",...tFt];new Set(djs);/** * 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 Hte(){return Hte=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=Net(d,JSON.parse(l),i,u.relative==="path");s==null&&t!=="/"&&(h.pathname=h.pathname==="/"?t:nL([t,h.pathname])),(u.replace?r.replace:r.push)(h,u.state,u)},[t,r,l,i,s])}const mjs=j.createContext(null);function fjs(s){let t=j.useContext(a3).outlet;return t&&j.createElement(mjs.Provider,{value:s},t)}function Wi(){let{matches:s}=j.useContext(a3),t=s[s.length-1];return t?t.params:{}}function nLe(s,t){let{relative:n}=t===void 0?{}:t,{future:r}=j.useContext(AT),{matches:a}=j.useContext(a3),{pathname:i}=mu(),l=JSON.stringify(jet(a,r.v7_relativeSplatPath));return j.useMemo(()=>Net(s,JSON.parse(l),i,n==="path"),[s,l,i,n])}function pjs(s,t){return gjs(s,t)}function gjs(s,t,n,r){ZW()||Vg(!1);let{navigator:a}=j.useContext(AT),{matches:i}=j.useContext(a3),l=i[i.length-1],o=l?l.params:{};l&&l.pathname;let c=l?l.pathnameBase:"/";l&&l.route;let d=mu(),u;if(t){var h;let y=typeof t=="string"?YW(t):t;c==="/"||(h=y.pathname)!=null&&h.startsWith(c)||Vg(!1),u=y}else u=d;let m=u.pathname||"/",f=m;if(c!=="/"){let y=c.replace(/^\//,"").split("/");f="/"+m.replace(/^\//,"").split("/").slice(y.length).join("/")}let g=Vws(s,{pathname:f}),x=_js(g&&g.map(y=>Object.assign({},y,{params:Object.assign({},o,y.params),pathname:nL([c,a.encodeLocation?a.encodeLocation(y.pathname).pathname:y.pathname]),pathnameBase:y.pathnameBase==="/"?c:nL([c,a.encodeLocation?a.encodeLocation(y.pathnameBase).pathname:y.pathnameBase])})),i,n,r);return t&&x?j.createElement(sLe.Provider,{value:{location:Hte({pathname:"/",search:"",hash:"",state:null,key:"default"},u),navigationType:fI.Pop}},x):x}function xjs(){let s=kjs(),t=cjs(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 yjs=j.createElement(xjs,null);class vjs 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(a3.Provider,{value:this.props.routeContext},j.createElement(nFt.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function bjs(s){let{routeContext:t,match:n,children:r}=s,a=j.useContext(tLe);return a&&a.static&&a.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(a.staticContext._deepestRenderedBoundaryId=n.route.id),j.createElement(a3.Provider,{value:t},r)}function _js(s,t,n,r){var a;if(t===void 0&&(t=[]),n===void 0&&(n=null),r===void 0&&(r=null),s==null){var i;if(!n)return null;if(n.errors)s=n.matches;else if((i=r)!=null&&i.v7_partialHydration&&t.length===0&&!n.initialized&&n.matches.length>0)s=n.matches;else return null}let l=s,o=(a=n)==null?void 0:a.errors;if(o!=null){let u=l.findIndex(h=>h.route.id&&(o==null?void 0:o[h.route.id])!==void 0);u>=0||Vg(!1),l=l.slice(0,Math.min(l.length,u+1))}let c=!1,d=-1;if(n&&r&&r.v7_partialHydration)for(let u=0;u=0?l=l.slice(0,d+1):l=[l[0]];break}}}return l.reduceRight((u,h,m)=>{let f,g=!1,x=null,y=null;n&&(f=o&&h.route.id?o[h.route.id]:void 0,x=h.route.errorElement||yjs,c&&(d<0&&m===0?(Cjs("route-fallback"),g=!0,y=null):d===m&&(g=!0,y=h.route.hydrateFallbackElement||null)));let v=t.concat(l.slice(0,m+1)),b=()=>{let w;return f?w=x:g?w=y:h.route.Component?w=j.createElement(h.route.Component,null):h.route.element?w=h.route.element:w=u,j.createElement(bjs,{match:h,routeContext:{outlet:u,matches:v,isDataRoute:n!=null},children:w})};return n&&(h.route.ErrorBoundary||h.route.errorElement||m===0)?j.createElement(vjs,{location:n.location,revalidation:n.revalidation,component:x,error:f,children:b(),routeContext:{outlet:null,matches:v,isDataRoute:!0}}):b()},null)}var aFt=function(s){return s.UseBlocker="useBlocker",s.UseRevalidator="useRevalidator",s.UseNavigateStable="useNavigate",s}(aFt||{}),iFt=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}(iFt||{});function wjs(s){let t=j.useContext(tLe);return t||Vg(!1),t}function jjs(s){let t=j.useContext(sFt);return t||Vg(!1),t}function Njs(s){let t=j.useContext(a3);return t||Vg(!1),t}function oFt(s){let t=Njs(),n=t.matches[t.matches.length-1];return n.route.id||Vg(!1),n.route.id}function kjs(){var s;let t=j.useContext(nFt),n=jjs(),r=oFt();return t!==void 0?t:(s=n.errors)==null?void 0:s[r]}function Sjs(){let{router:s}=wjs(aFt.UseNavigateStable),t=oFt(iFt.UseNavigateStable),n=j.useRef(!1);return rFt(()=>{n.current=!0}),j.useCallback(function(a,i){i===void 0&&(i={}),n.current&&(typeof a=="number"?s.navigate(a):s.navigate(a,Hte({fromRouteId:t},i)))},[s,t])}const Xgt={};function Cjs(s,t,n){Xgt[s]||(Xgt[s]=!0)}function Ajs(s,t){s==null||s.v7_startTransition,s==null||s.v7_relativeSplatPath}function Rd(s){let{to:t,replace:n,state:r,relative:a}=s;ZW()||Vg(!1);let{future:i,static:l}=j.useContext(AT),{matches:o}=j.useContext(a3),{pathname:c}=mu(),d=Xn(),u=Net(t,jet(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 ket(s){return fjs(s.context)}function rs(s){Vg(!1)}function Ejs(s){let{basename:t="/",children:n=null,location:r,navigationType:a=fI.Pop,navigator:i,static:l=!1,future:o}=s;ZW()&&Vg(!1);let c=t.replace(/^\/*/,"/"),d=j.useMemo(()=>({basename:c,navigator:i,static:l,future:Hte({v7_relativeSplatPath:!1},o)}),[c,o,i,l]);typeof r=="string"&&(r=YW(r));let{pathname:u="/",search:h="",hash:m="",state:f=null,key:g="default"}=r,x=j.useMemo(()=>{let y=fG(u,c);return y==null?null:{location:{pathname:y,search:h,hash:m,state:f,key:g},navigationType:a}},[c,u,h,m,f,g,a]);return x==null?null:j.createElement(AT.Provider,{value:d},j.createElement(sLe.Provider,{children:n,value:x}))}function pG(s){let{children:t,location:n}=s;return pjs(oHe(t),n)}new Promise(()=>{});function oHe(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,oHe(r.props.children,i));return}r.type!==rs&&Vg(!1),!r.props.index||!r.props.children||Vg(!1);let l={id:r.props.id||i.join("-"),caseSensitive:r.props.caseSensitive,element:r.props.element,Component:r.props.Component,index:r.props.index,path:r.props.path,loader:r.props.loader,action:r.props.action,errorElement:r.props.errorElement,ErrorBoundary:r.props.ErrorBoundary,hasErrorBoundary:r.props.ErrorBoundary!=null||r.props.errorElement!=null,shouldRevalidate:r.props.shouldRevalidate,handle:r.props.handle,lazy:r.props.lazy};r.props.children&&(l.children=oHe(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 gEe(){return gEe=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 Pjs(s,t){let n=lHe(s);return t&&t.forEach((r,a)=>{n.has(a)||t.getAll(a).forEach(i=>{n.append(a,i)})}),n}const Ijs=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","viewTransition"],Ljs=["aria-current","caseSensitive","className","end","style","to","viewTransition","children"],Rjs="6";try{window.__reactRouterVersion=Rjs}catch{}const Djs=j.createContext({isTransitioning:!1}),Fjs="startTransition",Qgt=SB[Fjs];function Ojs(s){let{basename:t,children:n,future:r,window:a}=s,i=j.useRef();i.current==null&&(i.current=$ws({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&&Qgt?Qgt(()=>c(h)):c(h)},[c,d]);return j.useLayoutEffect(()=>l.listen(u),[l,u]),j.useEffect(()=>Ajs(r),[r]),j.createElement(Ejs,{basename:t,children:n,location:o.location,navigationType:o.action,navigator:l,future:r})}const zjs=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",Bjs=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,wr=j.forwardRef(function(t,n){let{onClick:r,relative:a,reloadDocument:i,replace:l,state:o,target:c,to:d,preventScrollReset:u,viewTransition:h}=t,m=lFt(t,Ijs),{basename:f}=j.useContext(AT),g,x=!1;if(typeof d=="string"&&Bjs.test(d)&&(g=d,zjs))try{let w=new URL(window.location.href),S=d.startsWith("//")?new URL(w.protocol+d):new URL(d),A=fG(S.pathname,f);S.origin===w.origin&&A!=null?d=A+S.search+S.hash:x=!0}catch{}let y=ujs(d,{relative:a}),v=Ujs(d,{replace:l,state:o,target:c,preventScrollReset:u,relative:a,viewTransition:h});function b(w){r&&r(w),w.defaultPrevented||v(w)}return j.createElement("a",gEe({},m,{href:g||y,onClick:x||i?r:b,ref:n,target:c}))}),oP=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=lFt(t,Ljs),m=nLe(c,{relative:h.relative}),f=mu(),g=j.useContext(sFt),{navigator:x,basename:y}=j.useContext(AT),v=g!=null&&qjs(m)&&d===!0,b=x.encodeLocation?x.encodeLocation(m).pathname:m.pathname,w=f.pathname,S=g&&g.navigation&&g.navigation.location?g.navigation.location.pathname:null;a||(w=w.toLowerCase(),S=S?S.toLowerCase():null,b=b.toLowerCase()),S&&y&&(S=fG(S,y)||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:v},R=E?r:void 0,D;typeof i=="function"?D=i(P):D=[i,E?"active":null,I?"pending":null,v?"transitioning":null].filter(Boolean).join(" ");let O=typeof o=="function"?o(P):o;return j.createElement(wr,gEe({},h,{"aria-current":R,className:D,ref:n,style:O,to:c,viewTransition:d}),typeof u=="function"?u(P):u)});var cHe;(function(s){s.UseScrollRestoration="useScrollRestoration",s.UseSubmit="useSubmit",s.UseSubmitFetcher="useSubmitFetcher",s.UseFetcher="useFetcher",s.useViewTransitionState="useViewTransitionState"})(cHe||(cHe={}));var Jgt;(function(s){s.UseFetcher="useFetcher",s.UseFetchers="useFetchers",s.UseScrollRestoration="useScrollRestoration"})(Jgt||(Jgt={}));function $js(s){let t=j.useContext(tLe);return t||Vg(!1),t}function Ujs(s,t){let{target:n,replace:r,state:a,preventScrollReset:i,relative:l,viewTransition:o}=t===void 0?{}:t,c=Xn(),d=mu(),u=nLe(s,{relative:l});return j.useCallback(h=>{if(Mjs(h,n)){h.preventDefault();let m=r!==void 0?r:pEe(d)===pEe(u);c(s,{replace:m,state:a,preventScrollReset:i,relative:l,viewTransition:o})}},[d,c,u,r,a,n,s,i,l,o])}function gc(s){let t=j.useRef(lHe(s)),n=j.useRef(!1),r=mu(),a=j.useMemo(()=>Pjs(r.search,n.current?null:t.current),[r.search]),i=Xn(),l=j.useCallback((o,c)=>{const d=lHe(typeof o=="function"?o(a):o);n.current=!0,i("?"+d,c)},[i,a]);return[a,l]}function qjs(s,t){t===void 0&&(t={});let n=j.useContext(Djs);n==null&&Vg(!1);let{basename:r}=$js(cHe.useViewTransitionState),a=nLe(s,{relative:t.relative});if(!n.isTransitioning)return!1;let i=fG(n.currentLocation.pathname,r)||n.currentLocation.pathname,l=fG(n.nextLocation.pathname,r)||n.nextLocation.pathname;return iHe(a.pathname,l)!=null||iHe(a.pathname,i)!=null}var Vjs=typeof Element<"u",Hjs=typeof Map=="function",Gjs=typeof Set=="function",Wjs=typeof ArrayBuffer=="function"&&!!ArrayBuffer.isView;function U4e(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(!U4e(s[r],t[r]))return!1;return!0}var i;if(Hjs&&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(!U4e(r.value[1],t.get(r.value[0])))return!1;return!0}if(Gjs&&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(Wjs&&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(Vjs&&s instanceof Element)return!1;for(r=n;r--!==0;)if(!((a[r]==="_owner"||a[r]==="__v"||a[r]==="__o")&&s.$$typeof)&&!U4e(s[a[r]],t[a[r]]))return!1;return!0}return s!==s&&t!==t}var Kjs=function(t,n){try{return U4e(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 Yjs=ru(Kjs);var Zjs=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}},Xjs=Zjs;const ext=ru(Xjs);var Qjs=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))(cFt||{}),Tze={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"]}},txt=Object.values(cFt),Cet={accesskey:"accessKey",charset:"charSet",class:"className",contenteditable:"contentEditable",contextmenu:"contextMenu","http-equiv":"httpEquiv",itemprop:"itemProp",tabindex:"tabIndex"},e2s=Object.entries(Cet).reduce((s,[t,n])=>(s[n]=t,s),{}),VS="data-rh",yV={DEFAULT_TITLE:"defaultTitle",DEFER:"defer",ENCODE_SPECIAL_CHARACTERS:"encodeSpecialCharacters",ON_CHANGE_CLIENT_STATE:"onChangeClientState",TITLE_TEMPLATE:"titleTemplate",PRIORITIZE_SEO_TAGS:"prioritizeSeoTags"},vV=(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},t2s=s=>{let t=vV(s,"title");const n=vV(s,yV.TITLE_TEMPLATE);if(Array.isArray(t)&&(t=t.join("")),n&&t)return n.replace(/%s/g,()=>t);const r=vV(s,yV.DEFAULT_TITLE);return t||r||void 0},s2s=s=>vV(s,yV.ON_CHANGE_CLIENT_STATE)||(()=>{}),Mze=(s,t)=>t.filter(n=>typeof n[s]<"u").map(n=>n[s]).reduce((n,r)=>({...n,...r}),{}),n2s=(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),xZ=(s,t,n)=>{const r={};return n.filter(a=>Array.isArray(a[s])?!0:(typeof a[s]<"u"&&r2s(`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:n2s(["href"],s),bodyAttributes:Mze("bodyAttributes",s),defer:vV(s,yV.DEFER),encode:vV(s,yV.ENCODE_SPECIAL_CHARACTERS),htmlAttributes:Mze("htmlAttributes",s),linkTags:xZ("link",["rel","href"],s),metaTags:xZ("meta",["name","charset","http-equiv","property","itemprop"],s),noscriptTags:xZ("noscript",["innerHTML"],s),onChangeClientState:s2s(s),scriptTags:xZ("script",["src","innerHTML"],s),styleTags:xZ("style",["cssText"],s),title:t2s(s),titleAttributes:Mze("titleAttributes",s),prioritizeSeoTags:a2s(s,yV.PRIORITIZE_SEO_TAGS)}),dFt=s=>Array.isArray(s)?s.join(""):s,o2s=(s,t)=>{const n=Object.keys(s);for(let r=0;rArray.isArray(s)?s.reduce((n,r)=>(o2s(r,t)?n.priority.push(r):n.default.push(r),n),{priority:[],default:[]}):{default:s,priority:[]},sxt=(s,t)=>({...s,[t]:void 0}),l2s=["noscript","script","style"],dHe=(s,t=!0)=>t===!1?String(s):String(s).replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'"),uFt=s=>Object.keys(s).reduce((t,n)=>{const r=typeof s[n]<"u"?`${n}="${s[n]}"`:`${n}`;return t?`${t} ${r}`:r},""),c2s=(s,t,n,r)=>{const a=uFt(n),i=dFt(t);return a?`<${s} ${VS}="true" ${a}>${dHe(i,r)}`:`<${s} ${VS}="true">${dHe(i,r)}`},d2s=(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}="${dHe(i[u],n)}"`;return d?`${d} ${h}`:h},""),o=i.innerHTML||i.cssText||"",c=l2s.indexOf(s)===-1;return`${r}<${s} ${VS}="true" ${l}${c?"/>":`>${o}`}`},""),hFt=(s,t={})=>Object.keys(s).reduce((n,r)=>{const a=Cet[r];return n[a||r]=s[r],n},t),u2s=(s,t,n)=>{const r={key:t,[VS]:!0},a=hFt(n,r);return[Gt.createElement("title",a,t)]},q4e=(s,t)=>t.map((n,r)=>{const a={key:r,[VS]:!0};return Object.keys(n).forEach(i=>{const o=Cet[i]||i;if(o==="innerHTML"||o==="cssText"){const c=n.innerHTML||n.cssText;a.dangerouslySetInnerHTML={__html:c}}else a[o]=n[i]}),Gt.createElement(s,a)}),gN=(s,t,n=!0)=>{switch(s){case"title":return{toComponent:()=>u2s(s,t.title,t.titleAttributes),toString:()=>c2s(s,t.title,t.titleAttributes,n)};case"bodyAttributes":case"htmlAttributes":return{toComponent:()=>hFt(t),toString:()=>uFt(t)};default:return{toComponent:()=>q4e(s,t),toString:()=>d2s(s,t,n)}}},h2s=({metaTags:s,linkTags:t,scriptTags:n,encode:r})=>{const a=Pze(s,Tze.meta),i=Pze(t,Tze.link),l=Pze(n,Tze.script);return{priorityMethods:{toComponent:()=>[...q4e("meta",a.priority),...q4e("link",i.priority),...q4e("script",l.priority)],toString:()=>`${gN("meta",a.priority,r)} ${gN("link",i.priority,r)} ${gN("script",l.priority,r)}`},metaTags:a.default,linkTags:i.default,scriptTags:l.default}},m2s=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}=h2s(s)),{priority:f,base:gN("base",t,r),bodyAttributes:gN("bodyAttributes",n,r),htmlAttributes:gN("htmlAttributes",a,r),link:gN("link",u,r),meta:gN("meta",h,r),noscript:gN("noscript",i,r),script:gN("script",m,r),style:gN("style",l,r),title:gN("title",{title:o,titleAttributes:c},r)}},uHe=m2s,vce=[],mFt=!!(typeof window<"u"&&window.document&&window.document.createElement),hHe=class{constructor(s,t){Nr(this,"instances",[]);Nr(this,"canUseDOM",mFt);Nr(this,"context");Nr(this,"value",{setHelmet:s=>{this.context.helmet=s},helmetInstances:{get:()=>this.canUseDOM?vce:this.instances,add:s=>{(this.canUseDOM?vce:this.instances).push(s)},remove:s=>{const t=(this.canUseDOM?vce:this.instances).indexOf(s);(this.canUseDOM?vce:this.instances).splice(t,1)}}});this.context=s,this.canUseDOM=t||!1,t||(s.helmet=uHe({baseTag:[],bodyAttributes:{},htmlAttributes:{},linkTags:[],metaTags:[],noscriptTags:[],scriptTags:[],styleTags:[],title:"",titleAttributes:{}}))}},f2s={},fFt=Gt.createContext(f2s),R8,pFt=(R8=class extends j.Component{constructor(n){super(n);Nr(this,"helmetData");this.helmetData=new hHe(this.props.context||{},R8.canUseDOM)}render(){return Gt.createElement(fFt.Provider,{value:this.helmetData.value},this.props.children)}},Nr(R8,"canUseDOM",mFt),R8),u$=(s,t)=>{const n=document.head||document.querySelector("head"),r=n.querySelectorAll(`${s}[${VS}]`),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(VS,"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}},mHe=(s,t)=>{const n=document.getElementsByTagName(s)[0];if(!n)return;const r=n.getAttribute(VS),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(VS):n.getAttribute(VS)!==l.join(",")&&n.setAttribute(VS,l.join(","))},p2s=(s,t)=>{typeof s<"u"&&document.title!==s&&(document.title=dFt(s)),mHe("title",t)},nxt=(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;mHe("body",r),mHe("html",a),p2s(h,m);const f={baseTag:u$("base",n),linkTags:u$("link",i),metaTags:u$("meta",l),noscriptTags:u$("noscript",o),scriptTags:u$("script",d),styleTags:u$("style",u)},g={},x={};Object.keys(f).forEach(y=>{const{newTags:v,oldTags:b}=f[y];v.length&&(g[y]=v),b.length&&(x[y]=f[y].oldTags)}),t&&t(),c(s,g,x)},yZ=null,g2s=s=>{yZ&&cancelAnimationFrame(yZ),s.defer?yZ=requestAnimationFrame(()=>{nxt(s,()=>{yZ=null})}):(nxt(s),yZ=null)},x2s=g2s,rxt=class extends j.Component{constructor(){super(...arguments);Nr(this,"rendered",!1)}shouldComponentUpdate(t){return!Jjs(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=i2s(t.get().map(i=>{const l={...i.props};return delete l.context,l}));pFt.canUseDOM?x2s(a):uHe&&(r=uHe(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}},Pqe,Dl=(Pqe=class extends j.Component{shouldComponentUpdate(s){return!Yjs(sxt(this.props,"helmetData"),sxt(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 ext(txt.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 ${txt.join(", ")} are allowed. Helmet does not support rendering <${s.type}> elements. Refer to our API for more information.`),ext(!t||typeof t=="string"||Array.isArray(t)&&!t.some(n=>typeof n!="string"),`Helmet expects a string as a child of <${s.type}>. Did you forget to wrap your children in braces? ( <${s.type}>{\`\`} ) Refer to our API for more information.`),!0}mapChildrenToProps(s,t){let n={};return Gt.Children.forEach(s,r=>{if(!r||!r.props)return;const{children:a,...i}=r.props,l=Object.keys(i).reduce((c,d)=>(c[e2s[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 hHe)){const a=r;r=new hHe(a.context,!0),delete n.helmetData}return r?Gt.createElement(rxt,{...n,context:r.value}):Gt.createElement(fFt.Consumer,null,a=>Gt.createElement(rxt,{...n,context:a}))}},Nr(Pqe,"defaultProps",{defer:!0,encodeSpecialCharacters:!0,prioritizeSeoTags:!1}),Pqe);const y2s=s=>{let t;return s?t=s:typeof fetch>"u"?t=(...n)=>ri(async()=>{const{default:r}=await Promise.resolve().then(()=>XW);return{default:r}},void 0).then(({default:r})=>r(...n)):t=fetch,(...n)=>t(...n)};class Aet extends Error{constructor(t,n="FunctionsError",r){super(t),this.name=n,this.context=r}}class v2s extends Aet{constructor(t){super("Failed to send a request to the Edge Function","FunctionsFetchError",t)}}class b2s extends Aet{constructor(t){super("Relay Error invoking the Edge Function","FunctionsRelayError",t)}}class kae extends Aet{constructor(t){super("Edge Function returned a non-2xx status code","FunctionsHttpError",t)}}var fHe;(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"})(fHe||(fHe={}));var _2s=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 w2s{constructor(t,{headers:n={},customFetch:r,region:a=fHe.Any}={}){this.url=t,this.headers=n,this.region=a,this.fetch=y2s(r)}setAuth(t){this.headers.Authorization=`Bearer ${t}`}invoke(t,n={}){var r;return _2s(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 v2s(g)}),h=u.headers.get("x-relay-error");if(h&&h==="true")throw new b2s(u);if(!u.ok)throw new kae(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 pw={},Eet={},rLe={},Sae={},aLe={},iLe={},j2s=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")},gG=j2s();const N2s=gG.fetch,gFt=gG.fetch.bind(gG),xFt=gG.Headers,k2s=gG.Request,S2s=gG.Response,XW=Object.freeze(Object.defineProperty({__proto__:null,Headers:xFt,Request:k2s,Response:S2s,default:gFt,fetch:N2s},Symbol.toStringTag,{value:"Module"})),C2s=Jps(XW);var oLe={};Object.defineProperty(oLe,"__esModule",{value:!0});let A2s=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}};oLe.default=A2s;var yFt=Sp&&Sp.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(iLe,"__esModule",{value:!0});const E2s=yFt(C2s),T2s=yFt(oLe);let M2s=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=E2s.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,n){return this.headers=Object.assign({},this.headers),this.headers[t]=n,this}then(t,n){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers["Accept-Profile"]=this.schema:this.headers["Content-Profile"]=this.schema),this.method!=="GET"&&this.method!=="HEAD"&&(this.headers["Content-Type"]="application/json");const r=this.fetch;let a=r(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async i=>{var l,o,c;let d=null,u=null,h=null,m=i.status,f=i.statusText;if(i.ok){if(this.method!=="HEAD"){const v=await i.text();v===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?u=v:u=JSON.parse(v))}const x=(l=this.headers.Prefer)===null||l===void 0?void 0:l.match(/count=(exact|planned|estimated)/),y=(o=i.headers.get("content-range"))===null||o===void 0?void 0:o.split("/");x&&y&&y.length>1&&(h=parseInt(y[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(u)&&(u.length>1?(d={code:"PGRST116",details:`Results contain ${u.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},u=null,h=null,m=406,f="Not Acceptable"):u.length===1?u=u[0]:u=null)}else{const x=await i.text();try{d=JSON.parse(x),Array.isArray(d)&&i.status===404&&(u=[],d=null,m=200,f="OK")}catch{i.status===404&&x===""?(m=204,f="No Content"):d={message:x}}if(d&&this.isMaybeSingle&&(!((c=d==null?void 0:d.details)===null||c===void 0)&&c.includes("0 rows"))&&(d=null,m=200,f="OK"),d&&this.shouldThrowOnError)throw new T2s.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}};iLe.default=M2s;var P2s=Sp&&Sp.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(aLe,"__esModule",{value:!0});const I2s=P2s(iLe);let L2s=class extends I2s.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}};aLe.default=L2s;var R2s=Sp&&Sp.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Sae,"__esModule",{value:!0});const D2s=R2s(aLe);let F2s=class extends D2s.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}};Sae.default=F2s;var O2s=Sp&&Sp.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(rLe,"__esModule",{value:!0});const vZ=O2s(Sae);let z2s=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 vZ.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 vZ.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 vZ.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 vZ.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 vZ.default({method:n,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};rLe.default=z2s;var lLe={},cLe={};Object.defineProperty(cLe,"__esModule",{value:!0});cLe.version=void 0;cLe.version="0.0.0-automated";Object.defineProperty(lLe,"__esModule",{value:!0});lLe.DEFAULT_HEADERS=void 0;const B2s=cLe;lLe.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${B2s.version}`};var vFt=Sp&&Sp.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Eet,"__esModule",{value:!0});const $2s=vFt(rLe),U2s=vFt(Sae),q2s=lLe;let V2s=class bFt{constructor(t,{headers:n={},schema:r,fetch:a}={}){this.url=t,this.headers=Object.assign(Object.assign({},q2s.DEFAULT_HEADERS),n),this.schemaName=r,this.fetch=a}from(t){const n=new URL(`${this.url}/${t}`);return new $2s.default(n,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(t){return new bFt(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 U2s.default({method:l,url:o,headers:d,schema:this.schemaName,body:c,fetch:this.fetch,allowEmpty:!1})}};Eet.default=V2s;var QW=Sp&&Sp.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(pw,"__esModule",{value:!0});pw.PostgrestError=pw.PostgrestBuilder=pw.PostgrestTransformBuilder=pw.PostgrestFilterBuilder=pw.PostgrestQueryBuilder=pw.PostgrestClient=void 0;const _Ft=QW(Eet);pw.PostgrestClient=_Ft.default;const wFt=QW(rLe);pw.PostgrestQueryBuilder=wFt.default;const jFt=QW(Sae);pw.PostgrestFilterBuilder=jFt.default;const NFt=QW(aLe);pw.PostgrestTransformBuilder=NFt.default;const kFt=QW(iLe);pw.PostgrestBuilder=kFt.default;const SFt=QW(oLe);pw.PostgrestError=SFt.default;var H2s=pw.default={PostgrestClient:_Ft.default,PostgrestQueryBuilder:wFt.default,PostgrestFilterBuilder:jFt.default,PostgrestTransformBuilder:NFt.default,PostgrestBuilder:kFt.default,PostgrestError:SFt.default};const{PostgrestClient:G2s,PostgrestQueryBuilder:kkr,PostgrestFilterBuilder:Skr,PostgrestTransformBuilder:Ckr,PostgrestBuilder:Akr,PostgrestError:Ekr}=H2s;let pHe;typeof window>"u"?pHe=require("ws"):pHe=window.WebSocket;const W2s="2.11.10",K2s={"X-Client-Info":`realtime-js/${W2s}`},Y2s="1.0.0",CFt=1e4,Z2s=1e3;var bV;(function(s){s[s.connecting=0]="connecting",s[s.open=1]="open",s[s.closing=2]="closing",s[s.closed=3]="closed"})(bV||(bV={}));var t_;(function(s){s.closed="closed",s.errored="errored",s.joined="joined",s.joining="joining",s.leaving="leaving"})(t_||(t_={}));var PS;(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"})(PS||(PS={}));var gHe;(function(s){s.websocket="websocket"})(gHe||(gHe={}));var GO;(function(s){s.Connecting="connecting",s.Open="open",s.Closing="closing",s.Closed="closed"})(GO||(GO={}));class X2s{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 AFt{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 axt=(s,t,n={})=>{var r;const a=(r=n.skipTypes)!==null&&r!==void 0?r:[];return Object.keys(t).reduce((i,l)=>(i[l]=Q2s(l,s,t,a),i),{})},Q2s=(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)?EFt(i,l):xHe(l)},EFt=(s,t)=>{if(s.charAt(0)==="_"){const n=s.slice(1,s.length);return sNs(t,n)}switch(s){case Bf.bool:return J2s(t);case Bf.float4:case Bf.float8:case Bf.int2:case Bf.int4:case Bf.int8:case Bf.numeric:case Bf.oid:return eNs(t);case Bf.json:case Bf.jsonb:return tNs(t);case Bf.timestamp:return nNs(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 xHe(t);default:return xHe(t)}},xHe=s=>s,J2s=s=>{switch(s){case"t":return!0;case"f":return!1;default:return s}},eNs=s=>{if(typeof s=="string"){const t=parseFloat(s);if(!Number.isNaN(t))return t}return s},tNs=s=>{if(typeof s=="string")try{return JSON.parse(s)}catch(t){return console.log(`JSON parse error: ${t}`),s}return s},sNs=(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=>EFt(t,o))}return s},nNs=s=>typeof s=="string"?s.replace(" ","T"):s,TFt=s=>{let t=s;return t=t.replace(/^ws/i,"http"),t=t.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),t.replace(/\/+$/,"")};class Ize{constructor(t,n,r={},a=CFt){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 ixt;(function(s){s.SYNC="sync",s.JOIN="join",s.LEAVE="leave"})(ixt||(ixt={}));class lee{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=lee.syncState(this.state,a,i,l),this.pendingDiffs.forEach(c=>{this.state=lee.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=lee.syncDiff(this.state,a,i,l),o())}),this.onJoin((a,i,l)=>{this.channel._trigger("presence",{event:"join",key:a,currentPresences:i,newPresences:l})}),this.onLeave((a,i,l)=>{this.channel._trigger("presence",{event:"leave",key:a,currentPresences:i,leftPresences:l})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(t,n,r,a){const i=this.cloneDeep(t),l=this.transformState(n),o={},c={};return this.map(i,(d,u)=>{l[d]||(c[d]=u)}),this.map(l,(d,u)=>{const h=i[d];if(h){const m=u.map(y=>y.presence_ref),f=h.map(y=>y.presence_ref),g=u.filter(y=>f.indexOf(y.presence_ref)<0),x=h.filter(y=>m.indexOf(y.presence_ref)<0);g.length>0&&(o[d]=g),x.length>0&&(c[d]=x)}else o[d]=u}),this.syncDiff(i,{joins:o,leaves:c},r,a)}static syncDiff(t,n,r,a){const{joins:i,leaves:l}={joins:this.transformState(n.joins),leaves:this.transformState(n.leaves)};return r||(r=()=>{}),a||(a=()=>{}),this.map(i,(o,c)=>{var d;const u=(d=t[o])!==null&&d!==void 0?d:[];if(t[o]=this.cloneDeep(c),u.length>0){const h=t[o].map(f=>f.presence_ref),m=u.filter(f=>h.indexOf(f.presence_ref)<0);t[o].unshift(...m)}r(o,u,c)}),this.map(l,(o,c)=>{let d=t[o];if(!d)return;const u=c.map(h=>h.presence_ref);d=d.filter(h=>u.indexOf(h.presence_ref)<0),t[o]=d,a(o,d,c),d.length===0&&delete t[o]}),t}static map(t,n){return Object.getOwnPropertyNames(t).map(r=>n(r,t[r]))}static transformState(t){return t=this.cloneDeep(t),Object.getOwnPropertyNames(t).reduce((n,r)=>{const a=t[r];return"metas"in a?n[r]=a.metas.map(i=>(i.presence_ref=i.phx_ref,delete i.phx_ref,delete i.phx_ref_prev,i)):n[r]=a,n},{})}static cloneDeep(t){return JSON.parse(JSON.stringify(t))}onJoin(t){this.caller.onJoin=t}onLeave(t){this.caller.onLeave=t}onSync(t){this.caller.onSync=t}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}}var oxt;(function(s){s.ALL="*",s.INSERT="INSERT",s.UPDATE="UPDATE",s.DELETE="DELETE"})(oxt||(oxt={}));var lxt;(function(s){s.BROADCAST="broadcast",s.PRESENCE="presence",s.POSTGRES_CHANGES="postgres_changes",s.SYSTEM="system"})(lxt||(lxt={}));var SA;(function(s){s.SUBSCRIBED="SUBSCRIBED",s.TIMED_OUT="TIMED_OUT",s.CLOSED="CLOSED",s.CHANNEL_ERROR="CHANNEL_ERROR"})(SA||(SA={}));class Tet{constructor(t,n={config:{}},r){this.topic=t,this.params=n,this.socket=r,this.bindings={},this.state=t_.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 Ize(this,PS.join,this.params,this.timeout),this.rejoinTimer=new AFt(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=t_.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=t_.closed,this.socket._remove(this)}),this._onError(a=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,a),this.state=t_.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=t_.errored,this.rejoinTimer.scheduleTimeout())}),this._on(PS.reply,{},(a,i)=>{this._trigger(this._replyEventName(i),a)}),this.presence=new lee(this),this.broadcastEndpointURL=TFt(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(SA.CHANNEL_ERROR,u)),this._onClose(()=>t==null?void 0:t(SA.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(SA.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=t_.errored,t==null||t(SA.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(u).join(", ")||"error")))}).receive("timeout",()=>{t==null||t(SA.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=t_.leaving;const n=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(PS.close,"leave",this._joinRef())};return this.joinPush.destroy(),new Promise(r=>{const a=new Ize(this,PS.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 Ize(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}=PS;if(r&&[o,c,d,u].indexOf(l)>=0&&r!==this._joinRef())return;let m=this._onMessage(l,n,r);if(n&&!m)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(l)?(a=this.bindings.postgres_changes)===null||a===void 0||a.filter(f=>{var g,x,y;return((g=f.filter)===null||g===void 0?void 0:g.event)==="*"||((y=(x=f.filter)===null||x===void 0?void 0:x.event)===null||y===void 0?void 0:y.toLocaleLowerCase())===l}).map(f=>f.callback(m,r)):(i=this.bindings[l])===null||i===void 0||i.filter(f=>{var g,x,y,v,b,w;if(["broadcast","presence","postgres_changes"].includes(l))if("id"in f){const S=f.id,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())===((y=n.data)===null||y===void 0?void 0:y.type.toLocaleLowerCase()))}else{const S=(b=(v=f==null?void 0:f.filter)===null||v===void 0?void 0:v.event)===null||b===void 0?void 0:b.toLocaleLowerCase();return S==="*"||S===((w=n==null?void 0:n.event)===null||w===void 0?void 0:w.toLocaleLowerCase())}else return f.type.toLocaleLowerCase()===l}).map(f=>{if(typeof m=="object"&&"ids"in m){const g=m.data,{schema:x,table:y,commit_timestamp:v,type:b,errors:w}=g;m=Object.assign(Object.assign({},{schema:x,table:y,commit_timestamp:v,eventType:b,new:{},old:{},errors:w}),this._getPayloadRecords(g))}f.callback(m,r)})}_isClosed(){return this.state===t_.closed}_isJoined(){return this.state===t_.joined}_isJoining(){return this.state===t_.joining}_isLeaving(){return this.state===t_.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&&Tet.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(PS.close,{},t)}_onError(t){this._on(PS.error,{},n=>t(n))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(t=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=t_.joining,this.joinPush.resend(t))}_getPayloadRecords(t){const n={new:{},old:{}};return(t.type==="INSERT"||t.type==="UPDATE")&&(n.new=axt(t.columns,t.record)),(t.type==="UPDATE"||t.type==="DELETE")&&(n.old=axt(t.columns,t.old_record)),n}}const cxt=()=>{},rNs=` addEventListener("message", (e) => { if (e.data.event === "start") { setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); } });`;class aNs{constructor(t,n){var r;this.accessTokenValue=null,this.apiKey=null,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers=K2s,this.params={},this.timeout=CFt,this.heartbeatIntervalMs=25e3,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=cxt,this.ref=0,this.logger=cxt,this.conn=null,this.sendBuffer=[],this.serializer=new X2s,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(()=>XW);return{default:c}},void 0).then(({default:c})=>c(...o)):l=fetch,(...o)=>l(...o)},this.endPoint=`${t}/${gHe.websocket}`,this.httpEndpoint=TFt(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 AFt(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=pHe),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 iNs(this.endpointURL(),void 0,{close:()=>{this.conn=null}})}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:Y2s}))}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 bV.connecting:return GO.Connecting;case bV.open:return GO.Open;case bV.closing:return GO.Closing;default:return GO.Closed}}isConnected(){return this.connectionState()===GO.Open}channel(t,n={config:{}}){const r=`realtime:${t}`,a=this.getChannels().find(i=>i.topic===r);if(a)return a;{const i=new Tet(`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(PS.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(Z2s,"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(PS.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([rNs],{type:"application/javascript"});n=URL.createObjectURL(r)}return n}}class iNs{constructor(t,n,r){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=bV.connecting,this.send=()=>{},this.url=null,this.url=t,this.close=r.close}}class Met extends Error{constructor(t){super(t),this.__isStorageError=!0,this.name="StorageError"}}function ov(s){return typeof s=="object"&&s!==null&&"__isStorageError"in s}class oNs extends Met{constructor(t,n){super(t),this.name="StorageApiError",this.status=n}toJSON(){return{name:this.name,message:this.message,status:this.status}}}class yHe extends Met{constructor(t,n){super(t),this.name="StorageUnknownError",this.originalError=n}}var lNs=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 MFt=s=>{let t;return s?t=s:typeof fetch>"u"?t=(...n)=>ri(async()=>{const{default:r}=await Promise.resolve().then(()=>XW);return{default:r}},void 0).then(({default:r})=>r(...n)):t=fetch,(...n)=>t(...n)},cNs=()=>lNs(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield ri(()=>Promise.resolve().then(()=>XW),void 0)).Response:Response}),vHe=s=>{if(Array.isArray(s))return s.map(n=>vHe(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]=vHe(r)}),t};var PB=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 Lze=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),dNs=(s,t,n)=>PB(void 0,void 0,void 0,function*(){const r=yield cNs();s instanceof r&&!(n!=null&&n.noResolveJson)?s.json().then(a=>{t(new oNs(Lze(a),s.status||500))}).catch(a=>{t(new yHe(Lze(a),a))}):t(new yHe(Lze(s),s))}),uNs=(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 Cae(s,t,n,r,a,i){return PB(this,void 0,void 0,function*(){return new Promise((l,o)=>{s(n,uNs(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=>dNs(c,o,r))})})}function xEe(s,t,n,r){return PB(this,void 0,void 0,function*(){return Cae(s,"GET",t,n,r)})}function lP(s,t,n,r,a){return PB(this,void 0,void 0,function*(){return Cae(s,"POST",t,r,a,n)})}function hNs(s,t,n,r,a){return PB(this,void 0,void 0,function*(){return Cae(s,"PUT",t,r,a,n)})}function mNs(s,t,n,r){return PB(this,void 0,void 0,function*(){return Cae(s,"HEAD",t,Object.assign(Object.assign({},n),{noResolveJson:!0}),r)})}function PFt(s,t,n,r,a){return PB(this,void 0,void 0,function*(){return Cae(s,"DELETE",t,r,a,n)})}var X_=function(s,t,n,r){function a(i){return i instanceof n?i:new n(function(l){l(i)})}return new(n||(n=Promise))(function(i,l){function o(u){try{d(r.next(u))}catch(h){l(h)}}function c(u){try{d(r.throw(u))}catch(h){l(h)}}function d(u){u.done?i(u.value):a(u.value).then(o,c)}d((r=r.apply(s,t||[])).next())})};const fNs={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},dxt={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class pNs{constructor(t,n={},r,a){this.url=t,this.headers=n,this.bucketId=r,this.fetch=MFt(a)}uploadOrUpdate(t,n,r,a){return X_(this,void 0,void 0,function*(){try{let i;const l=Object.assign(Object.assign({},dxt),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(ov(i))return{data:null,error:i};throw i}})}upload(t,n,r){return X_(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",t,n,r)})}uploadToSignedUrl(t,n,r,a){return X_(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:dxt.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(ov(c))return{data:null,error:c};throw c}})}createSignedUploadUrl(t,n){return X_(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 lP(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 Met("No token returned by API");return{data:{signedUrl:l.toString(),path:t,token:o},error:null}}catch(r){if(ov(r))return{data:null,error:r};throw r}})}update(t,n,r){return X_(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",t,n,r)})}move(t,n,r){return X_(this,void 0,void 0,function*(){try{return{data:yield lP(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(ov(a))return{data:null,error:a};throw a}})}copy(t,n,r){return X_(this,void 0,void 0,function*(){try{return{data:{path:(yield lP(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(ov(a))return{data:null,error:a};throw a}})}createSignedUrl(t,n,r){return X_(this,void 0,void 0,function*(){try{let a=this._getFinalPath(t),i=yield lP(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(ov(a))return{data:null,error:a};throw a}})}createSignedUrls(t,n,r){return X_(this,void 0,void 0,function*(){try{const a=yield lP(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(ov(a))return{data:null,error:a};throw a}})}download(t,n){return X_(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 xEe(this.fetch,`${this.url}/${a}/${o}${l}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(o){if(ov(o))return{data:null,error:o};throw o}})}info(t){return X_(this,void 0,void 0,function*(){const n=this._getFinalPath(t);try{const r=yield xEe(this.fetch,`${this.url}/object/info/${n}`,{headers:this.headers});return{data:vHe(r),error:null}}catch(r){if(ov(r))return{data:null,error:r};throw r}})}exists(t){return X_(this,void 0,void 0,function*(){const n=this._getFinalPath(t);try{return yield mNs(this.fetch,`${this.url}/object/${n}`,{headers:this.headers}),{data:!0,error:null}}catch(r){if(ov(r)&&r instanceof yHe){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 X_(this,void 0,void 0,function*(){try{return{data:yield PFt(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:t},{headers:this.headers}),error:null}}catch(n){if(ov(n))return{data:null,error:n};throw n}})}list(t,n,r){return X_(this,void 0,void 0,function*(){try{const a=Object.assign(Object.assign(Object.assign({},fNs),n),{prefix:t||""});return{data:yield lP(this.fetch,`${this.url}/object/list/${this.bucketId}`,a,{headers:this.headers},r),error:null}}catch(a){if(ov(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 gNs="2.7.1",xNs={"X-Client-Info":`storage-js/${gNs}`};var h$=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 yNs{constructor(t,n={},r){this.url=t,this.headers=Object.assign(Object.assign({},xNs),n),this.fetch=MFt(r)}listBuckets(){return h$(this,void 0,void 0,function*(){try{return{data:yield xEe(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(t){if(ov(t))return{data:null,error:t};throw t}})}getBucket(t){return h$(this,void 0,void 0,function*(){try{return{data:yield xEe(this.fetch,`${this.url}/bucket/${t}`,{headers:this.headers}),error:null}}catch(n){if(ov(n))return{data:null,error:n};throw n}})}createBucket(t,n={public:!1}){return h$(this,void 0,void 0,function*(){try{return{data:yield lP(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(ov(r))return{data:null,error:r};throw r}})}updateBucket(t,n){return h$(this,void 0,void 0,function*(){try{return{data:yield hNs(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(ov(r))return{data:null,error:r};throw r}})}emptyBucket(t){return h$(this,void 0,void 0,function*(){try{return{data:yield lP(this.fetch,`${this.url}/bucket/${t}/empty`,{},{headers:this.headers}),error:null}}catch(n){if(ov(n))return{data:null,error:n};throw n}})}deleteBucket(t){return h$(this,void 0,void 0,function*(){try{return{data:yield PFt(this.fetch,`${this.url}/bucket/${t}`,{},{headers:this.headers}),error:null}}catch(n){if(ov(n))return{data:null,error:n};throw n}})}}class vNs extends yNs{constructor(t,n={},r){super(t,n,r)}from(t){return new pNs(this.url,this.headers,t,this.fetch)}}const bNs="2.49.10";let nQ="";typeof Deno<"u"?nQ="deno":typeof document<"u"?nQ="web":typeof navigator<"u"&&navigator.product==="ReactNative"?nQ="react-native":nQ="node";const _Ns={"X-Client-Info":`supabase-js-${nQ}/${bNs}`},wNs={headers:_Ns},jNs={schema:"public"},NNs={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},kNs={};var SNs=function(s,t,n,r){function a(i){return i instanceof n?i:new n(function(l){l(i)})}return new(n||(n=Promise))(function(i,l){function o(u){try{d(r.next(u))}catch(h){l(h)}}function c(u){try{d(r.throw(u))}catch(h){l(h)}}function d(u){u.done?i(u.value):a(u.value).then(o,c)}d((r=r.apply(s,t||[])).next())})};const CNs=s=>{let t;return s?t=s:typeof fetch>"u"?t=gFt:t=fetch,(...n)=>t(...n)},ANs=()=>typeof Headers>"u"?xFt:Headers,ENs=(s,t,n)=>{const r=CNs(n),a=ANs();return(i,l)=>SNs(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 TNs=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 MNs(s){return s.endsWith("/")?s:s+"/"}function PNs(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:()=>TNs(this,void 0,void 0,function*(){return""})};return s.accessToken?m.accessToken=s.accessToken:delete m.accessToken,m}const IFt="2.69.1",uU=30*1e3,bHe=3,Rze=bHe*uU,INs="http://localhost:9999",LNs="supabase.auth.token",RNs={"X-Client-Info":`gotrue-js/${IFt}`},_He="X-Supabase-Api-Version",LFt={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},DNs=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,FNs=6e5;class Pet 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 ONs extends Pet{constructor(t,n,r){super(t,n,r),this.name="AuthApiError",this.status=n,this.code=r}}function zNs(s){return Ld(s)&&s.name==="AuthApiError"}class RFt extends Pet{constructor(t,n){super(t),this.name="AuthUnknownError",this.originalError=n}}class e6 extends Pet{constructor(t,n,r,a){super(t,r,a),this.name=n,this.status=r}}class $M extends e6{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function BNs(s){return Ld(s)&&s.name==="AuthSessionMissingError"}class Dze extends e6{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class bce extends e6{constructor(t){super(t,"AuthInvalidCredentialsError",400,void 0)}}class _ce extends e6{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 $Ns(s){return Ld(s)&&s.name==="AuthImplicitGrantRedirectError"}class uxt extends e6{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 wHe extends e6{constructor(t,n){super(t,"AuthRetryableFetchError",n,void 0)}}function Fze(s){return Ld(s)&&s.name==="AuthRetryableFetchError"}class hxt extends e6{constructor(t,n,r){super(t,"AuthWeakPasswordError",n,"weak_password"),this.reasons=r}}class cee extends e6{constructor(t){super(t,"AuthInvalidJwtError",400,"invalid_jwt")}}const mxt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),fxt=` \r=`.split(""),UNs=(()=>{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 pxt(s){const t=[],n=l=>{t.push(String.fromCodePoint(l))},r={utf8seq:0,codepoint:0},a={queue:0,queuedBits:0},i=l=>{HNs(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 VNs(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}qNs(r,t)}}function HNs(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 GNs(s){const t=[],n={queue:0,queuedBits:0},r=a=>{t.push(a)};for(let a=0;at.push(n)),new Uint8Array(t)}function KNs(s){return Math.round(Date.now()/1e3)+s}function YNs(){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 g5=()=>typeof window<"u"&&typeof document<"u",dR={tested:!1,writable:!1},dee=()=>{if(!g5())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(dR.tested)return dR.writable;const s=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(s,s),globalThis.localStorage.removeItem(s),dR.tested=!0,dR.writable=!0}catch{dR.tested=!0,dR.writable=!1}return dR.writable};function ZNs(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 FFt=s=>{let t;return s?t=s:typeof fetch>"u"?t=(...n)=>ri(async()=>{const{default:r}=await Promise.resolve().then(()=>XW);return{default:r}},void 0).then(({default:r})=>r(...n)):t=fetch,(...n)=>t(...n)},XNs=s=>typeof s=="object"&&s!==null&&"status"in s&&"ok"in s&&"json"in s&&typeof s.json=="function",OFt=async(s,t,n)=>{await s.setItem(t,JSON.stringify(n))},wce=async(s,t)=>{const n=await s.getItem(t);if(!n)return null;try{return JSON.parse(n)}catch{return n}},jce=async(s,t)=>{await s.removeItem(t)};class dLe{constructor(){this.promise=new dLe.promiseConstructor((t,n)=>{this.resolve=t,this.reject=n})}}dLe.promiseConstructor=Promise;function Oze(s){const t=s.split(".");if(t.length!==3)throw new cee("Invalid JWT structure");for(let r=0;r{setTimeout(()=>t(null),s)})}function JNs(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 eks(s){return("0"+s.toString(16)).substr(-2)}function tks(){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,eks).join("")}async function sks(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 nks(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 sks(s);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function m$(s,t,n=!1){const r=tks();let a=r;n&&(a+="/PASSWORD_RECOVERY"),await OFt(s,`${t}-code-verifier`,a);const i=await nks(r);return[i,r===i?"plain":"s256"]}const rks=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function aks(s){const t=s.headers.get(_He);if(!t||!t.match(rks))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch{return null}}function iks(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 oks(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 lks=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),cks=[502,503,504];async function gxt(s){var t;if(!XNs(s))throw new wHe(MO(s),0);if(cks.includes(s.status))throw new wHe(MO(s),s.status);let n;try{n=await s.json()}catch(i){throw new RFt(MO(i),i)}let r;const a=aks(s);if(a&&a.getTime()>=LFt["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 hxt(MO(n),s.status,((t=n.weak_password)===null||t===void 0?void 0:t.reasons)||[]);if(r==="session_not_found")throw new $M}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 hxt(MO(n),s.status,n.weak_password.reasons);throw new ONs(MO(n),s.status||500,r)}const dks=(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 Ru(s,t,n,r){var a;const i=Object.assign({},r==null?void 0:r.headers);i[_He]||(i[_He]=LFt["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 uks(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 uks(s,t,n,r,a,i){const l=dks(t,r,a,i);let o;try{o=await s(n,Object.assign({},l))}catch(c){throw console.error(c),new wHe(MO(c),0)}if(o.ok||await gxt(o),r!=null&&r.noResolveJson)return o;try{return await o.json()}catch(c){await gxt(c)}}function UM(s){var t;let n=null;pks(s)&&(n=Object.assign({},s),s.expires_at||(n.expires_at=KNs(s.expires_in)));const r=(t=s.user)!==null&&t!==void 0?t:s;return{data:{session:n,user:r},error:null}}function xxt(s){const t=UM(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 NP(s){var t;return{data:{user:(t=s.user)!==null&&t!==void 0?t:s},error:null}}function hks(s){return{data:s,error:null}}function mks(s){const{action_link:t,email_otp:n,hashed_token:r,redirect_to:a,verification_type:i}=s,l=lks(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 fks(s){return s}function pks(s){return s.access_token&&s.refresh_token&&s.expires_in}var gks=function(s,t){var n={};for(var r in s)Object.prototype.hasOwnProperty.call(s,r)&&t.indexOf(r)<0&&(n[r]=s[r]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var a=0,r=Object.getOwnPropertySymbols(s);a0&&(f.forEach(g=>{const x=parseInt(g.split(";")[0].split("=")[1].substring(0,1)),y=JSON.parse(g.split(";")[1].split("=")[1]);d[`${y}Page`]=x}),d.total=parseInt(m)),{data:Object.assign(Object.assign({},h),d),error:null}}catch(d){if(Ld(d))return{data:{users:[]},error:d};throw d}}async getUserById(t){try{return await Ru(this.fetch,"GET",`${this.url}/admin/users/${t}`,{headers:this.headers,xform:NP})}catch(n){if(Ld(n))return{data:{user:null},error:n};throw n}}async updateUserById(t,n){try{return await Ru(this.fetch,"PUT",`${this.url}/admin/users/${t}`,{body:n,headers:this.headers,xform:NP})}catch(r){if(Ld(r))return{data:{user:null},error:r};throw r}}async deleteUser(t,n=!1){try{return await Ru(this.fetch,"DELETE",`${this.url}/admin/users/${t}`,{headers:this.headers,body:{should_soft_delete:n},xform:NP})}catch(r){if(Ld(r))return{data:{user:null},error:r};throw r}}async _listFactors(t){try{const{data:n,error:r}=await Ru(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 Ru(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 yks={getItem:s=>dee()?globalThis.localStorage.getItem(s):null,setItem:(s,t)=>{dee()&&globalThis.localStorage.setItem(s,t)},removeItem:s=>{dee()&&globalThis.localStorage.removeItem(s)}};function yxt(s={}){return{getItem:t=>s[t]||null,setItem:(t,n)=>{s[t]=n},removeItem:t=>{delete s[t]}}}function vks(){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 f$={debug:!!(globalThis&&dee()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class zFt extends Error{constructor(t){super(t),this.isAcquireTimeout=!0}}class bks extends zFt{}async function _ks(s,t,n){f$.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",s,t);const r=new globalThis.AbortController;return t>0&&setTimeout(()=>{r.abort(),f$.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){f$.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",s,a.name);try{return await n()}finally{f$.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",s,a.name)}}else{if(t===0)throw f$.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",s),new bks(`Acquiring an exclusive Navigator LockManager lock "${s}" immediately failed`);if(f$.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()}}))}vks();const wks={url:INs,storageKey:LNs,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:RNs,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1};async function vxt(s,t,n){return await n()}class Gte{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=Gte.nextInstanceID,Gte.nextInstanceID+=1,this.instanceID>0&&g5()&&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({},wks),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 xks({url:a.url,headers:a.headers,fetch:a.fetch}),this.url=a.url,this.headers=a.headers,this.fetch=FFt(a.fetch),this.lock=a.lock||vxt,this.detectSessionInUrl=a.detectSessionInUrl,this.flowType=a.flowType,this.hasCustomAuthorizationHeader=a.hasCustomAuthorizationHeader,a.lock?this.lock=a.lock:g5()&&(!((n=globalThis==null?void 0:globalThis.navigator)===null||n===void 0)&&n.locks)?this.lock=_ks:this.lock=vxt,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:dee()?this.storage=yks:(this.memoryStorage={},this.storage=yxt(this.memoryStorage)):(this.memoryStorage={},this.storage=yxt(this.memoryStorage)),g5()&&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} (${IFt}) ${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=ZNs(window.location.href);let r="none";if(this._isImplicitGrantCallback(n)?r="implicit":await this._isPKCECallback(n)&&(r="pkce"),g5()&&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),$Ns(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 RFt("Unexpected error during initialization",n)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(t){var n,r,a;try{const i=await Ru(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:UM}),{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 m$(this.storage,this.storageKey)),i=await Ru(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:UM})}else if("phone"in t){const{phone:u,password:h,options:m}=t;i=await Ru(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:UM})}else throw new bce("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 Ru(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:xxt})}else if("phone"in t){const{phone:i,password:l,options:o}=t;n=await Ru(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:xxt})}else throw new bce("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 Dze}:(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 wce(this.storage,`${this.storageKey}-code-verifier`),[r,a]=(n??"").split("/");try{const{data:i,error:l}=await Ru(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:t,code_verifier:r},xform:UM});if(await jce(this.storage,`${this.storageKey}-code-verifier`),l)throw l;return!i||!i.session||!i.user?{data:{user:null,session:null,redirectType:null},error:new Dze}:(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 Ru(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:UM}),{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 Dze}:(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 m$(this.storage,this.storageKey));const{error:h}=await Ru(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 Ru(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 bce("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 Ru(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},t),{gotrue_meta_security:{captcha_token:i}}),redirectTo:a,xform:UM});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 m$(this.storage,this.storageKey)),await Ru(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:hks})}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 $M;const{error:a}=await Ru(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 Ru(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 Ru(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 bce("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 wce(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 Ru(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:t,xform:NP}):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 $M}:await Ru(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:NP})})}catch(n){if(Ld(n))return BNs(n)&&(await this._removeSession(),await jce(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 $M;const l=a.session;let o=null,c=null;this.flowType==="pkce"&&t.email!=null&&([o,c]=await m$(this.storage,this.storageKey));const{data:d,error:u}=await Ru(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:NP});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 $M;const n=Date.now()/1e3;let r=n,a=!0,i=null;const{payload:l}=Oze(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 $M;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(!g5())throw new _ce("No browser detected.");if(t.error||t.error_description||t.error_code)throw new _ce(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 uxt("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new _ce("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 uxt("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 _ce("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<=uU&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${f}s, should have been closer to ${h}s`);const g=m-h;u-g>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",g,m,u):u-g<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",g,m,u);const{data:x,error:y}=await this._getUser(i);if(y)throw y;const v={provider_token:r,provider_refresh_token:a,access_token:i,expires_in:h,expires_at:m,refresh_token:l,token_type:d,user:x.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:v,redirectType:t.type},error:null}}catch(r){if(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 wce(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&&!(zNs(o)&&(o.status===404||o.status===401||o.status===403)))return{error:o}}return t!=="others"&&(await this._removeSession(),await jce(this.storage,`${this.storageKey}-code-verifier`)),{error:null}})}onAuthStateChange(t){const n=YNs(),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 m$(this.storage,this.storageKey,!0));try{return await Ru(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 Ru(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 g5()&&!(!((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 Ru(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 JNs(async a=>(a>0&&await QNs(200*Math.pow(2,a-1)),this._debug(n,"refreshing attempt",a),await Ru(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:t},headers:this.headers,xform:UM})),(a,i)=>{const l=200*Math.pow(2,a);return i&&Fze(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(),uU);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)/uU);this._debug("#_autoRefreshTokenTick()",`access token expires in ${a} ticks, a tick lasts ${uU}ms, refresh threshold is ${bHe} ticks`),a<=bHe&&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 zFt)this._debug("auto refresh token tick lock not available");else throw t}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!g5()||!(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 m$(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 Ru(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 Ru(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 Ru(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 Ru(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}=Oze(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+FNs>Date.now()))return r;const{data:a,error:i}=await Ru(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 cee("JWKS is empty");if(this.jwks=a,this.jwks_cached_at=Date.now(),r=a.keys.find(l=>l.kid===t),!r)throw new cee("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}}=Oze(r);if(iks(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=oks(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,WNs(`${o}.${c}`)))throw new cee("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}}}Gte.nextInstanceID=0;const jks=Gte;class Nks extends jks{constructor(t){super(t)}}var kks=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 Sks{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=MNs(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:jNs,realtime:kNs,auth:Object.assign(Object.assign({},NNs),{storageKey:d}),global:wNs},h=PNs(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=ENs(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 G2s(new URL("rest/v1",c).href,{headers:this.headers,schema:h.db.schema,fetch:this.fetch}),h.accessToken||this._listenForAuthEvents()}get functions(){return new w2s(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}get storage(){return new vNs(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 kks(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 Nks({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 aNs(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 Cks=(s,t,n)=>new Sks(s,t,n);function Aks(){var y,v;if(typeof window>"u")return;const s=location.hostname,n=["lovableproject.com","lovableproject-dev.com","lovable.app","gpt-eng.com","gptengineer.run"].some(b=>s===b||s.endsWith("."+b)),r="[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}",a=n?((y=s.match(new RegExp("^(?:id-preview(?:-[a-z0-9]+)?|project)--("+r+")(?:-dev)?(?=\\.|$)","i")))==null?void 0:y[1])??((v=s.match(new RegExp("^("+r+")(?=[.-])","i")))==null?void 0:v[1]):void 0,i=window.parent&&window.parent!==window;if(!a||!i)return localStorage;const l=s.endsWith(".lovableproject-dev.com")||s.endsWith(".gpt-eng.com"),o=l?/^https:\/\/([a-z0-9-]+\.)*(lovable\.dev|gptengineer\.app)$|^http:\/\/localhost:3000$/:/^https:\/\/([a-z0-9-]+\.)*(lovable\.dev|gptengineer\.app)$/,c=location.ancestorOrigins&&location.ancestorOrigins[0]||(document.referrer?new URL(document.referrer).origin:""),d=c&&o.test(c)?[c]:l?["https://lovable.dev","http://localhost:3000"]:["https://lovable.dev"],u="lovable-preview-auth:result",h=2e3,m=()=>Math.random().toString(36).slice(2)+Date.now().toString(36),f=(b,w,S)=>new Promise(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(S=>{S&&S.ok&&typeof S.value=="string"&&localStorage.getItem(b)===w&&(S.value===""?localStorage.removeItem(b):localStorage.setItem(b,S.value))})),removeItem:b=>(localStorage.removeItem(b),f("lovable-preview-auth:remove",b).then(()=>{}))}}const Eks="https://relzejiswnotikjgvjhz.supabase.co",Tks="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM",q=Cks(Eks,Tks,{auth:{storage:Aks(),persistSession:!0,autoRefreshToken:!0}}),Mks=Object.freeze(Object.defineProperty({__proto__:null,supabase:q},Symbol.toStringTag,{value:"Module"})),BFt=j.createContext(void 0),Pks=({children:s})=>{const[t,n]=j.useState(null),[r,a]=j.useState(null),[i,l]=j.useState(!0),[o,c]=j.useState(!0),[d,u]=j.useState(!1),[h,m]=j.useState(!1),[f,g]=j.useState(!1),[x,y]=j.useState(null),[v,b]=j.useState([]),[w,S]=j.useState(null),A=j.useRef(null),E=j.useRef(!1),I=j.useRef(!1),P=Xn(),R=()=>{u(!1),m(!1),g(!1),y(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:Y,error:X},{data:ae,error:le},{data:ne,error:te}]=await Promise.all([q.rpc("has_role",{_user_id:V,_role:"admin"}),q.rpc("has_role",{_user_id:V,_role:"brokerage_manager"}),q.rpc("has_role",{_user_id:V,_role:"coach"})]);if(X||le)console.error("Role RPC errors:",{isAdminError:X,isBrokerError:le,isCoachError:te}),u(!1),m(!1),g(!1);else{const _e=!!Y,he=!!ae,ue=!!ne;console.log("RPC roles result:",{adminValue:_e,brokerValue:he,coachValue:ue}),u(_e),m(he),g(ue)}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 _e=J.paused_reason;try{sessionStorage.setItem("accountPausedReason",_e||"")}catch{}await q.auth.signOut(),R(),P("/auth?paused=1",{replace:!0});return}if(y(!ce&&J?J.brokerage_id:null),ae){console.log("Fetching managed brokerages for user:",V);const{data:_e,error:he}=await q.from("brokerage_manager_assignments").select("brokerage_id").eq("user_id",V);if(console.log("Managed brokerage assignments result:",{assignments:_e,assignmentsError:he}),he||!_e){console.error("Error fetching managed brokerage assignments:",he),b([]);return}const ue=Array.from(new Set(_e.map(Le=>Le.brokerage_id).filter(Boolean)));if(ue.length===0){b([]);return}const{data:ve,error:Ee}=await q.from("brokerages").select("id, name").in("id",ue);if(console.log("Managed brokerages details result:",{brokeragesData:ve,brokeragesError:Ee}),Ee||!ve){console.error("Error fetching managed brokerages details:",Ee),b([]);return}const Se=ve.map(Le=>({id:Le.id,name:Le.name})).sort((Le,Fe)=>ue.indexOf(Le.id)-ue.indexOf(Fe.id));console.log("Parsed managed brokerages:",Se),b(Se),Se.length>0&&S(Le=>Le??Se[0].id)}else console.log("User is not a brokerage manager, skipping managed brokerages fetch"),b([]);A.current=V,E.current=!0}catch(Y){console.error("Unexpected error in checkRoles:",Y),R()}finally{window.clearTimeout(G),I.current=!1,c(!1)}};j.useEffect(()=>{let V=!0,G=!1;const Y=()=>{!V||G||(G=!0,l(!1))},{data:{subscription:X}}=q.auth.onAuthStateChange((le,ne)=>{console.log("Auth event:",le),V&&(a(ne),n((ne==null?void 0:ne.user)??null),Y(),le==="PASSWORD_RECOVERY"&&(console.log("Password recovery detected, redirecting to profile"),setTimeout(()=>{P("/profile?reset=true")},100)),ne!=null&&ne.user?(!E.current||A.current!==ne.user.id)&&setTimeout(()=>{D(ne.user.id)},0):(R(),c(!1)))}),ae=window.setTimeout(()=>{console.warn("Auth initialization timeout reached. Continuing without blocking UI."),Y()},8e3);return()=>{V=!1,window.clearTimeout(ae),X.unsubscribe()}},[]);const O=async(V,G)=>{var le;const Y=(V||"").trim().toLowerCase(),{data:X,error:ae}=await q.auth.signInWithPassword({email:Y,password:G});if(ae)throw re.error(/invalid login credentials/i.test(ae.message)?`That email and password don't match an account. Check the email address, or use "Forgot password" to set a new password.`:ae.message),ae;if((le=X.user)!=null&&le.id){const{data:ne}=await q.from("profiles").select("is_paused, paused_reason").eq("id",X.user.id).maybeSingle();if(ne!=null&&ne.is_paused){const te=ne.paused_reason||"";try{sessionStorage.setItem("accountPausedReason",te)}catch{}await q.auth.signOut(),R(),n(null),a(null);const J=new Error(te?`Your account is paused. ${te}`:"Your account is paused. Please contact LevelUp support to reactivate it.");throw J.name="AccountPaused",re.error(J.message),J}}re.success("Welcome back!")},U=async(V,G,Y)=>{var te;const X="https://dashboard.relevelup.com/dashboard",ae=localStorage.getItem("levelup_referral_code")||null,{data:le,error:ne}=await q.auth.signUp({email:V,password:G,options:{emailRedirectTo:X,data:{name:Y,referred_by_code:ae}}});if(ne)throw re.error(ne.message),ne;if(ae&&((te=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)}re.success("Account created! Welcome to LevelUp."),P("/dashboard")},W=async()=>{try{const{data:{session:V}}=await q.auth.getSession();if(V){const{error:G}=await q.auth.signOut();G?G.message==="Auth session missing!"?console.warn("Sign out warning (ignored):",G.message):(console.error("Sign out error:",G),re.error(G.message)):re.success("Signed out successfully")}else console.log("No active session found, redirecting to auth");n(null),a(null),u(!1),m(!1),y(null),b([]),S(null),P("/auth")}catch(V){console.error("Unexpected sign out error:",V),P("/auth")}};return e.jsx(BFt.Provider,{value:{user:t,session:r,loading:i,rolesLoading:o,signIn:O,signUp:U,signOut:W,isAdmin:d,isBrokerageManager:h,isCoach:f,brokerageId:x,managedBrokerages:v,selectedBrokerageId:w,setSelectedBrokerageId:S},children:s})},bs=()=>{const s=j.useContext(BFt);if(s===void 0)throw new Error("useAuth must be used within an AuthProvider");return s},$Ft=j.createContext({onlineUsers:[],totalOnline:0}),Iks=3*60*1e3,Lks=45*1e3,Rks=30*1e3,Dks=({children:s})=>{const{user:t,brokerageId:n,isAdmin:r}=bs(),[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()-Iks).toISOString(),{data:h}=await q.from("user_presence").select("user_id, last_seen_at, online_since").gte("last_seen_at",u).order("last_seen_at",{ascending:!1}).limit(200);if(!(h!=null&&h.length)){i([]);return}const m=h.map(x=>x.user_id),{data:f}=await q.from("profiles").select("id, name, email, avatar_url, brokerage_id").in("id",m),g=new Map((f||[]).map(x=>[x.id,x]));i(h.map(x=>{var v;const y=g.get(x.user_id);return{id:x.user_id,name:(y==null?void 0:y.name)||((v=y==null?void 0:y.email)==null?void 0:v.split("@")[0])||"Member",avatarUrl:(y==null?void 0:y.avatar_url)||void 0,brokerageId:(y==null?void 0:y.brokerage_id)||void 0,onlineSince:x.online_since||x.last_seen_at}}))},[t==null?void 0:t.id]);j.useEffect(()=>{if(!t){i([]);return}l.current=new Date().toISOString();let u=!1;const h=async()=>{u||(await o(),await c())};h();const m=window.setInterval(()=>{o()},Lks),f=window.setInterval(()=>{c()},Rks),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($Ft.Provider,{value:{onlineUsers:d,totalOnline:d.length},children:s})},UFt=()=>j.useContext($Ft),qFt=j.createContext(void 0),uR="levelup_admin_session",xM="levelup_impersonation",zze="levelup_impersonation_return",Fks=({children:s})=>{const[t,n]=j.useState(!1),[r,a]=j.useState(null),[i,l]=j.useState(!1);j.useEffect(()=>{const d=sessionStorage.getItem(xM);if(d)try{const u=JSON.parse(d);n(!0),a(u)}catch{sessionStorage.removeItem(xM)}},[]);const o=async(d,u)=>{l(!0);try{const{data:{session:h}}=await q.auth.getSession();if(!h)return re.error("No active session found"),!1;const m={access_token:h.access_token,refresh_token:h.refresh_token};sessionStorage.setItem(uR,JSON.stringify(m)),u&&sessionStorage.setItem(zze,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(xM,JSON.stringify(x)),g.method==="session"){const{error:y}=await q.auth.setSession({access_token:g.access_token,refresh_token:g.refresh_token});if(y)throw console.error("Set session error:",y),sessionStorage.removeItem(uR),sessionStorage.removeItem(xM),new Error("Failed to establish impersonation session")}else{const y=g.type||"recovery",{error:v}=await q.auth.verifyOtp({token_hash:g.token_hash,type:y});if(v)throw console.error("Verify OTP error:",v),sessionStorage.removeItem(uR),sessionStorage.removeItem(xM),new Error("Failed to establish impersonation session")}return n(!0),a(x),re.success(`Now viewing as ${x.name}`),window.location.href="/dashboard",!0}catch(h){return console.error("Impersonation error:",h),re.error(h.message||"Failed to impersonate user"),sessionStorage.removeItem(uR),sessionStorage.removeItem(xM),!1}finally{l(!1)}},c=async()=>{l(!0);try{const d=sessionStorage.getItem(uR);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(uR),sessionStorage.removeItem(xM),h){console.error("Failed to restore admin session:",h),re.error("Admin session expired, please sign in again"),window.location.href="/auth";return}n(!1),a(null),re.success("Returned to your account");const m=sessionStorage.getItem(zze)||"/admin/members";sessionStorage.removeItem(zze),window.location.href=m}catch(d){console.error("Stop impersonation error:",d),re.error("Failed to restore admin session"),sessionStorage.removeItem(uR),sessionStorage.removeItem(xM),window.location.href="/auth"}finally{l(!1)}};return e.jsx(qFt.Provider,{value:{isImpersonating:t,impersonatedUser:r,startImpersonation:o,stopImpersonation:c,isLoading:i},children:s})},uLe=()=>{const s=j.useContext(qFt);if(s===void 0)throw new Error("useImpersonation must be used within an ImpersonationProvider");return s},Oks=()=>{const{isImpersonating:s,impersonatedUser:t,stopImpersonation:n,isLoading:r}=uLe();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(pr,{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"})]})})]})})},VFt=j.createContext(void 0),p$="levelup_acting_as",Nce="levelup_acting_as_self",zks=({children:s})=>{const{user:t}=bs(),[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(Nce)==="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(Nce)==="true")f(!0),o(null),d({});else{const R=sessionStorage.getItem(p$);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(p$,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(p$,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(Nce),b?(sessionStorage.setItem(p$,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(p$),d({}))},x=()=>{f(!0),o(null),d({}),sessionStorage.setItem(Nce,"true"),sessionStorage.removeItem(p$)},y=b=>!n||m?!0:c[b]===!0,v=n&&l&&!m?l.id:(t==null?void 0:t.id)||null;return e.jsx(VFt.Provider,{value:{isAssistant:n,assignedAgents:a,actingAsAgent:l,setActingAsAgent:g,effectiveUserId:v,permissions:c,hasPermission:y,isLoading:u,isActingAsSelf:m,setActingAsSelf:x},children:s})},Aae=()=>{const s=j.useContext(VFt);if(s===void 0)throw new Error("useActingAs must be used within an ActingAsProvider");return s},Sa=()=>{const{effectiveUserId:s}=Aae();return s};var Bks=Object.defineProperty,cT=(s,t)=>Bks(s,"name",{value:t,configurable:!0}),HFt="Avatar",[$ks,Tkr]=tp(HFt),Uks=[0,()=>{}],[qks,GFt]=$ks(HFt),WFt=j.forwardRef(cT(function(t,n){const{__scopeAvatar:r,...a}=t,[i,l]=j.useState("idle"),[o,c]=XFt();return e.jsx(qks,{scope:r,imageLoadingStatus:i,setImageLoadingStatus:l,imageCount:o,setImageCount:c,children:e.jsx(Ei.span,{...a,ref:n})})},"Avatar")),Vks="AvatarImage",KFt=j.forwardRef(cT(function(t,n){const{__scopeAvatar:r,src:a,onLoadingStatusChange:i,...l}=t,o=GFt(Vks,r);o.setImageCount;const c=ZFt(a,{referrerPolicy:l.referrerPolicy,crossOrigin:l.crossOrigin,loadingStatus:o.imageLoadingStatus,setLoadingStatus:o.setImageLoadingStatus}),d=Zp(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")),Hks="AvatarFallback",YFt=j.forwardRef(cT(function(t,n){const{__scopeAvatar:r,delayMs:a,...i}=t,l=GFt(Hks,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 ZFt(s,{loadingStatus:t,setLoadingStatus:n,referrerPolicy:r,crossOrigin:a}){return Af(()=>{if(!s){n("error");return}const i=new window.Image,l=cT(c=>{const d=c.currentTarget;n(jHe(d))},"handleLoad"),o=cT(()=>n("error"),"handleError");return i.addEventListener("load",l),i.addEventListener("error",o),r&&(i.referrerPolicy=r),i.crossOrigin=a??null,i.src=s,n(jHe(i)),()=>{i.removeEventListener("load",l),i.removeEventListener("error",o),n("idle")}},[s,a,r,n]),t}cT(ZFt,"useImageLoadingStatus");function jHe(s){return s.complete?s.naturalWidth>0?"loaded":"error":"loading"}cT(jHe,"getImageLoadingStatus");function XFt(){return Uks}cT(XFt,"useImageCount");function Gks(s){}cT(Gks,"useUpdateImageCount");const Oa=j.forwardRef(({className:s,...t},n)=>e.jsx(WFt,{ref:n,className:Pt("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",s),...t}));Oa.displayName=WFt.displayName;const Ii=j.forwardRef(({className:s,...t},n)=>e.jsx(KFt,{ref:n,className:Pt("aspect-square h-full w-full",s),...t}));Ii.displayName=KFt.displayName;const za=j.forwardRef(({className:s,...t},n)=>e.jsx(YFt,{ref:n,className:Pt("flex h-full w-full items-center justify-center rounded-full bg-muted",s),...t}));za.displayName=YFt.displayName;const Wks=MB("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(Wks({variant:t}),s),...n})}var Kks=Object.defineProperty,Yks=(s,t)=>Kks(s,"name",{value:t,configurable:!0}),Zks=j.createContext(void 0);function i3(s){const t=j.useContext(Zks);return s||t||"ltr"}Yks(i3,"useDirection");var Xks=Object.defineProperty,Iet=(s,t)=>Xks(s,"name",{value:t,configurable:!0}),Bze=!1;function QFt(){const[s,t]=j.useState(Bze);return j.useEffect(()=>{Bze||(Bze=!0,t(!0))},[]),s}Iet(QFt,"useIsHydrated");var JFt=SB[" useSyncExternalStore ".trim().toString()];function eOt(){return()=>{}}Iet(eOt,"subscribe");function tOt(){return JFt(eOt,()=>!0,()=>!1)}Iet(tOt,"useIsHydratedModern");var Qks=typeof JFt=="function"?tOt:QFt,Jks=Object.defineProperty,IB=(s,t)=>Jks(s,"name",{value:t,configurable:!0}),$ze="rovingFocusGroup.onEntryFocus",eSs={bubbles:!1,cancelable:!0},hLe="RovingFocusGroup",[NHe,sOt,tSs]=EB(hLe),[sSs,t6]=tp(hLe,[tSs]),[nSs,rSs]=sSs(hLe),aSs=j.forwardRef(IB(function(t,n){return e.jsx(NHe.Provider,{scope:t.__scopeRovingFocusGroup,children:e.jsx(NHe.Slot,{scope:t.__scopeRovingFocusGroup,children:e.jsx(iSs,{...t,ref:n})})})},"RovingFocusGroup")),iSs=j.forwardRef(IB(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=i3(l),[y,v]=hy({prop:o,defaultProp:c??null,onChange:d,caller:hLe}),[b,w]=j.useState(!1),S=Zp(u),A=sOt(r),E=j.useRef(!1),[I,P]=j.useState(0);return j.useEffect(()=>{const R=f.current;if(R)return R.addEventListener($ze,S),()=>R.removeEventListener($ze,S)},[S]),e.jsx(nSs,{scope:r,orientation:a,dir:x,loop:i,currentTabStopId:y,onItemFocus:j.useCallback(R=>v(R),[v]),onItemShiftTab:j.useCallback(()=>w(!0),[]),onFocusableItemAdd:j.useCallback(()=>P(R=>R+1),[]),onFocusableItemRemove:j.useCallback(()=>P(R=>R-1),[]),children:e.jsx(Ei.div,{tabIndex:b||I===0?-1:0,"data-orientation":a,...m,ref:g,style:{outline:"none",...t.style},onMouseDown:Ra(t.onMouseDown,()=>{E.current=!0}),onFocus:Ra(t.onFocus,R=>{const D=!E.current;if(R.target===R.currentTarget&&D&&!b){const O=new CustomEvent($ze,eSs);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===y),Y=[W,V,...U].filter(Boolean).map(X=>X.ref.current);Let(Y,h)}}E.current=!1}),onBlur:Ra(t.onBlur,()=>w(!1))})})},"RovingFocusGroupImpl")),oSs="RovingFocusGroupItem",lSs=j.forwardRef(IB(function(t,n){const{__scopeRovingFocusGroup:r,focusable:a=!0,active:i=!1,tabStopId:l,children:o,...c}=t,d=uy(),u=l||d,h=rSs(oSs,r),m=h.currentTabStopId===u,f=sOt(r),{onFocusableItemAdd:g,onFocusableItemRemove:x,currentTabStopId:y}=h,v=Qks();return Af(()=>{if(!(!v||!a))return g(),()=>x()},[v,a,g,x]),j.useEffect(()=>{if(!(v||!a))return g(),()=>x()},[v,a,g,x]),e.jsx(NHe.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=rOt(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?aOt(A,E+1):A.slice(E+1)}setTimeout(()=>Let(A))}}),children:typeof o=="function"?o({isCurrentTabStop:m,hasTabStop:y!=null}):o})})},"RovingFocusGroupItem")),cSs={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function nOt(s,t){return t!=="rtl"?s:s==="ArrowLeft"?"ArrowRight":s==="ArrowRight"?"ArrowLeft":s}IB(nOt,"getDirectionAwareKey");function rOt(s,t,n){const r=nOt(s.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return cSs[r]}IB(rOt,"getFocusIntent");function Let(s,t=!1){const n=document.activeElement;for(const r of s)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}IB(Let,"focusFirst");function aOt(s,t){return s.map((n,r)=>s[(t+r)%s.length])}IB(aOt,"wrapArray");var mLe=aSs,fLe=lSs,dSs=Object.defineProperty,Uh=(s,t)=>dSs(s,"name",{value:t,configurable:!0}),kHe=["Enter"," "],uSs=["ArrowDown","PageUp","Home"],iOt=["ArrowUp","PageDown","End"],hSs=[...uSs,...iOt],mSs={ltr:[...kHe,"ArrowRight"],rtl:[...kHe,"ArrowLeft"]},fSs={ltr:["ArrowLeft"],rtl:["ArrowRight"]},pLe="Menu",[Wte,pSs,gSs]=EB(pLe),[LB,oOt]=tp(pLe,[gSs,r3,t6]),Ret=r3(),lOt=t6(),[xSs,RB]=LB(pLe),[ySs,Eae]=LB(pLe),vSs=Uh(s=>{const{__scopeMenu:t,open:n=!1,children:r,dir:a,onOpenChange:i,modal:l=!0}=s,o=Ret(t),[c,d]=j.useState(null),u=j.useRef(!1),h=Zp(i),m=i3(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(wae,{...o,children:e.jsx(xSs,{scope:t,open:n,onOpenChange:h,content:c,onContentChange:d,children:e.jsx(ySs,{scope:t,onClose:j.useCallback(()=>h(!1),[h]),isUsingKeyboardRef:u,dir:m,modal:l,children:r})})})},"Menu"),cOt=j.forwardRef(Uh(function(t,n){const{__scopeMenu:r,...a}=t,i=Ret(r);return e.jsx(jae,{...i,...a,ref:n})},"MenuAnchor")),dOt="MenuPortal",[bSs,uOt]=LB(dOt,{forceMount:void 0}),_Ss=Uh(s=>{const{__scopeMenu:t,forceMount:n,children:r,container:a}=s,i=RB(dOt,t);return e.jsx(bSs,{scope:t,forceMount:n,children:e.jsx(py,{present:n||i.open,children:e.jsx(gae,{asChild:!0,container:a,children:r})})})},"MenuPortal"),nC="MenuContent",[wSs,Det]=LB(nC),jSs=j.forwardRef(Uh(function(t,n){const r=uOt(nC,t.__scopeMenu),{forceMount:a=r.forceMount,...i}=t,l=RB(nC,t.__scopeMenu),o=Eae(nC,t.__scopeMenu);return e.jsx(Wte.Provider,{scope:t.__scopeMenu,children:e.jsx(py,{present:a||l.open,children:e.jsx(Wte.Slot,{scope:t.__scopeMenu,children:o.modal?e.jsx(NSs,{...i,ref:n}):e.jsx(kSs,{...i,ref:n})})})})},"MenuContent")),NSs=j.forwardRef(Uh(function(t,n){const r=RB(nC,t.__scopeMenu),a=j.useRef(null),i=Vo(n,a);return j.useEffect(()=>{const l=a.current;if(l)return VIe(l)},[]),e.jsx(Fet,{...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")),kSs=j.forwardRef(Uh(function(t,n){const r=RB(nC,t.__scopeMenu);return e.jsx(Fet,{...t,ref:n,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>r.onOpenChange(!1)})},"MenuRootContentNonModal")),SSs=mC("MenuContent.ScrollLock"),Fet=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,...y}=t,v=RB(nC,r),b=Eae(nC,r),w=Ret(r),S=lOt(r),A=pSs(r),[E,I]=j.useState(null),P=j.useRef(null),R=Vo(n,P,v.onContentChange),D=j.useRef(0),O=j.useRef(""),U=j.useRef(0),W=j.useRef(null),V=j.useRef("right"),G=j.useRef(0),Y=x?yae:j.Fragment,X=x?{as:SSs,allowPinchZoom:!0}:void 0,ae=Uh(ne=>{var Ee,Se;const te=O.current+ne,J=A().filter(Le=>!Le.disabled),ce=document.activeElement,_e=(Ee=J.find(Le=>Le.ref.current===ce))==null?void 0:Ee.textValue,he=J.map(Le=>Le.textValue),ue=yOt(he,te,_e),ve=(Se=J.find(Le=>Le.textValue===ue))==null?void 0:Se.ref.current;Uh(function Le(Fe){O.current=Fe,window.clearTimeout(D.current),Fe!==""&&(D.current=window.setTimeout(()=>Le(""),1e3))},"updateSearch")(te),ve&&setTimeout(()=>ve.focus())},"handleTypeaheadSearch");j.useEffect(()=>()=>window.clearTimeout(D.current),[]),UW();const le=j.useCallback(ne=>{var J,ce;return V.current===((J=W.current)==null?void 0:J.side)&&bOt(ne,(ce=W.current)==null?void 0:ce.area)},[]);return e.jsx(wSs,{scope:r,searchRef:O,onItemEnter:j.useCallback(ne=>{le(ne)&&ne.preventDefault()},[le]),onItemLeave:j.useCallback(ne=>{var te;le(ne)||((te=P.current)==null||te.focus(),I(null))},[le]),onTriggerLeave:j.useCallback(ne=>{le(ne)&&ne.preventDefault()},[le]),pointerGraceTimerRef:U,onPointerGraceIntentChange:j.useCallback(ne=>{W.current=ne},[]),children:e.jsx(Y,{...X,children:e.jsx(UIe,{asChild:!0,trapped:i,onMountAutoFocus:Ra(l,ne=>{var te;ne.preventDefault(),(te=P.current)==null||te.focus({preventScroll:!0})}),onUnmountAutoFocus:o,children:e.jsx(TB,{asChild:!0,disableOutsidePointerEvents:c,onEscapeKeyDown:u,onPointerDownOutside:h,onFocusOutside:m,onInteractOutside:f,onDismiss:g,children:e.jsx(mLe,{asChild:!0,...S,dir:b.dir,orientation:"vertical",loop:a,currentTabStopId:E,onCurrentTabStopIdChange:I,onEntryFocus:Ra(d,ne=>{b.isUsingKeyboardRef.current||ne.preventDefault()}),preventScrollOnEntryFocus:!0,children:e.jsx(Nae,{role:"menu","aria-orientation":"vertical","data-state":zet(v.open),"data-radix-menu-content":"",dir:b.dir,...w,...y,ref:R,style:{outline:"none",...y.style},onKeyDown:Ra(y.onKeyDown,ne=>{const J=ne.target.closest("[data-radix-menu-content]")===ne.currentTarget,ce=ne.ctrlKey||ne.altKey||ne.metaKey,_e=ne.key.length===1;J&&(ne.key==="Tab"&&ne.preventDefault(),!ce&&_e&&ae(ne.key));const he=P.current;if(ne.target!==he||!hSs.includes(ne.key))return;ne.preventDefault();const ve=A().filter(Ee=>!Ee.disabled).map(Ee=>Ee.ref.current);iOt.includes(ne.key)&&ve.reverse(),gOt(ve)}),onBlur:Ra(t.onBlur,ne=>{ne.currentTarget.contains(ne.target)||(window.clearTimeout(D.current),O.current="")}),onPointerMove:Ra(t.onPointerMove,xG(ne=>{const te=ne.target,J=G.current!==ne.clientX;if(ne.currentTarget.contains(te)&&J){const ce=ne.clientX>G.current?"right":"left";V.current=ce,G.current=ne.clientX}}))})})})})})})},"MenuContentImpl")),CSs=j.forwardRef(Uh(function(t,n){const{__scopeMenu:r,...a}=t;return e.jsx(Ei.div,{...a,ref:n})},"MenuLabel")),SHe="MenuItem",bxt="menu.itemSelect",Oet=j.forwardRef(Uh(function(t,n){const{disabled:r=!1,onSelect:a,...i}=t,l=j.useRef(null),o=Eae(SHe,t.__scopeMenu),c=Det(SHe,t.__scopeMenu),d=Vo(n,l),u=j.useRef(!1),h=Uh(()=>{const m=l.current;if(!r&&m){const f=new CustomEvent(bxt,{bubbles:!0,cancelable:!0});m.addEventListener(bxt,g=>a==null?void 0:a(g),{once:!0}),OIe(m,f),f.defaultPrevented?u.current=!1:o.onClose()}},"handleSelect");return e.jsx(hOt,{...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===" "||kHe.includes(m.key)&&(m.currentTarget.click(),m.preventDefault())})})},"MenuItem")),hOt=j.forwardRef(Uh(function(t,n){const{__scopeMenu:r,disabled:a=!1,textValue:i,...l}=t,o=Det(SHe,r),c=lOt(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(Wte.ItemSlot,{scope:r,disabled:a,textValue:i??f,children:e.jsx(fLe,{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,xG(x=>{a?o.onItemLeave(x):(o.onItemEnter(x),x.defaultPrevented||x.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:Ra(t.onPointerLeave,xG(x=>o.onItemLeave(x))),onFocus:Ra(t.onFocus,()=>m(!0)),onBlur:Ra(t.onBlur,()=>m(!1))})})})},"MenuItemImpl")),ASs=j.forwardRef(Uh(function(t,n){const{checked:r=!1,onCheckedChange:a,...i}=t;return e.jsx(fOt,{scope:t.__scopeMenu,checked:r,children:e.jsx(Oet,{role:"menuitemcheckbox","aria-checked":Kte(r)?"mixed":r,...i,ref:n,"data-state":gLe(r),onSelect:Ra(i.onSelect,()=>a==null?void 0:a(Kte(r)?!0:!r),{checkForDefaultPrevented:!1})})})},"MenuCheckboxItem")),ESs="MenuRadioGroup",[Mkr,TSs]=LB(ESs,{value:void 0,onValueChange:Uh(()=>{},"onValueChange")}),MSs="MenuRadioItem",PSs=j.forwardRef(Uh(function(t,n){const{value:r,...a}=t,i=TSs(MSs,t.__scopeMenu),l=r===i.value;return e.jsx(fOt,{scope:t.__scopeMenu,checked:l,children:e.jsx(Oet,{role:"menuitemradio","aria-checked":l,...a,ref:n,"data-state":gLe(l),onSelect:Ra(a.onSelect,()=>{var o;return(o=i.onValueChange)==null?void 0:o.call(i,r)},{checkForDefaultPrevented:!1})})})},"MenuRadioItem")),mOt="MenuItemIndicator",[fOt,ISs]=LB(mOt,{checked:!1}),LSs=j.forwardRef(Uh(function(t,n){const{__scopeMenu:r,forceMount:a,...i}=t,l=ISs(mOt,r);return e.jsx(py,{present:a||Kte(l.checked)||l.checked===!0,children:e.jsx(Ei.span,{...i,ref:n,"data-state":gLe(l.checked)})})},"MenuItemIndicator")),RSs=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")),DSs="MenuSub",[Pkr,pOt]=LB(DSs),kce="MenuSubTrigger",FSs=j.forwardRef(Uh(function(t,n){const r=RB(kce,t.__scopeMenu),a=Eae(kce,t.__scopeMenu),i=pOt(kce,t.__scopeMenu),l=Det(kce,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(cOt,{asChild:!0,...u,children:e.jsx(hOt,{id:i.triggerId,"aria-haspopup":"menu","aria-expanded":r.open,"aria-controls":r.open?i.contentId:void 0,"data-state":zet(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,xG(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,xG(f=>{var x,y;h();const g=(x=r.content)==null?void 0:x.getBoundingClientRect();if(g){const v=(y=r.content)==null?void 0:y.dataset.side,b=v==="right",w=b?-5:5,S=g[b?"left":"right"],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:v}),window.clearTimeout(c.current),c.current=window.setTimeout(()=>l.onPointerGraceIntentChange(null),300)}else{if(l.onTriggerLeave(f),f.defaultPrevented)return;l.onPointerGraceIntentChange(null)}})),onKeyDown:Ra(t.onKeyDown,f=>{var x;t.disabled||f.target!==f.currentTarget||l.searchRef.current!==""&&f.key===" "||mSs[a.dir].includes(f.key)&&(r.onOpenChange(!0),(x=r.content)==null||x.focus(),f.preventDefault())})})})},"MenuSubTrigger")),OSs="MenuSubContent",zSs=j.forwardRef(Uh(function(t,n){const r=uOt(nC,t.__scopeMenu),{forceMount:a=r.forceMount,align:i="start",...l}=t,o=RB(nC,t.__scopeMenu),c=Eae(nC,t.__scopeMenu),d=pOt(OSs,t.__scopeMenu),u=j.useRef(null),h=Vo(n,u);return e.jsx(Wte.Provider,{scope:t.__scopeMenu,children:e.jsx(py,{present:a||o.open,children:e.jsx(Wte.Slot,{scope:t.__scopeMenu,children:e.jsx(Fet,{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=fSs[c.dir].includes(m.key);f&&g&&(o.onOpenChange(!1),(x=d.trigger)==null||x.focus(),m.preventDefault())})})})})})},"MenuSubContent"));function zet(s){return s?"open":"closed"}Uh(zet,"getOpenState");function Kte(s){return s==="indeterminate"}Uh(Kte,"isIndeterminate");function gLe(s){return Kte(s)?"indeterminate":s?"checked":"unchecked"}Uh(gLe,"getCheckedState");function gOt(s){const t=document.activeElement;for(const n of s)if(n===t||(n.focus(),document.activeElement!==t))return}Uh(gOt,"focusFirst");function xOt(s,t){return s.map((n,r)=>s[(t+r)%s.length])}Uh(xOt,"wrapArray");function yOt(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=xOt(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(yOt,"getNextMatch");function vOt(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(vOt,"isPointInPolygon");function bOt(s,t){if(!t)return!1;const n={x:s.clientX,y:s.clientY};return vOt(n,t)}Uh(bOt,"isPointerInGraceArea");function xG(s){return t=>t.pointerType==="mouse"?s(t):void 0}Uh(xG,"whenMouse");var BSs=vSs,$Ss=cOt,USs=_Ss,qSs=jSs,VSs=CSs,HSs=Oet,GSs=ASs,WSs=PSs,KSs=LSs,YSs=RSs,ZSs=FSs,XSs=zSs,QSs=Object.defineProperty,_k=(s,t)=>QSs(s,"name",{value:t,configurable:!0}),Bet="DropdownMenu",[JSs,Ikr]=tp(Bet,[oOt]),wk=oOt(),[eCs,_Ot]=JSs(Bet),tCs=_k(s=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:a,defaultOpen:i,onOpenChange:l,modal:o=!0}=s,c=wk(t),d=j.useRef(null),[u,h]=hy({prop:a,defaultProp:i??!1,onChange:l,caller:Bet});return e.jsx(eCs,{scope:t,triggerId:uy(),triggerRef:d,contentId:uy(),open:u,onOpenChange:h,onOpenToggle:j.useCallback(()=>h(m=>!m),[h]),modal:o,children:e.jsx(BSs,{...c,open:u,onOpenChange:h,dir:r,modal:o,children:n})})},"DropdownMenu"),sCs="DropdownMenuTrigger",nCs=j.forwardRef(_k(function(t,n){const{__scopeDropdownMenu:r,disabled:a=!1,...i}=t,l=_Ot(sCs,r),o=wk(r),c=Vo(n,l.triggerRef);return e.jsx($Ss,{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")),rCs=_k(s=>{const{__scopeDropdownMenu:t,...n}=s,r=wk(t);return e.jsx(USs,{...r,...n})},"DropdownMenuPortal"),aCs="DropdownMenuContent",iCs=j.forwardRef(_k(function(t,n){const{__scopeDropdownMenu:r,...a}=t,i=_Ot(aCs,r),l=wk(r),o=j.useRef(!1);return e.jsx(qSs,{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")),oCs=j.forwardRef(_k(function(t,n){const{__scopeDropdownMenu:r,...a}=t,i=wk(r);return e.jsx(VSs,{...i,...a,ref:n})},"DropdownMenuLabel")),lCs=j.forwardRef(_k(function(t,n){const{__scopeDropdownMenu:r,...a}=t,i=wk(r);return e.jsx(HSs,{...i,...a,ref:n})},"DropdownMenuItem")),cCs=j.forwardRef(_k(function(t,n){const{__scopeDropdownMenu:r,...a}=t,i=wk(r);return e.jsx(GSs,{...i,...a,ref:n})},"DropdownMenuCheckboxItem")),dCs=j.forwardRef(_k(function(t,n){const{__scopeDropdownMenu:r,...a}=t,i=wk(r);return e.jsx(WSs,{...i,...a,ref:n})},"DropdownMenuRadioItem")),uCs=j.forwardRef(_k(function(t,n){const{__scopeDropdownMenu:r,...a}=t,i=wk(r);return e.jsx(KSs,{...i,...a,ref:n})},"DropdownMenuItemIndicator")),hCs=j.forwardRef(_k(function(t,n){const{__scopeDropdownMenu:r,...a}=t,i=wk(r);return e.jsx(YSs,{...i,...a,ref:n})},"DropdownMenuSeparator")),mCs=j.forwardRef(_k(function(t,n){const{__scopeDropdownMenu:r,...a}=t,i=wk(r);return e.jsx(ZSs,{...i,...a,ref:n})},"DropdownMenuSubTrigger")),fCs=j.forwardRef(_k(function(t,n){const{__scopeDropdownMenu:r,...a}=t,i=wk(r);return e.jsx(XSs,{...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")),pCs=tCs,gCs=nCs,xCs=rCs,wOt=iCs,jOt=oCs,NOt=lCs,kOt=cCs,SOt=dCs,COt=uCs,AOt=hCs,EOt=mCs,TOt=fCs;const $u=pCs,Uu=gCs,yCs=j.forwardRef(({className:s,inset:t,children:n,...r},a)=>e.jsxs(EOt,{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"})]}));yCs.displayName=EOt.displayName;const vCs=j.forwardRef(({className:s,...t},n)=>e.jsx(TOt,{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}));vCs.displayName=TOt.displayName;const Au=j.forwardRef(({className:s,sideOffset:t=4,...n},r)=>e.jsx(xCs,{children:e.jsx(wOt,{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})}));Au.displayName=wOt.displayName;const ja=j.forwardRef(({className:s,inset:t,...n},r)=>e.jsx(NOt,{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=NOt.displayName;const bCs=j.forwardRef(({className:s,children:t,checked:n,...r},a)=>e.jsxs(kOt,{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(COt,{children:e.jsx(ca,{className:"h-4 w-4"})})}),t]}));bCs.displayName=kOt.displayName;const _Cs=j.forwardRef(({className:s,children:t,...n},r)=>e.jsxs(SOt,{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(COt,{children:e.jsx(Og,{className:"h-2 w-2 fill-current"})})}),t]}));_Cs.displayName=SOt.displayName;const jL=j.forwardRef(({className:s,inset:t,...n},r)=>e.jsx(jOt,{ref:r,className:Pt("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",s),...n}));jL.displayName=jOt.displayName;const I0=j.forwardRef(({className:s,...t},n)=>e.jsx(AOt,{ref:n,className:Pt("-mx-1 my-1 h-px bg-muted",s),...t}));I0.displayName=AOt.displayName;const wCs=()=>{const{isAssistant:s,actingAsAgent:t,assignedAgents:n,setActingAsAgent:r,isActingAsSelf:a,setActingAsSelf:i}=Aae();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($u,{children:[e.jsx(Uu,{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(Au,{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(I0,{}),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 _C(){var c,d;const{user:s,isAdmin:t}=bs(),{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 $et={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"},Lkr=Object.keys($et),jCs={home:null,crm:"crm",deals:"deals",listings:"listing_exchange",marketing:"marketing_studio",websites:"website",academy:"learn",events:"learn",apps:null,brokerage:"community",more:null},_xt={"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"},NCs={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 kCs(s){return s.id in _xt?_xt[s.id]:jCs[s.primaryCategory]??null}function SCs(s){return NCs[s]??null}const CCs=[["/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 MOt(s){let t=null;for(const n of CCs){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 Gn=j.forwardRef(({className:s,...t},n)=>e.jsx("p",{ref:n,className:Pt("text-sm text-muted-foreground",s),...t}));Gn.displayName="CardDescription";const Ie=j.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:Pt("p-6 pt-0",s),...t}));Ie.displayName="CardContent";const yEe=j.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:Pt("flex items-center p-6 pt-0",s),...t}));yEe.displayName="CardFooter";const Ls=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}));Ls.displayName="Textarea";const zs=HIe,jl=iet,ACs=GIe,Rkr=_ae,POt=j.forwardRef(({className:s,...t},n)=>e.jsx(qW,{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}));POt.displayName=qW.displayName;const Os=j.forwardRef(({className:s,children:t,overlayClassName:n,...r},a)=>e.jsxs(ACs,{children:[e.jsx(POt,{className:n}),e.jsxs(VW,{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(_ae,{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(pr,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Os.displayName=VW.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 Sr=({className:s,...t})=>e.jsx("div",{className:Pt("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",s),...t});Sr.displayName="DialogFooter";const Bs=j.forwardRef(({className:s,...t},n)=>e.jsx(vae,{ref:n,className:Pt("text-lg font-semibold leading-none tracking-tight",s),...t}));Bs.displayName=vae.displayName;const Pr=j.forwardRef(({className:s,...t},n)=>e.jsx(bae,{ref:n,className:Pt("text-sm text-muted-foreground",s),...t}));Pr.displayName=bae.displayName;function ECs({featureKey:s,open:t,onOpenChange:n}){const{user:r}=bs(),a=Wt(),[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"]}),re.success("Request sent — we'll be in touch shortly."),l(""),n(!1)},onError:h=>re.error((h==null?void 0:h.message)||"Could not send your request")}),u=$et[s]||s;return e.jsx(zs,{open:t,onOpenChange:n,children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(Nn,{className:"h-5 w-5 text-primary"}),"Request ",u]}),e.jsxs(Pr,{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(ca,{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(Ls,{placeholder:"Anything we should know? (optional)",value:i,onChange:h=>l(h.target.value),rows:4}),e.jsxs(Sr,{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 TCs({featureKey:s}){const[t,n]=j.useState(!1),r=$et[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(Ie,{className:"p-8 text-center space-y-4",children:[e.jsx("div",{className:"mx-auto h-12 w-12 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx(pc,{className:"h-6 w-6 text-primary"})}),e.jsxs("h2",{className:"text-2xl font-semibold",children:[r," is a Signature feature"]}),e.jsxs("p",{className:"text-muted-foreground",children:["Your current package doesn't include ",r,". Request access and our team will upgrade your account."]}),e.jsxs($,{onClick:()=>n(!0),className:"gap-2",children:[e.jsx(Nn,{className:"h-4 w-4"})," Request access"]})]})}),e.jsx(ECs,{featureKey:s,open:t,onOpenChange:n})]})}const IOt=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)}}}},LOt=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},MCs=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},Tae=()=>{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")}},wxt="community_last_seen_post_at";function PCs(){const{user:s}=bs(),t=mu(),[n,r]=j.useState(0),[a,i]=j.useState(null);j.useEffect(()=>{if(!s)return;const o=localStorage.getItem(`${wxt}_${s.id}`);i(o)},[s]),j.useEffect(()=>{if(!s)return;const o=`community_unread_count_${s.id}`,c=2*60*1e3;(async()=>{try{const f=sessionStorage.getItem(o);if(f){const g=JSON.parse(f);if(g.ts&&Date.now()-g.ts{if(!s)return;const o=q.channel("community-new-posts").on("postgres_changes",{event:"INSERT",schema:"public",table:"community_posts"},async c=>{const d=c.new;if(d.user_id===s.id)return;const u=t.pathname==="/community";u||r(x=>x+1);const{data:h}=await q.from("profiles").select("name").eq("id",d.user_id).single(),m=(h==null?void 0:h.name)||"Someone",f=d.content.replace(/@\[([^\]]+)\]\([^)]+\)/g,"@$1"),g=f.length>50?f.substring(0,50)+"...":f;u||re("New Community Post",{description:`${m}: ${g}`,action:{label:"View",onClick:()=>{window.location.href="/community"}}})}).subscribe();return()=>{q.removeChannel(o)}},[s,t.pathname]);const l=j.useCallback(()=>{if(!s)return;const o=new Date().toISOString();localStorage.setItem(`${wxt}_${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 ICs(){const{isAdmin:s}=bs(),{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 Uze=s=>`levelup:activeTeam:${s}`,Mae=()=>{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})},zw=()=>{const s=Sa(),t=Mae(),n=j.useMemo(()=>t.data||[],[t.data]),[r,a]=j.useState(()=>!s||typeof window>"u"?null:window.localStorage.getItem(Uze(s)));j.useEffect(()=>{!s||typeof window>"u"||a(window.localStorage.getItem(Uze(s)))},[s]);const i=j.useCallback(o=>{a(o),s&&typeof window<"u"&&window.localStorage.setItem(Uze(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}},GU="weekly_reels";function xLe(){const{user:s,loading:t,isAdmin:n}=bs(),{data:r,isLoading:a}=st({queryKey:["feature-entitlement",GU,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",GU).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 Gy=HIe,Pae=iet,LCs=GIe,ROt=j.forwardRef(({className:s,...t},n)=>e.jsx(qW,{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}));ROt.displayName=qW.displayName;const RCs=MB("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"}}),my=j.forwardRef(({side:s="right",className:t,children:n,...r},a)=>e.jsxs(LCs,{children:[e.jsx(ROt,{}),e.jsxs(VW,{ref:a,className:Pt(RCs({side:s}),t),...r,children:[n,e.jsxs(_ae,{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(pr,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));my.displayName=VW.displayName;const L0=({className:s,...t})=>e.jsx("div",{className:Pt("flex flex-col space-y-2 text-center sm:text-left",s),...t});L0.displayName="SheetHeader";const DOt=({className:s,...t})=>e.jsx("div",{className:Pt("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",s),...t});DOt.displayName="SheetFooter";const R0=j.forwardRef(({className:s,...t},n)=>e.jsx(vae,{ref:n,className:Pt("text-lg font-semibold text-foreground",s),...t}));R0.displayName=vae.displayName;const DB=j.forwardRef(({className:s,...t},n)=>e.jsx(bae,{ref:n,className:Pt("text-sm text-muted-foreground",s),...t}));DB.displayName=bae.displayName;var DCs=Object.defineProperty,FCs=(s,t)=>DCs(s,"name",{value:t,configurable:!0});function yG(s,[t,n]){return Math.min(n,Math.max(t,s))}FCs(yG,"clamp");var OCs=Object.defineProperty,ku=(s,t)=>OCs(s,"name",{value:t,configurable:!0});function FOt(s,t){return j.useReducer((n,r)=>t[n][r]??n,s)}ku(FOt,"useStateMachine");var OOt="ScrollArea",[zOt,Dkr]=tp(OOt),[zCs,jk]=zOt(OOt),BCs=j.forwardRef(ku(function(t,n){const{__scopeScrollArea:r,type:a="hover",dir:i,scrollHideDelay:l=600,...o}=t,[c,d]=j.useState(null),[u,h]=j.useState(null),[m,f]=j.useState(null),[g,x]=j.useState(null),[y,v]=j.useState(null),[b,w]=j.useState(0),[S,A]=j.useState(0),[E,I]=j.useState(!1),[P,R]=j.useState(!1),D=Vo(n,d),O=i3(i);return e.jsx(zCs,{scope:r,type:a,dir:O,scrollHideDelay:l,scrollArea:c,viewport:u,onViewportChange:h,content:m,onContentChange:f,scrollbarX:g,onScrollbarXChange:x,scrollbarXEnabled:E,onScrollbarXEnabledChange:I,scrollbarY:y,onScrollbarYChange:v,scrollbarYEnabled:P,onScrollbarYEnabledChange:R,onCornerWidthChange:w,onCornerHeightChange: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")),$Cs="ScrollAreaViewport",UCs=j.forwardRef(ku(function(t,n){const{__scopeScrollArea:r,children:a,nonce:i,...l}=t,o=jk($Cs,r),c=j.useRef(null),d=Vo(n,c,o.onViewportChange);return e.jsxs(e.Fragment,{children:[e.jsx(qCs,{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")),qCs=j.memo(ku(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),ET="ScrollAreaScrollbar",BOt=j.forwardRef(ku(function(t,n){const{forceMount:r,...a}=t,i=jk(ET,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(VCs,{...a,ref:n,forceMount:r}):i.type==="scroll"?e.jsx(HCs,{...a,ref:n,forceMount:r}):i.type==="auto"?e.jsx($Ot,{...a,ref:n,forceMount:r}):i.type==="always"?e.jsx(Uet,{...a,ref:n,"data-state":"visible"}):null},"ScrollAreaScrollbar")),VCs=j.forwardRef(ku(function(t,n){const{forceMount:r,...a}=t,i=jk(ET,t.__scopeScrollArea),[l,o]=j.useState(!1);return j.useEffect(()=>{const c=i.scrollArea;let d=0;if(c){const u=ku(()=>{window.clearTimeout(d),o(!0)},"handlePointerEnter"),h=ku(()=>{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(py,{present:r||l,children:e.jsx($Ot,{"data-state":l?"visible":"hidden",...a,ref:n})})},"ScrollAreaScrollbarHover")),HCs=j.forwardRef(ku(function(t,n){const{forceMount:r,...a}=t,i=jk(ET,t.__scopeScrollArea),l=t.orientation==="horizontal",o=Lae(()=>d("SCROLL_END"),100),[c,d]=FOt("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=ku(()=>{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(py,{present:r||c!=="hidden",children:e.jsx(Uet,{"data-state":c==="hidden"?"hidden":"visible",...a,ref:n,onPointerEnter:Ra(t.onPointerEnter,()=>d("POINTER_ENTER")),onPointerLeave:Ra(t.onPointerLeave,()=>d("POINTER_LEAVE"))})})},"ScrollAreaScrollbarScroll")),$Ot=j.forwardRef(ku(function(t,n){const r=jk(ET,t.__scopeScrollArea),{forceMount:a,...i}=t,[l,o]=j.useState(!1),c=t.orientation==="horizontal",d=Lae(()=>{if(r.viewport){const u=r.viewport.offsetWidth0&&u<1,onThumbChange:ku(f=>l.current=f,"onThumbChange"),onThumbPointerUp:ku(()=>o.current=0,"onThumbPointerUp"),onThumbPointerDown:ku(f=>o.current=f,"onThumbPointerDown")};function m(f,g){return HOt(f,o.current,c,g)}return ku(m,"getScrollPosition"),r==="horizontal"?e.jsx(GCs,{...h,ref:n,onThumbPositionChange:()=>{if(i.viewport&&l.current){const f=i.viewport.scrollLeft,g=AHe(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(WCs,{...h,ref:n,onThumbPositionChange:()=>{if(i.viewport&&l.current){const f=i.viewport.scrollTop,g=AHe(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")),GCs=j.forwardRef(ku(function(t,n){const{sizes:r,onSizesChange:a,...i}=t,l=jk(ET,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(qOt,{"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":Iae(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),Het(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:Yte(o.paddingLeft),paddingEnd:Yte(o.paddingRight)}})}})},"ScrollAreaScrollbarX")),WCs=j.forwardRef(ku(function(t,n){const{sizes:r,onSizesChange:a,...i}=t,l=jk(ET,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(qOt,{"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":Iae(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),Het(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:Yte(o.paddingTop),paddingEnd:Yte(o.paddingBottom)}})}})},"ScrollAreaScrollbarY")),[KCs,UOt]=zOt(ET),qOt=j.forwardRef(ku(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=jk(ET,r),[x,y]=j.useState(null),v=Vo(n,y),b=j.useRef(null),w=j.useRef(""),S=g.viewport,A=a.content-a.viewport,E=Zp(h),I=Zp(d),P=Lae(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 ku(R,"handleDragScroll"),j.useEffect(()=>{const D=ku(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]),B7(x,P),B7(g.content,P),e.jsx(KCs,{scope:r,scrollbar:x,hasThumb:i,onThumbChange:Zp(l),onThumbPointerUp:Zp(o),onThumbPositionChange:I,onThumbPointerDown:Zp(c),children:e.jsx(Ei.div,{...f,ref:v,style:{position:"absolute",...f.style},onPointerDown:Ra(t.onPointerDown,D=>{D.button===0&&(D.target.setPointerCapture(D.pointerId),b.current=x.getBoundingClientRect(),w.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",g.viewport&&(g.viewport.style.scrollBehavior="auto"),R(D))}),onPointerMove:Ra(t.onPointerMove,R),onPointerUp:Ra(t.onPointerUp,D=>{const O=D.target;O.hasPointerCapture(D.pointerId)&&O.releasePointerCapture(D.pointerId),document.body.style.webkitUserSelect=w.current,g.viewport&&(g.viewport.style.scrollBehavior=""),b.current=null})})})},"ScrollAreaScrollbarImpl")),CHe="ScrollAreaThumb",YCs=j.forwardRef(ku(function(t,n){const{forceMount:r,...a}=t,i=UOt(CHe,t.__scopeScrollArea);return e.jsx(py,{present:r||i.hasThumb,children:e.jsx(ZCs,{ref:n,...a})})},"ScrollAreaThumb")),ZCs=j.forwardRef(ku(function(t,n){const{__scopeScrollArea:r,style:a,...i}=t,l=jk(CHe,r),o=UOt(CHe,r),{onThumbPositionChange:c}=o,d=Vo(n,o.onThumbChange),u=j.useRef(void 0),h=Lae(()=>{u.current&&(u.current(),u.current=void 0)},100);return j.useEffect(()=>{const m=l.viewport;if(m){const f=ku(()=>{if(h(),!u.current){const g=JCs(m,c);u.current=g,c()}},"handleScroll");return c(),m.addEventListener("scroll",f),()=>m.removeEventListener("scroll",f)}},[l.viewport,h,c]),e.jsx(Ei.div,{"data-state":o.hasThumb?"visible":"hidden",...i,ref:d,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...a},onPointerDownCapture:Ra(t.onPointerDownCapture,m=>{const g=m.target.getBoundingClientRect(),x=m.clientX-g.left,y=m.clientY-g.top;o.onThumbPointerDown({x,y})}),onPointerUp:Ra(t.onPointerUp,o.onThumbPointerUp)})},"ScrollAreaThumbImpl")),VOt="ScrollAreaCorner",XCs=j.forwardRef(ku(function(t,n){const r=jk(VOt,t.__scopeScrollArea),a=!!(r.scrollbarX&&r.scrollbarY);return r.type!=="scroll"&&a?e.jsx(QCs,{...t,ref:n}):null},"ScrollAreaCorner")),QCs=j.forwardRef(ku(function(t,n){const{__scopeScrollArea:r,...a}=t,i=jk(VOt,r),[l,o]=j.useState(0),[c,d]=j.useState(0),u=!!(l&&c),{onCornerWidthChange:h,onCornerHeightChange:m}=i;return B7(i.scrollbarX,()=>{var g;const f=((g=i.scrollbarX)==null?void 0:g.offsetHeight)||0;i.onCornerHeightChange(f),d(f)}),B7(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 Yte(s){return s?parseInt(s,10):0}ku(Yte,"toInt");function qet(s,t){const n=s/t;return isNaN(n)?0:n}ku(qet,"getThumbRatio");function Iae(s){const t=qet(s.viewport,s.content),n=s.scrollbar.paddingStart+s.scrollbar.paddingEnd,r=(s.scrollbar.size-n)*t;return Math.max(r,18)}ku(Iae,"getThumbSize");function HOt(s,t,n,r="ltr"){const a=Iae(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 Vet([c,d],h)(s)}ku(HOt,"getScrollPositionFromPointer");function AHe(s,t,n="ltr"){const r=Iae(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=yG(s,c);return Vet([0,l],[0,o])(d)}ku(AHe,"getThumbOffsetFromScroll");function Vet(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])}}ku(Vet,"linearScale");function Het(s,t){return s>0&&s{})=>{let n={left:s.scrollLeft,top:s.scrollTop},r=0;return ku(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 Lae(s,t){const n=Zp(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])}ku(Lae,"useDebounceCallback");function B7(s,t){const n=Zp(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])}ku(B7,"useResizeObserver");var GOt=BCs,e5s=UCs,t5s=XCs;const uo=j.forwardRef(({className:s,children:t,...n},r)=>e.jsxs(GOt,{ref:r,className:Pt("relative overflow-hidden",s),...n,children:[e.jsx(e5s,{className:"h-full w-full rounded-[inherit]",children:t}),e.jsx(Rae,{}),e.jsx(t5s,{})]}));uo.displayName=GOt.displayName;const Rae=j.forwardRef(({className:s,orientation:t="vertical",...n},r)=>e.jsx(BOt,{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(YCs,{className:"relative flex-1 rounded-full bg-border"})}));Rae.displayName=BOt.displayName;const s5s="/assets/levelup-logo-Eif24dqY.png",n5s="/assets/levelup-logo-icon-C-7iromj.png",r5s="/assets/levelup-logo-mobile-B9skSjUG.png";var Dae=s=>s.type==="checkbox",yLe=s=>s.type==="file",pI=s=>s instanceof Date,dv=s=>s==null;const Get=s=>typeof s=="object";var Kp=s=>!dv(s)&&!Array.isArray(s)&&Get(s)&&!pI(s),EHe=s=>Kp(s)&&s.target?Dae(s.target)?s.target.checked:yLe(s.target)?s.target.files:s.target.value:s;const a5s=/[.[\]'"]/;var $7=s=>s.split(a5s).filter(Boolean);function i5s(s,t){const n=$7(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("."))),vLe=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(vLe&&(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 cP={BLUR:"blur",FOCUS_OUT:"focusout",CHANGE:"change",SUBMIT:"submit",TRIGGER:"trigger",VALID:"valid"},IN={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit",onTouched:"onTouched",all:"all"},lS={max:"max",min:"min",maxLength:"maxLength",minLength:"minLength",pattern:"pattern",required:"required",validate:"validate"},KOt="root",Wet=["__proto__","constructor","prototype"],o5s=/^\w*$/;var vG=s=>o5s.test(s),Oh=s=>s===void 0,Ri=(s,t,n)=>{if(!t||!Kp(s))return n;const r=vG(t)?[t]:$7(t);if(r.some(i=>Wet.includes(i)))return n;const a=r.reduce((i,l)=>dv(i)?void 0:i[l],s);return Oh(a)||a===s?Oh(s[t])?n:s[t]:a},qj=s=>typeof s=="boolean",u1=s=>typeof s=="function",Qh=(s,t,n)=>{let r=-1;const a=vG(t)?[t]:$7(t),i=a.length,l=i-1;for(;++rGt.useContext(Ket);var YOt=(s,t,n,r=!0)=>{const a={};for(const i in s)Object.defineProperty(a,i,{get:()=>{const l=i;return t._proxyFormState[l]!==IN.all&&(t._proxyFormState[l]=!r||IN.all),n&&(n[l]=!0),s[l]}});return a};const Zet=vLe?Gt.useLayoutEffect:Gt.useEffect;var l5s=s=>{const t=s.constructor&&s.constructor.prototype;return Kp(t)&&t.hasOwnProperty("isPrototypeOf")},THe=s=>dv(s)||!Get(s);const jxt=(s,t)=>t.length===0&&!Array.isArray(s)&&!l5s(s);function uw(s,t,n=new WeakMap){if(s===t)return!0;if(THe(s)||THe(t))return Object.is(s,t);if(pI(s)&&pI(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(jxt(s,r)||jxt(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(pI(o)&&pI(c)||(Kp(o)||Array.isArray(o))&&(Kp(c)||Array.isArray(c))?!uw(o,c,n):!Object.is(o,c))return!1}}return!0}function Xet(s){const t=Gt.useRef(!1),n=Gt.useRef(!1),r=Gt.useRef(void 0),a=Gt.useRef(0);a.current++,!n.current&&s&&(n.current=!0,r.current=Uf(s()));const i=Gt.useCallback((o,c,d)=>{if(o&&(t.current||n.current&&a.current>1)){const u=c();uw(r.current,u)||d(u)}t.current=!0},[]),l=Gt.useCallback((o,c)=>{o&&(r.current=Uf(c()))},[]);return{resyncIfNeeded:i,snapshot:l}}function c5s(s){const t=Yet(),{control:n=t,disabled:r,name:a,exact:i}=s||{},l=()=>({...n._formState,defaultValues:n._defaultValues}),[o,c]=Gt.useState(l),d=Gt.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,validatingFields:!1,isValidating:!1,isValid:!1,errors:!1}),{resyncIfNeeded:u,snapshot:h}=Xet(l);return Zet(()=>{u(!r,l,c);const m=n._subscribe({name:a,formState:d.current,exact:i,callback:f=>{!r&&c({...n._formState,...f,defaultValues:n._defaultValues})}});return()=>{m(),h(!r,l)}},[n,a,r,i,u,h]),Gt.useEffect(()=>{d.current.isValid&&n._setValid(!0)},[n]),Gt.useMemo(()=>YOt(o,n,d.current,!1),[o,n])}var fv=s=>typeof s=="string",MHe=(s,t,n,r,a)=>fv(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 d5s(s){const t=Yet(),{control:n=t,name:r,defaultValue:a,disabled:i,exact:l,compute:o}=s||{},c=Gt.useRef(a),d=Gt.useRef(o),u=Gt.useRef(n),h=Gt.useRef(r);d.current=o;const m=()=>{const R=n._getWatch(r,c.current);return d.current?d.current(R):R},[f,g]=Gt.useState(m),x=Gt.useRef(f),y=Gt.useCallback(R=>{const D=MHe(r,n._names,R||n._formValues,!1,c.current);return d.current?d.current(D):D},[n._formValues,n._names,r]),v=Gt.useCallback(R=>{if(!i){const D=MHe(r,n._names,R||n._formValues,!1,c.current);if(d.current){const O=d.current(D);uw(O,x.current)||(g(O),x.current=O)}else g(D)}},[n._formValues,n._names,i,r]),{resyncIfNeeded:b,snapshot:w}=Xet(m),S=Gt.useRef(v);S.current=v;const A=Gt.useRef(y);A.current=y,Zet(()=>{u.current!==n||!uw(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]),Gt.useEffect(()=>n._removeUnmounted());const E=u.current!==n,I=h.current;return Gt.useMemo(()=>{if(i)return!1;const R=!E&&!uw(I,r);return E||R},[i,E,r,I])?y():f}function u5s(s){const t=Yet(),{name:n,disabled:r,control:a=t,shouldUnregister:i,defaultValue:l,exact:o=!0}=s,c=WOt(a._names.array,n),d=Gt.useMemo(()=>{const S=Ri(a._formValues,n,Ri(a._defaultValues,n,l));return Oh(S)?i5s(a,n):S},[a,n,l]),u=d5s({control:a,name:n,defaultValue:d,exact:o}),h=c5s({control:a,name:n,exact:o}),m=Gt.useRef(s),f=Gt.useRef(null),g=Gt.useRef(a.register(n,{...s.rules,value:u,...qj(s.disabled)?{disabled:s.disabled}:{}}));m.current=s;const x=Gt.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]),y=Gt.useCallback(S=>{const A=EHe(S);return Ri(a._fields,n)||(g.current=a.register(n,{...m.current.rules,value:A})),g.current.onChange({target:{value:EHe(S),name:n},type:cP.CHANGE})},[n,a]),v=Gt.useCallback(()=>g.current.onBlur({target:{value:Ri(a._formValues,n),name:n},type:cP.BLUR}),[n,a._formValues]),b=Gt.useCallback(S=>{S&&(f.current={focus:()=>u1(S.focus)&&S.focus(),select:()=>u1(S.select)&&S.select(),setCustomValidity:E=>u1(S.setCustomValidity)&&S.setCustomValidity(E),reportValidity:()=>u1(S.reportValidity)&&S.reportValidity()});const A=Ri(a._fields,n);A&&A._f&&S&&(A._f.ref=f.current)},[a._fields,n]),w=Gt.useMemo(()=>({name:n,value:u,...qj(r)||h.disabled?{disabled:h.disabled||r}:{},onChange:y,onBlur:v,ref:b}),[n,r,h.disabled,y,v,b,u]);return Gt.useEffect(()=>{const S=a._options.shouldUnregister||i;g.current=a.register(n,{...m.current.rules,...qj(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]),Gt.useEffect(()=>{a._setDisabledField({disabled:r,name:n})},[r,n,a]),Gt.useMemo(()=>({field:w,formState:h,fieldState:x}),[w,h,x])}const h5s=s=>s.render(u5s(s));var Sce=s=>({isOnSubmit:!s||s===IN.onSubmit,isOnBlur:s===IN.onBlur,isOnChange:s===IN.onChange,isOnAll:s===IN.all,isOnTouch:s===IN.onTouched}),qze=(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 uee=(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(uee(a,t))return!0}else if((Kp(a)||Array.isArray(a))&&uee(a,t))return!0}}};var Nxt=(s,t,n)=>{const r=Ri(s,n),a=Array.isArray(r)?r:[];return Qh(a,KOt,t[n]),Qh(s,n,a),s},Ay=s=>Kp(s)&&!Object.keys(s).length,vEe=s=>{if(!vLe)return!1;const t=s?s.ownerDocument:0;return s instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},Qet=s=>s.type==="radio",bEe=s=>s instanceof RegExp,ZOt=(s,t,n,r,a)=>t?{...n[s],types:{...n[s]&&n[s].types?n[s].types:{},[r]:a||!0}}:{};const kxt={value:!1,isValid:!1},Sxt={value:!0,isValid:!0};var XOt=s=>{if(!Array.isArray(s))return kxt;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?kxt:!t.attributes||!("value"in t.attributes)||Oh(t.value)||t.value===""?Sxt:{value:t.value,isValid:!0}};const Cxt={isValid:!1,value:null};var QOt=s=>Array.isArray(s)?s.reduce((t,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:t,Cxt):Cxt;function Axt(s,t,n="validate"){if(fv(s)||Array.isArray(s)&&s.every(fv)||qj(s)&&!s)return{type:n,message:fv(s)?s:"",ref:t}}var g$=s=>Kp(s)&&!bEe(s)?s:{value:s,message:""},Ext=async(s,t,n,r,a,i)=>{const{ref:l,refs:o,required:c,maxLength:d,minLength:u,min:h,max:m,pattern:f,validate:g,name:x,valueAsNumber:y,mount:v}=s._f,b=Ri(n,x);if(!v||t.has(x))return{};const w=o?o[0]:l,S=W=>{if(a&&w.reportValidity){const V=qj(W)?"":W||"";o?o.forEach(G=>G.setCustomValidity(V)):w.setCustomValidity(V),w.reportValidity()}},A={},E=Qet(l),I=Dae(l),P=E||I,R=(y||yLe(l))&&Oh(l.value)&&Oh(b)||vEe(l)&&l.value===""||b===""||Array.isArray(b)&&!b.length,D=ZOt.bind(null,x,r,A),O=(W,V,G,Y=lS.maxLength,X=lS.minLength)=>{const ae=W?V:G;A[x]={type:W?Y:X,message:ae,ref:l,...D(W?Y:X,ae)}};if(i?!Array.isArray(b)||!b.length:c&&(!P&&(R||dv(b))||qj(b)&&!b||I&&!XOt(o).isValid||E&&!QOt(o).isValid)){const{value:W,message:V}=fv(c)?{value:!!c,message:c}:g$(c);if(W&&(A[x]={type:lS.required,message:V,ref:w,...D(lS.required,V)},!r))return S(V),A}if(!R&&(!dv(h)||!dv(m))){let W,V;const G=g$(m),Y=g$(h);if(!dv(b)&&!pI(b)&&!isNaN(b)){const X=l.valueAsNumber||b&&+b;dv(G.value)||(W=X>G.value),dv(Y.value)||(V=Xnew Date(new Date().toDateString()+" "+te),le=l.type=="time",ne=l.type=="week";fv(G.value)&&b&&(W=le?ae(b)>ae(G.value):ne?b>G.value:X>new Date(G.value)),fv(Y.value)&&b&&(V=le?ae(b)+W.value,Y=!dv(V.value)&&b.length<+V.value;if((G||Y)&&(O(G,W.message,V.message),!r))return S(A[x].message),A}if(f&&!R&&fv(b)){const{value:W,message:V}=g$(f);if(bEe(W)&&!b.match(W)&&(A[x]={type:lS.pattern,message:V,ref:l,...D(lS.pattern,V)},!r))return S(V),A}if(g){if(u1(g)){const W=await g(b,n),V=Axt(W,w);if(V&&(A[x]={...V,...D(lS.validate,V.message)},!r))return S(V.message),A}else if(Kp(g)){let W={};for(const V in g){if(!Ay(W)&&!r)break;const G=Axt(await g[V](b,n),w,V);G&&(W={...G,...D(V,G.message)},r||S(G.message),r&&(A[x]=W))}if(!Ay(W)&&(A[x]={ref:w,...W},!r))return A}}const U=A[x];return S(U?U.message:!0),A},V4e=s=>Array.isArray(s)?s:[s],JOt=s=>Array.isArray(s)?s.filter(Boolean):[];function m5s(s,t){const n=t.length-1;let r=0;for(;rWet.includes(String(l))))return s;const r=n.length===1?s:m5s(s,n),a=n.length-1,i=n[a];return r&&delete r[i],a!==0&&(Kp(r)&&Ay(r)||Array.isArray(r)&&f5s(r))&&ux(s,n.slice(0,-1)),s}const Jet=Gt.createContext(null);Jet.displayName="HookFormContext";const p5s=()=>Gt.useContext(Jet),g5s=({children:s,watch:t,getValues:n,getErrors:r,getFieldState:a,setError:i,clearErrors:l,setValue:o,setValues:c,trigger:d,formState:u,resetField:h,reset:m,resetDefaultValues:f,handleSubmit:g,unregister:x,control:y,register:v,setFocus:b,subscribe:w})=>{const S=Gt.useMemo(()=>({watch:t,getValues:n,getErrors:r,getFieldState:a,setError:i,clearErrors:l,setValue:o,setValues:c,trigger:d,formState:u,resetField:h,reset:m,resetDefaultValues:f,handleSubmit:g,unregister:x,control:y,register:v,setFocus:b,subscribe:w}),[l,y,u,r,a,n,g,v,m,f,h,i,b,o,c,w,d,x,t]);return Gt.createElement(Jet.Provider,{value:S},Gt.createElement(Ket.Provider,{value:S.control},s))};var Txt=()=>{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 e8t(s,t){const n={};for(const r in s)if(s.hasOwnProperty(r)){const a=s[r],i=t[r];if(a&&Kp(a)&&i){const l=e8t(a,i);Kp(l)&&(n[r]=l)}else s[r]&&(n[r]=i)}return n}const Mxt=(s,t)=>s!==null&&Get(s)&&Object.prototype.hasOwnProperty.call(s,t);var x5s=(s,t)=>{if(!t)return!1;let n=s;for(const r of vG(t)?[t]:$7(t)){if(!Mxt(n,r))return Mxt(s,t);n=n[r]}return!0},t8t=s=>s.type==="select-multiple",y5s=s=>Qet(s)||Dae(s),Vze=s=>vEe(s)&&s.isConnected;function Pxt(s){return Array.isArray(s)||Kp(s)}function s8t(s,t,n="",r=[]){for(const a in s){const i=n?`${n}.${a}`:a,l=s[a];Pxt(l)&&Pxt(Ri(t,i))?s8t(l,t,i,r):r.push(i)}return r}var v5s=s=>{for(const t in s)if(u1(s[t]))return!0;return!1};function n8t(s){return Array.isArray(s)||Kp(s)&&!v5s(s)}function r8t(s){return!!(s&&"_f"in s)}function a8t(s){return Array.isArray(s)?!s.some(t=>!Oh(t)):!Object.keys(s).length}function PHe(s,t){Array.isArray(s)?s[t]=void 0:delete s[t]}function IHe(s,t={},n){for(const r in s){const a=s[r],i=n&&n[r];n8t(a)&&(!Array.isArray(a)||!r8t(i))?(t[r]=Array.isArray(a)?[]:{},IHe(a,t[r],i),a8t(t[r])&&PHe(t,r)):Oh(a)||(t[r]=!0)}return t}function qM(s,t,n,r){n||(n=IHe(t,{},r));for(const a in s){const i=s[a],l=r&&r[a];n8t(i)&&(!Array.isArray(i)||!r8t(l))?(Oh(t)||THe(n[a])?n[a]=IHe(i,Array.isArray(i)?[]:{},l):qM(i,dv(t)?{}:t[a],n[a],l),a8t(n[a])&&PHe(n,a)):uw(i,t[a])?PHe(n,a):n[a]=!0}return n}var b5s=(s,t)=>{const n=t.split("."),r=[];let a=n[0];for(let i=1;iOh(s)?s:t?s===""?NaN:s&&+s:n&&fv(s)?new Date(s):r?r(s):s;function Ixt(s){const t=s.ref;return yLe(t)?t.files:Qet(t)?QOt(s.refs).value:t8t(t)?[...t.selectedOptions].map(({value:n})=>n):Dae(t)?XOt(s.refs).value:LHe(t.value,s)}var _5s=(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}},bZ=s=>Oh(s)?s:bEe(s)?s.source:Kp(s)?bEe(s.value)?s.value.source:s.value:s;const Lxt="AsyncFunction";var w5s=s=>{if(!s||!s.validate)return!1;if(u1(s.validate))return s.validate.constructor.name===Lxt;if(Kp(s.validate)){for(const t in s.validate)if(s.validate[t].constructor.name===Lxt)return!0}return!1},j5s=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 Rxt(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 N5s=(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||IN.all))},k5s=(s,t,n)=>!s||!t||s===t||V4e(s).some(r=>r&&(n?r===t||r.startsWith(t+"."):r.startsWith(t)||t.startsWith(r))),S5s=(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,C5s=(s,t)=>{const n=Ri(s,t);!JOt(n).length&&!(n!=null&&n.root)&&ux(s,t)};const A5s={mode:IN.onSubmit,reValidateMode:IN.onChange,shouldFocusError:!0},Hze="form",E5s=(s,t)=>{for(const n in s)n in t||delete s[n];Object.assign(s,t)},i8t={submitCount:0,isDirty:!1,isReady:!1,isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{}};function T5s(s={}){let t={...A5s,...s},n={...Uf(i8t),isLoading:u1(t.defaultValues),errors:t.errors||{},disabled:t.disabled||!1},r={},a=Kp(t.defaultValues)||Kp(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=Sce(t.mode),m=Sce(t.reValidateMode);const f={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},g={...f};let x={...g};const y=(...wt)=>wt.some(gs=>g[gs]||x[gs]),v={array:Txt(),state:Txt()};let b=0,w=0,S=t.criteriaMode===IN.all;const A=(wt,gs)=>ks=>{clearTimeout(d[wt]),d[wt]=setTimeout(gs,ks)},E=wt=>{clearTimeout(d[wt]),delete d[wt],delete c[wt]},I=wt=>{E(wt);const gs=`${wt}.`;for(const ks of Object.keys(c))ks.startsWith(gs)&&E(ks)},P=async wt=>{if(!l.keepIsValid&&!t.disabled&&(y("isValid")||wt)){const gs=++b;let ks;t.resolver?(ks=Ay((await le()).errors),gs===b&&R()):ks=await J({fields:r,onlyCheckValid:!0,eventType:cP.VALID}),gs===b&&ks!==n.isValid&&v.state.next({isValid:ks})}},R=(wt,gs)=>{!t.disabled&&y("isValidating","validatingFields")&&((wt||o.mount).forEach(ks=>{ks&&(gs?Qh(n.validatingFields,ks,gs):ux(n.validatingFields,ks))}),v.state.next({validatingFields:n.validatingFields,isValidating:!Ay(n.validatingFields)}))},D=()=>{n.dirtyFields=qM(a,i,void 0,r)},O=(wt,gs=[],ks,Is,Xs=!0,ds=!0)=>{if(Is&&ks&&!t.disabled){l.action=!0;const Ss=Ri(r,wt);if(l.actionArrayLengths.has(wt)||l.actionArrayLengths.set(wt,Array.isArray(Ss)?Ss.length:0),ds&&Array.isArray(Ss)){const Ut=ks(Ss,Is.argA,Is.argB);Xs&&Qh(r,wt,Ut)}const yn=Ri(n.errors,wt);if(ds&&Array.isArray(yn)){const Ut=yn.root,hn=ks(yn,Is.argA,Is.argB)||yn;Ut&&(hn.root=Ut),Xs&&Qh(n.errors,wt,hn),C5s(n.errors,wt)}const Js=Ri(n.touchedFields,wt);if(y("touchedFields")&&ds&&Array.isArray(Js)){const Ut=ks(Js,Is.argA,Is.argB);Xs&&Qh(n.touchedFields,wt,Ut)}y("dirtyFields")&&D(),v.state.next({name:wt,isDirty:_e(wt,gs),dirtyFields:n.dirtyFields,errors:n.errors,isValid:n.isValid})}else Qh(i,wt,gs)},U=(wt,gs)=>{Qh(n.errors,wt,gs),n.errors={...n.errors},v.state.next({errors:n.errors})},W=wt=>{Object.keys(c).forEach(E),n.errors=wt,v.state.next({errors:n.errors,isValid:!1})},V=wt=>{const gs=vG(wt)?[wt]:$7(wt);let ks=i,Is=a;for(let Xs=0;Xs{if(!l.actionArrayLengths.size)return!1;const gs=vG(wt)?[wt]:$7(wt);let ks=i,Is="",Xs=-1,ds=0;for(let Ss=0;Ss=ks.length)return Xs===-1?!1:Ss===Xs?+ynXs&&+gs[Xs]{const Xs=Ri(r,wt);if(Xs){if(V(wt)||G(wt))return;const ds=Oh(Ri(i,wt)),Ss=Ri(i,wt,Oh(ks)?Ri(a,wt):ks);Oh(Ss)||Is&&Is.defaultChecked||gs?Qh(i,wt,gs?Ss:Ixt(Xs._f)):ve(wt,Ss),l.mount&&!l.action&&(P(),ds&&n.isDirty&&y("isDirty")&&(_e()||(n.isDirty=!1,v.state.next({...n}))),s.shouldUnregister&&ds&&!Oh(Ri(i,wt))&&qze(wt,o)&&(l.watch=!0))}},X=(wt,gs,ks,Is,Xs)=>{let ds=!1,Ss=!1;const yn={name:wt};if(!t.disabled||Is===!0){if(!ks||Is){const Js=uw(Ri(a,wt),gs);y("isDirty")&&(Ss=n.isDirty,n.isDirty=yn.isDirty=!Js||_e(),ds=Ss!==yn.isDirty),Ss=!!Ri(n.dirtyFields,wt),Js!==n.isDirty?E5s(n.dirtyFields,qM(a,i,void 0,r)):Js?ux(n.dirtyFields,wt):Qh(n.dirtyFields,wt,!0),yn.dirtyFields=n.dirtyFields,ds=ds||y("dirtyFields")&&Ss!==!Js}if(ks){const Js=Ri(n.touchedFields,wt);Js||(Qh(n.touchedFields,wt,ks),yn.touchedFields=n.touchedFields,ds=ds||y("touchedFields")&&Js!==ks)}ds&&Xs&&v.state.next(yn)}return ds?yn:{}},ae=(wt,gs,ks,Is)=>{const Xs=Ri(n.errors,wt),ds=y("isValid")&&qj(gs)&&n.isValid!==gs;if(t.delayError&&ks?(c[wt]=A(wt,()=>U(wt,ks)),c[wt](t.delayError)):(E(wt),ks?Qh(n.errors,wt,ks):ux(n.errors,wt),n.errors={...n.errors}),(ks?!uw(Xs,ks):Xs)||!Ay(Is)||ds){const Ss={...Is,...ds&&qj(gs)?{isValid:gs}:{},errors:n.errors,name:wt};v.state.next(Ss)}},le=async wt=>(R(wt,!0),await t.resolver(i,t.context,_5s(wt||o.mount,r,t.criteriaMode,t.shouldUseNativeValidation))),ne=async wt=>{const gs=w,{errors:ks}=await le(wt);if(gs!==w)return ks;if(R(wt),wt){for(const Is of wt){const Xs=Ri(ks,Is);E(Is);const ds=o.array.has(Is)&&Kp(Xs)&&!Object.keys(Xs).some(Js=>!Number.isNaN(Number(Js))),Ss=Ri(r,Is),yn=Kp(Ss)&&Object.keys(Ss).some(Js=>Js!=="_f");ds?Nxt(n.errors,{[Is]:Xs},Is):Xs!=null&&Xs.type||Xs!=null&&Xs.message||Array.isArray(Xs)||Kp(Xs)&&yn?Qh(n.errors,Is,Xs):ux(n.errors,Is)}n.errors={...n.errors}}else Object.keys(c).forEach(E),n.errors=ks;return ks},te=async({name:wt,eventType:gs})=>{if(s.validate){const ks=await s.validate({formValues:i,formState:n,name:wt,eventType:gs});if(Kp(ks))for(const Is in ks){const Xs=ks[Is];Xs&&qe(`${Hze}.${Is}`,{message:fv(Xs.message)?Xs.message:"",type:Xs.type||lS.validate})}else fv(ks)||!ks?qe(Hze,{message:ks||"",type:lS.validate}):ze(Hze);return ks}return!0},J=async({fields:wt,onlyCheckValid:gs,name:ks,eventType:Is,context:Xs={valid:!0,runRootValidation:!1}})=>{if(s.validate&&(Xs.runRootValidation=!0,!await te({name:ks,eventType:Is})&&(Xs.valid=!1,gs)))return Xs.valid;for(const ds in wt){const Ss=wt[ds];if(Ss){const{_f:yn,...Js}=Ss;if(yn){const Ut=o.array.has(yn.name),hn=Ss._f&&w5s(Ss._f),hr=y("isValidating","validatingFields");hn&&hr&&R([yn.name],!0);const Rs=await Ext(Ss,o.disabled,i,S,t.shouldUseNativeValidation&&!gs,Ut);if(hn&&hr&&R([yn.name]),Rs[yn.name]&&(Xs.valid=!1,gs)||(gs||(E(yn.name),Ri(Rs,yn.name)?Ut?Nxt(n.errors,Rs,yn.name):Qh(n.errors,yn.name,Rs[yn.name]):ux(n.errors,yn.name)),s.shouldUseNativeValidation&&Rs[yn.name]))break}!Ay(Js)&&await J({context:Xs,onlyCheckValid:gs,fields:Js,name:ds,eventType:Is})}}return Xs.valid},ce=()=>{for(const wt of o.unMount){const gs=Ri(r,wt);gs&&(gs._f.refs?gs._f.refs.every(ks=>!Vze(ks)):!Vze(gs._f.ref))&&rt(wt)}o.unMount=new Set},_e=(wt,gs)=>(wt&&gs&&Qh(i,wt,gs),!uw(l.mount?i:a,a)),he=(wt,gs,ks)=>MHe(wt,o,{...l.mount?i:Oh(gs)||fv(wt)?a:gs},ks,gs),ue=wt=>JOt(Ri(l.mount?i:a,wt,t.shouldUnregister?Ri(a,wt,[]):[])),ve=(wt,gs,ks={},Is=!1,Xs=!1,ds=!1)=>{const Ss=Ri(r,wt);let yn=gs;if(Ss){const Js=Ss._f;Js&&(!Js.disabled&&Qh(i,wt,LHe(gs,Js)),yn=vEe(Js.ref)&&dv(gs)?"":gs,t8t(Js.ref)?[...Js.ref.options].forEach(Ut=>Ut.selected=yn.includes(Ut.value)):Js.refs?Dae(Js.ref)?Js.refs.forEach(Ut=>{(!Ut.defaultChecked||!Ut.disabled)&&(Array.isArray(yn)?Ut.checked=!!yn.find(hn=>hn===Ut.value):Ut.checked=yn===Ut.value||!!yn)}):Js.refs.forEach(Ut=>Ut.checked=Ut.value===yn):yLe(Js.ref)?Js.ref.value="":(Js.ref.value=yn,!Js.ref.type&&!Xs&&!ds&&v.state.next({name:wt,values:Is?i:Uf(i)})))}(ks.shouldDirty||ks.shouldTouch)&&X(wt,Ss&&Ss._f&&!Ss._f.disabled&&(Ss._f.valueAsNumber||Ss._f.valueAsDate||Ss._f.setValueAs)?LHe(gs,Ss._f):yn,ks.shouldTouch,ks.shouldDirty,!Xs),ks.shouldValidate&&Ne(wt,{delayError:ks.delayError})},Ee=(wt,gs,ks,Is=!1,Xs=!1,ds=!1)=>{o.array.has(wt)&&v.array.next({name:wt,values:Is?i:Uf(i)});for(const Ss in gs){if(!gs.hasOwnProperty(Ss))continue;const yn=gs[Ss],Js=wt+"."+Ss,Ut=Ri(r,Js);(o.array.has(wt)||Kp(yn)||Ut&&!Ut._f)&&!pI(yn)?Ee(Js,yn,ks,Is,Xs,ds):ve(Js,yn,ks,Is,Xs,ds)}},Se=(wt,gs,ks,Is,Xs=!1)=>{const ds=Ri(r,wt),Ss=o.array.has(wt),yn=Is?gs:Uf(gs),Js=Ri(i,wt),Ut=uw(Js,yn);if(Ut||Qh(i,wt,yn),Ss)v.array.next({name:wt,values:Is?i:Uf(i)}),y("isDirty","dirtyFields")&&ks.shouldDirty&&(D(),Xs||v.state.next({name:wt,dirtyFields:n.dirtyFields,isDirty:_e(wt,yn)}));else{const hn=Array.isArray(yn)&&!yn.length||Ay(yn),hr=!Ut&&!Xs;!ds||ds._f||dv(yn)||hn?ve(wt,yn,ks,Is,Xs,hr):Ee(wt,yn,ks,Is,Xs,hr)}if(!Ut&&!Xs){const hn=qze(wt,o),hr=Is?i:Uf(i);if(v.state.next({...hn&&n,name:l.mount||hn?wt:void 0,values:hr}),!Ss)for(const Rs of b5s(o.array,wt))v.state.next({name:Rs,values:hr})}},Le=(wt,gs,ks={})=>Se(wt,gs,ks,!1),Fe=(wt,gs={})=>{const ks=u1(wt)?wt(i):wt;if(!uw(i,ks)){i={...i,...ks};for(const Is of o.mount)x5s(ks,Is)&&Se(Is,Ri(ks,Is),gs,!0,!0);v.state.next({...n,name:void 0,type:void 0,...u?{values:i}:{}}),gs.shouldValidate&&P()}},ke=async wt=>{l.mount=!0;const gs=wt.target;let ks=gs.name,Is=!0;const Xs=Ri(r,ks),ds=Ss=>{Is=Number.isNaN(Ss)||pI(Ss)&&isNaN(Ss.getTime())||uw(Ss,Ri(i,ks,Ss))};if(Xs){let Ss,yn;const Js=gs.type?Ixt(Xs._f):EHe(wt),Ut=wt.type===cP.BLUR||wt.type===cP.FOCUS_OUT,hn=!j5s(Xs._f)&&!s.validate&&!t.resolver&&!Ri(n.errors,ks)&&!Xs._f.deps,hr=hn||S5s(Ut,Ri(n.touchedFields,ks),n.isSubmitted,m,h),Rs=qze(ks,o,Ut);if(Qh(i,ks,Uf(Js)),Ut){if(!gs||!gs.readOnly){Xs._f.onBlur&&Xs._f.onBlur(wt);const $n=c[ks];$n&&$n(0)}}else Xs._f.onChange&&Xs._f.onChange(wt);const jr=X(ks,Js,Ut),kr=!Ay(jr)||Rs;if(!Ut&&v.state.next({name:ks,type:wt.type,...u?{values:Uf(i)}:{}}),hr)return(!hn||!n.isValid)&&y("isValid")&&(t.mode==="onBlur"?Ut&&P():Ut||P()),kr&&v.state.next({name:ks,...Rs?{}:jr});if(!t.resolver&&s.validate&&await te({name:ks,eventType:wt.type}),!Ut&&Rs&&v.state.next({...n}),t.resolver){const{errors:$n}=await le([ks]);if(R([ks]),ds(Js),!Is){!Ay(jr)&&v.state.next(jr);return}const kn=Rxt(n.errors,r,ks),Fn=Rxt($n,r,kn.name||ks);Ss=Fn.error,ks=Fn.name,yn=Ay($n)}else R([ks],!0),Ss=(await Ext(Xs,o.disabled,i,S,t.shouldUseNativeValidation))[ks],R([ks]),ds(Js),Is&&(Ss?yn=!1:y("isValid")&&(yn=await J({fields:r,onlyCheckValid:!0,name:ks,eventType:wt.type})));Is&&(Xs._f.deps&&(!Array.isArray(Xs._f.deps)||Xs._f.deps.length>0)&&Ne(Xs._f.deps),ae(ks,yn,Ss,jr))}},Be=(wt,gs)=>{if(Ri(n.errors,gs)&&wt.focus)return wt.focus(),1},Ne=async(wt,gs={})=>{let ks,Is;const Xs=V4e(wt);if(t.resolver){const ds=w,Ss=await ne(Oh(wt)?wt:Xs);if(ks=Ay(Ss),Is=wt?!Xs.some(yn=>Ri(Ss,yn)):ks,ds!==w)return Is}else wt?(Is=(await Promise.all(Xs.map(async ds=>{const Ss=Ri(r,ds);return await J({fields:Ss&&Ss._f?{[ds]:Ss}:Ss,eventType:cP.TRIGGER})}))).every(Boolean),!(!Is&&!n.isValid)&&P()):Is=ks=await J({fields:r,name:wt,eventType:cP.TRIGGER});if(gs.delayError&&t.delayError&&fv(wt)){const ds=Ri(n.errors,wt);ds?(ux(n.errors,wt),c[wt]=A(wt,()=>U(wt,ds)),c[wt](t.delayError)):E(wt)}if(gs.shouldTouch)for(const ds of wt?Xs:o.mount)!o.array.has(ds)&&Qh(n.touchedFields,ds,!0);return v.state.next({...!fv(wt)||y("isValid")&&ks!==n.isValid?{}:{name:wt},...t.resolver||!wt?{isValid:ks}:{},...gs.shouldTouch&&y("touchedFields")?{touchedFields:n.touchedFields}:{},errors:n.errors}),gs.shouldFocus&&!Is&&uee(r,Be,wt?Xs:o.mount),Is},Ae=(wt,gs)=>{let ks={...l.mount?i:a};return gs&&(ks=e8t(gs.dirtyFields?n.dirtyFields:n.touchedFields,ks)),Oh(wt)?ks:fv(wt)?Ri(ks,wt):wt.map(Is=>Ri(ks,Is))},Ce=wt=>Oh(wt)?{...n.errors}:fv(wt)?Ri(n.errors,wt):wt.map(gs=>Ri(n.errors,gs)),Ve=(wt,gs)=>{const ks=gs||n,Is=Ri(ks.errors,wt);return{invalid:!!Is,isDirty:!!Ri(ks.dirtyFields,wt),error:Is,isValidating:!!Ri(ks.validatingFields,wt),isTouched:!!Ri(ks.touchedFields,wt)}},ze=wt=>{const gs=wt?V4e(wt):void 0;gs?gs.forEach(ks=>{I(ks),ux(n.errors,ks),v.state.next({name:ks,errors:n.errors})}):(Object.keys(c).forEach(E),n.errors={},v.state.next({errors:n.errors}))},qe=(wt,gs,ks)=>{E(wt);const Is=(Ri(r,wt,{_f:{}})._f||{}).ref,Xs=Ri(n.errors,wt)||{},{ref:ds,message:Ss,type:yn,types:Js,...Ut}=Xs;Qh(n.errors,wt,{...Ut,...gs,ref:Is}),v.state.next({name:wt,errors:n.errors,isValid:!1}),ks&&ks.shouldFocus&&Is&&Is.focus&&Is.focus()},dt=(wt,gs)=>{if(u1(wt)){u++;const{unsubscribe:ks}=v.state.subscribe({next:Xs=>"values"in Xs&&wt(Xs.values||he(void 0,gs),Xs)});let Is=!1;return{unsubscribe:()=>{Is||(Is=!0,u--,ks())}}}return he(wt,gs,!0)},Xe=wt=>{var gs;const ks=!!(!((gs=wt.formState)===null||gs===void 0)&&gs.values);ks&&u++;const{unsubscribe:Is}=v.state.subscribe({next:ds=>{if(k5s(wt.name,ds.name,wt.exact)&&N5s(ds,wt.formState||g,Ft,wt.reRenderRoot)){const Ss={...i};wt.callback({values:Ss,...n,...ds,defaultValues:a})}}});if(!ks)return Is;let Xs=!1;return()=>{Xs||(Xs=!0,u--,Is())}},at=wt=>(l.mount=!0,x={...x,...wt.formState},Xe({...wt,formState:{...f,...wt.formState}})),rt=(wt,gs={})=>{for(const ks of wt?V4e(wt):o.mount)o.mount.delete(ks),o.array.delete(ks),o.disabled.delete(ks),gs.keepValue||(ux(r,ks),ux(i,ks)),gs.keepError||(I(ks),ux(n.errors,ks)),!gs.keepDirty&&ux(n.dirtyFields,ks),!gs.keepTouched&&ux(n.touchedFields,ks),!gs.keepIsValidating&&ux(n.validatingFields,ks),!t.shouldUnregister&&!gs.keepDefaultValue&&ux(a,ks);u&&v.state.next({values:Uf(i)}),v.state.next({...n,...gs.keepDirty?{}:{isDirty:_e()},...gs.keepIsValidating?{}:{isValidating:!Ay(n.validatingFields)}}),!gs.keepIsValid&&P()},Ke=({disabled:wt,name:gs})=>{if(qj(wt)&&l.mount||wt||o.disabled.has(gs)){const Xs=o.disabled.has(gs)!==!!wt;wt?o.disabled.add(gs):o.disabled.delete(gs),Xs&&l.mount&&!l.action&&P()}},Je=(wt,gs={})=>{let ks=Ri(r,wt);const Is=qj(gs.disabled)||qj(t.disabled),Xs=!o.registerName.has(wt)&&ks&&ks._f&&!ks._f.mount;return Qh(r,wt,{...ks||{},_f:{...ks&&ks._f?ks._f:{ref:{name:wt}},name:wt,mount:!0,...gs}}),o.mount.add(wt),ks&&!Xs?Ke({disabled:qj(gs.disabled)?gs.disabled:t.disabled,name:wt}):Y(wt,!0,gs.value),{...Is?{disabled:gs.disabled||t.disabled}:{},...t.progressive?{required:!!gs.required,min:bZ(gs.min),max:bZ(gs.max),minLength:bZ(gs.minLength),maxLength:bZ(gs.maxLength),pattern:bZ(gs.pattern)}:{},name:wt,onChange:ke,onBlur:ke,ref:ds=>{if(ds){o.registerName.add(wt),Je(wt,gs),o.registerName.delete(wt),ks=Ri(r,wt);const Ss=Oh(ds.value)&&ds.querySelectorAll&&ds.querySelectorAll("input,select,textarea")[0]||ds,yn=y5s(Ss),Js=ks._f.refs||[];if(yn?Js.find(hn=>hn===Ss):Ss===ks._f.ref)return;const Ut={...ks._f};yn?(Ut.refs=[...Js.filter(Vze),Ss,...Array.isArray(Ri(a,wt))?[{}]:[]],Ut.ref={type:Ss.type,name:wt}):(Ut.ref=Ss,delete Ut.refs),Qh(r,wt,{_f:Ut}),Y(wt,!1,void 0,Ss)}else ks=Ri(r,wt,{}),ks._f&&(ks._f.mount=!1),(t.shouldUnregister||gs.shouldUnregister)&&!(WOt(o.array,wt)&&l.action)&&o.unMount.add(wt)}}},pt=()=>t.shouldFocusError&&!t.shouldUseNativeValidation&&uee(r,Be,o.mount),gt=wt=>{qj(wt)&&(v.state.next({disabled:wt}),uee(r,(gs,ks)=>{const Is=Ri(r,ks);Is&&(gs.disabled=Is._f.disabled||wt,Array.isArray(Is._f.refs)&&Is._f.refs.forEach(Xs=>{Xs.disabled=Is._f.disabled||wt}))},0))},ss=(wt,gs)=>async ks=>{let Is,Xs;ks&&(ks.preventDefault&&ks.preventDefault(),ks.persist&&ks.persist());let ds=Uf(i);if(v.state.next({isSubmitting:!0}),t.resolver){const Ss=w,{errors:yn,values:Js}=await le();if(Ss!==w)return;R(),Object.keys(c).forEach(E),n.errors=yn,ds=Uf(Js)}else await J({fields:r,eventType:cP.SUBMIT}),ux(n.errors,KOt);if(o.disabled.size)for(const Ss of o.disabled)ux(ds,Ss);if(Ay(n.errors)){v.state.next({errors:{}});try{Is=await wt(ds,ks)}catch(Ss){Xs=Ss}}else gs&&await gs({...n.errors},ks),pt(),setTimeout(pt);if(v.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:Ay(n.errors)&&!Xs,submitCount:n.submitCount+1,errors:n.errors}),Xs)throw Xs;return Is},Yt=(wt,gs={})=>{Ri(r,wt)&&(ux(n.validatingFields,wt),Oh(gs.defaultValue)?Le(wt,Uf(Ri(a,wt))):(Le(wt,gs.defaultValue),Qh(a,wt,Uf(gs.defaultValue))),gs.keepTouched||ux(n.touchedFields,wt),gs.keepDirty||(ux(n.dirtyFields,wt),n.isDirty=gs.defaultValue?_e(wt,Uf(Ri(a,wt))):_e()),gs.keepError||(E(wt),ux(n.errors,wt),P()),v.state.next({...n,isValidating:!Ay(n.validatingFields)}))},ts=(wt,gs={})=>{w++;const ks=wt?Uf(wt):a,Is=Uf(ks),Xs=Ay(wt),ds=Is,Ss=r;if(Object.keys(c).forEach(E),gs.keepDefaultValues||(a=ks),!gs.keepValues){if(gs.keepDirtyValues){const yn=new Set([...o.mount,...s8t(qM(a,i,void 0,Ss),n.dirtyFields)]);for(const Js of yn){const Ut=Ri(n.dirtyFields,Js),hn=Ri(i,Js),hr=Ri(ds,Js);Ut&&!Oh(hn)?Qh(ds,Js,hn):!Ut&&!Oh(hr)&&Le(Js,hr)}}else{if(vLe&&Oh(wt))for(const yn of o.mount){const Js=Ri(r,yn);if(Js&&Js._f){const Ut=Array.isArray(Js._f.refs)?Js._f.refs[0]:Js._f.ref;if(vEe(Ut)){const hn=Ut.closest("form");if(hn){hn.reset();break}}}}if(gs.keepFieldsRef)for(const yn of o.mount)Le(yn,Ri(ds,yn));else r={}}if(t.shouldUnregister){if(i=gs.keepDefaultValues?Uf(a):{},gs.keepFieldsRef)for(const yn of o.mount)Qh(i,yn,Ri(ds,yn))}else i=Uf(ds);v.array.next({values:{...ds}}),v.state.next({name:void 0,type:void 0,values:{...ds}})}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&&!Ay(ds),l.watch=!!t.shouldUnregister,l.keepIsValid=!!gs.keepIsValid,l.action=!1,l.actionArrayLengths.clear(),gs.keepErrors||(n.errors={}),v.state.next({submitCount:gs.keepSubmitCount?n.submitCount:0,isDirty:Xs?!1:gs.keepDirty?n.isDirty:gs.keepValues?_e():!!(gs.keepDefaultValues&&!uw(wt,a)),isSubmitted:gs.keepIsSubmitted?n.isSubmitted:!1,dirtyFields:Xs?{}:gs.keepDirtyValues?gs.keepDefaultValues&&i?qM(a,i,void 0,Ss):n.dirtyFields:gs.keepDefaultValues&&wt?qM(a,wt,void 0,Ss):gs.keepDirty?n.dirtyFields:gs.keepValues?qM(a,i,void 0,Ss):{},touchedFields:gs.keepTouched?n.touchedFields:{},...!gs.keepIsValidating&&(n.isValidating||!Ay(n.validatingFields))?{validatingFields:{},isValidating:!1}:null,errors:gs.keepErrors?n.errors:{},isSubmitSuccessful:gs.keepIsSubmitSuccessful?n.isSubmitSuccessful:!1,isSubmitting:!1,defaultValues:a})},ys=(wt,gs)=>ts(u1(wt)?wt(i):wt,{...t.resetOptions,...gs}),Bt=(wt,gs={})=>{const ks=Ri(r,wt),Is=ks&&ks._f;if(Is){const Xs=Is.refs?Is.refs[0]:Is.ref;Xs.focus&&setTimeout(()=>{Xs.focus(),gs.shouldSelect&&u1(Xs.select)&&Xs.select()})}},Ft=wt=>{const{name:gs,type:ks,values:Is,...Xs}=wt;n={...n,...Xs}};v.state.subscribe({next:Ft});const Ks={control:{register:Je,unregister:rt,getFieldState:Ve,handleSubmit:ss,setError:qe,_subscribe:Xe,_runSchema:le,_updateIsValidating:R,_focusError:pt,_getWatch:he,_getDirty:_e,_setValid:P,_setFieldArray:O,_setDisabledField:Ke,_setErrors:W,_getFieldArray:ue,_reset:ts,_resetDefaultValues:()=>u1(t.defaultValues)&&t.defaultValues().then(wt=>{ys(wt,t.resetOptions),v.state.next({isLoading:!1})}),_removeUnmounted:ce,_disableForm:gt,_subjects:v,_proxyFormState:g,get _fields(){return r},get _formValues(){return i},get _state(){return l},set _state(wt){l=wt},get _defaultValues(){return a},get _names(){return o},set _names(wt){o=wt},get _formState(){return n},get _options(){return t},set _options(wt){t={...t,...wt},h=Sce(t.mode),m=Sce(t.reValidateMode),S=t.criteriaMode===IN.all}},subscribe:at,trigger:Ne,register:Je,handleSubmit:ss,watch:dt,setValue:Le,setValues:Fe,getValues:Ae,getErrors:Ce,reset:ys,resetField:Yt,resetDefaultValues:(wt,gs={})=>{if(a=Uf(wt),!gs.keepDirty){const ks=qM(a,i,void 0,r);n.dirtyFields=ks,n.isDirty=!Ay(ks)}gs.keepIsValid||P(),v.state.next({...n,defaultValues:a})},clearErrors:ze,unregister:rt,setError:qe,setFocus:Bt,getFieldState:Ve};return{...Ks,formControl:Ks}}function bLe(s={}){const t=Gt.useRef(void 0),n=Gt.useRef(void 0),r=Gt.useRef(s.formControl),[a,i]=Gt.useState(()=>({...Uf(i8t),isLoading:u1(s.defaultValues),errors:s.errors||{},disabled:s.disabled||!1,defaultValues:u1(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&&!u1(s.defaultValues)&&s.formControl.reset(s.defaultValues,s.resetOptions);else{const{formControl:u,...h}=T5s(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}=Xet(o);return Zet(()=>{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]),Gt.useEffect(()=>l._disableForm(s.disabled),[l,s.disabled]),Gt.useEffect(()=>{s.mode&&(l._options.mode=s.mode),s.reValidateMode&&(l._options.reValidateMode=s.reValidateMode)},[l,s.mode,s.reValidateMode]),Gt.useEffect(()=>{s.errors&&(l._setErrors(s.errors),l._focusError())},[l,s.errors]),Gt.useEffect(()=>{s.shouldUnregister&&l._subjects.state.next({values:l._getWatch()})},[l,s.shouldUnregister]),Gt.useEffect(()=>{if(l._proxyFormState.isDirty){const u=l._getDirty();u!==a.isDirty&&l._subjects.state.next({isDirty:u})}},[l,a.isDirty]),Gt.useEffect(()=>{var u;s.values&&!uw(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]),Gt.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=Gt.useMemo(()=>YOt(a,l),[l,a]),t.current}const Dxt=(s,t,n)=>{if(s&&"reportValidity"in s){const r=Ri(n,t);s.setCustomValidity(r&&r.message||""),s.reportValidity()}},o8t=(s,t)=>{for(const n in t.fields){const r=t.fields[n];r&&r.ref&&"reportValidity"in r.ref?Dxt(r.ref,n,s):r.refs&&r.refs.forEach(a=>Dxt(a,n,s))}},M5s=(s,t)=>{t.shouldUseNativeValidation&&o8t(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(P5s(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},P5s=(s,t)=>s.some(n=>n.startsWith(t+"."));var I5s=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]=ZOt(l,t,n,a,d?[].concat(d,r.message):r.message)}s.shift()}return n},_Le=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&&o8t({},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:M5s(I5s(l.errors,!i.shouldUseNativeValidation&&i.criteriaMode==="all"),i)};throw l}))}catch(l){return Promise.reject(l)}}};function RHe(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 Fxt(s,t="|"){return s.map(n=>m8t(n)).join(t)}function DHe(s,t){return typeof t=="bigint"?t.toString():t}class L5s{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 ett(s){return new L5s(s)}function R5s(s){return s==null}function ttt(s){const t=s.startsWith("^")?1:0,n=s.endsWith("$")?s.length-1:s.length;return s.slice(t,n)}function D5s(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}):d8t(s,i,r?r(l.value,i):l.value))}}function F5s(s,t){for(const n of Reflect.ownKeys(t)){const r=Object.getOwnPropertyDescriptor(t,n);r.enumerable&&(r.get?c8t(s,n,()=>t[n]):d8t(s,n,r.value))}}function Gj(...s){const t={};for(const n of s){const r=Object.getOwnPropertyDescriptors(n);Object.assign(t,r)}return Object.defineProperties({},t)}function O5s(s){return JSON.stringify(s)}function z5s(s){return s.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const u8t="captureStackTrace"in Error?Error.captureStackTrace:(...s)=>{};function _Ee(s){return typeof s=="object"&&s!==null&&!Array.isArray(s)}const B5s=ett(()=>{var s;if(H4.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 Zte(s){if(_Ee(s)===!1)return!1;const t=s.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(_Ee(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function h8t(s){return Zte(s)?{...s}:Array.isArray(s)?[...s]:s instanceof Map?new Map(s):s instanceof Set?new Set(s):s}const $5s=new Set(["string","number","symbol"]);function bG(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function s6(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 m8t(s){return typeof s=="bigint"?s.toString()+"n":typeof s=="string"?`"${s}"`:`${s}`}function U5s(s){return Object.keys(s).filter(t=>s[t]._zod.optin!==void 0&&s[t]._zod.optout==="optional")}const f8t={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]},q5s={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function V5s(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 U7(i,s,wLe(s,t)),s6(s,Gj(n,{shape:i,checks:[]}))}function wLe(s,t){var a;const n=dT(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 H5s(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(wLe(s,t)),l={};return U7(l,s,Reflect.ownKeys(dT(s)).filter(o=>!i.has(o))),s6(s,Gj(n,{shape:l,checks:[]}))}function G5s(s,t){if(!Zte(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=dT(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 s6(s,Gj(s._zod.def,{shape:p8t(s,t)}))}function p8t(s,t){const n={};return U7(n,s,Reflect.ownKeys(dT(s))),F5s(n,t),n}function W5s(s,t){if(!Zte(t))throw new Error("Invalid input to safeExtend: expected a plain object");return s6(s,Gj(s._zod.def,{shape:p8t(s,t)}))}function K5s(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={};U7(n,s,Reflect.ownKeys(dT(s))),U7(n,t,Reflect.ownKeys(dT(t)));const r=Gj(s._zod.def,{shape:n,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return s6(s,r)}function Oxt(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(wLe(t,n)):void 0,c={};return U7(c,t,Reflect.ownKeys(dT(t)),s&&((d,u)=>o&&!o.has(u)?d:new s({type:"optional",innerType:d}))),s6(t,Gj(t._zod.def,{shape:c,checks:[]}))}function Y5s(s,t,n){const r=n?new Set(wLe(t,n)):void 0,a={};return U7(a,t,Reflect.ownKeys(dT(t)),(i,l)=>r&&!r.has(l)?i:new s({type:"nonoptional",innerType:i})),s6(t,Gj(t._zod.def,{shape:a}))}function xE(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 _Z(s){return typeof s=="string"?s:s==null?void 0:s.message}function zxt(s,t,n){var r;for(let a=t;as;return t[r4s]=!0,t}var Bxt;const Wze={value:void 0,enumerable:!1};let $xt="captureStackTrace"in Error?Error:null;function i4s(s){const t=$xt;if(t){const n=t.stackTraceLimit;if(typeof n=="number"){try{t.stackTraceLimit=0}catch{return $xt=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{Wze.value=new i(f);try{Object.defineProperty(m,"_zod",Wze)}finally{Wze.value=void 0}}if(m._zod.traits.add(s),t(m,f),o){const x=Object.getPrototypeOf(m),y=m._zod.constr.prototype;let v=x;for(;v&&v!==y;)v=Object.getPrototypeOf(v);const b=v??x;o.has(b)||(o.add(b),J5s(b,l))}const g=h.prototype;for(const x in g)Object.prototype.hasOwnProperty.call(g,x)&&(x in m||(m[x]=g[x].bind(m)))}const d=(r==null?void 0:r.Parent)??Object;class u extends d{}Object.defineProperty(u,"name",{value:s});function h(m){var y;const f=r!=null&&r.Parent?i4s(u):this;c(f,m);const g=f._zod.deferred;if(g){for(const v of g)v();f._zod.deferred=void 0}const x=(y=globalThis.__zod_globalConfig)==null?void 0:y.postProcessor;return x&&x(f),f}return Object.defineProperty(h,"init",{value:c}),Object.defineProperty(h,Symbol.hasInstance,{value:m=>{var f,g;return r!=null&&r.Parent&&m instanceof r.Parent?!0:(g=(f=m==null?void 0:m._zod)==null?void 0:f.traits)==null?void 0:g.has(s)}}),Object.defineProperty(h,"name",{value:s}),h}class i7 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class v8t extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(Bxt=globalThis).__zod_globalConfig??(Bxt.__zod_globalConfig={});const H4=globalThis.__zod_globalConfig;function n6(s){return s&&Object.assign(H4,s),H4}function o4s(){const s=this._zod;return s.message??(s.message=JSON.stringify(s.def,DHe,2)),s.message}function l4s(s){this._zod.message=s}const c4s={get:o4s,set:l4s,enumerable:!0,configurable:!0},Kze={value:void 0,enumerable:!1},Uxt=new WeakSet([Object.prototype,Error.prototype]),d4s=(s,t)=>{s.name="$ZodError",Kze.value=t,Object.defineProperty(s,"issues",Kze),Kze.value=void 0,Object.defineProperty(s,"message",c4s);const n=Object.getPrototypeOf(s);Uxt.has(n)||(Uxt.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})}}))},u4s=Ma("$ZodError",d4s);function h4s(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 m4s(s,t=n=>n.message){const n={},r=[];for(const a of s.issues)a.path.length>0?h4s(n,a.path[0],()=>[]).push(t(a)):r.push(t(a));return{formErrors:r,fieldErrors:n}}function f4s(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 i7;if(o.issues.length){const c=new((i==null?void 0:i.Err)??s)(o.issues.map(d=>JW(d,l,n6())));throw u8t(c,(i==null?void 0:i.callee)??t),c}return o.value};return t},att=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=>JW(d,l,n6())));throw u8t(c,(i==null?void 0:i.callee)??t),c}return o.value};return t},itt=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 i7;return i.issues.length?b8t(s,i.issues,a):{success:!0,data:i.value}};function b8t(s,t,n){let r;return{success:!1,get error(){return r||(r=new s(t.map(a=>JW(a,n,n6()))),t=void 0,n=void 0),r},set error(a){r=a,t=void 0,n=void 0}}}const ott=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?b8t(s,i.issues,a):{success:!0,data:i.value}},p4s=Symbol.for("zod.compile.invalid"),g4s=Symbol.for("zod.compile.fallback"),x4s=(s,t,n)=>{const r=s._zod.bag.validator;if(r!==void 0){if(r(t)!==p4s)return!0;if(r.definite===!0&&n===void 0)return!1}return y4s(s,t,n)};function y4s(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[g4s]=!0,i=a({value:t,issues:[]},r)):i=s._zod.run({value:t,issues:[]},r),i instanceof Promise)throw new i7;return i.issues.length===0}const v4s=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},b4s=s=>{const t=rtt(s),n=(r,a,i,l)=>{const o=i?{...i,direction:"backward"}:{direction:"backward"};return t(r,a,o,jLe(n,l))};return n},_4s=s=>{const t=rtt(s),n=(r,a,i,l)=>t(r,a,i,jLe(n,l));return n},w4s=s=>{const t=att(s),n=async(r,a,i,l)=>{const o=i?{...i,direction:"backward"}:{direction:"backward"};return await t(r,a,o,jLe(n,l))};return n},j4s=s=>{const t=att(s),n=async(r,a,i,l)=>await t(r,a,i,jLe(n,l));return n},N4s=s=>(t,n,r)=>{const a=r?{...r,direction:"backward"}:{direction:"backward"};return itt(s)(t,n,a)},k4s=s=>(t,n,r)=>itt(s)(t,n,r),S4s=s=>async(t,n,r)=>{const a=r?{...r,direction:"backward"}:{direction:"backward"};return ott(s)(t,n,a)},C4s=s=>async(t,n,r)=>ott(s)(t,n,r),A4s=/^[cC][0-9a-z]{6,}$/,E4s=/^[0-9a-z]+$/,T4s=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,M4s=/^[0-9a-vA-V]{20}$/,P4s=/^[A-Za-z0-9]{27}$/,I4s=/^[a-zA-Z0-9_-]{21}$/;function L4s(s){return new RegExp(`^[a-zA-Z0-9_-]{${s}}$`)}const R4s=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,D4s=/^([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})$/,qxt=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)$/,F4s=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,O4s="^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$";function z4s(){return new RegExp(O4s,"u")}const B4s=/^(?:(?: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])$/,$4s=/^(([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}|:))$/,U4s=/^((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])$/,q4s=/^(([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])$/,V4s=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,H4s=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/,G4s=/^https?$/,W4s=/^\+[1-9]\d{6,14}$/,_8t="(?:(?:\\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 K4s(s){return new RegExp(`^${s}$`)}const Y4s=K4s(_8t);function FHe(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 Z4s(s){return new RegExp(`^${FHe(s)}$`)}function X4s(s){const t=["Z"];s.offset&&t.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const n=`${FHe({precision:s.precision,seconds:!0})}(?:${t.join("|")})`,r=s.local?`${n}|${FHe({precision:s.precision})}`:n;return new RegExp(`^${_8t}T(?:${r})$`)}const Q4s=/^[\s\S]{0,}$/,J4s=/^-?\d+(?:\.\d+)?$/,e3s=/^(?:true|false)$/i,t3s=/^[^A-Z]*$/,s3s=/^[^a-z]*$/,Bw=Ma("$ZodCheck",(s,t)=>{var n;s._zod??(s._zod={}),s._zod.def=t,(n=s._zod).onattach??(n.onattach=[])}),ltt=s=>{const t=s.value;return!R5s(t)&&t.length!==void 0},wEe={number:"number",bigint:"bigint",object:"date"},w8t=Ma("$ZodCheckLessThan",(s,t)=>{Bw.init(s,t);const n=wEe[typeof t.value];s._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value{Bw.init(s,t);const n=wEe[typeof t.value];s._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:wEe[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})}}),n3s=Ma("$ZodCheckMultipleOf",(s,t)=>{Bw.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):D5s(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})}}),r3s=Ma("$ZodCheckNumberFormat",(s,t)=>{var l;Bw.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]=f8t[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})}}),a3s=Ma("$ZodCheckMaxLength",(s,t)=>{var n;Bw.init(s,t),(n=s._zod.def).when??(n.when=ltt),s._zod.check=r=>{const a=r.value,i=a.length;if((typeof a=="string"&&i>t.maximum?stt(a):i)<=t.maximum)return;const o=ntt(a);r.issues.push({origin:o,code:"too_big",maximum:t.maximum,inclusive:!0,input:a,inst:s,continue:!t.abort})}}),i3s=Ma("$ZodCheckMinLength",(s,t)=>{var n;Bw.init(s,t),(n=s._zod.def).when??(n.when=ltt),s._zod.check=r=>{const a=r.value,i=a.length;if((typeof a=="string"&&i>=t.minimum&&i=t.minimum)return;const o=ntt(a);r.issues.push({origin:o,code:"too_small",minimum:t.minimum,inclusive:!0,input:a,inst:s,continue:!t.abort})}}),o3s=Ma("$ZodCheckLengthEquals",(s,t)=>{var n;Bw.init(s,t),(n=s._zod.def).when??(n.when=ltt),s._zod.check=r=>{const a=r.value,i=a.length,l=typeof a=="string"&&i>=t.length&&i<=t.length*2?stt(a):i;if(l===t.length)return;const o=ntt(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})}}),NLe=Ma("$ZodCheckStringFormat",(s,t)=>{var n,r;Bw.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=()=>{})}),l3s=Ma("$ZodCheckRegex",(s,t)=>{NLe.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})}}),c3s=Ma("$ZodCheckLowerCase",(s,t)=>{t.pattern??(t.pattern=t3s),NLe.init(s,t)}),d3s=Ma("$ZodCheckUpperCase",(s,t)=>{t.pattern??(t.pattern=s3s),NLe.init(s,t)}),u3s=Ma("$ZodCheckIncludes",(s,t)=>{Bw.init(s,t);const n=bG(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})}}),h3s=Ma("$ZodCheckStartsWith",(s,t)=>{Bw.init(s,t);const n=new RegExp(`^${bG(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})}}),m3s=Ma("$ZodCheckEndsWith",(s,t)=>{Bw.init(s,t);const n=new RegExp(`.*${bG(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})}}),f3s=Ma("$ZodCheckOverwrite",(s,t)=>{Bw.init(s,t),s._zod.check=n=>{n.value=t.tx(n.value)}});class p3s{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 g3s={major:4,minor:6,patch:5},Mx=Ma("$ZodType",(s,t)=>{var i;var n;s??(s={}),s._zod.def=t,s._zod.bag=s._zod.bag||{},s._zod.version=g3s;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=xE(c),m;for(const f of d){if(f._zod.def.when){if(Z5s(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 i7;if(m||x instanceof Promise)m=(m??Promise.resolve()).then(async()=>{await x,c.issues.length!==g&&(zxt(c.issues,g,s),h||(h=xE(c,g)))});else{if(c.issues.length===g)continue;zxt(c.issues,g,s),h||(h=xE(c,g))}}return m?m.then(()=>c):c},o=(c,d,u)=>{if(xE(c))return c.aborted=!0,c;const h=l(d,a,u);if(h instanceof Promise){if(u.async===!1)throw new i7;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 i7;return u.then(h=>l(h,a,d))}return l(u,a,d)}}},{get"~standard"(){return x8t(this,"~standard",k8t(this))},set"~standard"(s){NL(this,"~standard",s)}}),N8t=(s,t)=>s.issues.length?{issues:s.issues.map(n=>JW(n,t,n6()))}:{value:s.value};async function x3s(s,t){const n={async:!0};return N8t(await s._zod.run({value:t,issues:[]},n),n)}function k8t(s){return{validate:t=>{const n={async:!1};try{const r=s._zod.run({value:t,issues:[]},n);if(!(r instanceof Promise))return N8t(r,n)}catch{}return x3s(s,t)},vendor:"zod",version:1}}const ctt=Ma("$ZodString",(s,t)=>{Mx.init(s,t),s._zod.pattern=t.pattern??Q4s,s._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:s}),n}}),sg=Ma("$ZodStringFormat",(s,t)=>{NLe.init(s,t),ctt.init(s,t)}),y3s=Ma("$ZodGUID",(s,t)=>{t.pattern??(t.pattern=D4s),sg.init(s,t)}),v3s=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=qxt(r))}else t.pattern??(t.pattern=qxt());sg.init(s,t)}),b3s=Ma("$ZodEmail",(s,t)=>{t.pattern??(t.pattern=F4s),sg.init(s,t)}),S8t=1,jEe=2;function C8t(s){try{return typeof URL<"u"&&typeof URL.canParse=="function"?URL.canParse(s):(new URL(s),!0)}catch{return!1}}function _3s(s,t){return!("normalize"in t)&&!("hostname"in t)&&!("protocol"in t)?C8t(s)||jEe:w3s(s,t)}function w3s(s,t){var n;if(!t.normalize&&((n=t.protocol)==null?void 0:n.source)===G4s.source&&!/^https?:\/\//i.test(s))return S8t;try{if(typeof URL<"u"){const r=URL;if(typeof r.parse=="function")return r.parse(s)??jEe}return new URL(s)}catch{return jEe}}const j3s=/[\t\n\r]/g;function Vxt(s){return s.replace(j3s,"")}function N3s(s,t){return t.lastIndex=0,t.test(s.hostname)}function k3s(s,t){return t.lastIndex=0,t.test(s.protocol.endsWith(":")?s.protocol.slice(0,-1):s.protocol)}const S3s=Ma("$ZodURL",(s,t)=>{sg.init(s,t),s._zod.check=n=>{try{const r=n.value.trim(),a=_3s(r,t);if(a===S8t){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:s,continue:!t.abort});return}if(a===jEe){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:s,continue:!t.abort});return}if(a===!0){n.value=Vxt(r);return}t.hostname&&!N3s(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&&!k3s(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:Vxt(r);return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:s,continue:!t.abort})}}}),C3s=Ma("$ZodEmoji",(s,t)=>{t.pattern??(t.pattern=z4s()),sg.init(s,t)}),A3s=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?I4s:L4s(t.length)),sg.init(s,t)}),E3s=Ma("$ZodCUID",(s,t)=>{t.pattern??(t.pattern=A4s),sg.init(s,t)}),T3s=Ma("$ZodCUID2",(s,t)=>{t.pattern??(t.pattern=E4s),sg.init(s,t)}),M3s=Ma("$ZodULID",(s,t)=>{t.pattern??(t.pattern=T4s),sg.init(s,t)}),P3s=Ma("$ZodXID",(s,t)=>{t.pattern??(t.pattern=M4s),sg.init(s,t)}),I3s=Ma("$ZodKSUID",(s,t)=>{t.pattern??(t.pattern=P4s),sg.init(s,t)}),L3s=Ma("$ZodISODateTime",(s,t)=>{t.pattern??(t.pattern=X4s(t)),sg.init(s,t)}),R3s=Ma("$ZodISODate",(s,t)=>{t.pattern??(t.pattern=Y4s),sg.init(s,t)}),D3s=Ma("$ZodISOTime",(s,t)=>{t.pattern??(t.pattern=Z4s(t)),sg.init(s,t)}),F3s=Ma("$ZodISODuration",(s,t)=>{t.pattern??(t.pattern=R4s),sg.init(s,t)}),O3s=Ma("$ZodIPv4",(s,t)=>{t.pattern??(t.pattern=B4s),sg.init(s,t)}),z3s=/^[0-9a-fA-F:.]+$/;function A8t(s){return z3s.test(s)?C8t(`http://[${s}]`):!1}const B3s=Ma("$ZodIPv6",(s,t)=>{t.pattern??(t.pattern=$4s),sg.init(s,t),s._zod.check=n=>{A8t(n.value)||n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:s,continue:!t.abort})}}),$3s=Ma("$ZodCIDRv4",(s,t)=>{t.pattern??(t.pattern=U4s),sg.init(s,t)});function U3s(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:A8t(n)}const q3s=Ma("$ZodCIDRv6",(s,t)=>{t.pattern??(t.pattern=q4s),sg.init(s,t),s._zod.check=n=>{U3s(n.value)||n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:s,continue:!t.abort})}});function E8t(s){if(s==="")return!0;if(/\s/.test(s)||s.length%4!==0)return!1;try{return atob(s),!0}catch{return!1}}const T8t=/^[0-9a-zA-Z+/]*={0,2}$/,V3s=Ma("$ZodBase64",(s,t)=>{t.pattern??(t.pattern=T8t),sg.init(s,t),s._zod.check=n=>{E8t(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:s,continue:!t.abort})}}),dtt=/^[A-Za-z0-9_-]*$/;function H3s(s){if(!dtt.test(s))return!1;const t=s.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return E8t(n)}const G3s=Ma("$ZodBase64URL",(s,t)=>{t.pattern??(t.pattern=dtt),sg.init(s,t),s._zod.check=n=>{H3s(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:s,continue:!t.abort})}}),W3s=Ma("$ZodE164",(s,t)=>{t.pattern??(t.pattern=W4s),sg.init(s,t)});function K3s(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 Y3s=Ma("$ZodJWT",(s,t)=>{sg.init(s,t),s._zod.check=n=>{K3s(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:s,continue:!t.abort})}}),M8t=Ma("$ZodNumber",(s,t)=>{Mx.init(s,t),s._zod.pattern=J4s,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}}),Z3s=Ma("$ZodNumberFormat",(s,t)=>{r3s.init(s,t),M8t.init(s,t)}),X3s=Ma("$ZodBoolean",(s,t)=>{Mx.init(s,t),s._zod.pattern=e3s,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}}),Q3s=Ma("$ZodUnknown",(s,t)=>{Mx.init(s,t),s._zod.parse=n=>n}),J3s=Ma("$ZodNever",(s,t)=>{Mx.init(s,t),s._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:s}),n)});function Hxt(s,t,n){s.issues.length&&t.issues.push(...g8t(n,s.issues)),t.value[n]=s.value}const eAs=Ma("$ZodArray",(s,t)=>{Mx.init(s,t);const n=H4.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;cHxt(h,r,c)));else if(Hxt(u,r,c),o&&u.issues.length!==0&&xE(u))break}return l.length?Promise.all(l).then(()=>r):r}});function NEe(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(...g8t(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 tAs=[];function P8t(s){var l,o,c,d;const t=Object.keys(s.shape),n=Object.getOwnPropertySymbols(s.shape),r=n.length?n:tAs,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=U5s(s.shape);return{...s,allKeys:a,symbolKeys:r,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(i)}}function I8t(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(xE(n,f))break;f=n.issues.length}if(c.has(g))continue;if(g==="__proto__"){u==="never"&&o.push(g);continue}if(u==="never"){o.push(g);continue}const x=d.run({value:t[g],issues:[]},r);x instanceof Promise?s.push(x.then(y=>NEe(y,n,g,t,h,m))):NEe(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 sAs=Ma("$ZodObject",(s,t)=>{Mx.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=ett(()=>P8t(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)||FB(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=_Ee,l=t.catchall;let o;const c=H4.memoizer;c==null||c.attach(s),s._zod.parse=(d,u)=>{o??(o=a.value);const h=d.value;if(!i(h))return d.issues.push({expected:"object",code:"invalid_type",input:h,inst:s}),d;d.value=c?c.alloc(s,d,{},u):{};const m=[],f=o.shape,g=u==null?void 0:u.abortEarly;let x=d.issues.length;for(const y of o.allKeys){if(g&&d.issues.length!==x){if(xE(d,x))break;x=d.issues.length}if(y==="__proto__")continue;const v=f[y],b=v._zod.optin,w=v._zod.optout,S=v._zod.run({value:h[y],issues:[]},u);S instanceof Promise?m.push(S.then(A=>NEe(A,d,y,h,b,w))):NEe(S,d,y,h,b,w)}return l?I8t(m,h,d,u,a.value,s,g===!0):m.length?Promise.all(m).then(()=>d):d}}),nAs=Ma("$ZodObjectJIT",(s,t)=>{sAs.init(s,t);const n=s._zod.parse,r=ett(()=>P8t(t)),a=H4.memoizer,i=f=>{var A,E;const g=r.value,x=g.symbolKeys,y=new p3s(["payload","ctx"],{shape:f,inst:s,memo:a,syms:x}),v=I=>`shape[${I}]._zod.run({ value: input[${I}], issues: [] }, ctx)`,b=(I,P)=>` let ${I}_ab = false; for (let i = 0; i < ${I}.issues.length; i++) { const iss = ${I}.issues[i]; iss.path = iss.path ? [${P}, ...iss.path] : [${P}]; payload.issues.push(iss); if (iss.continue !== true) ${I}_ab = true; } if (${I}_ab && ctx && ctx.abortEarly) { payload.value = newResult; return payload; }`;y.write("const input = payload.value;");const w=Object.create(null);let S=0;for(const I of g.allKeys)w[I]=`key_${S++}`;y.write(a?"const newResult = memo.alloc(inst, payload, {}, ctx);":"const newResult = {};");for(const I of g.allKeys){if(I==="__proto__")continue;const P=w[I],R=typeof I=="symbol"?`syms[${x.indexOf(I)}]`:O5s(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(y.write(`const ${P} = ${v(R)};`),W&&V){const G=U==="optional"?`${P}_present`:`${P}.value !== undefined || ${P}_present`;y.write(` const ${P}_present = ${D}; if (!${P}.issues.length || ${P}_present) { if (${P}.issues.length) {${b(P,R)} } if (${G}) { newResult[${R}] = ${P}.value; } } `)}else W?(y.write(` if (${P}.issues.length) {${b(P,R)} } `),U==="defaulted"?y.write(`newResult[${R}] = ${P}.value;`):y.write(` if (${P}.value !== undefined || ${D}) { newResult[${R}] = ${P}.value; } `)):y.write(` const ${P}_present = ${D}; if (${P}.issues.length) {${b(P,R)} } if (!${P}_present && !${P}.issues.length) { payload.issues.push({ code: "invalid_type", expected: "nonoptional", input: undefined, path: [${R}] }); if (ctx && ctx.abortEarly) { payload.value = newResult; return payload; } } if (${P}_present) { newResult[${R}] = ${P}.value; } `)}return y.write("payload.value = newResult;"),y.write("return payload;"),y.compile()};let l;const o=_Ee,c=!H4.jitless,u=c&&B5s.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?I8t([],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 Gxt(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=>!xE(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=>JW(l,r,n6())))}),t)}const rAs=Ma("$ZodUnion",(s,t)=>{Mx.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=>ttt(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=>Gxt(o,r,s,a)):Gxt(l,r,s,a)}}),aAs=Ma("$ZodIntersection",(s,t)=>{Mx.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])=>Wxt(n,c,d)):Wxt(n,i,l)}});function OHe(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(Zte(s)&&Zte(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=OHe(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=OHe(t.value,n.value);if(!c.valid){if(xE(s))return s;throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`)}return s.value=c.data,s}const iAs=Ma("$ZodEnum",(s,t)=>{Mx.init(s,t);const n=RHe(t.entries),r=new Set(n);s._zod.values=r,xm(s,"pattern",a=>{const i=RHe(a.def.entries).filter(l=>$5s.has(typeof l));return new RegExp(i.length?`^(${i.map(l=>bG(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}}),oAs=Ma("$ZodLiteral",(s,t)=>{Mx.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"?bG(i):i?bG(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}}),lAs=Ma("$ZodTransform",(s,t)=>{var n;Mx.init(s,t),s._zod.optin="optional",(n=H4.memoizer)==null||n.guard(s),s._zod.parse=(r,a)=>{if(a.direction==="backward")throw new v8t(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 i7;return r.value=i,r}});function Kxt(s,t){return s.value=t.issues.length?void 0:t.value,s}const L8t=Ma("$ZodOptional",(s,t)=>{Mx.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(`^(${ttt(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=>Kxt(n,i)):Kxt(n,a)}return t.innerType._zod.run(n,r)}}),cAs=Ma("$ZodExactOptional",(s,t)=>{L8t.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)}),dAs=Ma("$ZodNullable",(s,t)=>{Mx.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(`^(${ttt(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)}),uAs=Ma("$ZodDefault",(s,t)=>{Mx.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=>Yxt(i,t)):Yxt(a,t)}});function Yxt(s,t){return s.value===void 0&&(s.value=t.defaultValue),s}const hAs=Ma("$ZodPrefault",(s,t)=>{Mx.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))}),mAs=Ma("$ZodNonOptional",(s,t)=>{Mx.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=>Zxt(i,s)):Zxt(a,s)}});function Zxt(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 Xxt(s,t,n,r){return t.issues.length?(s.value=n.catchValue({...t,value:s.value,error:{issues:t.issues.map(a=>JW(a,r,n6()))},input:s.value}),s):(s.value=t.value,t.memo&&(s.memo=!0),s)}const fAs=Ma("$ZodCatch",(s,t)=>{Mx.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=>Xxt(n,i,t,r)):Xxt(n,a,t,r)}}),pAs=Ma("$ZodPipe",(s,t)=>{Mx.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=>Cce(l,t.in,r)):Cce(i,t.in,r)}const a=t.in._zod.run(n,r);return a instanceof Promise?a.then(i=>Cce(i,t.out,r)):Cce(a,t.out,r)}});function Cce(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 gAs=Ma("$ZodReadonly",(s,t)=>{Mx.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(Qxt):Qxt(a)}});function Qxt(s){return s.memo||(s.value=Object.freeze(s.value)),s}const xAs=Ma("$ZodCustom",(s,t)=>{Bw.init(s,t),Mx.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=>Jxt(i,n,r,s));Jxt(a,n,r,s)}});function Jxt(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(Xte(a))}}class yAs extends Error{constructor(){super("Cannot parse a reference cycle that closes through a transform"),this.name="ZodCyclicError"}}const zHe="~memo",eyt=[];function R8t(s){return s!==null&&typeof s=="object"}function Yze(s){return s.map(t=>t.path?{...t,path:t.path.slice()}:{...t})}const D8t=new WeakMap,rQ=0,H4e=1,hee=2;function G4e(s,t,n){const r=D8t.get(s);if(r!==void 0)return r?hee:rQ;if(t.has(s))return hee;t.add(s);let a=rQ;const i=u=>{if(a!==hee&&(u!=null&&u._zod)){const h=G4e(u,t);h>a&&(a=h)}},l=(u,h)=>{var f;let m=rQ;for(const g of Reflect.ownKeys(u)){const x=Object.getOwnPropertyDescriptor(u,g);if(!x.enumerable)continue;const y=x.get?H4e:(f=x.value)!=null&&f._zod?G4e(x.value,t):rQ;y>m&&(m=y)}return m},o=u=>{u>a&&(a=u)},c=s._zod.def;switch(c.type){case"object":{const u=l8t(c);o(u?l(u):H4e),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?G4e(u,t):H4e);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),vAs(s,a)}function vAs(s,t){return t!==H4e&&D8t.set(s,t===hee),t}function bAs(s,t){let n=s.buckets.get(t);return n||(n=new WeakMap,s.buckets.set(t,n)),n}let Ace;const Ece=[],_As={alloc(s,t,n){const r=Ace;if(!r)return n;Ace=void 0;const a={value:n,issues:null};return r.set(t.value,a),Ece.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"&&jAs(i,a.value))throw new yAs;return n(a,i)};s._zod.parse=r,s._zod.run===n&&(s._zod.run=r)})},attach(s){var t;let n,r=!1,a,i;(t=s._zod).deferred??(t.deferred=[]),s._zod.deferred.push(()=>{const l=s._zod.parse,o=(c,d)=>{if(n===void 0){const v=G4e(s,new Set);if(v===rQ)return s._zod.parse=l,s._zod.run===o&&(s._zod.run=l),l(c,d);v===hee||r?n=!0:r=!0}const u=c.value;if(!R8t(u))return l(c,d);let h=d[zHe];h||(h={buckets:new WeakMap,backEdges:void 0},d[zHe]=h);let m;a===d?m=i:(m=bAs(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(...Yze(f.issues)):(c.memo=!0,h.backEdges??(h.backEdges=new WeakSet),h.backEdges.add(f.value)),c;Ace=m;const g=Ece.length,x=l(c,d);Ace=void 0;const y=Ece.length>g?Ece.pop():void 0;return x instanceof Promise?x.then(v=>(y&&(y.issues=v.issues.length?Yze(v.issues):eyt),v)):(y&&(y.issues=x.issues.length?Yze(x.issues):eyt),x)};s._zod.parse=o,s._zod.run===l&&(s._zod.run=o)})}};function wAs(){return _As}function jAs(s,t){var r;const n=(r=s[zHe])==null?void 0:r.backEdges;return n!==void 0&&R8t(t)&&n.has(t)}const NAs=()=>{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=Q5s(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 ${m8t(i.values[0])}`:`Invalid option: expected one of ${Fxt(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":""}: ${Fxt(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 kAs(){return{localeError:NAs()}}var tyt;class SAs{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 CAs(){return new SAs}(tyt=globalThis).__zod_globalRegistry??(tyt.__zod_globalRegistry=CAs());const aQ=globalThis.__zod_globalRegistry;function F8t(s){return s.checks&&(s.checks=[...s.checks]),s}function AAs(s,t){return new s(F8t({type:"string",...Ml(t)}))}function EAs(s,t){return new s({type:"string",format:"email",check:"string_format",abort:!1,...Ml(t)})}function TAs(s,t){return new s({type:"string",format:"guid",check:"string_format",abort:!1,...Ml(t)})}function MAs(s,t){return new s({type:"string",format:"uuid",check:"string_format",abort:!1,...Ml(t)})}function PAs(s,t){return new s({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Ml(t)})}function IAs(s,t){return new s({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Ml(t)})}function LAs(s,t){return new s({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Ml(t)})}function RAs(s,t){return new s({type:"string",format:"url",check:"string_format",abort:!1,...Ml(t)})}function DAs(s,t){return new s({type:"string",format:"emoji",check:"string_format",abort:!1,...Ml(t)})}function FAs(s,t){return new s({type:"string",format:"nanoid",check:"string_format",abort:!1,...Ml(t)})}function OAs(s,t){return new s({type:"string",format:"cuid",check:"string_format",abort:!1,...Ml(t)})}function zAs(s,t){return new s({type:"string",format:"cuid2",check:"string_format",abort:!1,...Ml(t)})}function BAs(s,t){return new s({type:"string",format:"ulid",check:"string_format",abort:!1,...Ml(t)})}function $As(s,t){return new s({type:"string",format:"xid",check:"string_format",abort:!1,...Ml(t)})}function UAs(s,t){return new s({type:"string",format:"ksuid",check:"string_format",abort:!1,...Ml(t)})}function qAs(s,t){return new s({type:"string",format:"ipv4",check:"string_format",abort:!1,...Ml(t)})}function VAs(s,t){return new s({type:"string",format:"ipv6",check:"string_format",abort:!1,...Ml(t)})}function HAs(s,t){return new s({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Ml(t)})}function GAs(s,t){return new s({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Ml(t)})}function WAs(s,t){return new s({type:"string",format:"base64",check:"string_format",abort:!1,...Ml(t)})}function KAs(s,t){return new s({type:"string",format:"base64url",check:"string_format",abort:!1,...Ml(t)})}function YAs(s,t){return new s({type:"string",format:"e164",check:"string_format",abort:!1,...Ml(t)})}function ZAs(s,t){return new s({type:"string",format:"jwt",check:"string_format",abort:!1,...Ml(t)})}function XAs(s,t){return new s({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Ml(t)})}function QAs(s,t){return new s({type:"string",format:"date",check:"string_format",...Ml(t)})}function JAs(s,t){return new s({type:"string",format:"time",check:"string_format",precision:null,...Ml(t)})}function eEs(s,t){return new s({type:"string",format:"duration",check:"string_format",...Ml(t)})}function tEs(s,t){return new s(F8t({type:"number",checks:[],...Ml(t)}))}function sEs(s,t){return new s({type:"number",check:"number_format",abort:!1,format:"safeint",...Ml(t)})}function nEs(s,t){return new s({type:"boolean",...Ml(t)})}function rEs(s){return new s({type:"unknown"})}function aEs(s,t){return new s({type:"never",...Ml(t)})}function syt(s,t){return new w8t({check:"less_than",...Ml(t),value:s,inclusive:!1})}function Zze(s,t){return new w8t({check:"less_than",...Ml(t),value:s,inclusive:!0})}function nyt(s,t){return new j8t({check:"greater_than",...Ml(t),value:s,inclusive:!1})}function Xze(s,t){return new j8t({check:"greater_than",...Ml(t),value:s,inclusive:!0})}function ryt(s,t){return new n3s({check:"multiple_of",...Ml(t),value:s})}function O8t(s,t){return new a3s({check:"max_length",...Ml(t),maximum:s})}function kEe(s,t){return new i3s({check:"min_length",...Ml(t),minimum:s})}function z8t(s,t){return new o3s({check:"length_equals",...Ml(t),length:s})}function iEs(s,t){return new l3s({check:"string_format",format:"regex",...Ml(t),pattern:s})}function oEs(s){return new c3s({check:"string_format",format:"lowercase",...Ml(s)})}function lEs(s){return new d3s({check:"string_format",format:"uppercase",...Ml(s)})}function cEs(s,t){return new u3s({check:"string_format",format:"includes",...Ml(t),includes:s})}function dEs(s,t){return new h3s({check:"string_format",format:"starts_with",...Ml(t),prefix:s})}function uEs(s,t){return new m3s({check:"string_format",format:"ends_with",...Ml(t),suffix:s})}function eK(s){return new f3s({check:"overwrite",tx:s})}function hEs(s){return eK(t=>t.normalize(s))}function mEs(){return eK(s=>s.trim())}function fEs(){return eK(s=>s.toLowerCase())}function pEs(){return eK(s=>s.toUpperCase())}function gEs(){return eK(s=>z5s(s))}function xEs(s,t,n){return new s({type:"array",element:t,...Ml(n)})}function yEs(s,t,n){return new s({type:"custom",check:"custom",fn:t,...Ml(n)})}function vEs(s,t){const n=bEs(r=>(r.addIssue=a=>{if(typeof a=="string")r.issues.push(Xte(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(Xte(i))}},s(r.value,r)),t);return n}function bEs(s,t){const n=new Bw({check:"custom",...Ml(t)});return n._zod.check=s,n}function mee(s,...t){for(const n of t)for(const r of Reflect.ownKeys(n))Object.prototype.propertyIsEnumerable.call(n,r)&&FB(s,r,n[r]);return s}function B8t(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)??aQ,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 kL(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 Sb(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),Sb(f,t,m),t.seen.get(f).isParent=!0)}const c=t.metadataRegistry.get(s);return c&&mee(l.schema,c),t.io==="input"&&Z1(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 ayt(s){return s.replace(/~/g,"~0").replace(/\//g,"~1")}function $8t(s,t){var l,o,c,d;const n=s.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");if(s.external&&s.sharedDefsExtractedFor===s.external)return;const r=new Map;for(const u of s.seen.entries()){const h=(l=s.metadataRegistry.get(u[0]))==null?void 0:l.id;if(h){const m=r.get(h);if(m&&m!==u[0])throw new Error(`Duplicate schema id "${h}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(h,u[0])}}const a=u=>{var x;const h=s.target==="draft-2020-12"?"$defs":"definitions";if(s.external){const y=(x=s.external.registry.get(u[0]))==null?void 0:x.id,v=s.external.uri??(w=>w);if(y)return{ref:v(y)};const b=u[1].defId??u[1].schema.id??`schema${s.counter++}`;return u[1].defId=b,{defId:b,ref:`${v("__shared")}#/${h}/${ayt(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+ayt(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 U8t(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;U8t(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 q8t=new Set(["type","properties","required","additionalProperties"]),iyt=["oneOf","anyOf"];function oyt(s){const t=s.additionalProperties;return t===void 0||t===!1||typeof t!="object"||t===null?null:Object.keys(t).length?t:null}function BHe(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(!q8t.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])??oyt(u);h!=null&&(c.some(m=>JSON.stringify(m)===JSON.stringify(h))||c.push(h))}const d=c.length===1?c[0]:BHe(c)??{allOf:c};FB(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=oyt(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 _Es(s){const t=s.allOf;if(!Array.isArray(t)||t.length<2)return;for(const a of q8t)if(a in s)return;const n=t.filter(a=>iyt.some(i=>Array.isArray(a[i])));let r=null;if(!n.length)r=BHe(t);else{const a=n[0],i=iyt.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=>BHe([...l,c]));if(o.some(c=>!c))return;r={[i]:o}}r&&(delete s.allOf,mee(s,r))}function V8t(s,t){var o,c,d,u;const n=s.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=h=>{const m=s.seen.get(h);if(m.ref===null)return;const f=m.def??m.schema,g={...f},x=m.ref;if(m.ref=null,x){r(x);const v=s.seen.get(x),b=v.schema;if(b.$ref&&(s.target==="draft-07"||s.target==="draft-04"||s.target==="openapi-3.0")?(f.allOf=f.allOf??[],f.allOf.push(b)):mee(f,b),mee(f,g),h._zod.parent===x)for(const S in f)S==="$ref"||S==="allOf"||S in g||delete f[S];if(b.$ref&&v.def)for(const S in f)S==="$ref"||S==="allOf"||S in v.def&&JSON.stringify(f[S])===JSON.stringify(v.def[S])&&delete f[S]}const y=h._zod.parent;if(y&&y!==x){r(y);const v=s.seen.get(y);if(v!=null&&v.schema.$ref&&(f.$ref=v.schema.$ref,v.def))for(const b in f)b==="$ref"||b==="allOf"||b in v.def&&JSON.stringify(f[b])===JSON.stringify(v.def[b])&&delete f[b]}s.override({zodSchema:h,jsonSchema:f,path:m.path??[]})};if(!s.external||s.sharedEmitDoneFor!==s.external){for(const h of[...s.seen.entries()].reverse())r(h[0]);if(s.target!=="openapi-3.0")for(const h of s.seen.entries())U8t(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)??[])_Es(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)}mee(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,FB(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:SEe(t,"input",s.processors),output:SEe(t,"output",s.processors)}},enumerable:!1,writable:!1}),h}catch{throw new Error("Error converting schema to JSON.")}}function Z1(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 Z1(r.element,n);if(r.type==="set")return Z1(r.valueType,n);if(r.type==="lazy")return Z1(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 Z1(r.innerType,n);if(r.type==="intersection")return Z1(r.left,n)||Z1(r.right,n);if(r.type==="record"||r.type==="map")return Z1(r.keyType,n)||Z1(r.valueType,n);if(r.type==="pipe")return s._zod.traits.has("$ZodCodec")?!0:Z1(r.in,n)||Z1(r.out,n);if(r.type==="object"){for(const a in r.shape)if(Z1(r.shape[a],n))return!0;return!1}if(r.type==="union"){for(const a of r.options)if(Z1(a,n))return!0;return!1}if(r.type==="tuple"){for(const a of r.items)if(Z1(a,n))return!0;return!!(r.rest&&Z1(r.rest,n))}return!1}const wEs=(s,t={})=>n=>{const r=B8t({...n,processors:t});return Sb(s,r),$8t(r,s),V8t(r,s)},SEe=(s,t,n={})=>r=>{const{libraryOptions:a,target:i}=r??{},l=B8t({...a??{},target:i,io:t,processors:n});return Sb(s,l),$8t(l,s),V8t(l,s)},_G=(s,t,n)=>{(s[t]===void 0||n>s[t])&&(s[t]=n)},wG=(s,t,n)=>{(s[t]===void 0||n{_G(s,"minimum",t),wG(s,"maximum",t)},H8t=(s,t)=>{s.multipleOf??(s.multipleOf=[]),s.multipleOf.includes(t)||s.multipleOf.push(t)},G8t=(s,t)=>{s.patterns??(s.patterns=new Set),s.patterns.add(t)},W8t=(s,t)=>{s.mime=s.mime?s.mime.filter(n=>t.includes(n)):[...t]},K8t=(s,t)=>{s.format=t,t.includes("int")&&(s.isInt=!0)},cyt=(s,t)=>_G(s,"minimum",t.minimum),dyt=(s,t)=>wG(s,"maximum",t.maximum),uyt=s=>(t,n)=>{K8t(t,n.format);const[r,a]=s[n.format];_G(t,"minimum",r),wG(t,"maximum",a)},Qze={greater_than:(s,t)=>_G(s,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(s,t)=>wG(s,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(s,t)=>H8t(s,t.value),number_format:uyt(f8t),bigint_format:uyt(q5s),min_length:cyt,max_length:dyt,length_equals:(s,t)=>lyt(s,t.length),min_size:cyt,max_size:dyt,size_equals:(s,t)=>lyt(s,t.size),string_format:(s,t)=>{K8t(s,t.format),t.pattern&&G8t(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)=>W8t(s,t.mime)};function p4(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=Qze[l._zod.def.check])==null||i.call(Qze,t,l._zod.def);const a=s._zod.bag;a.minimum!==void 0&&_G(t,"minimum",a.minimum),a.exclusiveMinimum!==void 0&&_G(t,"exclusiveMinimum",a.exclusiveMinimum),a.maximum!==void 0&&wG(t,"maximum",a.maximum),a.exclusiveMaximum!==void 0&&wG(t,"exclusiveMaximum",a.exclusiveMaximum),a.multipleOf!==void 0&&H8t(t,a.multipleOf),a.format!==void 0&&(t.format??(t.format=a.format),a.format.includes("int")&&(t.isInt=!0)),a.mime&&W8t(t,a.mime);for(const l of a.patterns??[])G8t(t,l);return t}const jEs={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},NEs=new Map([[T8t,V4s],[dtt,H4s]]),kEs=s=>NEs.get(s)??s,SEs=(s,t,n,r)=>{const a=n;a.type="string";const{minimum:i,maximum:l,format:o,patterns:c,contentEncoding:d,laxFormat:u}=p4(s);if(typeof i=="number"&&(a.minLength=i),typeof l=="number"&&(a.maxLength=l),o&&(a.format=jEs[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(kEs);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}))])}},CEs=(s,t,n,r)=>{const a=n,{minimum:i,maximum:l,multipleOf:o,exclusiveMaximum:c,exclusiveMinimum:d,isInt:u}=p4(s);a.type=u?"integer":"number";const h=typeof d=="number"&&d>=(i??Number.NEGATIVE_INFINITY),m=typeof c=="number"&&c<=(l??Number.POSITIVE_INFINITY),f=t.target==="draft-04"||t.target==="openapi-3.0";if(h?f?(a.minimum=d,a.exclusiveMinimum=!0):a.exclusiveMinimum=d:typeof i=="number"&&(a.minimum=i),m?f?(a.maximum=c,a.exclusiveMaximum=!0):a.exclusiveMaximum=c:typeof l=="number"&&(a.maximum=l),o){const g=new Set;for(const v of o)Number.isFinite(v)&&v!==0?g.add(Math.abs(v)):kL(s,t,a,r,`A multipleOf divisor of ${v} cannot be represented in JSON Schema`);const[x,...y]=g;x!==void 0&&(a.multipleOf=x),y.length&&(a.allOf=[...a.allOf??[],...y.map(v=>({multipleOf:v}))])}},AEs=(s,t,n,r)=>{n.type="boolean"},EEs=(s,t,n,r)=>{n.not={}},TEs=(s,t,n,r)=>{},MEs=(s,t,n,r)=>{const a=s._zod.def,i=RHe(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},PEs=(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(kL(s,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof l=="bigint"){if(kL(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},IEs=(s,t,n,r)=>{kL(s,t,n,r,"Custom types cannot be represented in JSON Schema")},LEs=(s,t,n,r)=>{kL(s,t,n,r,"Transforms cannot be represented in JSON Schema")},REs=(s,t,n,r)=>{const a=n,i=s._zod.def,{minimum:l,maximum:o}=p4(s);typeof l=="number"&&(a.minItems=l),typeof o=="number"&&(a.maxItems=o),a.type="array",a.items=Sb(i.element,t,{...r,path:[...r.path,"items"]})};function $He(s){const t=s._zod.def;return t.type==="pipe"&&t.in._zod.traits.has("$ZodTransform")?$He(t.out):t.type==="catch"?$He(t.innerType):s._zod.optin}const DEs=(s,t,n,r)=>{var d;const a=n,i=s._zod.def,l=i.shape;if(Object.getOwnPropertySymbols(l).length&&kL(s,t,a,r,"Symbol keys cannot be represented in JSON Schema"))return;a.type="object",a.properties={};for(const u in l)FB(a.properties,u,Sb(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"?$He(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=Sb(i.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):t.io==="output"&&(a.additionalProperties=!1)},FEs=(s,t,n,r)=>{const a=s._zod.def,i=a.inclusive===!1,l=a.options.map((o,c)=>Sb(o,t,{...r,path:[...r.path,i?"oneOf":"anyOf",c]}));i?n.oneOf=l:n.anyOf=l},OEs=(s,t,n,r)=>{const a=s._zod.def,i=Sb(a.left,t,{...r,path:[...r.path,"allOf",0]}),l=Sb(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)},zEs=(s,t,n,r)=>{const a=s._zod.def,i=Sb(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"}]},BEs=(s,t,n,r)=>{const a=s._zod.def;Sb(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType},utt=Symbol();function Y8t(s,t,n,r,a){let i=!1;const l=JSON.stringify(s,(o,c)=>typeof c!="bigint"?c:(i=!0,null));return i?(kL(t,n,r,a,"BigInt defaults cannot be represented in JSON Schema"),utt):JSON.parse(l)}const $Es=(s,t,n,r)=>{const a=s._zod.def;Sb(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType;const l=Y8t(a.defaultValue,s,t,n,r);l!==utt&&(n.default=l)},UEs=(s,t,n,r)=>{const a=s._zod.def;Sb(a.innerType,t,r);const i=t.seen.get(s);if(i.ref=a.innerType,t.io!=="input")return;const l=Y8t(a.defaultValue,s,t,n,r);l!==utt&&(n._prefault=l)},qEs=(s,t,n,r)=>{const a=s._zod.def;Sb(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType;let l;try{l=a.catchValue(void 0)}catch{kL(s,t,n,r,"Dynamic catch values are not supported in JSON Schema");return}n.default=l},VEs=(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;Sb(l,t,r);const o=t.seen.get(s);o.ref=l},HEs=(s,t,n,r)=>{const a=s._zod.def;Sb(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType,n.readOnly=!0},Z8t=(s,t,n,r)=>{const a=s._zod.def;Sb(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType},hyt=new WeakSet([Object.prototype,Error.prototype]);function Tce(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 X8t=(s,t)=>{u4s.init(s,t),s.name="ZodError";const n=Object.getPrototypeOf(s);hyt.has(n)||(hyt.add(n),Tce(n,"format",r=>a=>f4s(r,a)),Tce(n,"flatten",r=>a=>m4s(r,a)),Tce(n,"addIssue",r=>a=>{r.issues.push(a),r.message=JSON.stringify(r.issues,DHe,2)}),Tce(n,"addIssues",r=>a=>{r.issues.push(...a),r.message=JSON.stringify(r.issues,DHe,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},GEs=Ma("ZodError",X8t),Nk=Ma("ZodError",X8t,void 0,{Parent:Error}),WEs=rtt(Nk),KEs=att(Nk),YEs=itt(Nk),ZEs=ott(Nk),XEs=b4s(Nk),QEs=_4s(Nk),JEs=w4s(Nk),eTs=j4s(Nk),tTs=N4s(Nk),sTs=k4s(Nk),nTs=S4s(Nk),rTs=C4s(Nk);function aTs(){H4.localeError||n6(kAs())}function htt(){H4.memoizer||n6({memoizer:wAs()})}const Px=Ma("ZodType",(s,t)=>(aTs(),Mx.init(s,t),s.def=t,s.type=t.type,s),{check(...s){const t=this.def;return this.clone(Gj(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 s6(this,s,t)},brand(){return this},register(s,t){return s.add(this,t),this},refine(s,t){return this.check(rMs(s,t))},superRefine(s,t){return this.check(aMs(s,t))},overwrite(s){return this.check(eK(s))},optional(){return pyt(this)},exactOptional(){return HTs(this)},nullable(){return gyt(this)},nullish(){return pyt(gyt(this))},nonoptional(s){return XTs(this,s)},array(){return DTs(this)},or(s){return zTs([this,s])},and(s){return $Ts(this,s)},transform(s){return xyt(this,VTs(s))},default(s){return KTs(this,s)},prefault(s){return ZTs(this,s)},catch(s){return JTs(this,s)},pipe(s){return xyt(this,s)},readonly(){return sMs(this)},describe(s){const t=this.clone();return aQ.add(t,{description:s}),t},meta(...s){if(s.length===0)return aQ.get(this);const t=this.clone();return aQ.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 x8t(this,"~standard",{...k8t(this),jsonSchema:{input:SEe(this,"input"),output:SEe(this,"output")}})},set"~standard"(s){NL(this,"~standard",s)},parse:function s(t,n){return WEs(this,t,n,{callee:s})},parseAsync:async function s(t,n){return await KEs(this,t,n,{callee:s})},safeParse(s,t){return YEs(this,s,t)},async safeParseAsync(s,t){return ZEs(this,s,t)},get spa(){return this==null?void 0:this.safeParseAsync},set spa(s){NL(this,"spa",s)},validate(s,t){return x4s(this,s,t)},validateAsync(s,t){return v4s(this,s,t)},encode:function s(t,n){return XEs(this,t,n,{callee:s})},decode:function s(t,n){return QEs(this,t,n,{callee:s})},encodeAsync:async function s(t,n){return await JEs(this,t,n,{callee:s})},decodeAsync:async function s(t,n){return await eTs(this,t,n,{callee:s})},safeEncode(s,t){return tTs(this,s,t)},safeDecode(s,t){return sTs(this,s,t)},async safeEncodeAsync(s,t){return nTs(this,s,t)},async safeDecodeAsync(s,t){return rTs(this,s,t)},toJSONSchema(s){return wEs(this,{})(s)},get description(){var s;return(s=aQ.get(this))==null?void 0:s.description},get _def(){return this._zod.def}}),Q8t=Ma("_ZodString",(s,t)=>{ctt.init(s,t),Px.init(s,t),s._zod.processJSONSchema=(n,r,a)=>SEs(s,n,r)},y8t({format:s=>p4(s).format??null,minLength:s=>p4(s).minimum??null,maxLength:s=>p4(s).maximum??null},{regex(...s){return this.check(iEs(...s))},includes(...s){return this.check(cEs(...s))},startsWith(...s){return this.check(dEs(...s))},endsWith(...s){return this.check(uEs(...s))},min(...s){return this.check(kEe(...s))},max(...s){return this.check(O8t(...s))},length(...s){return this.check(z8t(...s))},nonempty(...s){return this.check(kEe(1,...s))},lowercase(s){return this.check(oEs(s))},uppercase(s){return this.check(lEs(s))},trim(){return this.check(mEs())},normalize(...s){return this.check(hEs(...s))},toLowerCase(){return this.check(fEs())},toUpperCase(){return this.check(pEs())},slugify(){return this.check(gEs())}})),iTs=Ma("ZodString",(s,t)=>{ctt.init(s,t),Q8t.init(s,t)},{email(s){return this.check(EAs(uTs,s))},url(s){return this.check(RAs(mTs,s))},jwt(s){return this.check(ZAs(ATs,s))},emoji(s){return this.check(DAs(fTs,s))},guid(s){return this.check(TAs(hTs,s))},uuid(s){return this.check(MAs(Mce,s))},uuidv4(s){return this.check(PAs(Mce,s))},uuidv6(s){return this.check(IAs(Mce,s))},uuidv7(s){return this.check(LAs(Mce,s))},nanoid(s){return this.check(FAs(pTs,s))},cuid(s){return this.check(OAs(gTs,s))},cuid2(s){return this.check(zAs(xTs,s))},ulid(s){return this.check(BAs(yTs,s))},base64(s){return this.check(WAs(kTs,s))},base64url(s){return this.check(KAs(STs,s))},xid(s){return this.check($As(vTs,s))},ksuid(s){return this.check(UAs(bTs,s))},ipv4(s){return this.check(qAs(_Ts,s))},ipv6(s){return this.check(VAs(wTs,s))},cidrv4(s){return this.check(HAs(jTs,s))},cidrv6(s){return this.check(GAs(NTs,s))},e164(s){return this.check(YAs(CTs,s))},datetime(s){return this.check(XAs(oTs,s))},date(s){return this.check(QAs(lTs,s))},time(s){return this.check(JAs(cTs,s))},duration(s){return this.check(eEs(dTs,s))}});function vl(s){return AAs(iTs,s)}const Kg=Ma("ZodStringFormat",(s,t)=>{sg.init(s,t),Q8t.init(s,t)}),oTs=Ma("ZodISODateTime",(s,t)=>{L3s.init(s,t),Kg.init(s,t)}),lTs=Ma("ZodISODate",(s,t)=>{R3s.init(s,t),Kg.init(s,t)}),cTs=Ma("ZodISOTime",(s,t)=>{D3s.init(s,t),Kg.init(s,t)}),dTs=Ma("ZodISODuration",(s,t)=>{F3s.init(s,t),Kg.init(s,t)}),uTs=Ma("ZodEmail",(s,t)=>{b3s.init(s,t),Kg.init(s,t)}),hTs=Ma("ZodGUID",(s,t)=>{y3s.init(s,t),Kg.init(s,t)}),Mce=Ma("ZodUUID",(s,t)=>{v3s.init(s,t),Kg.init(s,t)}),mTs=Ma("ZodURL",(s,t)=>{S3s.init(s,t),Kg.init(s,t)}),fTs=Ma("ZodEmoji",(s,t)=>{C3s.init(s,t),Kg.init(s,t)}),pTs=Ma("ZodNanoID",(s,t)=>{A3s.init(s,t),Kg.init(s,t)}),gTs=Ma("ZodCUID",(s,t)=>{E3s.init(s,t),Kg.init(s,t)}),xTs=Ma("ZodCUID2",(s,t)=>{T3s.init(s,t),Kg.init(s,t)}),yTs=Ma("ZodULID",(s,t)=>{M3s.init(s,t),Kg.init(s,t)}),vTs=Ma("ZodXID",(s,t)=>{P3s.init(s,t),Kg.init(s,t)}),bTs=Ma("ZodKSUID",(s,t)=>{I3s.init(s,t),Kg.init(s,t)}),_Ts=Ma("ZodIPv4",(s,t)=>{O3s.init(s,t),Kg.init(s,t)}),wTs=Ma("ZodIPv6",(s,t)=>{B3s.init(s,t),Kg.init(s,t)}),jTs=Ma("ZodCIDRv4",(s,t)=>{$3s.init(s,t),Kg.init(s,t)}),NTs=Ma("ZodCIDRv6",(s,t)=>{q3s.init(s,t),Kg.init(s,t)}),kTs=Ma("ZodBase64",(s,t)=>{V3s.init(s,t),Kg.init(s,t)}),STs=Ma("ZodBase64URL",(s,t)=>{G3s.init(s,t),Kg.init(s,t)}),CTs=Ma("ZodE164",(s,t)=>{W3s.init(s,t),Kg.init(s,t)}),ATs=Ma("ZodJWT",(s,t)=>{Y3s.init(s,t),Kg.init(s,t)}),J8t=Ma("ZodNumber",(s,t)=>{M8t.init(s,t),Px.init(s,t),s._zod.processJSONSchema=(n,r,a)=>CEs(s,n,r,a),s.isFinite=!0},y8t({minValue:s=>{const{minimum:t,exclusiveMinimum:n}=p4(s);return Math.max(t??Number.NEGATIVE_INFINITY,n??Number.NEGATIVE_INFINITY)},maxValue:s=>{const{maximum:t,exclusiveMaximum:n}=p4(s);return Math.min(t??Number.POSITIVE_INFINITY,n??Number.POSITIVE_INFINITY)},isInt:s=>{const{isInt:t,multipleOf:n}=p4(s);return!!t||!!(n!=null&&n.some(Number.isSafeInteger))},format:s=>p4(s).format??null},{gt(s,t){return this.check(nyt(s,t))},gte(s,t){return this.check(Xze(s,t))},min(s,t){return this.check(Xze(s,t))},lt(s,t){return this.check(syt(s,t))},lte(s,t){return this.check(Zze(s,t))},max(s,t){return this.check(Zze(s,t))},int(s){return this.check(myt(s))},safe(s){return this.check(myt(s))},positive(s){return this.check(nyt(0,s))},nonnegative(s){return this.check(Xze(0,s))},negative(s){return this.check(syt(0,s))},nonpositive(s){return this.check(Zze(0,s))},multipleOf(s,t){return this.check(ryt(s,t))},step(s,t){return this.check(ryt(s,t))},finite(){return this}}));function fee(s){return tEs(J8t,s)}const ETs=Ma("ZodNumberFormat",(s,t)=>{Z3s.init(s,t),J8t.init(s,t)});function myt(s){return sEs(ETs,s)}const TTs=Ma("ZodBoolean",(s,t)=>{X3s.init(s,t),Px.init(s,t),s._zod.processJSONSchema=(n,r,a)=>AEs(s,n,r)});function MTs(s){return nEs(TTs,s)}const PTs=Ma("ZodUnknown",(s,t)=>{Q3s.init(s,t),Px.init(s,t),s._zod.processJSONSchema=(n,r,a)=>TEs()});function fyt(){return rEs(PTs)}const ITs=Ma("ZodNever",(s,t)=>{J3s.init(s,t),Px.init(s,t),s._zod.processJSONSchema=(n,r,a)=>EEs(s,n,r)});function LTs(s){return aEs(ITs,s)}const RTs=Ma("ZodArray",(s,t)=>{htt(),eAs.init(s,t),Px.init(s,t),s._zod.processJSONSchema=(n,r,a)=>REs(s,n,r,a),s.element=t.element},{min(s,t){return this.check(kEe(s,t))},nonempty(s){return this.check(kEe(1,s))},max(s,t){return this.check(O8t(s,t))},length(s,t){return this.check(z8t(s,t))},unwrap(){return this.element}});function DTs(s,t){return xEs(RTs,s,t)}const FTs=Ma("ZodObject",(s,t)=>{htt(),nAs.init(s,t),Px.init(s,t),s._zod.processJSONSchema=(n,r,a)=>DEs(s,n,r,a),n4s(s,"shape",n=>n._zod.def.shape,!1)},{keyof(){return mtt(Object.keys(this._zod.def.shape))},catchall(s){return this.clone(Gj(this._zod.def,{catchall:s}))},passthrough(){return this.clone(Gj(this._zod.def,{catchall:fyt()}))},loose(){return this.clone(Gj(this._zod.def,{catchall:fyt()}))},strict(){return this.clone(Gj(this._zod.def,{catchall:LTs()}))},strip(){return this.clone(Gj(this._zod.def,{catchall:void 0}))},extend(s){return G5s(this,s)},safeExtend(s){return W5s(this,s)},merge(s){return K5s(this,s)},pick(s){return V5s(this,s)},omit(s){return H5s(this,s)},partial(...s){return Oxt(ezt,this,s[0])},exactPartial(...s){return Oxt(tzt,this,s[0],"exactPartial")},required(...s){return Y5s(szt,this,s[0])}});function z2(s,t){const n={type:"object",shape:s??{},...Ml(t)};return new FTs(n)}const OTs=Ma("ZodUnion",(s,t)=>{rAs.init(s,t),Px.init(s,t),s._zod.processJSONSchema=(n,r,a)=>FEs(s,n,r,a),s.options=t.options});function zTs(s,t){return new OTs({type:"union",options:s,...Ml(t)})}const BTs=Ma("ZodIntersection",(s,t)=>{aAs.init(s,t),Px.init(s,t),s._zod.processJSONSchema=(n,r,a)=>OEs(s,n,r,a)});function $Ts(s,t){return new BTs({type:"intersection",left:s,right:t})}const UHe=Ma("ZodEnum",(s,t)=>{iAs.init(s,t),Px.init(s,t),s._zod.processJSONSchema=(r,a,i)=>MEs(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 UHe({...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 UHe({...t,checks:[],...Ml(a),entries:i})}});function mtt(s,t){const n=Array.isArray(s)?Object.fromEntries(s.map(r=>[r,r])):s;return new UHe({type:"enum",entries:n,...Ml(t)})}const UTs=Ma("ZodLiteral",(s,t)=>{oAs.init(s,t),Px.init(s,t),s._zod.processJSONSchema=(n,r,a)=>PEs(s,n,r,a),s.values=new Set(t.values),Object.defineProperty(s,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function yx(s,t){return new UTs({type:"literal",values:Array.isArray(s)?s:[s],...Ml(t)})}const qTs=Ma("ZodTransform",(s,t)=>{htt(),lAs.init(s,t),Px.init(s,t),s._zod.processJSONSchema=(n,r,a)=>LEs(s,n,r,a),s._zod.parse=(n,r)=>{if(r.direction==="backward")throw new v8t(s.constructor.name);n.addIssue=i=>{if(typeof i=="string")n.issues.push(Xte(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(Xte(l))}};const a=t.transform(n.value,n);return a instanceof Promise?a.then(i=>(n.value=i,n)):(n.value=a,n)}});function VTs(s){return new qTs({type:"transform",transform:s})}const ezt=Ma("ZodOptional",(s,t)=>{L8t.init(s,t),Px.init(s,t),s._zod.processJSONSchema=(n,r,a)=>Z8t(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function pyt(s){return new ezt({type:"optional",innerType:s})}const tzt=Ma("ZodExactOptional",(s,t)=>{cAs.init(s,t),Px.init(s,t),s._zod.processJSONSchema=(n,r,a)=>Z8t(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function HTs(s){return new tzt({type:"optional",innerType:s})}const GTs=Ma("ZodNullable",(s,t)=>{dAs.init(s,t),Px.init(s,t),s._zod.processJSONSchema=(n,r,a)=>zEs(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function gyt(s){return new GTs({type:"nullable",innerType:s})}const WTs=Ma("ZodDefault",(s,t)=>{uAs.init(s,t),Px.init(s,t),s._zod.processJSONSchema=(n,r,a)=>$Es(s,n,r,a),s.unwrap=()=>s._zod.def.innerType,s.removeDefault=s.unwrap});function KTs(s,t){return new WTs({type:"default",innerType:s,get defaultValue(){return typeof t=="function"?t():h8t(t)}})}const YTs=Ma("ZodPrefault",(s,t)=>{hAs.init(s,t),Px.init(s,t),s._zod.processJSONSchema=(n,r,a)=>UEs(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function ZTs(s,t){return new YTs({type:"prefault",innerType:s,get defaultValue(){return typeof t=="function"?t():h8t(t)}})}const szt=Ma("ZodNonOptional",(s,t)=>{mAs.init(s,t),Px.init(s,t),s._zod.processJSONSchema=(n,r,a)=>BEs(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function XTs(s,t){return new szt({type:"nonoptional",innerType:s,...Ml(t)})}const QTs=Ma("ZodCatch",(s,t)=>{fAs.init(s,t),Px.init(s,t),s._zod.processJSONSchema=(n,r,a)=>qEs(s,n,r,a),s.unwrap=()=>s._zod.def.innerType,s.removeCatch=s.unwrap});function JTs(s,t){return new QTs({type:"catch",innerType:s,catchValue:typeof t=="function"?t:a4s(t)})}const eMs=Ma("ZodPipe",(s,t)=>{pAs.init(s,t),Px.init(s,t),s._zod.processJSONSchema=(n,r,a)=>VEs(s,n,r,a),s.in=t.in,s.out=t.out});function xyt(s,t){return new eMs({type:"pipe",in:s,out:t})}const tMs=Ma("ZodReadonly",(s,t)=>{gAs.init(s,t),Px.init(s,t),s._zod.processJSONSchema=(n,r,a)=>HEs(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function sMs(s){return new tMs({type:"readonly",innerType:s})}const nMs=Ma("ZodCustom",(s,t)=>{xAs.init(s,t),Px.init(s,t),s._zod.processJSONSchema=(n,r,a)=>IEs(s,n,r,a)});function rMs(s,t={}){return yEs(nMs,s,t)}function aMs(s,t){return vEs(s,t)}var iMs=Object.defineProperty,oMs=(s,t)=>iMs(s,"name",{value:t,configurable:!0}),lMs=j.forwardRef(oMs(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")),nzt=lMs;const cMs=MB("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),ee=j.forwardRef(({className:s,...t},n)=>e.jsx(nzt,{ref:n,className:Pt(cMs(),s),...t}));ee.displayName=nzt.displayName;const kLe=g5s,rzt=j.createContext({}),jg=({...s})=>e.jsx(rzt.Provider,{value:{name:s.name},children:e.jsx(h5s,{...s})}),SLe=()=>{const s=j.useContext(rzt),t=j.useContext(azt),{getFieldState:n,formState:r}=p5s(),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}},azt=j.createContext({}),Up=j.forwardRef(({className:s,...t},n)=>{const r=j.useId();return e.jsx(azt.Provider,{value:{id:r},children:e.jsx("div",{ref:n,className:Pt("space-y-2",s),...t})})});Up.displayName="FormItem";const qp=j.forwardRef(({className:s,...t},n)=>{const{error:r,formItemId:a}=SLe();return e.jsx(ee,{ref:n,className:Pt(r&&"text-destructive",s),htmlFor:a,...t})});qp.displayName="FormLabel";const Vp=j.forwardRef(({...s},t)=>{const{error:n,formItemId:r,formDescriptionId:a,formMessageId:i}=SLe();return e.jsx(YJe,{ref:t,id:r,"aria-describedby":n?`${a} ${i}`:`${a}`,"aria-invalid":!!n,...s})});Vp.displayName="FormControl";const W4e=j.forwardRef(({className:s,...t},n)=>{const{formDescriptionId:r}=SLe();return e.jsx("p",{ref:n,id:r,className:Pt("text-sm text-muted-foreground",s),...t})});W4e.displayName="FormDescription";const f_=j.forwardRef(({className:s,children:t,...n},r)=>{const{error:a,formMessageId:i}=SLe(),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});f_.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 dMs=Object.defineProperty,uMs=(s,t)=>dMs(s,"name",{value:t,configurable:!0});function ftt(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])}uMs(ftt,"usePrevious");var hMs=Object.defineProperty,Du=(s,t)=>hMs(s,"name",{value:t,configurable:!0}),mMs=[" ","Enter","ArrowUp","ArrowDown"],fMs=[" ","Enter"],jG="Select",[CLe,ALe,pMs]=EB(jG),[OB,Fkr]=tp(jG,[pMs,r3]),ptt=r3(),[gMs,r6]=OB(jG),[xMs,yMs]=OB(jG);function izt(s){const{__scopeSelect:t,children:n,open:r,defaultOpen:a,onOpenChange:i,value:l,defaultValue:o,onValueChange:c,dir:d,name:u,autoComplete:h,disabled:m,required:f,form:g,internal_do_not_use_render:x}=s,y=ptt(t),[v,b]=j.useState(null),[w,S]=j.useState(null),[A,E]=j.useState(!1),I=i3(d),[P,R]=hy({prop:r,defaultProp:a??!1,onChange:i,caller:jG}),[D,O]=hy({prop:l,defaultProp:o,onChange:c,caller:jG}),U=j.useRef(null),W=j.useRef(D);j.useEffect(()=>{const J=g?v==null?void 0:v.ownerDocument.getElementById(g):v==null?void 0:v.form;if(J instanceof HTMLFormElement){const ce=Du(()=>O(W.current),"reset");return J.addEventListener("reset",ce),()=>J.removeEventListener("reset",ce)}},[g,v,O]);const V=v?!!g||!!v.closest("form"):!0,[G,Y]=j.useState(new Set),X=uy(),ae=Array.from(G).map(J=>J.props.value).join(";"),le=j.useCallback(J=>{Y(ce=>new Set(ce).add(J))},[]),ne=j.useCallback(J=>{Y(ce=>{const _e=new Set(ce);return _e.delete(J),_e})},[]),te={required:f,trigger:v,onTriggerChange:b,valueNode:w,onValueNodeChange:S,valueNodeHasChildren: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(wae,{...y,children:e.jsx(gMs,{scope:t,...te,children:e.jsx(CLe.Provider,{scope:t,children:e.jsx(xMs,{scope:t,onNativeOptionAdd:le,onNativeOptionRemove:ne,children:xzt(x)?x(te):n})})})})}Du(izt,"SelectProvider");var vMs=Du(s=>{const{__scopeSelect:t,children:n,...r}=s;return e.jsx(izt,{__scopeSelect:t,...r,internal_do_not_use_render:({isFormControl:a})=>e.jsxs(e.Fragment,{children:[n,a?e.jsx(VMs,{__scopeSelect:t}):null]})})},"Select"),bMs="SelectTrigger",ozt=j.forwardRef(Du(function(t,n){const{__scopeSelect:r,disabled:a=!1,...i}=t,l=ptt(r),o=r6(bMs,r),c=o.disabled||a,d=Vo(n,o.onTriggerChange),u=ALe(r),h=j.useRef("touch"),[m,f,g]=xtt(y=>{const v=u().filter(S=>!S.disabled),b=v.find(S=>S.value===o.value),w=ytt(v,y,b);w!==void 0&&o.onValueChange(w.value)}),x=Du(y=>{c||(o.onOpenChange(!0),g()),y&&(o.triggerPointerDownPosRef.current={x:Math.round(y.pageX),y:Math.round(y.pageY)})},"handleOpen");return e.jsx(jae,{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":Fae(o.value)?"":void 0,...i,ref:d,onClick:Ra(i.onClick,y=>{y.currentTarget.focus(),h.current!=="mouse"&&x(y)}),onPointerDown:Ra(i.onPointerDown,y=>{h.current=y.pointerType;const v=y.target;v.hasPointerCapture(y.pointerId)&&v.releasePointerCapture(y.pointerId),y.button===0&&y.ctrlKey===!1&&y.pointerType==="mouse"&&(x(y),y.preventDefault())}),onKeyDown:Ra(i.onKeyDown,y=>{const v=m.current!=="";!(y.ctrlKey||y.altKey||y.metaKey)&&y.key.length===1&&f(y.key),!(v&&y.key===" ")&&mMs.includes(y.key)&&(x(),y.preventDefault())})})})},"SelectTrigger")),_Ms="SelectValue",wMs=j.forwardRef(Du(function(t,n){const{__scopeSelect:r,className:a,style:i,children:l,placeholder:o="",...c}=t,d=r6(_Ms,r),{onValueNodeHasChildrenChange:u}=d,h=l!==void 0,m=Vo(n,d.onValueNodeChange);Af(()=>{u(h)},[u,h]);const f=Fae(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")),jMs=j.forwardRef(Du(function(t,n){const{__scopeSelect:r,children:a,...i}=t;return e.jsx(Ei.span,{"aria-hidden":!0,...i,ref:n,children:a||"▼"})},"SelectIcon")),NMs="SelectPortal",[kMs,SMs]=OB(NMs,{forceMount:void 0}),CMs=Du(s=>{const{__scopeSelect:t,forceMount:n,...r}=s;return e.jsx(kMs,{scope:s.__scopeSelect,forceMount:n,children:e.jsx(gae,{asChild:!0,...r})})},"SelectPortal"),q7="SelectContent",lzt=j.forwardRef(Du(function(t,n){const r=SMs(q7,t.__scopeSelect),{forceMount:a=r.forceMount,...i}=t,l=r6(q7,t.__scopeSelect),[o,c]=j.useState();return Af(()=>{c(new DocumentFragment)},[]),e.jsx(py,{present:a||l.open,children:({present:d})=>d?e.jsx(TMs,{...i,ref:n}):e.jsx(AMs,{...i,fragment:o})})},"SelectContent")),AMs=j.forwardRef(Du(function(t,n){const{__scopeSelect:r,children:a,fragment:i}=t;return i?vv.createPortal(e.jsx(czt,{scope:r,children:e.jsx(CLe.Slot,{scope:r,children:e.jsx("div",{ref:n,children:a})})}),i):null},"SelectContentFragment")),cS=10,[czt,zB]=OB(q7),EMs=mC("SelectContent.RemoveScroll"),TMs=j.forwardRef(Du(function(t,n){const{__scopeSelect:r}=t,{position:a="item-aligned",onCloseAutoFocus:i,onEscapeKeyDown:l,onPointerDownOutside:o,side:c,sideOffset:d,align:u,alignOffset:h,arrowPadding:m,collisionBoundary:f,collisionPadding:g,sticky:x,hideWhenDetached:y,avoidCollisions:v,...b}=t,w=r6(q7,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=ALe(r),[V,G]=j.useState(!1),Y=j.useRef(!1);j.useEffect(()=>{if(S)return VIe(S)},[S]),UW();const X=j.useCallback(Ee=>{const[Se,...Le]=W().map(Be=>Be.ref.current),[Fe]=Le.slice(-1),ke=document.activeElement;for(const Be of Ee)if(Be===ke||(Be==null||Be.scrollIntoView({block:"nearest"}),Be===Se&&E&&(E.scrollTop=0),Be===Fe&&E&&(E.scrollTop=E.scrollHeight),Be==null||Be.focus(),document.activeElement!==ke))return},[W,E]),ae=j.useCallback(()=>X([R,S]),[X,R,S]);j.useEffect(()=>{V&&ae()},[V,ae]);const{onOpenChange:le,triggerPointerDownPosRef:ne}=w;j.useEffect(()=>{if(S){let Ee={x:0,y:0};const Se=Du(Fe=>{var ke,Be;Ee={x:Math.abs(Math.round(Fe.pageX)-(((ke=ne.current)==null?void 0:ke.x)??0)),y:Math.abs(Math.round(Fe.pageY)-(((Be=ne.current)==null?void 0:Be.y)??0))}},"handlePointerMove"),Le=Du(Fe=>{Ee.x<=10&&Ee.y<=10?Fe.preventDefault():Fe.composedPath().includes(S)||le(!1),document.removeEventListener("pointermove",Se),ne.current=null},"handlePointerUp");return ne.current!==null&&(document.addEventListener("pointermove",Se),document.addEventListener("pointerup",Le,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",Se),document.removeEventListener("pointerup",Le,{capture:!0})}}},[S,le,ne]),j.useEffect(()=>{const Ee=Du(()=>le(!1),"close");return window.addEventListener("blur",Ee),window.addEventListener("resize",Ee),()=>{window.removeEventListener("blur",Ee),window.removeEventListener("resize",Ee)}},[le]);const[te,J]=xtt(Ee=>{const Se=W().filter(ke=>!ke.disabled),Le=Se.find(ke=>ke.ref.current===document.activeElement),Fe=ytt(Se,Ee,Le);Fe&&setTimeout(()=>{var ke;return(ke=Fe.ref.current)==null?void 0:ke.focus()})}),ce=j.useCallback((Ee,Se,Le)=>{const Fe=!Y.current&&!Le;(w.value!==void 0&&w.value===Se||Fe)&&(D(Ee),Fe&&(Y.current=!0))},[w.value]),_e=j.useCallback(()=>S==null?void 0:S.focus(),[S]),he=j.useCallback((Ee,Se,Le)=>{const Fe=!Y.current&&!Le;(w.value!==void 0&&w.value===Se||Fe)&&U(Ee)},[w.value]),ue=a==="popper"?yyt:MMs,ve=ue===yyt?{side:c,sideOffset:d,align:u,alignOffset:h,arrowPadding:m,collisionBoundary:f,collisionPadding:g,sticky:x,hideWhenDetached:y,avoidCollisions:v}:{};return e.jsx(czt,{scope:r,content:S,viewport:E,onViewportChange:I,itemRefCallback:ce,selectedItem:R,onItemLeave:_e,itemTextRefCallback:he,focusSelectedItem:ae,selectedItemText:O,position:a,isPositioned:V,searchRef:te,children:e.jsx(yae,{as:EMs,allowPinchZoom:!0,children:e.jsx(UIe,{asChild:!0,trapped:w.open,onMountAutoFocus:Ee=>{Ee.preventDefault()},onUnmountAutoFocus:Ra(i,Ee=>{var Se;(Se=w.trigger)==null||Se.focus({preventScroll:!0}),Ee.preventDefault()}),children:e.jsx(TB,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:l,onPointerDownOutside:o,onFocusOutside:Ee=>Ee.preventDefault(),onDismiss:()=>w.onOpenChange(!1),children:e.jsx(ue,{role:"listbox",id:w.contentId,"data-state":w.open?"open":"closed",dir:w.dir,onContextMenu:Ee=>Ee.preventDefault(),...b,...ve,onPlaced:()=>G(!0),ref:P,style:{display:"flex",flexDirection:"column",outline:"none",...b.style},onKeyDown:Ra(b.onKeyDown,Ee=>{const Se=Ee.ctrlKey||Ee.altKey||Ee.metaKey;if(Ee.key==="Tab"&&Ee.preventDefault(),!Se&&Ee.key.length===1&&J(Ee.key),["ArrowUp","ArrowDown","Home","End"].includes(Ee.key)){let Fe=W().filter(ke=>!ke.disabled).map(ke=>ke.ref.current);if(["ArrowUp","End"].includes(Ee.key)&&(Fe=Fe.slice().reverse()),["ArrowUp","ArrowDown"].includes(Ee.key)){const ke=Ee.target,Be=Fe.indexOf(ke);Fe=Fe.slice(Be+1)}setTimeout(()=>X(Fe)),Ee.preventDefault()}})})})})})})},"SelectContentImpl")),MMs=j.forwardRef(Du(function(t,n){const{__scopeSelect:r,onPlaced:a,...i}=t,l=r6(q7,r),o=zB(q7,r),[c,d]=j.useState(null),[u,h]=j.useState(null),m=Vo(n,h),f=ALe(r),g=j.useRef(!1),x=j.useRef(!0),{viewport:y,selectedItem:v,selectedItemText:b,focusSelectedItem:w}=o,S=j.useCallback(()=>{if(l.trigger&&l.valueNode&&c&&u&&y&&v&&b){const P=l.trigger.getBoundingClientRect(),R=u.getBoundingClientRect(),D=l.valueNode.getBoundingClientRect(),O=b.getBoundingClientRect();if(l.dir!=="rtl"){const ke=O.left-R.left,Be=D.left-ke,Ne=P.left-Be,Ae=P.width+Ne,Ce=Math.max(Ae,R.width),Ve=window.innerWidth-cS,ze=yG(Be,[cS,Math.max(cS,Ve-Ce)]);c.style.minWidth=Ae+"px",c.style.left=ze+"px"}else{const ke=R.right-O.right,Be=window.innerWidth-D.right-ke,Ne=window.innerWidth-P.right-Be,Ae=P.width+Ne,Ce=Math.max(Ae,R.width),Ve=window.innerWidth-cS,ze=yG(Be,[cS,Math.max(cS,Ve-Ce)]);c.style.minWidth=Ae+"px",c.style.right=ze+"px"}const U=f(),W=window.innerHeight-cS*2,V=y.scrollHeight,G=window.getComputedStyle(u),Y=parseInt(G.borderTopWidth,10),X=parseInt(G.paddingTop,10),ae=parseInt(G.borderBottomWidth,10),le=parseInt(G.paddingBottom,10),ne=Y+X+V+le+ae,te=Math.min(v.offsetHeight*5,ne),J=window.getComputedStyle(y),ce=parseInt(J.paddingTop,10),_e=parseInt(J.paddingBottom,10),he=P.top+P.height/2-cS,ue=W-he,ve=v.offsetHeight/2,Ee=v.offsetTop+ve,Se=Y+X+Ee,Le=ne-Se;if(Se<=he){const ke=U.length>0&&v===U[U.length-1].ref.current;c.style.bottom="0px";const Be=u.clientHeight-y.offsetTop-y.offsetHeight,Ne=Math.max(ue,ve+(ke?_e:0)+Be+ae),Ae=Se+Ne;c.style.height=Ae+"px"}else{const ke=U.length>0&&v===U[0].ref.current;c.style.top="0px";const Ne=Math.max(he,Y+y.offsetTop+(ke?ce:0)+ve)+Le;c.style.height=Ne+"px",y.scrollTop=Se-he+y.offsetTop}c.style.margin=`${cS}px 0`,c.style.minHeight=te+"px",c.style.maxHeight=W+"px",a==null||a(),requestAnimationFrame(()=>g.current=!0)}},[f,l.trigger,l.valueNode,c,u,y,v,b,l.dir,a]);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(PMs,{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")),yyt=j.forwardRef(Du(function(t,n){const{__scopeSelect:r,align:a="start",collisionPadding:i=cS,...l}=t,o=ptt(r);return e.jsx(Nae,{...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")),[PMs,gtt]=OB(q7,{}),vyt="SelectViewport",IMs=j.forwardRef(Du(function(t,n){const{__scopeSelect:r,nonce:a,...i}=t,l=zB(vyt,r),o=gtt(vyt,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(CLe.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-cS*2,y=parseFloat(m.style.minHeight),v=parseFloat(m.style.height),b=Math.max(y,v);if(b0?A:0,m.style.justifyContent="flex-end")}}}d.current=h.scrollTop})})})]})},"SelectViewport")),LMs="SelectGroup",[RMs,DMs]=OB(LMs),FMs=j.forwardRef(Du(function(t,n){const{__scopeSelect:r,...a}=t,i=uy();return e.jsx(RMs,{scope:r,id:i,children:e.jsx(Ei.div,{role:"group","aria-labelledby":i,...a,ref:n})})},"SelectGroup")),OMs="SelectLabel",dzt=j.forwardRef(Du(function(t,n){const{__scopeSelect:r,...a}=t,i=DMs(OMs,r);return e.jsx(Ei.div,{id:i.id,...a,ref:n})},"SelectLabel")),qHe="SelectItem",[zMs,uzt]=OB(qHe),hzt=j.forwardRef(Du(function(t,n){const{__scopeSelect:r,value:a,disabled:i=!1,textValue:l,...o}=t,c=r6(qHe,r),d=zB(qHe,r),u=c.value===a,[h,m]=j.useState(l??""),[f,g]=j.useState(!1),x=Zp(S=>{var A;return(A=d.itemRefCallback)==null?void 0:A.call(d,S,a,i)}),y=Vo(n,x),v=uy(),b=j.useRef("touch"),w=Du(()=>{i||(c.onValueChange(a),c.onOpenChange(!1))},"handleSelect");return e.jsx(zMs,{scope:r,value:a,disabled:i,textId:v,isSelected:u,onItemTextChange:j.useCallback(S=>{m(A=>A||((S==null?void 0:S.textContent)??"").trim())},[]),children:e.jsx(CLe.ItemSlot,{scope:r,value:a,disabled:i,textValue:h,children:e.jsx(Ei.div,{role:"option","aria-labelledby":v,"data-highlighted":f?"":void 0,"aria-selected":u&&f,"data-state":u?"checked":"unchecked","aria-disabled":i||void 0,"data-disabled":i?"":void 0,tabIndex:i?void 0:-1,...o,ref:y,onFocus:Ra(o.onFocus,()=>g(!0)),onBlur:Ra(o.onBlur,()=>g(!1)),onClick:Ra(o.onClick,()=>{b.current!=="mouse"&&w()}),onPointerUp:Ra(o.onPointerUp,()=>{b.current==="mouse"&&w()}),onPointerDown:Ra(o.onPointerDown,S=>{b.current=S.pointerType}),onPointerMove:Ra(o.onPointerMove,S=>{var 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===" "||(fMs.includes(S.key)&&w(),S.key===" "&&S.preventDefault())})})})})},"SelectItem")),Pce="SelectItemText",BMs=j.forwardRef(Du(function(t,n){const{__scopeSelect:r,className:a,style:i,...l}=t,o=r6(Pce,r),c=zB(Pce,r),d=uzt(Pce,r),u=yMs(Pce,r),[h,m]=j.useState(null),f=Zp(w=>{var S;return(S=c.itemTextRefCallback)==null?void 0:S.call(c,w,d.value,d.disabled)}),g=Vo(n,m,d.onItemTextChange,f),x=h==null?void 0:h.textContent,y=j.useMemo(()=>e.jsx("option",{value:d.value,disabled:d.disabled,children:x},d.value),[d.disabled,d.value,x]),{onNativeOptionAdd:v,onNativeOptionRemove:b}=u;return Af(()=>(v(y),()=>b(y)),[v,b,y]),e.jsxs(e.Fragment,{children:[e.jsx(Ei.span,{id:d.textId,...l,ref:g}),d.isSelected&&o.valueNode&&!o.valueNodeHasChildren&&!Fae(o.value)?vv.createPortal(l.children,o.valueNode):null]})},"SelectItemText")),$Ms="SelectItemIndicator",UMs=j.forwardRef(Du(function(t,n){const{__scopeSelect:r,...a}=t;return uzt($Ms,r).isSelected?e.jsx(Ei.span,{"aria-hidden":!0,...a,ref:n}):null},"SelectItemIndicator")),byt="SelectScrollUpButton",mzt=j.forwardRef(Du(function(t,n){const r=zB(byt,t.__scopeSelect),a=gtt(byt,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)};Du(c,"handleScroll");const d=r.viewport;return c(),d.addEventListener("scroll",c),()=>d.removeEventListener("scroll",c)}},[r.viewport,r.isPositioned]),i?e.jsx(pzt,{...t,ref:o,onAutoScroll:()=>{const{viewport:c,selectedItem:d}=r;c&&d&&(c.scrollTop=c.scrollTop-d.offsetHeight)}}):null},"SelectScrollUpButton")),_yt="SelectScrollDownButton",fzt=j.forwardRef(Du(function(t,n){const r=zB(_yt,t.__scopeSelect),a=gtt(_yt,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(pzt,{...t,ref:o,onAutoScroll:()=>{const{viewport:c,selectedItem:d}=r;c&&d&&(c.scrollTop=c.scrollTop+d.offsetHeight)}}):null},"SelectScrollDownButton")),pzt=j.forwardRef(Du(function(t,n){const{__scopeSelect:r,onAutoScroll:a,...i}=t,l=zB("SelectScrollButton",r),o=j.useRef(null),c=ALe(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")),gzt=j.forwardRef(Du(function(t,n){const{__scopeSelect:r,...a}=t;return e.jsx(Ei.div,{"aria-hidden":!0,...a,ref:n})},"SelectSeparator")),qMs="SelectBubbleInput",VMs=j.forwardRef(Du(function({__scopeSelect:t,...n},r){const a=r6(qMs,t),{value:i,onValueChange:l,required:o,disabled:c,name:d,autoComplete:u,form:h}=a,{nativeOptions:m,nativeSelectKey:f}=a,g=j.useRef(null),x=Vo(r,g),y=i??"",v=ftt(y),b=Array.from(m).some(w=>(w.props.value??"")==="");return j.useEffect(()=>{const w=g.current;if(!w)return;const S=window.HTMLSelectElement.prototype,E=Object.getOwnPropertyDescriptor(S,"value").set;if(v!==y&&E){const I=new Event("change",{bubbles:!0});E.call(w,y),w.dispatchEvent(I)}},[v,y]),e.jsxs(Ei.select,{"aria-hidden":!0,required:o,tabIndex:-1,name:d,autoComplete:u,disabled:c,form:h,onChange:w=>l(w.target.value),...n,style:{...mRt,...n.style},ref:x,defaultValue:y,children:[Fae(i)&&!b?e.jsx("option",{value:""}):null,Array.from(m)]},f)},"SelectBubbleInput"));function xzt(s){return typeof s=="function"}Du(xzt,"isFunction");function Fae(s){return s===""||s===void 0}Du(Fae,"shouldShowPlaceholder");function xtt(s){const t=Zp(s),n=j.useRef(""),r=j.useRef(0),a=j.useCallback(l=>{const o=n.current+l;t(o),Du(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]}Du(xtt,"useTypeaheadSearch");function ytt(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=yzt(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}Du(ytt,"findNextItem");function yzt(s,t){return s.map((n,r)=>s[(t+r)%s.length])}Du(yzt,"wrapArray");const ms=vMs,HMs=FMs,fs=wMs,us=j.forwardRef(({className:s,children:t,...n},r)=>e.jsxs(ozt,{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(jMs,{asChild:!0,children:e.jsx(wl,{className:"h-4 w-4 opacity-50"})})]}));us.displayName=ozt.displayName;const vzt=j.forwardRef(({className:s,...t},n)=>e.jsx(mzt,{ref:n,className:Pt("flex cursor-default items-center justify-center py-1",s),...t,children:e.jsx(yb,{className:"h-4 w-4"})}));vzt.displayName=mzt.displayName;const bzt=j.forwardRef(({className:s,...t},n)=>e.jsx(fzt,{ref:n,className:Pt("flex cursor-default items-center justify-center py-1",s),...t,children:e.jsx(wl,{className:"h-4 w-4"})}));bzt.displayName=fzt.displayName;const hs=j.forwardRef(({className:s,children:t,position:n="popper",...r},a)=>e.jsx(CMs,{children:e.jsxs(lzt,{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(vzt,{}),e.jsx(IMs,{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(bzt,{})]})}));hs.displayName=lzt.displayName;const _zt=j.forwardRef(({className:s,...t},n)=>e.jsx(dzt,{ref:n,className:Pt("py-1.5 pl-8 pr-2 text-sm font-semibold",s),...t}));_zt.displayName=dzt.displayName;const Ge=j.forwardRef(({className:s,children:t,...n},r)=>e.jsxs(hzt,{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(UMs,{children:e.jsx(ca,{className:"h-4 w-4"})})}),e.jsx(BMs,{children:t})]}));Ge.displayName=hzt.displayName;const GMs=j.forwardRef(({className:s,...t},n)=>e.jsx(gzt,{ref:n,className:Pt("-mx-1 my-1 h-px bg-muted",s),...t}));GMs.displayName=gzt.displayName;const WMs=z2({category:mtt(["general","technology","crm","marketing"]),subject:vl().min(5,"Subject must be at least 5 characters").max(200),description:vl().min(20,"Please provide more details (at least 20 characters)").max(2e3)}),KMs={general:"General Support",technology:"Technology Support",crm:"CRM Support",marketing:"Marketing Support"};function VHe({trigger:s}){const[t,n]=j.useState(!1),[r,a]=j.useState(!1),{user:i}=bs(),l=bLe({resolver:_Le(WMs),defaultValues:{category:"general",subject:"",description:""}}),o=async c=>{if(!i){re.error("You must be logged in to submit a ticket");return}a(!0);try{const{error:d}=await q.from("support_tickets").insert({user_id:i.id,category:c.category,subject:c.subject,description:c.description});if(d)throw d;try{await q.functions.invoke("support-ticket-notify",{body:{category:KMs[c.category],subject:c.subject}})}catch(u){console.log("Notification send attempted:",u)}re.success("Support ticket submitted successfully!"),l.reset(),n(!1)}catch(d){console.error("Error submitting ticket:",d),re.error("Failed to submit ticket. Please try again.")}finally{a(!1)}};return e.jsxs(zs,{open:t,onOpenChange:n,children:[e.jsx(jl,{asChild:!0,children:s||e.jsxs($,{variant:"ghost",size:"icon",className:"relative",children:[e.jsx(DJ,{className:"h-5 w-5"}),e.jsx("span",{className:"sr-only",children:"Support"})]})}),e.jsxs(Os,{className:"sm:max-w-[500px]",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Need Help?"}),e.jsx(Pr,{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(kLe,{...l,children:e.jsxs("form",{onSubmit:l.handleSubmit(o),className:"space-y-4",children:[e.jsx(jg,{control:l.control,name:"category",render:({field:c})=>e.jsxs(Up,{children:[e.jsx(qp,{children:"Category"}),e.jsxs(ms,{onValueChange:c.onChange,defaultValue:c.value,children:[e.jsx(Vp,{children:e.jsx(us,{children:e.jsx(fs,{placeholder:"Select a category"})})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"general",children:"General Support"}),e.jsx(Ge,{value:"technology",children:"Technology Support"}),e.jsx(Ge,{value:"crm",children:"CRM Support"}),e.jsx(Ge,{value:"marketing",children:"Marketing Support"})]})]}),e.jsx(f_,{})]})}),e.jsx(jg,{control:l.control,name:"subject",render:({field:c})=>e.jsxs(Up,{children:[e.jsx(qp,{children:"Subject"}),e.jsx(Vp,{children:e.jsx(pe,{placeholder:"Brief description of your issue",...c})}),e.jsx(f_,{})]})}),e.jsx(jg,{control:l.control,name:"description",render:({field:c})=>e.jsxs(Up,{children:[e.jsx(qp,{children:"Description"}),e.jsx(Vp,{children:e.jsx(Ls,{placeholder:"Please describe your issue in detail...",className:"min-h-[120px]",...c})}),e.jsx(f_,{})]})}),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 Ev(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 wzt(s,t){const n=+So(s);return Em(s,n+t)}const vtt=6048e5,YMs=864e5,ELe=6e4,TLe=36e5,ZMs=1e3,Ice=43200,wyt=1440;function jyt(s,t){return wzt(s,t*TLe)}let XMs={};function a6(){return XMs}function j1(s,t){var o,c,d,u;const n=a6(),r=(t==null?void 0:t.weekStartsOn)??((c=(o=t==null?void 0:t.locale)==null?void 0:o.options)==null?void 0:c.weekStartsOn)??n.weekStartsOn??((u=(d=n.locale)==null?void 0:d.options)==null?void 0:u.weekStartsOn)??0,a=So(s),i=a.getDay(),l=(i=a.getTime()?n+1:t.getTime()>=l.getTime()?n:n-1}function Mg(s){const t=So(s);return t.setHours(0,0,0,0),t}function SL(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 ub(s,t){const n=Mg(s),r=Mg(t),a=+n-SL(n),i=+r-SL(r);return Math.round((a-i)/YMs)}function QMs(s){const t=jzt(s),n=Em(s,0);return n.setFullYear(t,0,4),n.setHours(0,0,0,0),uT(n)}function Nyt(s,t){return wzt(s,t*ELe)}function a8(s,t){const n=t*7;return Am(s,n)}function JMs(s,t){return Ev(s,t*12)}function ePs(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 K4e(s,t){const n=So(s),r=So(t),a=n.getTime()-r.getTime();return a<0?-1:a>0?1:a}function MLe(s){return Em(s,Date.now())}function sf(s,t){const n=Mg(s),r=Mg(t);return+n==+r}function btt(s){return s instanceof Date||typeof s=="object"&&Object.prototype.toString.call(s)==="[object Date]"}function HHe(s){if(!btt(s)&&typeof s!="number")return!1;const t=So(s);return!isNaN(Number(t))}function NG(s,t){const n=So(s),r=So(t),a=n.getFullYear()-r.getFullYear(),i=n.getMonth()-r.getMonth();return a*12+i}function sPs(s,t,n){const r=j1(s,n),a=j1(t,n),i=+r-SL(r),l=+a-SL(a);return Math.round((i-l)/vtt)}function dk(s,t){const n=So(s),r=So(t),a=kyt(n,r),i=Math.abs(ub(n,r));n.setDate(n.getDate()-a*i);const l=+(kyt(n,r)===-a),o=a*(i-l);return o===0?0:o}function kyt(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 nPs(s){return t=>{const r=(s?Math[s]:Math.trunc)(t);return r===0?0:r}}function rPs(s,t){return+So(s)-+So(t)}function aPs(s){const t=So(s);return t.setHours(23,59,59,999),t}function hw(s){const t=So(s),n=t.getMonth();return t.setFullYear(t.getFullYear(),n+1,0),t.setHours(23,59,59,999),t}function iPs(s){const t=So(s);return+aPs(t)==+hw(t)}function oPs(s,t){const n=So(s),r=So(t),a=K4e(n,r),i=Math.abs(NG(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=K4e(n,r)===-a;iPs(So(s))&&i===1&&K4e(s,r)===1&&(o=!1),l=a*(i-Number(o))}return l===0?0:l}function lPs(s,t,n){const r=rPs(s,t)/1e3;return nPs(n==null?void 0:n.roundingMethod)(r)}function cPs(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 dPs(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 _tt(s){const t=So(s),n=Em(s,0);return n.setFullYear(t.getFullYear(),0,1),n.setHours(0,0,0,0),n}function PLe(s,t){var o,c,d,u;const n=a6(),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=uPs[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 Jze(s){return(t={})=>{const n=t.width?String(t.width):s.defaultWidth;return s.formats[n]||s.formats[s.defaultWidth]}}const mPs={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},fPs={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},pPs={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},gPs={date:Jze({formats:mPs,defaultWidth:"full"}),time:Jze({formats:fPs,defaultWidth:"full"}),dateTime:Jze({formats:pPs,defaultWidth:"full"})},xPs={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},yPs=(s,t,n,r)=>xPs[s];function wZ(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 vPs={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},bPs={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},_Ps={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"]},wPs={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"]},jPs={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"}},NPs={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"}},kPs=(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"},SPs={ordinalNumber:kPs,era:wZ({values:vPs,defaultWidth:"wide"}),quarter:wZ({values:bPs,defaultWidth:"wide",argumentCallback:s=>s-1}),month:wZ({values:_Ps,defaultWidth:"wide"}),day:wZ({values:wPs,defaultWidth:"wide"}),dayPeriod:wZ({values:jPs,defaultWidth:"wide",formattingValues:NPs,defaultFormattingWidth:"wide"})};function jZ(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)?APs(o,h=>h.test(l)):CPs(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 CPs(s,t){for(const n in s)if(Object.prototype.hasOwnProperty.call(s,n)&&t(s[n]))return n}function APs(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 TPs=/^(\d+)(th|st|nd|rd)?/i,MPs=/\d+/i,PPs={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},IPs={any:[/^b/i,/^(a|c)/i]},LPs={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},RPs={any:[/1/i,/2/i,/3/i,/4/i]},DPs={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},FPs={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]},OPs={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},zPs={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]},BPs={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},$Ps={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}},UPs={ordinalNumber:EPs({matchPattern:TPs,parsePattern:MPs,valueCallback:s=>parseInt(s,10)}),era:jZ({matchPatterns:PPs,defaultMatchWidth:"wide",parsePatterns:IPs,defaultParseWidth:"any"}),quarter:jZ({matchPatterns:LPs,defaultMatchWidth:"wide",parsePatterns:RPs,defaultParseWidth:"any",valueCallback:s=>s+1}),month:jZ({matchPatterns:DPs,defaultMatchWidth:"wide",parsePatterns:FPs,defaultParseWidth:"any"}),day:jZ({matchPatterns:OPs,defaultMatchWidth:"wide",parsePatterns:zPs,defaultParseWidth:"any"}),dayPeriod:jZ({matchPatterns:BPs,defaultMatchWidth:"any",parsePatterns:$Ps,defaultParseWidth:"any"})},ILe={code:"en-US",formatDistance:hPs,formatLong:gPs,formatRelative:yPs,localize:SPs,match:UPs,options:{weekStartsOn:0,firstWeekContainsDate:1}};function qPs(s){const t=So(s);return ub(t,_tt(t))+1}function wtt(s){const t=So(s),n=+uT(t)-+QMs(t);return Math.round(n/vtt)+1}function jtt(s,t){var u,h,m,f;const n=So(s),r=n.getFullYear(),a=a6(),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=j1(l,t),c=Em(s,0);c.setFullYear(r,0,i),c.setHours(0,0,0,0);const d=j1(c,t);return n.getTime()>=o.getTime()?r+1:n.getTime()>=d.getTime()?r:r-1}function VPs(s,t){var o,c,d,u;const n=a6(),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=jtt(s,t),i=Em(s,0);return i.setFullYear(a,0,r),i.setHours(0,0,0,0),j1(i,t)}function Ntt(s,t){const n=So(s),r=+j1(n,t)-+VPs(n,t);return Math.round(r/vtt)+1}function Sm(s,t){const n=s<0?"-":"",r=Math.abs(s).toString().padStart(t,"0");return n+r}const yM={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)}},x$={midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},Syt={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 yM.y(s,t)},Y:function(s,t,n,r){const a=jtt(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=jzt(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 yM.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=Ntt(s,r);return t==="wo"?n.ordinalNumber(a,{unit:"week"}):Sm(a,t.length)},I:function(s,t,n){const r=wtt(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"}):yM.d(s,t)},D:function(s,t,n){const r=qPs(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=x$.noon:r===0?a=x$.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=x$.evening:r>=12?a=x$.afternoon:r>=4?a=x$.morning:a=x$.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 yM.h(s,t)},H:function(s,t,n){return t==="Ho"?n.ordinalNumber(s.getHours(),{unit:"hour"}):yM.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"}):yM.m(s,t)},s:function(s,t,n){return t==="so"?n.ordinalNumber(s.getSeconds(),{unit:"second"}):yM.s(s,t)},S:function(s,t){return yM.S(s,t)},X:function(s,t,n){const r=s.getTimezoneOffset();if(r===0)return"Z";switch(t){case"X":return Ayt(r);case"XXXX":case"XX":return PO(r);case"XXXXX":case"XXX":default:return PO(r,":")}},x:function(s,t,n){const r=s.getTimezoneOffset();switch(t){case"x":return Ayt(r);case"xxxx":case"xx":return PO(r);case"xxxxx":case"xxx":default:return PO(r,":")}},O:function(s,t,n){const r=s.getTimezoneOffset();switch(t){case"O":case"OO":case"OOO":return"GMT"+Cyt(r,":");case"OOOO":default:return"GMT"+PO(r,":")}},z:function(s,t,n){const r=s.getTimezoneOffset();switch(t){case"z":case"zz":case"zzz":return"GMT"+Cyt(r,":");case"zzzz":default:return"GMT"+PO(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 Cyt(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 Ayt(s,t){return s%60===0?(s>0?"-":"+")+Sm(Math.abs(s)/60,2):PO(s,t)}function PO(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 Eyt=(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"})}},kzt=(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"})}},HPs=(s,t)=>{const n=s.match(/(P+)(p+)?/)||[],r=n[1],a=n[2];if(!a)return Eyt(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}}",Eyt(r,t)).replace("{{time}}",kzt(a,t))},GHe={p:kzt,P:HPs},GPs=/^D+$/,WPs=/^Y+$/,KPs=["D","DD","YY","YYYY"];function Szt(s){return GPs.test(s)}function Czt(s){return WPs.test(s)}function WHe(s,t,n){const r=YPs(s,t,n);if(console.warn(r),KPs.includes(s))throw new RangeError(r)}function YPs(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 ZPs=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,XPs=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,QPs=/^'([^]*?)'?$/,JPs=/''/g,eIs=/[a-zA-Z]/;function en(s,t,n){var u,h,m,f,g,x,y,v;const r=a6(),a=(n==null?void 0:n.locale)??r.locale??ILe,i=(n==null?void 0:n.firstWeekContainsDate)??((h=(u=n==null?void 0:n.locale)==null?void 0:u.options)==null?void 0:h.firstWeekContainsDate)??r.firstWeekContainsDate??((f=(m=r.locale)==null?void 0:m.options)==null?void 0:f.firstWeekContainsDate)??1,l=(n==null?void 0:n.weekStartsOn)??((x=(g=n==null?void 0:n.locale)==null?void 0:g.options)==null?void 0:x.weekStartsOn)??r.weekStartsOn??((v=(y=r.locale)==null?void 0:y.options)==null?void 0:v.weekStartsOn)??0,o=So(s);if(!HHe(o))throw new RangeError("Invalid time value");let c=t.match(XPs).map(b=>{const w=b[0];if(w==="p"||w==="P"){const S=GHe[w];return S(b,a.formatLong)}return b}).join("").match(ZPs).map(b=>{if(b==="''")return{isToken:!1,value:"'"};const w=b[0];if(w==="'")return{isToken:!1,value:tIs(b)};if(Syt[w])return{isToken:!0,value:b};if(w.match(eIs))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)&&Czt(w)||!(n!=null&&n.useAdditionalDayOfYearTokens)&&Szt(w))&&WHe(w,t,String(s));const S=Syt[w[0]];return S(o,w,a.localize,d)}).join("")}function tIs(s){const t=s.match(QPs);return t?t[1].replace(JPs,"'"):s}function sIs(s,t,n){const r=a6(),a=(n==null?void 0:n.locale)??r.locale??ILe,i=2520,l=K4e(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=lPs(d,c),h=(SL(d)-SL(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 rC(s,t){const n=So(s),r=So(t);return+n<+r}function cIs(s){return+So(s)>Date.now()}function dIs(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 uIs=10;class Azt{constructor(){Nr(this,"subPriority",0)}validate(t,n){return!0}}class hIs extends Azt{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 mIs extends Azt{constructor(){super(...arguments);Nr(this,"priority",uIs);Nr(this,"subPriority",-1)}set(n,r){return r.timestampIsSet?n:Em(n,dIs(n,Date))}}class om{run(t,n,r,a){const i=this.parse(t,n,r,a);return i?{setter:new hIs(i.value,this.validate,this.set,this.priority,this.subPriority),rest:i.rest}:null}validate(t,n,r){return!0}}class fIs extends om{constructor(){super(...arguments);Nr(this,"priority",140);Nr(this,"incompatibleTokens",["R","u","t","T"])}parse(n,r,a){switch(r){case"G":case"GG":case"GGG":return a.era(n,{width:"abbreviated"})||a.era(n,{width:"narrow"});case"GGGGG":return a.era(n,{width:"narrow"});case"GGGG":default:return a.era(n,{width:"wide"})||a.era(n,{width:"abbreviated"})||a.era(n,{width:"narrow"})}}set(n,r,a){return r.era=a,n.setFullYear(a,0,1),n.setHours(0,0,0,0),n}}const ly={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}/},l4={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 cy(s,t){return s&&{value:t(s.value),rest:s.rest}}function Ag(s,t){const n=t.match(s);return n?{value:parseInt(n[0],10),rest:t.slice(n[0].length)}:null}function c4(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*TLe+i*ELe+l*ZMs),rest:t.slice(n[0].length)}}function Ezt(s){return Ag(ly.anyDigitsSigned,s)}function Ex(s,t){switch(s){case 1:return Ag(ly.singleDigit,t);case 2:return Ag(ly.twoDigits,t);case 3:return Ag(ly.threeDigits,t);case 4:return Ag(ly.fourDigits,t);default:return Ag(new RegExp("^\\d{1,"+s+"}"),t)}}function CEe(s,t){switch(s){case 1:return Ag(ly.singleDigitSigned,t);case 2:return Ag(ly.twoDigitsSigned,t);case 3:return Ag(ly.threeDigitsSigned,t);case 4:return Ag(ly.fourDigitsSigned,t);default:return Ag(new RegExp("^-?\\d{1,"+s+"}"),t)}}function ktt(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 Tzt(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 Mzt(s){return s%400===0||s%4===0&&s%100!==0}class pIs extends om{constructor(){super(...arguments);Nr(this,"priority",130);Nr(this,"incompatibleTokens",["Y","R","u","w","I","i","e","c","t","T"])}parse(n,r,a){const i=l=>({year:l,isTwoDigitYear:r==="yy"});switch(r){case"y":return cy(Ex(4,n),i);case"yo":return cy(a.ordinalNumber(n,{unit:"year"}),i);default:return cy(Ex(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=Tzt(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 gIs extends om{constructor(){super(...arguments);Nr(this,"priority",130);Nr(this,"incompatibleTokens",["y","R","u","Q","q","M","L","I","d","D","i","t","T"])}parse(n,r,a){const i=l=>({year:l,isTwoDigitYear:r==="YY"});switch(r){case"Y":return cy(Ex(4,n),i);case"Yo":return cy(a.ordinalNumber(n,{unit:"year"}),i);default:return cy(Ex(r.length,n),i)}}validate(n,r){return r.isTwoDigitYear||r.year>0}set(n,r,a,i){const l=jtt(n,i);if(a.isTwoDigitYear){const c=Tzt(a.year,l);return n.setFullYear(c,0,i.firstWeekContainsDate),n.setHours(0,0,0,0),j1(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),j1(n,i)}}class xIs extends om{constructor(){super(...arguments);Nr(this,"priority",130);Nr(this,"incompatibleTokens",["G","y","Y","u","Q","q","M","L","w","d","D","e","c","t","T"])}parse(n,r){return CEe(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),uT(i)}}class yIs extends om{constructor(){super(...arguments);Nr(this,"priority",130);Nr(this,"incompatibleTokens",["G","y","Y","R","w","I","i","e","c","t","T"])}parse(n,r){return CEe(r==="u"?4:r.length,n)}set(n,r,a){return n.setFullYear(a,0,1),n.setHours(0,0,0,0),n}}class vIs extends om{constructor(){super(...arguments);Nr(this,"priority",120);Nr(this,"incompatibleTokens",["Y","R","q","M","L","w","I","d","D","i","e","c","t","T"])}parse(n,r,a){switch(r){case"Q":case"QQ":return Ex(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 bIs extends om{constructor(){super(...arguments);Nr(this,"priority",120);Nr(this,"incompatibleTokens",["Y","R","Q","M","L","w","I","d","D","i","e","c","t","T"])}parse(n,r,a){switch(r){case"q":case"qq":return Ex(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 _Is extends om{constructor(){super(...arguments);Nr(this,"incompatibleTokens",["Y","R","q","Q","L","w","I","D","i","e","c","t","T"]);Nr(this,"priority",110)}parse(n,r,a){const i=l=>l-1;switch(r){case"M":return cy(Ag(ly.month,n),i);case"MM":return cy(Ex(2,n),i);case"Mo":return cy(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 wIs extends om{constructor(){super(...arguments);Nr(this,"priority",110);Nr(this,"incompatibleTokens",["Y","R","q","Q","M","w","I","D","i","e","c","t","T"])}parse(n,r,a){const i=l=>l-1;switch(r){case"L":return cy(Ag(ly.month,n),i);case"LL":return cy(Ex(2,n),i);case"Lo":return cy(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 jIs(s,t,n){const r=So(s),a=Ntt(r,n)-t;return r.setDate(r.getDate()-a*7),r}class NIs extends om{constructor(){super(...arguments);Nr(this,"priority",100);Nr(this,"incompatibleTokens",["y","R","u","q","Q","M","L","I","d","D","i","t","T"])}parse(n,r,a){switch(r){case"w":return Ag(ly.week,n);case"wo":return a.ordinalNumber(n,{unit:"week"});default:return Ex(r.length,n)}}validate(n,r){return r>=1&&r<=53}set(n,r,a,i){return j1(jIs(n,a,i),i)}}function kIs(s,t){const n=So(s),r=wtt(n)-t;return n.setDate(n.getDate()-r*7),n}class SIs extends om{constructor(){super(...arguments);Nr(this,"priority",100);Nr(this,"incompatibleTokens",["y","Y","u","q","Q","M","L","w","d","D","e","c","t","T"])}parse(n,r,a){switch(r){case"I":return Ag(ly.week,n);case"Io":return a.ordinalNumber(n,{unit:"week"});default:return Ex(r.length,n)}}validate(n,r){return r>=1&&r<=53}set(n,r,a){return uT(kIs(n,a))}}const CIs=[31,28,31,30,31,30,31,31,30,31,30,31],AIs=[31,29,31,30,31,30,31,31,30,31,30,31];class EIs extends om{constructor(){super(...arguments);Nr(this,"priority",90);Nr(this,"subPriority",1);Nr(this,"incompatibleTokens",["Y","R","q","Q","w","I","D","i","e","c","t","T"])}parse(n,r,a){switch(r){case"d":return Ag(ly.date,n);case"do":return a.ordinalNumber(n,{unit:"date"});default:return Ex(r.length,n)}}validate(n,r){const a=n.getFullYear(),i=Mzt(a),l=n.getMonth();return i?r>=1&&r<=AIs[l]:r>=1&&r<=CIs[l]}set(n,r,a){return n.setDate(a),n.setHours(0,0,0,0),n}}class TIs extends om{constructor(){super(...arguments);Nr(this,"priority",90);Nr(this,"subpriority",1);Nr(this,"incompatibleTokens",["Y","R","q","Q","M","L","w","I","d","E","i","e","c","t","T"])}parse(n,r,a){switch(r){case"D":case"DD":return Ag(ly.dayOfYear,n);case"Do":return a.ordinalNumber(n,{unit:"date"});default:return Ex(r.length,n)}}validate(n,r){const a=n.getFullYear();return Mzt(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 Stt(s,t,n){var h,m,f,g;const r=a6(),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 MIs extends om{constructor(){super(...arguments);Nr(this,"priority",90);Nr(this,"incompatibleTokens",["D","i","e","c","t","T"])}parse(n,r,a){switch(r){case"E":case"EE":case"EEE":return a.day(n,{width:"abbreviated",context:"formatting"})||a.day(n,{width:"short",context:"formatting"})||a.day(n,{width:"narrow",context:"formatting"});case"EEEEE":return a.day(n,{width:"narrow",context:"formatting"});case"EEEEEE":return a.day(n,{width:"short",context:"formatting"})||a.day(n,{width:"narrow",context:"formatting"});case"EEEE":default:return a.day(n,{width:"wide",context:"formatting"})||a.day(n,{width:"abbreviated",context:"formatting"})||a.day(n,{width:"short",context:"formatting"})||a.day(n,{width:"narrow",context:"formatting"})}}validate(n,r){return r>=0&&r<=6}set(n,r,a,i){return n=Stt(n,a,i),n.setHours(0,0,0,0),n}}class PIs extends om{constructor(){super(...arguments);Nr(this,"priority",90);Nr(this,"incompatibleTokens",["y","R","u","q","Q","M","L","I","d","D","E","i","c","t","T"])}parse(n,r,a,i){const l=o=>{const c=Math.floor((o-1)/7)*7;return(o+i.weekStartsOn+6)%7+c};switch(r){case"e":case"ee":return cy(Ex(r.length,n),l);case"eo":return cy(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=Stt(n,a,i),n.setHours(0,0,0,0),n}}class IIs extends om{constructor(){super(...arguments);Nr(this,"priority",90);Nr(this,"incompatibleTokens",["y","R","u","q","Q","M","L","I","d","D","E","i","e","t","T"])}parse(n,r,a,i){const l=o=>{const c=Math.floor((o-1)/7)*7;return(o+i.weekStartsOn+6)%7+c};switch(r){case"c":case"cc":return cy(Ex(r.length,n),l);case"co":return cy(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=Stt(n,a,i),n.setHours(0,0,0,0),n}}function LIs(s,t){const n=So(s),r=aIs(n),a=t-r;return Am(n,a)}class RIs extends om{constructor(){super(...arguments);Nr(this,"priority",90);Nr(this,"incompatibleTokens",["y","Y","u","q","Q","M","L","w","d","D","E","e","c","t","T"])}parse(n,r,a){const i=l=>l===0?7:l;switch(r){case"i":case"ii":return Ex(r.length,n);case"io":return a.ordinalNumber(n,{unit:"day"});case"iii":return cy(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 cy(a.day(n,{width:"narrow",context:"formatting"}),i);case"iiiiii":return cy(a.day(n,{width:"short",context:"formatting"})||a.day(n,{width:"narrow",context:"formatting"}),i);case"iiii":default:return cy(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=LIs(n,a),n.setHours(0,0,0,0),n}}class DIs extends om{constructor(){super(...arguments);Nr(this,"priority",80);Nr(this,"incompatibleTokens",["b","B","H","k","t","T"])}parse(n,r,a){switch(r){case"a":case"aa":case"aaa":return a.dayPeriod(n,{width:"abbreviated",context:"formatting"})||a.dayPeriod(n,{width:"narrow",context:"formatting"});case"aaaaa":return a.dayPeriod(n,{width:"narrow",context:"formatting"});case"aaaa":default:return a.dayPeriod(n,{width:"wide",context:"formatting"})||a.dayPeriod(n,{width:"abbreviated",context:"formatting"})||a.dayPeriod(n,{width:"narrow",context:"formatting"})}}set(n,r,a){return n.setHours(ktt(a),0,0,0),n}}class FIs extends om{constructor(){super(...arguments);Nr(this,"priority",80);Nr(this,"incompatibleTokens",["a","B","H","k","t","T"])}parse(n,r,a){switch(r){case"b":case"bb":case"bbb":return a.dayPeriod(n,{width:"abbreviated",context:"formatting"})||a.dayPeriod(n,{width:"narrow",context:"formatting"});case"bbbbb":return a.dayPeriod(n,{width:"narrow",context:"formatting"});case"bbbb":default:return a.dayPeriod(n,{width:"wide",context:"formatting"})||a.dayPeriod(n,{width:"abbreviated",context:"formatting"})||a.dayPeriod(n,{width:"narrow",context:"formatting"})}}set(n,r,a){return n.setHours(ktt(a),0,0,0),n}}class OIs extends om{constructor(){super(...arguments);Nr(this,"priority",80);Nr(this,"incompatibleTokens",["a","b","t","T"])}parse(n,r,a){switch(r){case"B":case"BB":case"BBB":return a.dayPeriod(n,{width:"abbreviated",context:"formatting"})||a.dayPeriod(n,{width:"narrow",context:"formatting"});case"BBBBB":return a.dayPeriod(n,{width:"narrow",context:"formatting"});case"BBBB":default:return a.dayPeriod(n,{width:"wide",context:"formatting"})||a.dayPeriod(n,{width:"abbreviated",context:"formatting"})||a.dayPeriod(n,{width:"narrow",context:"formatting"})}}set(n,r,a){return n.setHours(ktt(a),0,0,0),n}}class zIs extends om{constructor(){super(...arguments);Nr(this,"priority",70);Nr(this,"incompatibleTokens",["H","K","k","t","T"])}parse(n,r,a){switch(r){case"h":return Ag(ly.hour12h,n);case"ho":return a.ordinalNumber(n,{unit:"hour"});default:return Ex(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 BIs extends om{constructor(){super(...arguments);Nr(this,"priority",70);Nr(this,"incompatibleTokens",["a","b","h","K","k","t","T"])}parse(n,r,a){switch(r){case"H":return Ag(ly.hour23h,n);case"Ho":return a.ordinalNumber(n,{unit:"hour"});default:return Ex(r.length,n)}}validate(n,r){return r>=0&&r<=23}set(n,r,a){return n.setHours(a,0,0,0),n}}class $Is extends om{constructor(){super(...arguments);Nr(this,"priority",70);Nr(this,"incompatibleTokens",["h","H","k","t","T"])}parse(n,r,a){switch(r){case"K":return Ag(ly.hour11h,n);case"Ko":return a.ordinalNumber(n,{unit:"hour"});default:return Ex(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 UIs extends om{constructor(){super(...arguments);Nr(this,"priority",70);Nr(this,"incompatibleTokens",["a","b","h","H","K","t","T"])}parse(n,r,a){switch(r){case"k":return Ag(ly.hour24h,n);case"ko":return a.ordinalNumber(n,{unit:"hour"});default:return Ex(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 qIs extends om{constructor(){super(...arguments);Nr(this,"priority",60);Nr(this,"incompatibleTokens",["t","T"])}parse(n,r,a){switch(r){case"m":return Ag(ly.minute,n);case"mo":return a.ordinalNumber(n,{unit:"minute"});default:return Ex(r.length,n)}}validate(n,r){return r>=0&&r<=59}set(n,r,a){return n.setMinutes(a,0,0),n}}class VIs extends om{constructor(){super(...arguments);Nr(this,"priority",50);Nr(this,"incompatibleTokens",["t","T"])}parse(n,r,a){switch(r){case"s":return Ag(ly.second,n);case"so":return a.ordinalNumber(n,{unit:"second"});default:return Ex(r.length,n)}}validate(n,r){return r>=0&&r<=59}set(n,r,a){return n.setSeconds(a,0),n}}class HIs extends om{constructor(){super(...arguments);Nr(this,"priority",30);Nr(this,"incompatibleTokens",["t","T"])}parse(n,r){const a=i=>Math.trunc(i*Math.pow(10,-r.length+3));return cy(Ex(r.length,n),a)}set(n,r,a){return n.setMilliseconds(a),n}}class GIs extends om{constructor(){super(...arguments);Nr(this,"priority",10);Nr(this,"incompatibleTokens",["t","T","x"])}parse(n,r){switch(r){case"X":return c4(l4.basicOptionalMinutes,n);case"XX":return c4(l4.basic,n);case"XXXX":return c4(l4.basicOptionalSeconds,n);case"XXXXX":return c4(l4.extendedOptionalSeconds,n);case"XXX":default:return c4(l4.extended,n)}}set(n,r,a){return r.timestampIsSet?n:Em(n,n.getTime()-SL(n)-a)}}class WIs extends om{constructor(){super(...arguments);Nr(this,"priority",10);Nr(this,"incompatibleTokens",["t","T","X"])}parse(n,r){switch(r){case"x":return c4(l4.basicOptionalMinutes,n);case"xx":return c4(l4.basic,n);case"xxxx":return c4(l4.basicOptionalSeconds,n);case"xxxxx":return c4(l4.extendedOptionalSeconds,n);case"xxx":default:return c4(l4.extended,n)}}set(n,r,a){return r.timestampIsSet?n:Em(n,n.getTime()-SL(n)-a)}}class KIs extends om{constructor(){super(...arguments);Nr(this,"priority",40);Nr(this,"incompatibleTokens","*")}parse(n){return Ezt(n)}set(n,r,a){return[Em(n,a*1e3),{timestampIsSet:!0}]}}class YIs extends om{constructor(){super(...arguments);Nr(this,"priority",20);Nr(this,"incompatibleTokens","*")}parse(n){return Ezt(n)}set(n,r,a){return[Em(n,a),{timestampIsSet:!0}]}}const ZIs={G:new fIs,y:new pIs,Y:new gIs,R:new xIs,u:new yIs,Q:new vIs,q:new bIs,M:new _Is,L:new wIs,w:new NIs,I:new SIs,d:new EIs,D:new TIs,E:new MIs,e:new PIs,c:new IIs,i:new RIs,a:new DIs,b:new FIs,B:new OIs,h:new zIs,H:new BIs,K:new $Is,k:new UIs,m:new qIs,s:new VIs,S:new HIs,X:new GIs,x:new WIs,t:new KIs,T:new YIs},XIs=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,QIs=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,JIs=/^'([^]*?)'?$/,eLs=/''/g,tLs=/\S/,sLs=/[a-zA-Z]/;function Ctt(s,t,n,r){var x,y,v,b;const a=rIs(),i=a.locale??ILe,l=a.firstWeekContainsDate??((y=(x=a.locale)==null?void 0:x.options)==null?void 0:y.firstWeekContainsDate)??1,o=a.weekStartsOn??((b=(v=a.locale)==null?void 0:v.options)==null?void 0:b.weekStartsOn)??0;if(t==="")return s===""?So(n):Em(n,NaN);const c={firstWeekContainsDate:l,weekStartsOn:o,locale:i},d=[new mIs],u=t.match(QIs).map(w=>{const S=w[0];if(S in GHe){const A=GHe[S];return A(w,i.formatLong)}return w}).join("").match(XIs),h=[];for(let w of u){Czt(w)&&WHe(w,t,s),Szt(w)&&WHe(w,t,s);const S=w[0],A=ZIs[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(sLs))throw new RangeError("Format string contains an unescaped latin alphabet character `"+S+"`");if(w==="''"?w="'":S==="'"&&(w=nLs(w)),s.indexOf(w)===0)s=s.slice(w.length);else return Em(n,NaN)}}if(s.length>0&&tLs.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 nLs(s){return s.match(JIs)[1].replace(eLs,"'")}function D4(s){return+So(s)i-l);return n>=r&&n<=a}function Y4e(s,t){return Am(s,-t)}function gv(s,t){const r=uLs(s);let a;if(r.date){const c=hLs(r.date,2);a=mLs(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=fLs(r.time),isNaN(l)))return new Date(NaN);if(r.timezone){if(o=pLs(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 Lce={dateTimeDelimiter:/[T ]/,timeZoneDelimiter:/[Z ]/i,timezone:/([Z+-].*)$/},lLs=/^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/,cLs=/^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/,dLs=/^([+-])(\d{2})(?::?(\d{2}))?$/;function uLs(s){const t={},n=s.split(Lce.dateTimeDelimiter);let r;if(n.length>2)return t;if(/:/.test(n[0])?r=n[0]:(t.date=n[0],r=n[1],Lce.timeZoneDelimiter.test(t.date)&&(t.date=s.split(Lce.timeZoneDelimiter)[0],r=s.substr(t.date.length,s.length))),r){const a=Lce.timezone.exec(r);a?(t.time=r.replace(a[1],""),t.timezone=a[1]):t.time=r}return t}function hLs(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 mLs(s,t){if(t===null)return new Date(NaN);const n=s.match(lLs);if(!n)return new Date(NaN);const r=!!n[4],a=NZ(n[1]),i=NZ(n[2])-1,l=NZ(n[3]),o=NZ(n[4]),c=NZ(n[5])-1;if(r)return bLs(t,o,c)?gLs(t,o,c):new Date(NaN);{const d=new Date(0);return!yLs(t,i,l)||!vLs(t,a)?new Date(NaN):(d.setUTCFullYear(t,i,Math.max(a,l)),d)}}function NZ(s){return s?parseInt(s):1}function fLs(s){const t=s.match(cLs);if(!t)return NaN;const n=e7e(t[1]),r=e7e(t[2]),a=e7e(t[3]);return _Ls(n,r,a)?n*TLe+r*ELe+a*1e3:NaN}function e7e(s){return s&&parseFloat(s.replace(",","."))||0}function pLs(s){if(s==="Z")return 0;const t=s.match(dLs);if(!t)return 0;const n=t[1]==="+"?-1:1,r=parseInt(t[2]),a=t[3]&&parseInt(t[3])||0;return wLs(r,a)?n*(r*TLe+a*ELe):NaN}function gLs(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 xLs=[31,null,31,30,31,30,31,31,30,31,30,31];function Pzt(s){return s%400===0||s%4===0&&s%100!==0}function yLs(s,t,n){return t>=0&&t<=11&&n>=1&&n<=(xLs[t]||(Pzt(s)?29:28))}function vLs(s,t){return t>=1&&t<=(Pzt(s)?366:365)}function bLs(s,t,n){return t>=1&&t<=53&&n>=0&&n<=6}function _Ls(s,t,n){return s===24?t===0&&n===0:n>=0&&n<60&&t>=0&&t<60&&s>=0&&s<25}function wLs(s,t){return t>=0&&t<=59}function t7e(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=nIs(i);return n.setMonth(t,Math.min(a,l)),n}function Izt(s,t){const n=So(s);return n.setHours(t),n}function Lzt(s,t){const n=So(s);return n.setMinutes(t),n}function Myt(s,t){const n=So(s);return isNaN(+n)?Em(s,NaN):(n.setFullYear(t),n)}function i8(s,t){return Ev(s,-t)}const jLs=()=>{const{user:s}=bs(),t=Xn(),[n,r]=j.useState([]),[a,i]=j.useState(0),[l,o]=j.useState(!1),[c,d]=j.useState(null),u=j.useRef(null);j.useEffect(()=>{u.current=c},[c]),j.useEffect(()=>{if(!s)return;const x=`notification_last_read_${s.id}`,y=localStorage.getItem(x);y&&!u.current&&(u.current=y,d(y));const v=`nb_cache_${s.id}`,b=60*1e3,w=async()=>{try{const P=sessionStorage.getItem(v);if(P){const R=JSON.parse(P);if(R.ts&&Date.now()-R.ts{r(E);const I=u.current?new Date(u.current):null,P=E.filter(R=>I?new Date(R.created_at)>I:!0);i(P.length)};w();const 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(v,JSON.stringify({ts:Date.now(),data:D}))}catch{}return D});const P=u.current?new Date(u.current):null;(!P||new Date(I.created_at)>P)&&i(R=>R+1),Notification.permission==="granted"&&new Notification(I.title,{body:I.body,icon:"/favicon.ico"})}).subscribe();return()=>{q.removeChannel(A)}},[s]);const h=x=>{const y=x.toLowerCase();return y.includes("community")||y.includes("post")?eo:y.includes("academy")||y.includes("video")?ua:y.includes("template")?yd:y.includes("event")?Ta:y.includes("newsletter")?QN:y.includes("brokerage")?kx:y.includes("swag")||y.includes("social")?ul:y.includes("toolbox")||y.includes("tool")?L4:y.includes("brief")?Nn:eo},m=x=>{o(!1),x.url&&x.url!=="/"&&t(x.url)},f=()=>{if(!s)return;const x=new Date().toISOString(),y=`notification_last_read_${s.id}`;localStorage.setItem(y,x),d(x),i(0)},g=x=>{o(x),x&&a>0&&f()};return e.jsxs($u,{open:l,onOpenChange:g,children:[e.jsx(Uu,{asChild:!0,children:e.jsxs($,{variant:"ghost",size:"icon",className:"relative",children:[e.jsx(Uy,{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(Au,{align:"end",className:"w-80",children:[e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b",children:[e.jsx("span",{className:"font-semibold",children:"Notifications"}),n.length>0&&e.jsx($,{variant:"ghost",size:"sm",className:"text-xs h-6",onClick:f,children:"Mark all read"})]}),e.jsx(uo,{className:"h-[300px]",children:n.length===0?e.jsx("div",{className:"p-4 text-center text-muted-foreground text-sm",children:"No notifications yet"}):n.map(x=>{const y=h(x.title);return e.jsxs(ja,{className:"group flex items-start gap-3 p-3 cursor-pointer data-[highlighted]:bg-accent data-[highlighted]:text-accent-foreground",onClick:()=>m(x),children:[e.jsx("div",{className:"flex-shrink-0 mt-0.5",children:e.jsx(y,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"flex flex-col gap-1 min-w-0",children:[e.jsx("span",{className:"font-medium text-sm",children:x.title}),e.jsx("span",{className:"text-xs text-muted-foreground line-clamp-2 group-data-[highlighted]:text-accent-foreground/80",children:x.body}),e.jsx("span",{className:"text-xs text-muted-foreground group-data-[highlighted]:text-accent-foreground/80",children:hu(new Date(x.created_at),{addSuffix:!0})})]})]},x.id)})})]})]})};function NLs(s){return s!=null&&s.length?s.find(t=>t.is_active&&t.mls_provider_id&&!t.no_mls_mode)||s[0]:null}function ng(){const{user:s}=bs(),{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 NLs(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 LLe(s=!0){const{user:t}=bs(),{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 kLs="coaching_access";function Rzt(){const{user:s,loading:t,isAdmin:n,isCoach:r}=bs(),{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",kLs).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 Fu=q,AEe=[{value:"contract",label:"Under contract"},{value:"inspection",label:"Inspection / due diligence"},{value:"closing",label:"Closing"},{value:"closed",label:"Closed"}];function KHe(s){return s.total_items===0?"not_started":s.rejected_items>0?"changes_requested":s.approved_items>=s.total_items?"compliant":"in_review"}const Dzt={not_started:"Not started",in_review:"In review",changes_requested:"Changes requested",compliant:"Compliant"};function Att(){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 Fu.from("brokerage_transaction_admins").select("brokerage_id").eq("user_id",s.user.id);if(n)throw n;return t||[]}})}function SLs(s){return st({queryKey:["transaction-admins",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await Fu.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 Fu.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 CLs(){const s=Wt();return mt({mutationFn:async({brokerageId:t,userId:n})=>{const{error:r}=await Fu.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 ALs(){const s=Wt();return mt({mutationFn:async({id:t})=>{const{error:n}=await Fu.from("brokerage_transaction_admins").delete().eq("id",t);if(n)throw n},onSuccess:(t,n)=>s.invalidateQueries({queryKey:["transaction-admins",n.brokerageId]})})}function ELs(s){return st({queryKey:["compliance-settings",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await Fu.from("brokerage_compliance_settings").select("*").eq("brokerage_id",s).maybeSingle();if(n)throw n;return t}})}function TLs(){const s=Wt();return mt({mutationFn:async t=>{const{error:n}=await Fu.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 Fzt(s){return st({queryKey:["compliance-templates",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await Fu.from("brokerage_checklist_templates").select("*").eq("brokerage_id",s).order("created_at",{ascending:!0});if(n)throw n;return t||[]}})}function MLs(s){return st({queryKey:["compliance-template-items",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await Fu.from("brokerage_checklist_template_items").select("*").eq("template_id",s).order("sort_order",{ascending:!0});if(n)throw n;return t||[]}})}function PLs(){const s=Wt();return mt({mutationFn:async t=>{if(t.id){const{error:a}=await Fu.from("brokerage_checklist_templates").update(t).eq("id",t.id);if(a)throw a;return t.id}const{data:n,error:r}=await Fu.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 ILs(){const s=Wt();return mt({mutationFn:async({id:t})=>{const{error:n}=await Fu.from("brokerage_checklist_templates").delete().eq("id",t);if(n)throw n},onSuccess:(t,n)=>s.invalidateQueries({queryKey:["compliance-templates",n.brokerageId]})})}function LLs(){const s=Wt();return mt({mutationFn:async t=>{if(t.id){const{error:r}=await Fu.from("brokerage_checklist_template_items").update(t).eq("id",t.id);if(r)throw r;return}const{error:n}=await Fu.from("brokerage_checklist_template_items").insert(t);if(n)throw n},onSuccess:(t,n)=>s.invalidateQueries({queryKey:["compliance-template-items",n.template_id]})})}function RLs(){const s=Wt();return mt({mutationFn:async({id:t})=>{const{error:n}=await Fu.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 Ett(s){return st({queryKey:["compliance-deals",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await Fu.rpc("get_brokerage_compliance_deals",{_brokerage_id:s});if(n)throw n;return t||[]}})}function Ozt(s){return st({queryKey:["deal-compliance-items",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await Fu.from("deal_compliance_items").select("*").eq("deal_id",s).order("sort_order",{ascending:!0});if(n)throw n;return t||[]}})}function DLs(s){return st({queryKey:["deal-compliance-events",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await Fu.from("deal_compliance_events").select("*").eq("deal_id",s).order("created_at",{ascending:!1}).limit(200);if(n)throw n;return t||[]}})}async function RLe(s){var n;const{data:t}=await q.auth.getUser();await Fu.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 FLs(){const s=Wt();return mt({mutationFn:async({item:t,status:n,note:r})=>{var l;const{data:a}=await q.auth.getUser(),{error:i}=await Fu.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 RLe({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 OLs(){const s=Wt();return mt({mutationFn:async({dealId:t,brokerageId:n,templateId:r,deal:a})=>{const{data:i,error:l}=await Fu.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 Fu.from("deal_compliance_items").insert(c);if(d)throw d;await RLe({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 zLs(s){return st({queryKey:["deal-compliance-files",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await Fu.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 BLs(){const s=Wt();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 Fu.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 Fu.from("deal_files").update({is_current:!1}).eq("compliance_item_id",t.id);const{error:u}=await Fu.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 Fu.from("deal_compliance_items").update({status:"submitted",review_note:null,reviewed_at:null,reviewed_by:null}).eq("id",t.id),await RLe({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 Pyt(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 $Ls(s){return st({queryKey:["deal-compliance-messages",s],enabled:!!s,refetchInterval:3e4,queryFn:async()=>{const{data:t,error:n}=await Fu.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 Fu.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 ULs(){const s=Wt();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 Fu.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 qLs(){const s=Wt();return mt({mutationFn:async({dealId:t,senderRole:n})=>{const{error:r}=await Fu.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 VLs(s){return st({queryKey:["brokerage-agent-roster",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await Fu.from("profiles").select("id, name, email, avatar_url").eq("brokerage_id",s).order("name",{ascending:!0});if(n)throw n;return t||[]}})}function HLs(s){return st({queryKey:["agent-pipeline-stages",s],enabled:!!s,queryFn:async()=>{const t=async()=>{const{data:r,error:a}=await Fu.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 Fu.rpc("initialize_deal_pipeline_stages",{p_user_id:s});r||(n=await t())}return n}})}function GLs(){const s=Wt();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 Fu.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 Fu.rpc("ensure_deal_compliance",{_deal_id:i})}catch(l){console.error("ensure_deal_compliance failed",l)}return await RLe({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 DLe=[{id:"home",label:"Home",icon:WI,route:"/dashboard",accent:"nav-home"},{id:"crm",label:"CRM",icon:Jo,description:"Contacts and follow-up",accent:"nav-crm"},{id:"deals",label:"Deals",icon:l2,description:"Pipeline, transactions and tasks",accent:"nav-deals"},{id:"listings",label:"Listings",icon:ji,description:"Win and market listings",accent:"nav-listings"},{id:"marketing",label:"Marketing",icon:gm,description:"Content, email and video",accent:"nav-marketing"},{id:"websites",label:"Websites",icon:dl,description:"Your site and add-ons",accent:"nav-websites"},{id:"academy",label:"Learn",icon:af,description:"Training, programs and coaching",accent:"nav-academy"},{id:"events",label:"Events",icon:t7,route:"/events",accent:"nav-events"},{id:"apps",label:"Apps",icon:Fj,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:Oq,description:"Your brokerage, teams and recruiting",accent:"nav-brokerage",visible:s=>!s.isAdmin&&(!!s.brokerageId||s.isBrokerageManager||s.isOnTeam)},{id:"more",label:"More",icon:l_,description:"Community, marketplace and help",accent:"nav-more"}],K1=s=>t=>t.hasPermission(s),WLs=[{id:"mission-control",label:"Mission Control",route:"/mission-control",icon:E4,description:"Your daily relationship command center",primaryCategory:"crm",section:"Overview",visible:K1("contacts"),searchKeywords:["agent os","mission control","dashboard"],displayOrder:10},{id:"client-portals",label:"Client Portals",route:"/mission-control/client-portals",icon:Nn,description:"Private portals for buyers and sellers",primaryCategory:"crm",section:"Overview",searchKeywords:["portal","client portal"],displayOrder:20},{id:"contacts",label:"All Contacts",route:"/mission-control/contacts",icon:Yn,description:"Every contact in your database",primaryCategory:"crm",section:"Contacts",visible:K1("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:K1("contacts"),searchKeywords:["relationship","scorecard","report"],displayOrder:40},{id:"sphere-gaps",label:"Sphere Gaps",route:"/mission-control/sphere-gaps",icon:Jq,description:"Find missing info across your sphere",primaryCategory:"crm",section:"Contacts",visible:K1("contacts"),searchKeywords:["gaps","missing data"],displayOrder:50},{id:"sent-emails",label:"Sent Emails",route:"/mission-control/sent-emails",icon:Kr,description:"History of everything you have sent",primaryCategory:"crm",section:"Contacts",visible:K1("contacts"),searchKeywords:["sent","email history"],displayOrder:60},{id:"connect-page",label:"Connect Page",route:"/mission-control/connect-page",icon:Wd,description:"Your shareable intake and link page",primaryCategory:"crm",section:"Contacts",visible:K1("contacts"),searchKeywords:["connect","link in bio","intake"],displayOrder:70},{id:"property-intelligence",label:"Property Intelligence",route:"/mission-control/property-intelligence",icon:ji,description:"Enrich property data for your contacts",primaryCategory:"crm",section:"Contacts",visible:s=>s.isAdmin,searchKeywords:["property","zillow","enrichment","intelligence","home value"],displayOrder:75},{id:"touchplans",label:"TouchPlans",route:"/mission-control/plans",icon:Wc,description:"Structured touch plans for your people",primaryCategory:"crm",section:"Follow-Up",visible:K1("contacts"),searchKeywords:["touch plan","follow up plan"],displayOrder:80},{id:"smart-drips",label:"Smart Drips",route:"/mission-control/smart-drips",icon:eg,description:"Automated drip campaigns that pause when they reply",primaryCategory:"crm",section:"Follow-Up",badge:"beta",searchKeywords:["drip","automation","campaign"],displayOrder:90},{id:"email-templates",label:"Email Templates",route:"/email-campaigns/templates",icon:mn,description:"Reusable email templates",primaryCategory:"crm",section:"Follow-Up",searchKeywords:["email template"],displayOrder:100},{id:"signals",label:"Signals",route:"/mission-control/signals",icon:Wq,description:"Buying and selling signals from your database",primaryCategory:"crm",section:"Follow-Up",searchKeywords:["signals","intent","hot leads"],displayOrder:110},{id:"popbys",label:"Popbys",route:"/mission-control/popbys",icon:ul,description:"Plan and log in-person pop-bys",primaryCategory:"crm",section:"Follow-Up",visible:K1("popbys"),searchKeywords:["pop by","gifts","drop off"],displayOrder:120},{id:"pipeline",label:"Deal Pipeline",route:"/mission-control/pipeline",icon:l2,description:"Track every deal from lead to close",primaryCategory:"deals",section:"Pipeline",visible:K1("pipeline"),searchKeywords:["pipeline","deals","kanban"],displayOrder:130},{id:"transactions",label:"Transactions",route:"/mission-control/transactions",icon:KN,description:"Closed and in-progress transactions",primaryCategory:"deals",section:"Pipeline",visible:K1("pipeline"),searchKeywords:["transactions","closings"],displayOrder:140},{id:"forms",label:"Forms Library",route:"/mission-control/forms",icon:c_,description:"Your PDF form templates, filled from any deal",primaryCategory:"deals",section:"Pipeline",visible:K1("pipeline"),searchKeywords:["forms","pdf","templates","contracts","documents"],displayOrder:145},{id:"tasks",label:"Tasks",route:"/mission-control/tasks",icon:Vj,description:"Everything on your plate today",primaryCategory:"deals",section:"Pipeline",visible:K1("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:K1("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:ji,description:"Publish and browse member listings",primaryCategory:"listings",section:"Manage Listings",visible:K1("listings"),searchKeywords:["listings","exchange","my listings"],displayOrder:10},{id:"listing-presentation-studio",label:"Listing Presentation Studio",route:"/apps/listing-presentation-studio",icon:bb,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:a2,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:KN,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:tV,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:x1,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:x1,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:QN,description:"Send a branded monthly newsletter",primaryCategory:"marketing",section:"Email & Mail",badge:"new",toolId:"newsletter-pro",searchKeywords:["newsletter","email marketing"],displayOrder:50},{id:"mass-emails",label:"Mass Emails",route:"/admin/email-campaigns",icon:mn,description:"Email your whole database at once",primaryCategory:"marketing",section:"Email & Mail",toolId:"mass-emails",searchKeywords:["mass email","campaign","blast"],displayOrder:60},{id:"direct-mail",label:"Mail Studio (beta)",route:"/mission-control/direct-mail",icon:Kr,description:"Postcards & letters via your thanks.io account",primaryCategory:"marketing",section:"Email & Mail",visible:s=>s.isAdmin,toolId:"direct-mail",searchKeywords:["postcard","direct mail","farming","letter","thanks.io","mail studio"],displayOrder:70},{id:"card-studio",label:"Card Studio",route:"/mission-control/card-studio",icon:ul,description:"Send digital celebration cards",primaryCategory:"marketing",section:"Email & Mail",toolId:"card-studio",searchKeywords:["cards","birthday","anniversary"],displayOrder:80},{id:"video-library",label:"Video Library",route:"/mission-control/video-library",icon:ua,description:"All of your recorded videos",primaryCategory:"marketing",section:"Video",visible:K1("videos"),searchKeywords:["videos","library"],displayOrder:90},{id:"quickvid",label:"QuickVid",route:"/mission-control/video/record",icon:ua,description:"Record a personalized video in seconds",primaryCategory:"marketing",section:"Video",toolId:"quickvid",searchKeywords:["record video","video email","screen record"],displayOrder:100},{id:"reelflow",label:"ReelFlow",route:"/admin/beta/homereel",icon: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:qg,description:"Capture leads with focused landing pages",primaryCategory:"marketing",section:"Lead Capture",toolId:"landing-pages",searchKeywords:["landing page","lead capture","funnel"],displayOrder:120},{id:"buyer-match",label:"Buyer Match",route:"/mission-control/buyer-match",icon:vb,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:Wd,description:"Your digital business card",primaryCategory:"marketing",section:"Lead Capture",toolId:"smart-card",searchKeywords:["digital card","business card","qr"],displayOrder:130},{id:"my-websites",label:"My Websites",route:"/websites",icon:Qf,description:"Every site you can edit: yours, your company and your team",primaryCategory:"websites",section:"My Website",visible:s=>s.hasLeadSite||s.isBrokerageManager||s.isTeamLeader||s.isAdmin,searchKeywords:["websites","my sites","edit website","company site","team site"],displayOrder:1},{id:"get-my-website",label:"Get My Website",route:"/get-my-website",icon:dl,description:"Claim the free site your brokerage offers",primaryCategory:"websites",section:"My Website",visible:s=>!s.hasLeadSite&&s.hasFreeSiteOffer,searchKeywords:["website","claim site","free site"],displayOrder:5},{id:"need-a-website",label:"Need a Website",route:"/need-a-website",icon:dl,description:"Request your free beta agent website",primaryCategory:"websites",section:"My Website",badge:"beta",visible:s=>!s.hasLeadSite&&!s.hasFreeSiteOffer,searchKeywords:["website","need a website","beta site","free website"],displayOrder:6},{id:"view-site",label:"View Site",route:s=>s.siteUrl||"#",icon:Ca,description:"Open your live website",primaryCategory:"websites",section:"My Website",external:!0,openInNewTab:!0,visible:s=>s.hasLeadSite&&!!s.siteUrl,searchKeywords:["view site","live site"],displayOrder:10},{id:"edit-website",label:"Edit My Site",route:s=>`/my-website/${s.leadSiteId}/edit`,icon: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:ji,description:"Your company site: agents, listings, recruiting and leads",primaryCategory:"websites",section:"My Website",badge:"new",visible:s=>s.isBrokerageManager||s.isAdmin,searchKeywords:["website","company site","brokerage site","agents","roster"],displayOrder:24},{id:"team-website",label:"Edit Team Site",route:"/team/website",icon: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:x1,description:"The mobile-first agent console",primaryCategory:"websites",section:"My Website",visible:s=>s.hasLeadSite,searchKeywords:["mobile","command"],displayOrder:60},{id:"website-apps",label:"Website Apps",route:"/website-apps",icon:Nn,description:"Lead magnets, video greeter and more",primaryCategory:"websites",section:"Website Add-Ons",toolId:"website-apps",searchKeywords:["widgets","lead magnet","video greeter"],displayOrder:70},{id:"levelup-u",label:"LevelUp U",route:"/levelup-u",icon: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:Xf,description:"On-demand training videos",primaryCategory:"academy",section:"Learn",searchKeywords:["academy","videos","training"],displayOrder:20},{id:"toolbox",label:"Toolbox",route:"/toolbox",icon:L4,description:"Scripts, checklists and downloads",primaryCategory:"academy",section:"Learn",searchKeywords:["toolbox","scripts","downloads"],displayOrder:30},{id:"events",label:"Events",route:"/events",icon:t7,description:"Live trainings and member events",primaryCategory:"events",section:"Events",searchKeywords:["events","live","webinar"],displayOrder:10},{id:"programs",label:"Programs",route:"/programs",icon:qg,description:"Cohort programs like Reel Estate 90",primaryCategory:"academy",section:"Programs & Coaching",searchKeywords:["programs","reel estate 90","cohort"],displayOrder:50},{id:"coaching",label:"Coaching",route:"/coaching",icon: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:eo,description:"Talk shop with other LevelUp members",primaryCategory:"more",section:"Community",badgeKey:"community",searchKeywords:["community","forum","posts"],displayOrder:10},{id:"wishlist",label:"Wishlist",route:"/wishlist",icon:JS,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:Fr,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:sV,description:"Print and promo products",primaryCategory:"more",section:"The Goods",badge:"new",visible:s=>s.isMarketplaceEnabled,searchKeywords:["marketplace","shop","print"],displayOrder:40},{id:"reward-store",label:"Reward Store",route:"/reward-store",icon:Kl,description:"Spend the points you have earned",primaryCategory:"more",section:"The Goods",searchKeywords:["rewards","points","store"],displayOrder:50},{id:"refer-friends",label:"Refer & Earn",route:"/refer-friends",icon:ul,description:"Invite agents and earn rewards",primaryCategory:"more",section:"The Goods",searchKeywords:["referral","refer a friend"],displayOrder:60},{id:"support",label:"Support",route:"/support",icon:zq,description:"Get help from the LevelUp team",primaryCategory:"more",section:"Help & Services",searchKeywords:["support","help","ticket"],displayOrder:70},{id:"additional-services",label:"Additional Services",route:"/additional-services",icon:Nn,description:"Done-for-you services from LevelUp",primaryCategory:"more",section:"Help & Services",searchKeywords:["services","done for you"],displayOrder:80},{id:"integrations",label:"Integrations",route:"/mission-control/integrations",icon:JN,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:JN,description:"Install the LevelUp Chrome extension",primaryCategory:"more",section:"Help & Services",searchKeywords:["extension","chrome"],displayOrder:100},{id:"attract",label:"LevelUp Attract",route:"/attract",icon:Nn,description:"Relationship-first attraction coach",primaryCategory:"more",section:"Help & Services",badge:"beta",visible:s=>s.email==="jeremy@relevelup.com",searchKeywords:["attract","recruiting"],displayOrder:110},{id:"admin-dashboard",label:"Admin Dashboard",route:"/admin",icon:pc,description:"Manage members, content and settings",primaryCategory:"more",section:"Admin",visible:s=>s.isAdmin,searchKeywords:["admin"],displayOrder:120},{id:"agent-activation",label:"Agent Activation",route:"/admin/agent-activation",icon:eg,description:"Wake up dormant agents with branded email sequences",primaryCategory:"more",section:"Admin",visible:s=>s.isAdmin,searchKeywords:["activation","dormant","adoption","agents"],displayOrder:121},{id:"my-brokerage",label:"My Brokerage",route:"/my-brokerage",icon:ji,description:"Your brokerage hub",primaryCategory:"brokerage",section:"My Brokerage",visible:s=>!!s.brokerageId&&!s.isAdmin,searchKeywords:["brokerage"],displayOrder:130},{id:"help-board",label:"Help Board",route:"/brokerage/help-board",icon:s4,description:"Ask for showing and open house coverage",primaryCategory:"brokerage",section:"My Brokerage",visible:s=>!!s.brokerageId&&!s.isAdmin,searchKeywords:["help board","coverage"],displayOrder:140},{id:"brokerage-content",label:"Brokerage Content",route:"/brokerage-content",icon:Xf,description:"Content shared by your brokerage",primaryCategory:"brokerage",section:"My Brokerage",visible:s=>!!s.brokerageId&&!s.isAdmin,searchKeywords:["brokerage content"],displayOrder:150},{id:"team-hub",label:"Team Hub",route:"/team",icon: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:zg,description:"Onboarding checklists, documents and agent notes",primaryCategory:"brokerage",section:"Manage Brokerage",badge:"new",visible:s=>s.isBrokerageManager&&!s.isAdmin,searchKeywords:["onboarding","checklist","documents","new agent"],displayOrder:195},{id:"brokerage-operations",label:"Operations",route:"/brokerage/operations",icon:WI,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:Ew,description:"Commission plans, company dollar and fee statements",primaryCategory:"brokerage",section:"Manage Brokerage",badge:"new",visible:s=>(s.isBrokerageManager||s.isTransactionAdmin)&&!s.isAdmin,searchKeywords:["commission","split","cap","fees","agent plans"],displayOrder:195},{id:"brokerage-transactions",label:"Transactions & Compliance",route:"/brokerage/transactions",icon:zg,description:"Review agent files, required documents and closing compliance",primaryCategory:"brokerage",section:"Manage Brokerage",badge:"new",visible:s=>(s.isBrokerageManager||s.isTransactionAdmin)&&!s.isAdmin,searchKeywords:["compliance","transactions","documents","closing","paperless"],displayOrder:196},{id:"brokerage-vendors",label:"Vendors",route:"/brokerage/vendors",icon:vb,description:"Preferred vendor directory",primaryCategory:"brokerage",section:"Manage Brokerage",visible:s=>s.isBrokerageManager&&!s.isAdmin,searchKeywords:["vendors"],displayOrder:200},{id:"brokerage-forms",label:"Brokerage Forms",route:"/brokerage/forms",icon:Jr,description:"Official forms your agents can use",primaryCategory:"brokerage",section:"Manage Brokerage",badge:"new",visible:s=>s.isBrokerageManager&&!s.isAdmin,searchKeywords:["forms","pdf","documents"],displayOrder:205},{id:"brokerage-resources",label:"Brokerage Resources",route:"/brokerage-resources",icon:kx,description:"Documents and links for your agents",primaryCategory:"brokerage",section:"Manage Brokerage",visible:s=>s.isBrokerageManager&&!s.isAdmin,searchKeywords:["resources"],displayOrder:210},{id:"my-partnership",label:"My Package",route:"/my-partnership",icon:Nn,description:"What is included in your partnership package",primaryCategory:"more",section:"Account",visible:s=>s.isPartnershipMember,searchKeywords:["partnership","package","upgrade","exp luxury"],displayOrder:5},{id:"coaching-onboarding",label:"Coaching Onboarding",route:"/coaching/onboarding",icon:zg,description:"Tell your coach about your business before session one",primaryCategory:"academy",section:"Coaching",visible:s=>s.hasCoachingOnboarding,searchKeywords:["coaching","onboarding","intake"],displayOrder:45}];function zzt(s,t){return typeof s.route=="function"?s.route(t):s.route}function Bzt(){const{user:s,isAdmin:t,isBrokerageManager:n,isCoach:r,brokerageId:a}=bs(),{hasPermission:i}=Aae(),{isInnerCircleEnabled:l,isMarketplaceEnabled:o,isFeatureEnabled:c}=Tae(),{hasAccess:d}=xLe(),{data:u,teams:h}=zw(),{leadSite:m,hasLeadSite:f,siteUrl:g}=ng(),{hasOffer:x}=LLe(!f),y=_C(),{hasAccess:v}=Rzt(),{data:b}=Att(),w=Wt(),{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:y.isMember,hasCoachingOnboarding:y.isMember&&!!((X=y.pkg)!=null&&X.includes_coaching),hasCoachingAccess:!!v||y.isMember&&!!((ae=y.pkg)!=null&&ae.includes_coaching)}},[t,n,b,r,u,h,S,a,i,l,o,c,d,f,m,x,g,s==null?void 0:s.email,y.isMember,y.pkg,v]),R=j.useMemo(()=>WLs.filter(X=>X.visible?X.visible(P):!0).map(X=>{if(!y.isRestricted)return X;const ae=kCs(X);return!ae||y.hasFeature(ae)?X:{...X,locked:!0,route:`/upgrade/${ae}`}}).sort((X,ae)=>X.displayOrder-ae.displayOrder),[P,y.isRestricted,y.features]),D=j.useMemo(()=>DLe.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=[],ne=new Map;for(const te of ae)ne.has(te.section)||(ne.set(te.section,[]),le.push(te.section)),ne.get(te.section).push(te);return{id:X.id,label:X.label,sections:le.map(te=>({title:te,items:ne.get(te)}))}}),[R,D]),U=j.useMemo(()=>new Map(O.map(X=>[X.id,X])),[O]),W=X=>X.toolId||`nav:${X.id}`,V=X=>E.has(W(X));return{ctx:P,categories:O,railCategories:D,categoryMap:U,destinations:R,favorites:E,isFavorite:V,favoritesFor:X=>R.filter(ae=>ae.primaryCategory===X&&V(ae)),favoriteKey:W,toggleFavorite:X=>I.mutate(X),searchDestinations:X=>{const ae=X.trim().toLowerCase();return ae?R.map(ne=>{const te=ne.label.toLowerCase(),J=(ne.description||"").toLowerCase(),ce=(ne.searchKeywords||[]).join(" ").toLowerCase();let _e=0;return te===ae?_e=100:te.startsWith(ae)?_e=80:te.includes(ae)?_e=60:ce.includes(ae)?_e=40:J.includes(ae)?_e=20:ne.section.toLowerCase().includes(ae)&&(_e=10),_e&&V(ne)&&(_e+=5),{d:ne,score:_e}}).filter(ne=>ne.score>0).sort((ne,te)=>te.score-ne.score).map(ne=>ne.d):[]},routeFor:X=>zzt(X,P)}}var Iyt=1,KLs=.9,YLs=.8,ZLs=.17,s7e=.1,n7e=.999,XLs=.9999,QLs=.99,JLs=/[\\\/_+.#"@\[\(\{&]/,e6s=/[\\\/_+.#"@\[\(\{&]/g,t6s=/[\s-]/,$zt=/[\s-]/g;function YHe(s,t,n,r,a,i,l){if(i===t.length)return a===s.length?Iyt:QLs;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=YHe(s,t,n,r,d+1,i+1,l),h>u&&(d===a?h*=Iyt:JLs.test(s.charAt(d-1))?(h*=YLs,f=s.slice(a,d-1).match(e6s),f&&a>0&&(h*=Math.pow(n7e,f.length))):t6s.test(s.charAt(d-1))?(h*=KLs,g=s.slice(a,d-1).match($zt),g&&a>0&&(h*=Math.pow(n7e,g.length))):(h*=ZLs,a>0&&(h*=Math.pow(n7e,d-a))),s.charAt(d)!==t.charAt(i)&&(h*=XLs)),(hh&&(h=m*s7e)),h>u&&(u=h),d=n.indexOf(c,d+1);return l[o]=u,u}function Lyt(s){return s.toLowerCase().replace($zt," ")}function s6s(s,t,n){return s=n&&n.length>0?`${s+" "+n.join(" ")}`:s,YHe(s,t,Lyt(s),Lyt(t),0,0,{})}var kZ='[cmdk-group=""]',r7e='[cmdk-group-items=""]',n6s='[cmdk-group-heading=""]',Uzt='[cmdk-item=""]',Ryt=`${Uzt}:not([aria-disabled="true"])`,ZHe="cmdk-item-select",hU="data-value",r6s=(s,t,n)=>s6s(s,t,n),qzt=j.createContext(void 0),zae=()=>j.useContext(qzt),Vzt=j.createContext(void 0),Ttt=()=>j.useContext(Vzt),Hzt=j.createContext(void 0),Gzt=j.forwardRef((s,t)=>{let n=mU(()=>{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=mU(()=>new Set),a=mU(()=>new Map),i=mU(()=>new Map),l=mU(()=>new Set),o=Wzt(s),{label:c,children:d,value:u,onValueChange:h,filter:m,shouldFilter:f,loop:g,disablePointerSelection:x=!1,vimBindings:y=!0,...v}=s,b=uy(),w=uy(),S=uy(),A=j.useRef(null),E=p6s();V7(()=>{if(u!==void 0){let J=u.trim();n.current.value=J,I.emit()}},[u]),V7(()=>{E(6,W)},[]);let I=j.useMemo(()=>({subscribe:J=>(l.current.add(J),()=>l.current.delete(J)),snapshot:()=>n.current,setState:(J,ce,_e)=>{var he,ue,ve,Ee;if(!Object.is(n.current[J],ce)){if(n.current[J]=ce,J==="search")U(),D(),E(1,O);else if(J==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let Se=document.getElementById(S);Se?Se.focus():(he=document.getElementById(b))==null||he.focus()}if(E(7,()=>{var Se;n.current.selectedItemId=(Se=V())==null?void 0:Se.id,I.emit()}),_e||E(5,W),((ue=o.current)==null?void 0:ue.value)!==void 0){let Se=ce??"";(Ee=(ve=o.current).onValueChange)==null||Ee.call(ve,Se);return}}I.emit()}},emit:()=>{l.current.forEach(J=>J())}}),[]),P=j.useMemo(()=>({value:(J,ce,_e)=>{var he;ce!==((he=i.current.get(J))==null?void 0:he.value)&&(i.current.set(J,{value:ce,keywords:_e}),n.current.filtered.items.set(J,R(ce,_e)),E(2,()=>{D(),I.emit()}))},item:(J,ce)=>(r.current.add(J),ce&&(a.current.has(ce)?a.current.get(ce).add(J):a.current.set(ce,new Set([J]))),E(3,()=>{U(),D(),n.current.value||O(),I.emit()}),()=>{i.current.delete(J),r.current.delete(J),n.current.filtered.items.delete(J);let _e=V();E(4,()=>{U(),(_e==null?void 0:_e.getAttribute("id"))===J&&O(),I.emit()})}),group:J=>(a.current.has(J)||a.current.set(J,new Set),()=>{i.current.delete(J),a.current.delete(J)}),filter:()=>o.current.shouldFilter,label:c||s["aria-label"],getDisablePointerSelection:()=>o.current.disablePointerSelection,listId:b,inputId:S,labelId:w,listInnerRef:A}),[]);function R(J,ce){var _e,he;let ue=(he=(_e=o.current)==null?void 0:_e.filter)!=null?he:r6s;return J?ue(J,n.current.search,ce):0}function D(){if(!n.current.search||o.current.shouldFilter===!1)return;let J=n.current.filtered.items,ce=[];n.current.filtered.groups.forEach(he=>{let ue=a.current.get(he),ve=0;ue.forEach(Ee=>{let Se=J.get(Ee);ve=Math.max(Se,ve)}),ce.push([he,ve])});let _e=A.current;G().sort((he,ue)=>{var ve,Ee;let Se=he.getAttribute("id"),Le=ue.getAttribute("id");return((ve=J.get(Le))!=null?ve:0)-((Ee=J.get(Se))!=null?Ee:0)}).forEach(he=>{let ue=he.closest(r7e);ue?ue.appendChild(he.parentElement===ue?he:he.closest(`${r7e} > *`)):_e.appendChild(he.parentElement===_e?he:he.closest(`${r7e} > *`))}),ce.sort((he,ue)=>ue[1]-he[1]).forEach(he=>{var ue;let ve=(ue=A.current)==null?void 0:ue.querySelector(`${kZ}[${hU}="${encodeURIComponent(he[0])}"]`);ve==null||ve.parentElement.appendChild(ve)})}function O(){let J=G().find(_e=>_e.getAttribute("aria-disabled")!=="true"),ce=J==null?void 0:J.getAttribute(hU);I.setState("value",ce||void 0)}function U(){var J,ce,_e,he;if(!n.current.search||o.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let ue=0;for(let ve of r.current){let Ee=(ce=(J=i.current.get(ve))==null?void 0:J.value)!=null?ce:"",Se=(he=(_e=i.current.get(ve))==null?void 0:_e.keywords)!=null?he:[],Le=R(Ee,Se);n.current.filtered.items.set(ve,Le),Le>0&&ue++}for(let[ve,Ee]of a.current)for(let Se of Ee)if(n.current.filtered.items.get(Se)>0){n.current.filtered.groups.add(ve);break}n.current.filtered.count=ue}function W(){var J,ce,_e;let he=V();he&&(((J=he.parentElement)==null?void 0:J.firstChild)===he&&((_e=(ce=he.closest(kZ))==null?void 0:ce.querySelector(n6s))==null||_e.scrollIntoView({block:"nearest"})),he.scrollIntoView({block:"nearest"}))}function V(){var J;return(J=A.current)==null?void 0:J.querySelector(`${Uzt}[aria-selected="true"]`)}function G(){var J;return Array.from(((J=A.current)==null?void 0:J.querySelectorAll(Ryt))||[])}function Y(J){let ce=G()[J];ce&&I.setState("value",ce.getAttribute(hU))}function X(J){var ce;let _e=V(),he=G(),ue=he.findIndex(Ee=>Ee===_e),ve=he[ue+J];(ce=o.current)!=null&&ce.loop&&(ve=ue+J<0?he[he.length-1]:ue+J===he.length?he[0]:he[ue+J]),ve&&I.setState("value",ve.getAttribute(hU))}function ae(J){let ce=V(),_e=ce==null?void 0:ce.closest(kZ),he;for(;_e&&!he;)_e=J>0?m6s(_e,kZ):f6s(_e,kZ),he=_e==null?void 0:_e.querySelector(Ryt);he?I.setState("value",he.getAttribute(hU)):X(J)}let le=()=>Y(G().length-1),ne=J=>{J.preventDefault(),J.metaKey?le():J.altKey?ae(1):X(1)},te=J=>{J.preventDefault(),J.metaKey?Y(0):J.altKey?ae(-1):X(-1)};return j.createElement(Ei.div,{ref:t,tabIndex:-1,...v,"cmdk-root":"",onKeyDown:J=>{var ce;(ce=v.onKeyDown)==null||ce.call(v,J);let _e=J.nativeEvent.isComposing||J.keyCode===229;if(!(J.defaultPrevented||_e))switch(J.key){case"n":case"j":{y&&J.ctrlKey&&ne(J);break}case"ArrowDown":{ne(J);break}case"p":case"k":{y&&J.ctrlKey&&te(J);break}case"ArrowUp":{te(J);break}case"Home":{J.preventDefault(),Y(0);break}case"End":{J.preventDefault(),le();break}case"Enter":{J.preventDefault();let he=V();if(he){let ue=new Event(ZHe);he.dispatchEvent(ue)}}}}},j.createElement("label",{"cmdk-label":"",htmlFor:P.inputId,id:P.labelId,style:x6s},c),FLe(s,J=>j.createElement(Vzt.Provider,{value:I},j.createElement(qzt.Provider,{value:P},J))))}),a6s=j.forwardRef((s,t)=>{var n,r;let a=uy(),i=j.useRef(null),l=j.useContext(Hzt),o=zae(),c=Wzt(s),d=(r=(n=c.current)==null?void 0:n.forceMount)!=null?r:l==null?void 0:l.forceMount;V7(()=>{if(!d)return o.item(a,l==null?void 0:l.id)},[d]);let u=Kzt(a,i,[s.value,s.children,i],s.keywords),h=Ttt(),m=CL(E=>E.value&&E.value===u.current),f=CL(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(ZHe,g),()=>E.removeEventListener(ZHe,g)},[f,s.onSelect,s.disabled]);function g(){var E,I;x(),(I=(E=c.current).onSelect)==null||I.call(E,u.current)}function x(){h.setState("value",u.current,!0)}if(!f)return null;let{disabled:y,value:v,onSelect:b,forceMount:w,keywords:S,...A}=s;return j.createElement(Ei.div,{ref:D7(i,t),...A,id:a,"cmdk-item":"",role:"option","aria-disabled":!!y,"aria-selected":!!m,"data-disabled":!!y,"data-selected":!!m,onPointerMove:y||o.getDisablePointerSelection()?void 0:x,onClick:y?void 0:g},s.children)}),i6s=j.forwardRef((s,t)=>{let{heading:n,children:r,forceMount:a,...i}=s,l=uy(),o=j.useRef(null),c=j.useRef(null),d=uy(),u=zae(),h=CL(f=>a||u.filter()===!1?!0:f.search?f.filtered.groups.has(l):!0);V7(()=>u.group(l),[]),Kzt(l,o,[s.value,s.heading,c]);let m=j.useMemo(()=>({id:l,forceMount:a}),[a]);return j.createElement(Ei.div,{ref:D7(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),FLe(s,f=>j.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?d:void 0},j.createElement(Hzt.Provider,{value:m},f))))}),o6s=j.forwardRef((s,t)=>{let{alwaysRender:n,...r}=s,a=j.useRef(null),i=CL(l=>!l.search);return!n&&!i?null:j.createElement(Ei.div,{ref:D7(a,t),...r,"cmdk-separator":"",role:"separator"})}),l6s=j.forwardRef((s,t)=>{let{onValueChange:n,...r}=s,a=s.value!=null,i=Ttt(),l=CL(d=>d.search),o=CL(d=>d.selectedItemId),c=zae();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)}})}),c6s=j.forwardRef((s,t)=>{let{children:n,label:r="Suggestions",...a}=s,i=j.useRef(null),l=j.useRef(null),o=CL(d=>d.selectedItemId),c=zae();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:D7(i,t),...a,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":o,"aria-label":r,id:c.listId},FLe(s,d=>j.createElement("div",{ref:D7(l,c.listInnerRef),"cmdk-list-sizer":""},d)))}),d6s=j.forwardRef((s,t)=>{let{open:n,onOpenChange:r,overlayClassName:a,contentClassName:i,container:l,...o}=s;return j.createElement(HIe,{open:n,onOpenChange:r},j.createElement(GIe,{container:l},j.createElement(qW,{"cmdk-overlay":"",className:a}),j.createElement(VW,{"aria-label":s.label,"cmdk-dialog":"",className:i},j.createElement(Gzt,{ref:t,...o}))))}),u6s=j.forwardRef((s,t)=>CL(n=>n.filtered.count===0)?j.createElement(Ei.div,{ref:t,...s,"cmdk-empty":"",role:"presentation"}):null),h6s=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},FLe(s,l=>j.createElement("div",{"aria-hidden":!0},l)))}),$w=Object.assign(Gzt,{List:c6s,Item:a6s,Input:l6s,Group:i6s,Separator:o6s,Dialog:d6s,Empty:u6s,Loading:h6s});function m6s(s,t){let n=s.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function f6s(s,t){let n=s.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function Wzt(s){let t=j.useRef(s);return V7(()=>{t.current=s}),t}var V7=typeof window>"u"?j.useEffect:j.useLayoutEffect;function mU(s){let t=j.useRef();return t.current===void 0&&(t.current=s()),t}function CL(s){let t=Ttt(),n=()=>s(t.snapshot());return j.useSyncExternalStore(t.subscribe,n,n)}function Kzt(s,t,n,r=[]){let a=j.useRef(),i=zae();return V7(()=>{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(hU,o),a.current=o}),a}var p6s=()=>{let[s,t]=j.useState(),n=mU(()=>new Map);return V7(()=>{n.current.forEach(r=>r()),n.current=new Map},[s]),(r,a)=>{n.current.set(r,a),t({})}};function g6s(s){let t=s.type;return typeof t=="function"?t(s.props):"render"in t?t.render(s.props):s}function FLe({asChild:s,children:t},n){return s&&j.isValidElement(t)?j.cloneElement(g6s(t),{ref:t.ref},n(t.props.children)):n(t)}var x6s={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};const S2=j.forwardRef(({className:s,...t},n)=>e.jsx($w,{ref:n,className:Pt("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",s),...t}));S2.displayName=$w.displayName;const y6s=({children:s,...t})=>e.jsx(zs,{...t,children:e.jsx(Os,{className:"overflow-hidden p-0 shadow-lg",children:e.jsx(S2,{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})})}),C2=j.forwardRef(({className:s,...t},n)=>e.jsxs("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:[e.jsx(Zr,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),e.jsx($w.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})]}));C2.displayName=$w.Input.displayName;const A2=j.forwardRef(({className:s,...t},n)=>e.jsx($w.List,{ref:n,className:Pt("max-h-[300px] overflow-y-auto overflow-x-hidden",s),...t}));A2.displayName=$w.List.displayName;const E2=j.forwardRef((s,t)=>e.jsx($w.Empty,{ref:t,className:"py-6 text-center text-sm",...s}));E2.displayName=$w.Empty.displayName;const Dw=j.forwardRef(({className:s,...t},n)=>e.jsx($w.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}));Dw.displayName=$w.Group.displayName;const v6s=j.forwardRef(({className:s,...t},n)=>e.jsx($w.Separator,{ref:n,className:Pt("-mx-1 h-px bg-border",s),...t}));v6s.displayName=$w.Separator.displayName;const m1=j.forwardRef(({className:s,...t},n)=>e.jsx($w.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}));m1.displayName=$w.Item.displayName;const b6s={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:L4,color:"bg-green-500/10 text-green-600"},"social-swag":{label:"Social Swag",icon:Nn,color:"bg-fuchsia-500/10 text-fuchsia-600"}},Dyt=()=>{const[s,t]=j.useState(!1),[n,r]=j.useState(""),[a,i]=j.useState([]),[l,o]=j.useState(!1),c=Xn(),{searchDestinations:d,isFavorite:u,routeFor:h}=Bzt(),m=n.trim()?d(n).slice(0,6):[];j.useEffect(()=>{const y=v=>{v.key==="k"&&(v.metaKey||v.ctrlKey)&&(v.preventDefault(),t(b=>!b))};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[]);const f=j.useCallback(async y=>{if(!y.trim()){i([]);return}o(!0);const v=`%${y}%`;try{const[b,w,S,A,E]=await Promise.all([q.from("events").select("id, title, description, event_date").eq("is_published",!0).or(`title.ilike.${v},description.ilike.${v}`).limit(5),q.from("canva_templates").select("id, name, description, publish_date").or(`name.ilike.${v},description.ilike.${v}`).limit(5),q.from("academy_videos").select("id, title, description, publish_date").eq("is_published",!0).or(`title.ilike.${v},description.ilike.${v}`).limit(5),q.from("resource_kits").select("id, name, description, publish_date").eq("is_published",!0).or(`name.ilike.${v},description.ilike.${v}`).limit(5),q.from("social_swag").select("id, title, description, publish_date").eq("is_published",!0).or(`title.ilike.${v},description.ilike.${v}`).limit(5)]),I=[];b.data&&b.data.forEach(P=>{I.push({id:P.id,title:P.title,description:P.description,type:"event",date:P.event_date,path:`/event/${P.id}`})}),w.data&&w.data.forEach(P=>{I.push({id:P.id,title:P.name,description:P.description,type:"template",date:P.publish_date,path:`/templates/${P.id}`})}),S.data&&S.data.forEach(P=>{I.push({id:P.id,title:P.title,description:P.description,type:"academy",date:P.publish_date,path:`/academy/${P.id}`})}),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 y=setTimeout(()=>{f(n)},300);return()=>clearTimeout(y)},[n,f]);const g=y=>{t(!1),r(""),c(y)},x=a.reduce((y,v)=>(y[v.type]||(y[v.type]=[]),y[v.type].push(v),y),{});return e.jsxs(e.Fragment,{children:[e.jsxs($,{variant:"outline",className:"relative h-9 w-9 p-0 xl:h-9 xl:w-60 xl:justify-start xl:px-3 xl:py-2",onClick:()=>t(!0),children:[e.jsx(Zr,{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(y6s,{open:s,onOpenChange:t,children:[e.jsx(C2,{placeholder:"Search events, templates, academy, toolbox, social swag...",value:n,onValueChange:r}),e.jsxs(A2,{children:[m.length>0&&e.jsx(Dw,{heading:"Go to",children:m.map(y=>{const v=y.icon;return e.jsxs(m1,{value:`nav-${y.id}-${y.label}`,onSelect:()=>{const b=h(y);y.external||y.openInNewTab?(t(!1),r(""),window.open(b,"_blank","noopener,noreferrer")):g(b)},className:"flex items-start gap-3 py-3 cursor-pointer",children:[e.jsx("div",{className:"p-2 rounded-md bg-primary/10 text-primary",children:e.jsx(v,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium truncate flex items-center gap-1.5",children:[y.label,u(y)&&e.jsx(E0,{className:"h-3 w-3 fill-current text-primary"})]}),y.description&&e.jsx("div",{className:"text-sm text-muted-foreground truncate",children:y.description})]}),e.jsx($e,{variant:"secondary",className:"text-xs shrink-0",children:y.section})]},`nav-${y.id}`)})}),l&&e.jsx("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"Searching..."}),!l&&n&&a.length===0&&m.length===0&&e.jsxs(E2,{children:['No results found for "',n,'"']}),!l&&!n&&e.jsx("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"Start typing to search pages, apps and content..."}),Object.entries(x).map(([y,v])=>{const b=b6s[y],w=b.icon;return e.jsx(Dw,{heading:b.label,children:v.map(S=>e.jsxs(m1,{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}`))},y)})]})]})]})},_6s=({expiresAt:s,className:t,showUpgradeButton:n=!0})=>{const[r,a]=j.useState(null),i=Xn();if(j.useEffect(()=>{const d=()=>{const h=new Date().getTime(),f=new Date(s).getTime()-h;if(f<=0){a({days:0,hours:0,minutes:0});return}const g=Math.floor(f/(1e3*60*60*24)),x=Math.floor(f%(1e3*60*60*24)/(1e3*60*60)),y=Math.floor(f%(1e3*60*60)/(1e3*60));a({days:g,hours:x,minutes:y})};d();const u=setInterval(d,6e4);return()=>clearInterval(u)},[s]),!r)return null;const l=r.days===0&&r.hours===0&&r.minutes===0,o=r.days<=1,c=r.days<=3&&!o;return l?e.jsxs("div",{className:Pt("flex items-center justify-between gap-3 px-4 py-2 rounded-lg bg-destructive/10 border border-destructive/20",t),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(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(Nn,{className:"h-3 w-3 mr-1"}),"Upgrade Now"]})]}):e.jsxs("div",{className:Pt("flex items-center justify-between gap-3 px-4 py-2 rounded-lg border transition-colors",o?"bg-destructive/10 border-destructive/20":c?"bg-amber-500/10 border-amber-500/20":"bg-primary/10 border-primary/20",t),children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(da,{className:Pt("h-4 w-4",o?"text-destructive":c?"text-amber-500":"text-primary")}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:Pt("text-sm font-medium",o?"text-destructive":c?"text-amber-600":"text-primary"),children:"Free Trial:"}),e.jsxs("div",{className:"flex items-center gap-1",children:[r.days>0&&e.jsxs("span",{className:Pt("text-sm font-bold",o?"text-destructive":c?"text-amber-600":"text-primary"),children:[r.days,"d"]}),e.jsxs("span",{className:Pt("text-sm font-bold",o?"text-destructive":c?"text-amber-600":"text-primary"),children:[r.hours,"h"]}),e.jsxs("span",{className:Pt("text-sm font-bold",o?"text-destructive":c?"text-amber-600":"text-primary"),children:[r.minutes,"m"]}),e.jsx("span",{className:Pt("text-xs",o?"text-destructive/70":c?"text-amber-600/70":"text-primary/70"),children:"remaining"})]})]})]}),n&&e.jsxs($,{size:"sm",onClick:()=>i("/subscription"),variant:o?"destructive":c?"default":"outline",className:Pt("text-xs h-7 px-3",c&&"bg-amber-500 hover:bg-amber-600 text-white"),children:[e.jsx(Nn,{className:"h-3 w-3 mr-1"}),"Upgrade"]})]})},w6s=()=>{const s=Xn();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(Gn,{className:"text-base",children:"Your 7-day free trial has expired. Upgrade now to continue accessing all the powerful tools and resources LevelUp has to offer!"})]}),e.jsxs(Ie,{className:"space-y-6",children:[e.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[e.jsx(je,{className:"border-2 border-primary/20 hover:border-primary/50 transition-colors cursor-pointer",onClick:()=>s("/subscription"),children:e.jsxs(Ie,{className:"p-5 text-center",children:[e.jsx("div",{className:"mx-auto mb-3 h-12 w-12 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx(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(Nn,{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(Ie,{className:"p-5 text-center",children:[e.jsx("div",{className:"mx-auto mb-3 h-12 w-12 rounded-full bg-amber-500/10 flex items-center justify-center",children:e.jsx(ji,{className:"h-6 w-6 text-amber-600"})}),e.jsx("h3",{className:"font-semibold text-lg mb-1",children:"Brokerage"}),e.jsxs("p",{className:"text-2xl font-bold text-amber-600 mb-2",children:["$299",e.jsx("span",{className:"text-sm font-normal text-muted-foreground",children:"/mo"})]}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"For teams and brokerages"}),e.jsxs($,{variant:"outline",className:"w-full border-amber-500 text-amber-600 hover:bg-amber-50",onClick:t=>{t.stopPropagation(),s("/subscription")},children:[e.jsx(ji,{className:"h-4 w-4 mr-2"}),"Choose Brokerage"]})]})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm text-muted-foreground text-center",children:"With a full membership, you'll get:"}),e.jsxs("ul",{className:"text-sm space-y-1 text-muted-foreground grid sm:grid-cols-2 gap-x-4",children:[e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"✓"})," Unlimited access to all marketing templates"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"✓"})," Complete Academy training library"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"✓"})," AI-powered tools and resources"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"✓"})," Community forums and support"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"✓"})," Exclusive member events and workshops"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"✓"})," Deal pipeline & scorecard tracking"]})]})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-4 space-y-3",children:[e.jsx("p",{className:"text-sm font-medium text-center",children:"Questions? Contact us:"}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 justify-center",children:[e.jsxs("a",{href:"tel:1-866-527-8668",className:"flex items-center justify-center gap-2 text-primary hover:underline",children:[e.jsx(Da,{className:"h-4 w-4"}),e.jsx("span",{children:"1-866-527-8668"})]}),e.jsxs("a",{href:"mailto:support@relevelup.com",className:"flex items-center justify-center gap-2 text-primary hover:underline",children:[e.jsx(mn,{className:"h-4 w-4"}),e.jsx("span",{children:"support@relevelup.com"})]})]})]})]})]})})},j6s=({hasUnseenBrief:s,onClick:t,className:n})=>e.jsxs(iy,{children:[e.jsx(oy,{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(jx,{children:e.jsx("p",{children:"The LevelUp Brief"})})]});var N6s=Object.defineProperty,hT=(s,t)=>N6s(s,"name",{value:t,configurable:!0}),Mtt="Checkbox",[k6s,Okr]=tp(Mtt),[S6s,Ptt]=k6s(Mtt);function Yzt(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]=hy({prop:n,defaultProp:a??!1,onChange:c,caller:Mtt}),[g,x]=j.useState(null),[y,v]=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:$E(a)?!1:a,isFormControl:A,bubbleInput:y,setBubbleInput:v};return e.jsx(S6s,{scope:t,...E,children:Xzt(h)?h(E):r})}hT(Yzt,"CheckboxProvider");var C6s="CheckboxTrigger",A6s=j.forwardRef(hT(function({__scopeCheckbox:t,onKeyDown:n,onClick:r,...a},i){const{control:l,value:o,disabled:c,checked:d,required:u,setControl:h,setChecked:m,hasConsumerStoppedPropagationRef:f,onUserInteraction:g,isFormControl:x,bubbleInput:y}=Ptt(C6s,t),v=Vo(i,h),b=j.useRef(d);return j.useEffect(()=>{const w=l==null?void 0:l.form;if(w){const S=hT(()=>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":$E(d)?"mixed":d,"aria-required":u,"data-state":Itt(d),"data-disabled":c?"":void 0,disabled:c,value:o,...a,ref:v,onKeyDown:Ra(n,w=>{w.key==="Enter"&&w.preventDefault()}),onClick:Ra(r,w=>{g(),m(S=>$E(S)?!0:!S),y&&x&&(f.current=w.isPropagationStopped(),f.current||w.stopPropagation())})})},"CheckboxTrigger")),Zzt=j.forwardRef(hT(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(Yzt,{__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(A6s,{...m,ref:n,__scopeCheckbox:r}),f&&e.jsx(P6s,{__scopeCheckbox:r})]})})},"Checkbox")),E6s="CheckboxIndicator",T6s=j.forwardRef(hT(function(t,n){const{__scopeCheckbox:r,forceMount:a,...i}=t,l=Ptt(E6s,r);return e.jsx(py,{present:a||$E(l.checked)||l.checked===!0,children:e.jsx(Ei.span,{"data-state":Itt(l.checked),"data-disabled":l.disabled?"":void 0,...i,ref:n,style:{pointerEvents:"none",...t.style}})})},"CheckboxIndicator")),M6s="CheckboxBubbleInput",P6s=j.forwardRef(hT(function({__scopeCheckbox:t,onClick:n,...r},a){const{control:i,hasConsumerStoppedPropagationRef:l,userInteractionCount:o,checked:c,defaultChecked:d,required:u,disabled:h,name:m,value:f,form:g,bubbleInput:x,setBubbleInput:y}=Ptt(M6s,t),v=Vo(a,y),b=WW(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=$E(c),D.call(I,$E(c)?!1:c),I.dispatchEvent(V),w.current=!1}},[x,c,l,o]);const E=j.useRef($E(c)?!1:c);return e.jsx(Ei.input,{type:"checkbox","aria-hidden":!0,defaultChecked:d??E.current,required:u,disabled:h,name:m,value:f,form:g,...r,tabIndex:-1,ref:v,onClick:Ra(n,I=>{w.current&&I.stopPropagation()}),style:{...r.style,...b,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})},"CheckboxBubbleInput"));function Xzt(s){return typeof s=="function"}hT(Xzt,"isFunction");function $E(s){return s==="indeterminate"}hT($E,"isIndeterminate");function Itt(s){return $E(s)?"indeterminate":s?"checked":"unchecked"}hT(Itt,"getState");const ai=j.forwardRef(({className:s,...t},n)=>e.jsx(Zzt,{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(T6s,{className:Pt("flex items-center justify-center text-current"),children:e.jsx(ca,{className:"h-4 w-4"})})}));ai.displayName=Zzt.displayName;var I6s=Object.defineProperty,y1=(s,t)=>I6s(s,"name",{value:t,configurable:!0}),Qzt="Radio",[L6s,Jzt]=tp(Qzt),[R6s,OLe]=L6s(Qzt);function e7t(s){const{__scopeRadio:t,checked:n=!1,children:r,disabled:a,form:i,name:l,onCheck:o,required:c,value:d="on",internal_do_not_use_render:u}=s,[h,m]=j.useState(null),[f,g]=j.useState(null),x=j.useRef(!1),[y,v]=j.useReducer(S=>S+1,0),b=h?!!i||!!h.closest("form"):!0,w={checked:n,disabled:a,required:c,name:l,form:i,value:d,control:h,setControl:m,hasConsumerStoppedPropagationRef:x,userInteractionCount:y,onUserInteraction:v,isFormControl:b,bubbleInput:f,setBubbleInput:g,onCheck:y1(()=>o==null?void 0:o(),"onCheck")};return e.jsx(R6s,{scope:t,...w,children:t7t(u)?u(w):r})}y1(e7t,"RadioProvider");var D6s="RadioTrigger",F6s=j.forwardRef(y1(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}=OLe(D6s,t),g=Vo(a,c);return e.jsx(Ei.button,{type:"button",role:"radio","aria-checked":i,"data-state":Ltt(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")),O6s="RadioIndicator",z6s=j.forwardRef(y1(function(t,n){const{__scopeRadio:r,forceMount:a,...i}=t,l=OLe(O6s,r);return e.jsx(py,{present:a||l.checked,children:e.jsx(Ei.span,{"data-state":Ltt(l.checked),"data-disabled":l.disabled?"":void 0,...i,ref:n})})},"RadioIndicator")),B6s="RadioBubbleInput",$6s=j.forwardRef(y1(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}=OLe(B6s,t),y=Vo(a,f),v=WW(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:y,onClick:Ra(n,E=>{b.current&&E.stopPropagation()}),style:{...r.style,...v,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})},"RadioBubbleInput"));function t7t(s){return typeof s=="function"}y1(t7t,"isFunction");function Ltt(s){return s?"checked":"unchecked"}y1(Ltt,"getState");var U6s=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Rtt="RadioGroup",[q6s,zkr]=tp(Rtt,[t6,Jzt]),s7t=t6(),zLe=Jzt(),[V6s,H6s]=q6s(Rtt),n7t=j.forwardRef(y1(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=s7t(r),y=i3(h),[v,b]=hy({prop:o,defaultProp:l??null,onChange:f,caller:Rtt}),[w,S]=j.useState(null),A=Vo(n,S),E=j.useRef(v);return j.useEffect(()=>{const I=i?w==null?void 0:w.ownerDocument.getElementById(i):w==null?void 0:w.closest("form");if(I instanceof HTMLFormElement){const P=y1(()=>b(E.current),"reset");return I.addEventListener("reset",P),()=>I.removeEventListener("reset",P)}},[w,i,b]),e.jsx(V6s,{scope:r,name:a,form:i,required:c,disabled:d,value:v,onValueChange:b,children:e.jsx(mLe,{asChild:!0,...x,orientation:u,dir:y,loop:m,children:e.jsx(Ei.div,{role:"radiogroup","aria-required":c,"aria-orientation":u,"data-disabled":d?"":void 0,dir:y,...g,ref:A})})})},"RadioGroup")),G6s="RadioGroupItemProvider",W6s="RadioGroupItemTrigger";function r7t(s){const{__scopeRadioGroup:t,value:n,disabled:r,children:a,internal_do_not_use_render:i}=s,l=H6s(G6s,t),o=zLe(t),c=l.disabled||r;return e.jsx(e7t,{...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})}y1(r7t,"RadioGroupItemProvider");var K6s=j.forwardRef(y1(function(t,n){const{__scopeRadioGroup:r,...a}=t,i=s7t(r),l=zLe(r),{checked:o,disabled:c}=OLe(W6s,l.__scopeRadio),d=j.useRef(null),u=Vo(n,d),h=j.useRef(!1);return j.useEffect(()=>{const m=y1(g=>{U6s.includes(g.key)&&(h.current=!0)},"handleKeyDown"),f=y1(()=>h.current=!1,"handleKeyUp");return document.addEventListener("keydown",m),document.addEventListener("keyup",f),()=>{document.removeEventListener("keydown",m),document.removeEventListener("keyup",f)}},[]),e.jsx(fLe,{asChild:!0,...i,focusable:!c,active:o,children:e.jsx(F6s,{...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")),a7t=j.forwardRef(y1(function(t,n){const{__scopeRadioGroup:r,value:a,disabled:i,...l}=t;return e.jsx(r7t,{__scopeRadioGroup:r,value:a,disabled:i,internal_do_not_use_render:({isFormControl:o})=>e.jsxs(e.Fragment,{children:[e.jsx(K6s,{...l,ref:n,__scopeRadioGroup:r}),o&&e.jsx(Y6s,{__scopeRadioGroup:r})]})})},"RadioGroupItem")),Y6s=j.forwardRef(y1(function(t,n){const{__scopeRadioGroup:r,...a}=t,i=zLe(r);return e.jsx($6s,{...i,...a,ref:n})},"RadioGroupItemBubbleInput")),Z6s=j.forwardRef(y1(function(t,n){const{__scopeRadioGroup:r,...a}=t,i=zLe(r);return e.jsx(z6s,{...i,...a,ref:n})},"RadioGroupIndicator"));const vw=j.forwardRef(({className:s,...t},n)=>e.jsx(n7t,{className:Pt("grid gap-2",s),...t,ref:n}));vw.displayName=n7t.displayName;const Km=j.forwardRef(({className:s,...t},n)=>e.jsx(a7t,{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(Z6s,{className:"flex items-center justify-center",children:e.jsx(Og,{className:"h-2.5 w-2.5 fill-current text-current"})})}));Km.displayName=a7t.displayName;const X6s=({brief:s,open:t,onClose:n,onDismiss:r})=>{const{user:a}=bs(),[i,l]=j.useState({}),[o,c]=j.useState({}),[d,u]=j.useState([]);j.useEffect(()=>{t&&a&&s.polls.length>0&&h()},[t,a,s.polls]);const h=async()=>{if(!a)return;const y=s.polls.map(b=>b.id),{data:v}=await q.from("levelup_brief_poll_responses").select("poll_id, option_id").eq("user_id",a.id).in("poll_id",y);if(v){const b={};v.forEach(w=>{b[w.poll_id]||(b[w.poll_id]=[]),b[w.poll_id].push(w.option_id)}),c(b)}},m=(y,v)=>{l(b=>({...b,[y]:v}))},f=(y,v,b)=>{l(w=>{const S=w[y]||[];return b?{...w,[y]:[...S,v]}:{...w,[y]:S.filter(A=>A!==v)}})},g=async y=>{if(!a)return;const v=i[y];if(!v||Array.isArray(v)&&v.length===0){re.error("Please select an option");return}u(b=>[...b,y]);try{await q.from("levelup_brief_poll_responses").delete().eq("poll_id",y).eq("user_id",a.id);const b=Array.isArray(v)?v:[v],w=b.map(A=>({poll_id:y,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,[y]:b})),re.success("Response submitted!")}catch(b){console.error("Error submitting poll response:",b),re.error("Failed to submit response")}finally{u(b=>b.filter(w=>w!==y))}},x=y=>(y.includes("mediadelivery.net")||y.includes("bunny"),y);return e.jsx(zs,{open:t,onOpenChange:y=>!y&&n(),children:e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] p-0 overflow-hidden [&>button]:hidden",children:[e.jsxs("div",{className:"bg-gradient-to-r from-primary to-primary/80 p-4 pr-12 text-primary-foreground relative",children:[e.jsx("button",{onClick:n,className:"absolute top-3 right-3 p-1.5 rounded-full bg-white/30 hover:bg-white/50 transition-colors","aria-label":"Close",children:e.jsx(pr,{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(Bs,{className:"text-xl font-bold text-white",children:s.brief.title})]})]})]}),e.jsx(uo,{className:"max-h-[calc(90vh-240px)]",children:e.jsxs("div",{className:"p-6 space-y-6",children:[s.brief.description&&e.jsx("div",{className:"text-muted-foreground prose prose-sm max-w-none",dangerouslySetInnerHTML:{__html:s.brief.description}}),s.brief.video_url&&e.jsx("div",{className:"relative w-full aspect-video rounded-lg overflow-hidden bg-muted",children:e.jsx("iframe",{src:x(s.brief.video_url),className:"absolute inset-0 w-full h-full",allow:"autoplay; fullscreen; picture-in-picture",allowFullScreen:!0})}),s.brief.graphic_url&&!s.brief.video_url&&e.jsx("div",{className:"rounded-lg overflow-hidden bg-muted",children:s.brief.graphic_link_url?e.jsx("a",{href:s.brief.graphic_link_url,target:"_blank",rel:"noopener noreferrer",className:"block",children:e.jsx("img",{src:s.brief.graphic_url,alt:"Brief graphic",className:"w-full object-contain cursor-pointer hover:opacity-90 transition-opacity"})}):e.jsx("img",{src:s.brief.graphic_url,alt:"Brief graphic",className:"w-full object-contain"})}),s.links.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("h4",{className:"font-semibold text-foreground",children:"Quick Links"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:s.links.map(y=>e.jsxs($,{variant:"outline",size:"sm",onClick:()=>window.open(y.url,"_blank"),className:"gap-2",children:[e.jsx(Fr,{className:"h-4 w-4"}),y.title]},y.id))})]}),s.polls.map(y=>{var w,S;const v=((w=o[y.id])==null?void 0:w.length)>0,b=d.includes(y.id);return e.jsxs("div",{className:"space-y-3 p-4 bg-muted/50 rounded-lg border",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h4",{className:"font-semibold text-foreground",children:y.question}),v&&e.jsxs($e,{variant:"secondary",className:"gap-1",children:[e.jsx(Vr,{className:"h-3 w-3"}),"Responded"]})]}),y.poll_type==="single"?e.jsx(vw,{value:i[y.id]||((S=o[y.id])==null?void 0:S[0])||"",onValueChange:A=>m(y.id,A),className:"space-y-2",children:y.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:y.options.map(A=>{const I=(i[y.id]||o[y.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(y.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(y.id),disabled:b,children:b?"Submitting...":v?"Update Response":"Submit"})]},y.id)})]})}),e.jsxs("div",{className:"p-4 pb-[calc(1rem+env(safe-area-inset-bottom))] border-t bg-muted/30 flex flex-col items-center gap-2 sticky bottom-0 z-10",children:[e.jsx($,{onClick:n,className:"w-full max-w-xs",children:"Got it!"}),e.jsx($,{variant:"ghost",size:"sm",onClick:r,children:"Don't show again"})]})]})})},Q6s=()=>{const{user:s}=bs(),[t,n]=j.useState(null),[r,a]=j.useState(!1),[i,l]=j.useState(!0),[o,c]=j.useState(!1),d=j.useCallback(async()=>{if(!s){l(!1);return}try{const{data:g,error:x}=await q.from("levelup_briefs").select("*").eq("is_published",!0).lte("publish_date",new Date().toISOString()).order("publish_date",{ascending:!1}).limit(1).single();if(x||!g){l(!1);return}const{data:y}=await q.from("levelup_brief_views").select("*").eq("brief_id",g.id).eq("user_id",s.id).maybeSingle(),[v,b]=await Promise.all([q.from("levelup_brief_links").select("*").eq("brief_id",g.id).order("sort_order"),q.from("levelup_brief_polls").select("*").eq("brief_id",g.id).order("sort_order")]),w=[];if(b.data)for(const P of b.data){const{data:R}=await q.from("levelup_brief_poll_options").select("*").eq("poll_id",P.id).order("sort_order");w.push({...P,options:R||[]})}const S={brief:g,links:v.data||[],polls:w};n(S);const A=!!y,E=(y==null?void 0:y.dismissed_at)!=null,I=localStorage.getItem(`brief-dismissed-${g.id}`)==="true";if(E||I)c(!1),a(!1);else if(!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(y.viewed_at);(new Date().getTime()-P.getTime())/(1e3*60*60)>=24&&(a(!0),c(!0))}else c(!1)}catch(g){console.error("Error fetching brief:",g)}finally{l(!1)}},[s]);j.useEffect(()=>{d()},[d]);const u=async()=>{if(!(!s||!t))try{const{data:g}=await q.from("levelup_brief_views").select("id").eq("brief_id",t.brief.id).eq("user_id",s.id).maybeSingle();g?await q.from("levelup_brief_views").update({viewed_at:new Date().toISOString()}).eq("id",g.id):await q.from("levelup_brief_views").insert({brief_id:t.brief.id,user_id:s.id})}catch(g){console.error("Error marking brief as viewed:",g)}};return{currentBrief:t,shouldShowPopup:r,hasUnseenBrief:o,loading:i,openBrief:()=>{a(!0)},closeBrief:()=>{a(!1),u()},dismissBrief:async()=>{if(!(!s||!t)){a(!1),c(!1);try{const{data:g,error:x}=await q.from("levelup_brief_views").select("id").eq("brief_id",t.brief.id).eq("user_id",s.id).maybeSingle();if(x&&console.error("Error checking existing brief view:",x),g){const{error:y}=await q.from("levelup_brief_views").update({dismissed_at:new Date().toISOString()}).eq("id",g.id).eq("user_id",s.id);y&&console.error("Error updating brief dismiss:",y)}else{const{error:y}=await q.from("levelup_brief_views").insert({brief_id:t.brief.id,user_id:s.id,dismissed_at:new Date().toISOString()});y&&console.error("Error inserting brief dismiss:",y)}localStorage.setItem(`brief-dismissed-${t.brief.id}`,"true")}catch(g){console.error("Error dismissing brief:",g),t&&localStorage.setItem(`brief-dismissed-${t.brief.id}`,"true")}}},refetch:d}};function J6s(){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(xi,{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(ZJ,{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(pr,{className:"h-4 w-4"})})]})]})}):null}const eRs=({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=Wt(),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]),y=Math.min(a/h,1),v=y*180;return e.jsxs("div",{ref:c,className:"h-full overflow-auto",onTouchStart:f,onTouchMove:g,onTouchEnd:x,children:[e.jsx("div",{className:"flex justify-center items-center overflow-hidden transition-all duration-200 ease-out",style:{height:a>0?a:0,opacity:y},children:e.jsx("div",{className:`p-2 rounded-full bg-primary/10 ${l?"animate-spin":""}`,style:{transform:l?void 0:`rotate(${v}deg)`,transition:l?void 0:"transform 0.1s ease-out"},children:e.jsx(ro,{className:"h-5 w-5 text-primary"})})}),e.jsx("div",{style:{transform:a>0?`translateY(${Math.max(0,a-60)}px)`:void 0,transition:n?void 0:"transform 0.2s ease-out"},children:s})]})},i7t=()=>{const{user:s}=bs(),[t,n]=j.useState(!1),[r,a]=j.useState(!1),[i,l]=j.useState(0),[o,c]=j.useState(!0);j.useEffect(()=>{(async()=>{if(!s){c(!1);return}try{const{data:f}=await q.from("membership_reviews").select("id").eq("user_id",s.id).maybeSingle();if(f){a(!0),n(!1),c(!1);return}const{data:g}=await q.from("profiles").select("login_count").eq("id",s.id).single(),x=(g==null?void 0:g.login_count)||0;l(x);const y=sessionStorage.getItem("review-prompt-dismissed");n(x>=4&&!y)}catch(f){console.error("Error checking review eligibility:",f)}finally{c(!1)}})()},[s]);const d=j.useCallback(()=>{sessionStorage.setItem("review-prompt-dismissed","true"),n(!1)},[]),u=j.useCallback(async(m,f)=>{if(!s)return{success:!1,error:"Not authenticated"};try{const{error:g}=await q.from("membership_reviews").insert({user_id:s.id,rating:m,review_text:f});if(g)throw g;return a(!0),n(!1),{success:!0,pointsAwarded:25}}catch(g){return console.error("Error submitting review:",g),{success:!1,error:g.message}}},[s]),h=j.useCallback(async()=>{if(s)try{await q.from("membership_reviews").update({posted_to_google:!0}).eq("user_id",s.id)}catch(m){console.error("Error updating Google review status:",m)}},[s]);return{shouldShowPrompt:t,hasSubmittedReview:r,loginCount:i,isLoading:o,dismissPrompt:d,submitReview:u,markPostedToGoogle:h}},tRs="https://search.google.com/local/writereview?placeid=ChIJM73ERQD1QogRPxupMFObuck&source=g.page.m.ia._&laa=nmx-review-solicitation-ia2",sRs=()=>{const{shouldShowPrompt:s,isLoading:t,dismissPrompt:n,submitReview:r,markPostedToGoogle:a}=i7t(),[i,l]=j.useState(!1),[o,c]=j.useState("review"),[d,u]=j.useState(0),[h,m]=j.useState(0),[f,g]=j.useState(""),[x,y]=j.useState(!1),[v,b]=j.useState(!1);if(t||!s&&!v)return null;const w=async()=>{if(d===0){_a({title:"Please select a rating",variant:"destructive"});return}y(!0);const E=await r(d,f);y(!1),E.success?(b(!0),_a({title:"Thank you for your feedback!",description:"Your review helps us improve."}),c("google")):_a({title:"Error submitting review",description:E.error,variant:"destructive"})},S=async E=>{E&&(await navigator.clipboard.writeText(f||`${d} star rating for LevelUp!`),_a({title:"Review copied!",description:"Paste it on Google Reviews."}),await a(),window.open(tRs,"_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(zs,{open:i,onOpenChange:A,children:e.jsx(Os,{className:"sm:max-w-md",children:o==="review"?e.jsxs(e.Fragment,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{className:"text-center",children:"How are you enjoying LevelUp?"}),e.jsx(Pr,{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(Ls,{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(Bs,{className:"text-center",children:"🎉 Thank you!"}),e.jsx(Pr,{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 nRs(s){const t="=".repeat((4-s.length%4)%4),n=(s+t).replace(/-/g,"+").replace(/_/g,"/"),r=window.atob(n),a=new Uint8Array(r.length);for(let i=0;i{if(!h){l(!1);return}(async()=>{try{const x="vapid_public_key";let y=localStorage.getItem(x);if(!y){const{data:w,error:S}=await q.functions.invoke("get-vapid-public-key",{body:{}});if(S)throw S;if(y=(w==null?void 0:w.vapidPublicKey)??null,!y)throw new Error("Missing VAPID public key");localStorage.setItem(x,y)}u(y);const v=await navigator.serviceWorker.register("/push-sw.js",{scope:"/push-notifications/"});c(v),n(Notification.permission);const b=await v.pushManager.getSubscription();a(!!b)}catch(x){console.error("Error initializing push notifications:",x)}finally{l(!1)}})()},[h]);const m=j.useCallback(async()=>{if(!h||!o||!s)return console.error("Push notifications not supported or user not logged in"),!1;if(!d)return re.error("Push notifications are not ready yet. Please try again in a moment."),!1;try{l(!0);const g=await o.pushManager.getSubscription();if(g){try{await g.unsubscribe()}catch(S){console.warn("Failed to unsubscribe existing push subscription:",S)}const{error:w}=await q.from("push_subscriptions").delete().eq("user_id",s.id);w&&console.warn("Failed to cleanup push_subscriptions rows:",w)}if(Notification.permission!=="granted"){const w=await Notification.requestPermission();if(n(w),w!=="granted")return w==="denied"?re.error("Notifications blocked. Please enable them in your browser settings (click the lock icon in the address bar)."):re.error("Notification permission was dismissed. Please try again."),!1}const x=nRs(d);let y;try{y=await o.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:x})}catch(w){console.error("PushManager.subscribe() failed:",w);const S=(w==null?void 0:w.message)||String(w);return S.includes("permission")?re.error("Push permission denied. Check your browser notification settings."):S.includes("key")||S.includes("VAPID")?re.error("Push configuration error. Please contact support."):S.includes("AbortError")?re.error("Push subscription was cancelled. Please try again."):re.error(`Failed to subscribe: ${S}`),!1}const v=y.toJSON(),{error:b}=await q.from("push_subscriptions").upsert({user_id:s.id,endpoint:v.endpoint,p256dh_key:v.keys.p256dh,auth_key:v.keys.auth},{onConflict:"user_id,endpoint"});if(b)throw console.error("Error saving subscription:",b),re.error("Failed to save notification preferences. Please try again."),b;return a(!0),re.success("Push notifications enabled!"),!0}catch(g){if(console.error("Error subscribing to push notifications:",g),!(g instanceof Error&&g.message.includes("toast"))){const x=g instanceof Error?g.message:"Unknown error";re.error("Failed to enable push notifications: "+x)}return!1}finally{l(!1)}},[h,o,s,d]),f=j.useCallback(async()=>{if(!o||!s)return!1;try{l(!0);const g=await o.pushManager.getSubscription();return g&&await g.unsubscribe(),await q.from("push_subscriptions").delete().eq("user_id",s.id),a(!1),re.success("Push notifications disabled"),!0}catch(g){console.error("Error unsubscribing:",g);const x=g instanceof Error?g.message:"Unknown error";return re.error("Failed to disable push notifications: "+x),!1}finally{l(!1)}},[o,s]);return{isSupported:h,permission:t,isSubscribed:r,isLoading:i,vapidPublicKey:d,subscribe:m,unsubscribe:f}}const a7e="push_notification_prompt_dismissed",rRs=["/dashboard","/admin"],aRs=()=>{const{user:s}=bs(),{isSupported:t,isSubscribed:n,isLoading:r,subscribe:a}=o7t(),i=mu(),[l,o]=j.useState(!1),[c,d]=j.useState(!1),u=rRs.some(f=>i.pathname===f||i.pathname.startsWith(`${f}/`));j.useEffect(()=>{if(u){o(!1);return}if(!s||!t||n||r||localStorage.getItem(`${a7e}_${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(`${a7e}_${s.id}`,"true"),o(!1))},m=()=>{s&&localStorage.setItem(`${a7e}_${s.id}`,"true"),o(!1)};return!t||n||u?null:e.jsx(zs,{open:l,onOpenChange:f=>!f&&m(),children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsx("div",{className:"mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-primary/10",children:e.jsx(Uy,{className:"h-6 w-6 text-primary"})}),e.jsx(Bs,{className:"text-center",children:"Stay in the Loop!"}),e.jsx(Pr,{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."})]})})},Fyt=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},iRs=s=>s?Fyt(s):Fyt,oRs=s=>s;function lRs(s,t=oRs){const n=Gt.useSyncExternalStore(s.subscribe,Gt.useCallback(()=>t(s.getState()),[s,t]),Gt.useCallback(()=>t(s.getInitialState()),[s,t]));return Gt.useDebugValue(n),n}const Oyt=s=>{const t=iRs(s),n=r=>lRs(t,r);return Object.assign(n,t),n},cRs=s=>s?Oyt(s):Oyt;function dRs(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 XHe=s=>t=>{try{const n=s(t);return n instanceof Promise?n:{then(r){return XHe(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return XHe(r)(n)}}}},uRs=(s,t)=>(n,r,a)=>{let i={storage:dRs(()=>window.localStorage),partialize:y=>y,version:0,merge:(y,v)=>({...v,...y}),...t},l=!1,o=0;const c=new Set,d=new Set;let u=i.storage;if(!u)return s((...y)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...y)},r,a);const h=()=>{const y=i.partialize({...r()});return u.setItem(i.name,{state:y,version:i.version})},m=a.setState;a.setState=(y,v)=>(m(y,v),h());const f=s((...y)=>(n(...y),h()),r,a);a.getInitialState=()=>f;let g;const x=()=>{var y,v;if(!u)return;const b=++o;l=!1,c.forEach(S=>{var A;return S((A=r())!=null?A:f)});const w=((v=i.onRehydrateStorage)==null?void 0:v.call(i,(y=r())!=null?y:f))||void 0;return XHe(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:y=>{i={...i,...y},y.storage&&(u=y.storage)},clearStorage:()=>{++o,u==null||u.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>x(),hasHydrated:()=>l,onHydrate:y=>(c.add(y),()=>{c.delete(y)}),onFinishHydration:y=>(d.add(y),()=>{d.delete(y)})},i.skipHydration||x(),g||f},hRs=uRs,BLe=cRs()(hRs((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 mRs({activeCategory:s,currentCategory:t,onSelect:n,onHover:r,badgeCounts:a,categories:i=DLe}){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 fRs({category:s,top:t,left:n,onClose:r,onNavigate:a,isFavorite:i,favorites:l,onToggleFavorite:o,isCurrent:c,badgeCounts:d}){const u=j.useRef(null);j.useEffect(()=>{const m=g=>{g.key==="Escape"&&r()},f=g=>{var y;if(!u.current)return;const x=g.target;!u.current.contains(x)&&!((y=x==null?void 0:x.closest)!=null&&y.call(x,"[data-nav-rail]"))&&r()};return document.addEventListener("keydown",m),document.addEventListener("mousedown",f),()=>{document.removeEventListener("keydown",m),document.removeEventListener("mousedown",f)}},[r]);const h=m=>{const f=m.icon,g=m.badgeKey?(d==null?void 0:d[m.badgeKey])??0:0;return e.jsxs("div",{className:Pt("group flex items-start gap-3 rounded-lg p-2 transition-colors hover:bg-muted",c(m)&&"bg-muted"),children:[e.jsxs("button",{type:"button",onClick:()=>a(m),className:"flex flex-1 items-start gap-3 text-left focus:outline-none focus-visible:ring-2 focus-visible:ring-primary rounded-md",children:[e.jsx("span",{className:"mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-primary",children:e.jsx(f,{className:"h-4 w-4"})}),e.jsxs("span",{className:"min-w-0",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-sm font-medium text-foreground",children:m.label}),m.badge==="new"&&e.jsx("span",{className:"rounded bg-primary px-1 py-px text-[9px] font-bold uppercase tracking-wide text-primary-foreground",children:"New"}),m.badge==="beta"&&e.jsx("span",{className:"rounded border border-amber-500 bg-amber-500/10 px-1 py-px text-[9px] font-bold uppercase tracking-wide text-amber-600 dark:text-amber-400",children:"Beta"}),m.locked&&e.jsx(pc,{className:"h-3 w-3 text-muted-foreground","aria-label":"Upgrade required"}),g>0&&e.jsx("span",{className:"flex h-4 min-w-4 items-center justify-center rounded-full bg-muted-foreground/15 px-1 text-[10px] font-medium text-muted-foreground",children:g>9?"9+":g})]}),m.description&&e.jsx("span",{className:"mt-0.5 block text-xs leading-snug text-muted-foreground line-clamp-2",children:m.description})]})]}),e.jsx("button",{type:"button","aria-label":i(m)?`Remove ${m.label} from favorites`:`Add ${m.label} to favorites`,onClick:x=>{x.stopPropagation(),o(m)},className:Pt("mt-1 rounded p-1 opacity-0 transition-opacity focus:outline-none focus-visible:ring-2 focus-visible:ring-primary group-hover:opacity-100",i(m)&&"opacity-100 text-primary",!i(m)&&"text-muted-foreground/60 hover:text-primary"),children:e.jsx(E0,{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(E0,{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 pRs({categories:s,railCategories:t=DLe,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(y=>{const v=y.icon,b=y.badgeKey?(l==null?void 0:l[y.badgeKey])??0:0,w=(o==null?void 0:o(y))??!1;return e.jsxs("div",{className:Pt("flex w-full items-center gap-2 rounded-md pr-1 hover:bg-sidebar-accent",i(y)&&"bg-sidebar-accent"),children:[e.jsxs("button",{type:"button",onClick:()=>r(y),className:"flex flex-1 items-center gap-2 px-2 py-2 text-left text-sm text-sidebar-foreground",children:[e.jsx(v,{className:"h-4 w-4 shrink-0"}),e.jsx("span",{className:"truncate",children:y.label}),b>0&&e.jsx("span",{className:"ml-auto flex h-5 w-5 items-center justify-center rounded-full bg-muted text-xs text-muted-foreground",children:b>9?"9+":b})]}),c&&e.jsx("button",{type:"button","aria-label":w?`Remove ${y.label} from favorites`:`Add ${y.label} to favorites`,onClick:()=>c(y),className:Pt("rounded p-2",w?"text-primary":"text-muted-foreground/60"),children:e.jsx(E0,{className:Pt("h-4 w-4",w&&"fill-current")})})]},y.id)})]},x.title))})]},h.id)})})}function l7t(){const s=Xn(),t=mu(),n=Bzt(),r=j.useCallback(o=>zzt(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 gRs({communityUnreadCount:s=0,wishlistOpenCount:t=0,flyoutTop:n=64,flyoutLeft:r=80}){const{nav:a,navigate:i,currentCategory:l,isCurrent:o,go:c}=l7t(),[d,u]=j.useState(null),h=j.useRef(null),m=x=>{const y=DLe.find(v=>v.id===x);if(y!=null&&y.route){u(null),i(y.route);return}u(v=>v===x?null:x)},f=d?a.categoryMap.get(d):void 0,g={more:s+t};return e.jsxs("div",{"data-nav-rail":!0,className:"flex h-full flex-col",onMouseLeave:()=>{h.current&&window.clearTimeout(h.current),h.current=window.setTimeout(()=>u(null),250)},onMouseEnter:()=>{h.current&&window.clearTimeout(h.current)},children:[e.jsx(mRs,{activeCategory:d,currentCategory:l,onSelect:m,categories:a.railCategories,badgeCounts:g}),f&&e.jsx(fRs,{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 xRs({communityUnreadCount:s=0,wishlistOpenCount:t=0,onNavigated:n}){const{nav:r,navigate:a,currentCategory:i,isCurrent:l,go:o}=l7t();return e.jsx(pRs,{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 yRs=({bannerHeight:s,communityUnreadCount:t,wishlistOpenCount:n,isTrial:r,isExpired:a})=>{const i=Xn();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:n5s,alt:"LevelUp",className:"h-8 w-auto"})})}),e.jsxs(uo,{className:"flex-1 [&_[data-radix-scroll-area-scrollbar]]:w-1.5",children:[e.jsx(gRs,{communityUnreadCount:t,wishlistOpenCount:n,flyoutTop:s+64,flyoutLeft:80}),r&&!a&&e.jsx("div",{className:"p-2",children:e.jsxs("button",{type:"button",onClick:()=>i("/subscription"),className:"flex w-full flex-col items-center gap-1 rounded-xl border border-amber-500/30 bg-amber-500/10 px-1 py-2 text-[10px] font-semibold text-amber-600 dark:text-amber-400",children:[e.jsx(Nn,{className:"h-4 w-4"}),"Upgrade"]})})]})]})},vRs=({isTrial:s,isExpired:t,expiresAt:n,communityUnreadCount:r,wishlistOpenCount:a,pathname:i,onSignOut:l,onNavigated:o})=>{const c=Xn();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:s5s,alt:"LevelUp",className:"h-8 w-auto"})}),e.jsxs(uo,{className:"flex-1",children:[s&&!t&&e.jsx("div",{className:"p-2",children:e.jsx("button",{type:"button",onClick:()=>{c("/subscription"),o==null||o()},className:Pt("relative mb-1 w-full overflow-hidden rounded-md p-[1.5px]","bg-[linear-gradient(120deg,#f59e0b,#ef4444,#a855f7,#f59e0b)] bg-[length:200%_200%]","animate-gradient-x shadow-lg shadow-amber-500/20"),children:e.jsxs("span",{className:"flex items-center gap-2 rounded-[5px] bg-sidebar px-3 py-2 text-sm font-semibold text-sidebar-foreground",children:[e.jsx(Nn,{className:"h-4 w-4 text-amber-500"}),e.jsx("span",{className:"flex-1 text-left",children:"Ready to Upgrade?"}),n&&e.jsxs("span",{className:"rounded border border-amber-500/30 bg-amber-500/15 px-1.5 py-0.5 text-[10px] font-bold uppercase tracking-wide text-amber-600 dark:text-amber-400",children:[Math.max(0,Math.ceil((Date.parse(n)-Date.now())/864e5)),"d left"]})]})})}),e.jsx(xRs,{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(qz,{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}=bs(),{isAssistant:c,actingAsAgent:d,hasPermission:u}=Aae();xLe();const{isImpersonating:h}=uLe(),f=(c&&!!d?40:0)+(h?40:0),{avatarUrl:g}=IOt(n==null?void 0:n.id),{isTrial:x,isExpired:y,expiresAt:v}=MCs(n==null?void 0:n.id),{isMarketplaceEnabled:b}=Tae(),{currentBrief:w,shouldShowPopup:S,hasUnseenBrief:A,openBrief:E,closeBrief:I,dismissBrief:P}=Q6s(),{unreadCount:R}=PCs(),{openCount:D}=ICs();zw();const U=BLe(ce=>ce.cartItems).reduce((ce,_e)=>ce+_e.quantity,0),{hasLeadSite:W}=ng();LLe(!W);const V=Xn(),G=mu(),[Y,X]=j.useState(null);j.useEffect(()=>{n!=null&&n.id&&q.from("profiles").select("name").eq("id",n.id).single().then(({data:ce})=>{ce!=null&&ce.name&&X(ce.name)})},[n==null?void 0:n.id]);const ae=Y||((J=n==null?void 0:n.user_metadata)==null?void 0:J.name)||(n==null?void 0:n.email)||"User",[le,ne]=j.useState(!1),te=ce=>ce.split(" ").map(_e=>_e[0]).join("").toUpperCase().slice(0,2);return e.jsx(bk,{children:e.jsxs("div",{className:"min-h-screen bg-background flex",children:[x&&y&&G.pathname!=="/subscription"&&e.jsx(w6s,{}),typeof document<"u"&&vv.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(yRs,{bannerHeight:f,communityUnreadCount:R,wishlistOpenCount:D,isTrial:x,isExpired:y})}),document.body),e.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden md:ml-20",style:{height:`calc(100vh - ${f}px)`,marginTop:`${f}px`},children:[e.jsx("header",{className:"sticky top-0 z-40 bg-card border-b border-border flex-shrink-0",children:e.jsxs("div",{className:"flex items-center justify-between px-6 py-3",children:[e.jsxs(Gy,{open:le,onOpenChange:ne,children:[e.jsx(Pae,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"md:hidden",children:e.jsx(ME,{className:"h-5 w-5"})})}),e.jsx(my,{side:"left",className:"w-72 p-0 bg-card",children:e.jsx(vRs,{isTrial:x,isExpired:y,expiresAt:v,communityUnreadCount:R,wishlistOpenCount:D,pathname:G.pathname,onSignOut:r,onNavigated:()=>ne(!1)})})]}),e.jsx("div",{className:"flex-1 md:hidden",children:e.jsx("img",{src:r5s,alt:"LevelUp",className:"h-8 w-auto"})}),e.jsx("div",{className:"hidden md:flex flex-1 justify-center",children:e.jsx(Dyt,{})}),e.jsxs("div",{className:"flex items-center gap-3 ml-auto",children:[x&&!y&&v&&e.jsx(_6s,{expiresAt:v,className:"hidden lg:flex"}),e.jsx("div",{className:"md:hidden",children:e.jsx(Dyt,{})}),w&&e.jsx(j6s,{hasUnseenBrief:A,onClick:E}),b&&e.jsxs($,{variant:"ghost",size:"icon",className:"relative",onClick:()=>V("/marketplace/cart"),children:[e.jsx(tC,{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(jLs,{}),e.jsx(VHe,{}),e.jsxs("span",{className:"hidden sm:block text-sm font-medium text-foreground",children:["Hello, ",ae.split(" ")[0],"!"]}),e.jsxs($u,{children:[e.jsx(Uu,{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(Au,{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(JN,{className:"h-4 w-4 mr-2"}),"Integrations"]}),e.jsxs(ja,{onClick:()=>V("/mission-control/browser-extension"),className:"cursor-pointer",children:[e.jsx(JN,{className:"h-4 w-4 mr-2"}),"Browser Extension"]}),e.jsx(I0,{}),e.jsxs(ja,{onClick:r,className:"cursor-pointer text-destructive focus:text-destructive",children:[e.jsx(qz,{className:"h-4 w-4 mr-2"}),"Sign Out"]})]})]})]})]})}),e.jsx(eRs,{children:e.jsx("main",{className:"p-4 sm:p-6 lg:p-8 overflow-x-hidden",children:s})}),w&&e.jsx(X6s,{brief:w,open:S,onClose:I,onDismiss:P}),e.jsx(J6s,{}),e.jsx(sRs,{}),e.jsx(aRs,{})]})]})})},wn=({children:s,requireAdmin:t=!1,requireBrokerageManager:n=!1})=>{const{user:r,loading:a,rolesLoading:i,isAdmin:l,isBrokerageManager:o}=bs(),c=mu(),d=_C();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(Rd,{to:"/auth",replace:!0})}if(t&&!l)return e.jsx(Rd,{to:"/dashboard",replace:!0});if(n&&!o&&!l)return e.jsx(Rd,{to:"/dashboard",replace:!0});if(d.isRestricted&&!d.isLoading){const u=MOt(c.pathname);if(u&&!d.hasFeature(u))return e.jsx(Vs,{title:"Upgrade required",children:e.jsx(TCs,{featureKey:u})})}return e.jsx(e.Fragment,{children:s})};function i7e({children:s}){const{isAdmin:t,loading:n,rolesLoading:r}=bs(),{isFeatureEnabled:a,isLoading:i}=Tae();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(Rd,{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 Dtt={};(function s(t,n,r,a){var i=!!(t.Worker&&t.Blob&&t.Promise&&t.OffscreenCanvas&&t.OffscreenCanvasRenderingContext2D&&t.HTMLCanvasElement&&t.HTMLCanvasElement.prototype.transferControlToOffscreen&&t.URL&&t.URL.createObjectURL),l=typeof Path2D=="function"&&typeof DOMMatrix=="function",o=function(){if(!t.OffscreenCanvas)return!1;try{var ne=new OffscreenCanvas(1,1),te=ne.getContext("2d");te.fillRect(0,0,1,1);var J=ne.transferToImageBitmap();te.createPattern(J,"no-repeat")}catch{return!1}return!0}();function c(){}function d(ne){var te=n.exports.Promise,J=te!==void 0?te:t.Promise;return typeof J=="function"?new J(ne):(ne(c,c),null)}var u=function(ne,te){return{transform:function(J){if(ne)return J;if(te.has(J))return te.get(J);var ce=new OffscreenCanvas(J.width,J.height),_e=ce.getContext("2d");return _e.drawImage(J,0,0),te.set(J,ce),ce},clear:function(){te.clear()}}}(o,new Map),h=function(){var ne=Math.floor(16.666666666666668),te,J,ce={},_e=0;return typeof requestAnimationFrame=="function"&&typeof cancelAnimationFrame=="function"?(te=function(he){var ue=Math.random();return ce[ue]=requestAnimationFrame(function ve(Ee){_e===Ee||_e+ne-1{const{data:t,error:n}=await q.from("celebration_queue").select("*").eq("user_id",s.id).is("seen_at",null).order("created_at",{ascending:!0});if(n)throw n;return t},enabled:!!(s!=null&&s.id),refetchOnWindowFocus:!0,staleTime:0})}function _Rs(){const s=Wt();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 wRs(){const s=Wt(),{user:t}=bs();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 jRs={points_earned:Kl,listing_created:va,deal_closed:nu,custom:ei},Byt={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"},$yt=()=>{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 NRs(){const{user:s}=bs(),t=Wt(),{data:n}=bRs(),r=_Rs(),[a,i]=j.useState(null),[l,o]=j.useState(!1),c=j.useCallback(()=>{const f=Date.now()+3e3,g={startVelocity:30,spread:360,ticks:60,zIndex:9999},x=(v,b)=>Math.random()*(b-v)+v,y=setInterval(()=>{const v=f-Date.now();if(v<=0){clearInterval(y);return}const b=50*(v/3e3);zyt({...g,particleCount:b,origin:{x:x(.1,.3),y:Math.random()-.2},colors:["#ff6b6b","#feca57","#48dbfb","#ff9ff3","#54a0ff","#5f27cd"]}),zyt({...g,particleCount:b,origin:{x:x(.7,.9),y:Math.random()-.2},colors:["#ff6b6b","#feca57","#48dbfb","#ff9ff3","#54a0ff","#5f27cd"]})},250)},[]);j.useEffect(()=>{$yt()||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($yt()||!a)return null;const u=jRs[a.celebration_type]||ei,h=Byt[a.celebration_type]||Byt.custom;return e.jsx(zs,{open:l,onOpenChange:m=>!m&&d(),children:e.jsxs(Os,{className:"sm:max-w-md text-center border-0 overflow-hidden",children:[e.jsx("div",{className:`absolute inset-0 bg-gradient-to-br ${h} opacity-10`}),e.jsxs("div",{className:"relative z-10 py-6",children:[e.jsx("div",{className:"flex justify-center mb-4",children:e.jsx("div",{className:`w-20 h-20 rounded-full bg-gradient-to-br ${h} flex items-center justify-center animate-bounce`,children:e.jsx(u,{className:"w-10 h-10 text-white"})})}),e.jsxs("div",{className:"flex justify-center gap-1 mb-4",children:[e.jsx(Nn,{className:"w-5 h-5 text-yellow-500 animate-pulse"}),e.jsx(Nn,{className:"w-5 h-5 text-yellow-500 animate-pulse delay-75"}),e.jsx(Nn,{className:"w-5 h-5 text-yellow-500 animate-pulse delay-150"})]}),e.jsxs("h2",{className:"text-2xl font-bold mb-2 bg-gradient-to-r from-primary to-secondary bg-clip-text text-transparent",children:["🎉 ",a.title]}),a.points_amount&&a.points_amount>0&&e.jsxs("div",{className:"text-4xl font-bold text-primary mb-2",children:["+",a.points_amount," points!"]}),a.message&&e.jsx("p",{className:"text-muted-foreground mb-6",children:a.message}),e.jsx($,{onClick:d,className:"w-full",size:"lg",children:"Awesome! 🙌"}),n&&n.length>1&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-3",children:["+",n.length-1," more celebration",n.length>2?"s":""," waiting"]})]})]})})}function xn({className:s,...t}){return e.jsx("div",{className:Pt("animate-pulse rounded-md bg-muted",s),...t})}var kRs=Object.defineProperty,tK=(s,t)=>kRs(s,"name",{value:t,configurable:!0}),Ftt="Tabs",[SRs,Bkr]=tp(Ftt,[t6]),c7t=t6(),[CRs,Ott]=SRs(Ftt),ARs=j.forwardRef(tK(function(t,n){const{__scopeTabs:r,value:a,onValueChange:i,defaultValue:l,orientation:o="horizontal",dir:c,activationMode:d="automatic",...u}=t,h=i3(c),[m,f]=hy({prop:a,onChange:i,defaultProp:l??"",caller:Ftt});return e.jsx(CRs,{scope:r,baseId:uy(),value:m,onValueChange:f,orientation:o,dir:h,activationMode:d,children:e.jsx(Ei.div,{dir:h,"data-orientation":o,...u,ref:n})})},"Tabs")),ERs="TabsList",TRs=j.forwardRef(tK(function(t,n){const{__scopeTabs:r,loop:a=!0,...i}=t,l=Ott(ERs,r),o=c7t(r);return e.jsx(mLe,{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")),MRs="TabsTrigger",PRs=j.forwardRef(tK(function(t,n){const{__scopeTabs:r,value:a,disabled:i=!1,...l}=t,o=Ott(MRs,r),c=c7t(r),d=ztt(o.baseId,a),u=Btt(o.baseId,a),h=a===o.value;return e.jsx(fLe,{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")),IRs="TabsContent",LRs=j.forwardRef(tK(function(t,n){const{__scopeTabs:r,value:a,forceMount:i,children:l,...o}=t,c=Ott(IRs,r),d=ztt(c.baseId,a),u=Btt(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(py,{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 ztt(s,t){return`${s}-trigger-${t}`}tK(ztt,"makeTriggerId");function Btt(s,t){return`${s}-content-${t}`}tK(Btt,"makeContentId");var RRs=ARs,d7t=TRs,u7t=PRs,h7t=LRs;const ha=RRs,ma=j.forwardRef(({className:s,...t},n)=>e.jsx(d7t,{ref:n,className:Pt("inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",s),...t}));ma.displayName=d7t.displayName;const Zt=j.forwardRef(({className:s,...t},n)=>e.jsx(u7t,{ref:n,className:Pt("inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",s),...t}));Zt.displayName=u7t.displayName;const Xt=j.forwardRef(({className:s,...t},n)=>e.jsx(h7t,{ref:n,className:Pt("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",s),...t}));Xt.displayName=h7t.displayName;const Qte="#0d0d0d",EEe="#1a1a1a",lb="#c9a84c",Bae="#f0d78c",G4={captured:"lup_lead_captured_v1",stickyDismissed:"lup_sticky_dismissed_v1",exitShown:"lup_exit_shown_v1",savedListings:"lup_saved_listings_v1"};async function $Le(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(G4.captured,JSON.stringify({email:s.email,ts:Date.now()}))}catch{}return n}function $tt(){try{return!!localStorage.getItem(G4.captured)}catch{return!1}}function DRs(){try{const s=localStorage.getItem(G4.captured);return s?JSON.parse(s).email??null:null}catch{return null}}function Utt({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?vv.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, ${EEe} 0%, ${Qte} 100%)`,border:`1px solid ${lb}33`,boxShadow:`0 30px 80px rgba(0,0,0,0.6), 0 0 0 1px ${lb}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(pr,{className:"h-4 w-4"})}),n]})}),document.body):null}function qtt(){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 Vtt({values:s,setValues:t,honeypot:n,setHoneypot:r,showPhone:a=!0,showArea:i=!0,areaPlaceholder:l="City, ZIP, or neighborhood"}){const o="w-full rounded-lg px-11 py-3 text-sm text-white placeholder:text-white/40 border transition focus:outline-none",c={background:"rgba(255,255,255,0.04)",borderColor:"rgba(255,255,255,0.12)"};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(sl,{className:"absolute left-3.5 top-1/2 -translate-y-1/2 h-4 w-4 text-white/40"}),e.jsx("input",{type:"text",placeholder:"First name",value:s.first_name,onChange:d=>t({...s,first_name:d.target.value}),className:o,style:c})]}),e.jsxs("div",{className:"relative",children:[e.jsx(mn,{className:"absolute left-3.5 top-1/2 -translate-y-1/2 h-4 w-4 text-white/40"}),e.jsx("input",{type:"email",required:!0,placeholder:"Email address",value:s.email,onChange:d=>t({...s,email:d.target.value}),className:o,style:c})]}),a&&e.jsxs("div",{className:"relative",children:[e.jsx(Da,{className:"absolute left-3.5 top-1/2 -translate-y-1/2 h-4 w-4 text-white/40"}),e.jsx("input",{type:"tel",placeholder:"Phone (optional)",value:s.phone,onChange:d=>t({...s,phone:d.target.value}),className:o,style:c})]}),i&&e.jsxs("div",{className:"relative",children:[e.jsx(ci,{className:"absolute left-3.5 top-1/2 -translate-y-1/2 h-4 w-4 text-white/40"}),e.jsx("input",{type:"text",placeholder:l,value:s.area,onChange:d=>t({...s,area:d.target.value}),className:o,style:c})]}),e.jsx("input",{type:"text",value:n,onChange:d=>r(d.target.value),tabIndex:-1,autoComplete:"off",className:"absolute -left-[9999px] w-0 h-0 opacity-0","aria-hidden":"true"})]})}function Htt({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, ${Bae} 0%, ${lb} 100%)`,color:Qte,boxShadow:`0 8px 24px ${lb}55`},children:s})}function Uyt({open:s,onClose:t,initialCriteria:n}){const{values:r,setValues:a,loading:i,setLoading:l,honeypot:o,setHoneypot:c}=qtt(),[d,u]=j.useState(!1),h=async m=>{if(m.preventDefault(),!!r.email){l(!0);try{await $Le({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(G4.stickyDismissed,"1")}catch{}setTimeout(t,2200)}catch{re.error("Something went wrong. Please try again.")}finally{l(!1)}}};return e.jsx(Utt,{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(Uy,{className:"h-4 w-4",style:{color:lb}}),e.jsx("span",{className:"text-xs uppercase tracking-[0.2em]",style:{color:Bae},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:`${lb}22`,border:`1px solid ${lb}55`},children:e.jsx(Nn,{className:"h-5 w-5",style:{color:lb}})}),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(Vtt,{values:r,setValues:a,honeypot:o,setHoneypot:c}),e.jsx(Htt,{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 FRs(){const[s,t]=j.useState(!0),[n,r]=j.useState(!1);j.useEffect(()=>{try{const i=!!localStorage.getItem(G4.stickyDismissed)||$tt();t(i)}catch{t(!1)}},[]);const a=()=>{t(!0);try{localStorage.setItem(G4.stickyDismissed,"1")}catch{}};return s?e.jsx(Uyt,{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, ${EEe} 0%, ${Qte} 100%)`,borderTop:`1px solid ${lb}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:`${lb}22`,border:`1px solid ${lb}55`},children:e.jsx(Uy,{className:"h-4 w-4",style:{color:lb}})}),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, ${Bae} 0%, ${lb} 100%)`,color:Qte},children:"Get Alerts"}),e.jsx("button",{onClick:a,className:"p-2 text-white/50 hover:text-white transition","aria-label":"Dismiss",children:e.jsx(pr,{className:"h-4 w-4"})})]})}),e.jsx(Uyt,{open:n,onClose:()=>r(!1)})]})}function ORs(){const[s,t]=j.useState(!1),n=j.useRef(!1);j.useEffect(()=>{try{if(sessionStorage.getItem(G4.exitShown)||$tt())return}catch{}const m=setTimeout(()=>{n.current=!0},8e3),f=g=>{if(n.current&&!(g.clientY>0)){t(!0);try{sessionStorage.setItem(G4.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}=qtt(),[d,u]=j.useState(!1),h=async m=>{if(m.preventDefault(),!!r.email){l(!0);try{await $Le({lead_type:"exit_intent",email:r.email.trim().toLowerCase(),first_name:r.first_name.trim()||void 0,phone:r.phone.trim()||void 0,criteria:r.area.trim()?{area:r.area.trim()}:void 0}),u(!0),setTimeout(()=>t(!1),2200)}catch{re.error("Something went wrong. Please try again.")}finally{l(!1)}}};return e.jsx(Utt,{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, ${Qte} 0%, ${EEe} 60%, ${lb} 130%)`},children:e.jsx("div",{className:"absolute top-4 left-6",children:e.jsx("span",{className:"text-[10px] uppercase tracking-[0.25em]",style:{color:Bae},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:EEe,border:`1px solid ${lb}55`,boxShadow:"0 8px 24px rgba(0,0,0,0.5)"},children:e.jsx(Nn,{className:"h-6 w-6",style:{color:lb}})}),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(Vtt,{values:r,setValues:a,honeypot:o,setHoneypot:c,showPhone:!1}),e.jsx(Htt,{type:"submit",disabled:i||!r.email,children:i?"Sending…":"Send My List"})]})]})]})})}function zRs(){const[s,t]=j.useState([]);j.useEffect(()=>{try{const o=localStorage.getItem(G4.savedListings);o&&t(JSON.parse(o))}catch{}},[]);const n=o=>{t(o);try{localStorage.setItem(G4.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 BRs({listingId:s,listingAddress:t,className:n}){const{has:r,add:a,remove:i}=zRs(),l=r(s),[o,c]=j.useState(!1),d=()=>{if(l){i(s);return}if($tt()){a(s),re.success("Saved to your favorites"),$Le({lead_type:"saved_listing",email:DRs()||"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($Rs,{open:o,onClose:()=>c(!1),listingId:s,listingAddress:t,onSaved:()=>a(s)})]})}function $Rs({open:s,onClose:t,listingId:n,listingAddress:r,onSaved:a}){const{values:i,setValues:l,loading:o,setLoading:c,honeypot:d,setHoneypot:u}=qtt(),h=async m=>{if(m.preventDefault(),!!i.email){c(!0);try{await $Le({lead_type:"saved_listing",email:i.email.trim().toLowerCase(),first_name:i.first_name.trim()||void 0,phone:i.phone.trim()||void 0,listing_id:n,listing_address:r}),a(),re.success("Saved to your favorites"),t()}catch{re.error("Something went wrong. Please try again.")}finally{c(!1)}}};return e.jsx(Utt,{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:lb}}),e.jsx("span",{className:"text-xs uppercase tracking-[0.2em]",style:{color:Bae},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(Vtt,{values:i,setValues:l,honeypot:d,setHoneypot:u}),e.jsx(Htt,{type:"submit",disabled:o||!i.email,children:o?"Saving…":"Save Home"})]})]})})}var URs=Object.defineProperty,Bh=(s,t)=>URs(s,"name",{value:t,configurable:!0}),m7t=["PageUp","PageDown"],f7t=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],p7t={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},$ae="Slider",[QHe,qRs,VRs]=EB($ae),[Gtt,$kr]=tp($ae,[VRs]),[HRs,Uae]=Gtt($ae),g7t=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,...y}=t,v=j.useRef(new Set),b=j.useRef(0),w=j.useRef(!1),A=o==="horizontal"?GRs:WRs,[E,I]=j.useState(null),P=Vo(n,I),[R=[],D]=hy({prop:h,defaultProp:u,onChange:Bh(X=>{var le;(le=[...v.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=N7t(R,X);Y(X,ae)}Bh(W,"handleSlideStart");function V(X){Y(X,b.current)}Bh(V,"handleSlideMove");function G(){String(R)!==String(O.current)&&f(R)}Bh(G,"handleSlideEnd");function Y(X,ae,{commit:le}={commit:!1}){const ne=Ktt(l),te=pee(Math.round((X-a)/l)*l+a,ne),J=yG(te,[a,i]);D((ce=[])=>{const _e=w7t(ce,J,ae);if(C7t(_e,d*l)){b.current=_e.indexOf(J);const he=String(_e)!==String(ce);return he&&le&&f(_e),he?_e:ce}else return ce})}return Bh(Y,"updateValues"),e.jsx(HRs,{scope:t.__scopeSlider,name:r,disabled:c,min:a,max:i,valueIndexToChangeRef:b,thumbs:v.current,values:R,orientation:o,form:x,children:e.jsx(QHe.Provider,{scope:t.__scopeSlider,children:e.jsx(QHe.Slot,{scope:t.__scopeSlider,children:e.jsx(A,{"aria-disabled":c,"data-disabled":c?"":void 0,...y,ref:P,onPointerDown:Ra(y.onPointerDown,()=>{c||(O.current=R,w.current=!1)}),min:a,max:i,inverted:g,onSlideStart:c?void 0:W,onSlideMove:c?void 0:V,onSlideEnd:c?void 0:G,onHomeKeyDown:()=>{c||(w.current=!0,Y(a,0,{commit:!0}))},onEndKeyDown:()=>{c||(w.current=!0,Y(i,R.length-1,{commit:!0}))},onStepKeyDown:({event:X,direction:ae})=>{if(!c){w.current=!0;const te=m7t.includes(X.key)||X.shiftKey&&f7t.includes(X.key)?10:1,J=b.current,ce=R[J],_e=A7t(ce,{min:a,step:l,direction:ae,multiplier:te});Y(_e,J,{commit:!0})}}})})})})},"Slider")),[x7t,y7t]=Gtt($ae,{startEdge:"left",endEdge:"right",size:"width",direction:1}),GRs=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),y=i3(i),v=y==="ltr",b=v&&!l||!v&&l;function w(S){const A=x.current||m.getBoundingClientRect(),E=[0,A.width],P=ULe(E,b?[r,a]:[a,r]);return x.current=A,P(S-A.left)}return Bh(w,"getValueFromPointer"),e.jsx(x7t,{scope:t.__scopeSlider,startEdge:b?"left":"right",endEdge:b?"right":"left",direction:b?1:-1,size:"width",children:e.jsx(v7t,{dir:y,"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=p7t[b?"from-left":"from-right"].includes(S.key);u==null||u({event:S,direction:E?-1:1})}})})},"SliderHorizontal")),WRs=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(y){const v=f.current||h.current.getBoundingClientRect(),b=[0,v.height],S=ULe(b,g?[a,r]:[r,a]);return f.current=v,S(y-v.top)}return Bh(x,"getValueFromPointer"),e.jsx(x7t,{scope:t.__scopeSlider,startEdge:g?"bottom":"top",endEdge:g?"top":"bottom",size:"height",direction:g?1:-1,children:e.jsx(v7t,{"data-orientation":"vertical",...u,ref:m,style:{...u.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:y=>{const v=x(y.clientY);l==null||l(v)},onSlideMove:y=>{const v=x(y.clientY);o==null||o(v)},onSlideEnd:()=>{f.current=void 0,c==null||c()},onStepKeyDown:y=>{const b=p7t[g?"from-bottom":"from-top"].includes(y.key);d==null||d({event:y,direction:b?-1:1})}})})},"SliderVertical")),v7t=j.forwardRef(Bh(function(t,n){const{__scopeSlider:r,onSlideStart:a,onSlideMove:i,onSlideEnd:l,onHomeKeyDown:o,onEndKeyDown:c,onStepKeyDown:d,...u}=t,h=Uae($ae,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()):m7t.concat(f7t).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")),KRs="SliderTrack",YRs=j.forwardRef(Bh(function(t,n){const{__scopeSlider:r,...a}=t,i=Uae(KRs,r);return e.jsx(Ei.span,{"data-disabled":i.disabled?"":void 0,"data-orientation":i.orientation,...a,ref:n})},"SliderTrack")),qyt="SliderRange",ZRs=j.forwardRef(Bh(function(t,n){const{__scopeSlider:r,...a}=t,i=Uae(qyt,r),l=y7t(qyt,r),o=j.useRef(null),c=Vo(n,o),d=i.values.length,u=i.values.map(f=>Wtt(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")),XRs="SliderThumb",[QRs,b7t]=Gtt(XRs),JRs="SliderThumbProvider";function _7t(s){const{__scopeSlider:t,name:n,children:r,internal_do_not_use_render:a}=s,i=Uae(JRs,t),l=qRs(t),[o,c]=j.useState(null),d=j.useMemo(()=>o?l().findIndex(y=>y.ref.current===o):-1,[l,o]),u=WW(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:Wtt(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(QRs,{scope:t,...x,children:E7t(a)?a(x):r})}Bh(_7t,"SliderThumbProvider");var o7e="SliderThumbTrigger",eDs=j.forwardRef(Bh(function(t,n){const{__scopeSlider:r,...a}=t,i=Uae(o7e,r),l=y7t(o7e,r),{index:o,value:c,percent:d,size:u,onThumbChange:h}=b7t(o7e,r),m=Vo(n,h),f=j7t(o,i.values.length),g=u==null?void 0:u[l.size],x=g?k7t(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(QHe.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")),tDs=j.forwardRef(Bh(function(t,n){const{__scopeSlider:r,name:a,...i}=t;return e.jsx(_7t,{__scopeSlider:r,name:a,internal_do_not_use_render:({index:l,isFormControl:o})=>e.jsxs(e.Fragment,{children:[e.jsx(eDs,{...i,ref:n,__scopeSlider:r}),o?e.jsx(nDs,{__scopeSlider:r},l):null]})})},"SliderThumb")),sDs="SliderBubbleInput",nDs=j.forwardRef(Bh(function({__scopeSlider:t,...n},r){const{value:a,name:i,form:l}=b7t(sDs,t),o=j.useRef(null),c=Vo(o,r),d=ftt(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 w7t(s=[],t,n){const r=[...s];return r[n]=t,r.sort((a,i)=>a-i)}Bh(w7t,"getNextSortedValues");function Wtt(s,t,n){const i=100/(n-t)*(s-t);return yG(i,[0,100])}Bh(Wtt,"convertValueToPercentage");function j7t(s,t){return t>2?`Value ${s+1} of ${t}`:t===2?["Minimum","Maximum"][s]:void 0}Bh(j7t,"getLabel");function N7t(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(N7t,"getClosestValueIndex");function k7t(s,t,n){const r=s/2,i=ULe([0,50],[0,r]);return(r-i(t)*n)*n}Bh(k7t,"getThumbInBoundsOffset");function S7t(s){return s.slice(0,-1).map((t,n)=>s[n+1]-t)}Bh(S7t,"getStepsBetweenValues");function C7t(s,t){if(t>0){const n=S7t(s);return Math.min(...n)>=t}return!0}Bh(C7t,"hasMinStepsBetweenValues");function ULe(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(ULe,"linearScale");function Ktt(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(Ktt,"getDecimalCount");function pee(s,t){const n=Math.pow(10,t);return Math.round(s*n)/n}Bh(pee,"roundValue");function A7t(s,{min:t,step:n,direction:r,multiplier:a}){const i=Ktt(n),l=(s-t)/n,o=Math.round(l),c=pee(o*n+t,i)===pee(s,i);let d;return c?d=o+a*r:r>0?d=Math.ceil(l):d=Math.floor(l),pee(d*n+t,i)}Bh(A7t,"getNextStepValue");function E7t(s){return typeof s=="function"}Bh(E7t,"isFunction");const Nx=j.forwardRef(({className:s,...t},n)=>e.jsxs(g7t,{ref:n,className:Pt("relative flex w-full touch-none select-none items-center",s),...t,children:[e.jsx(YRs,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:e.jsx(ZRs,{className:"absolute h-full bg-primary"})}),e.jsx(tDs,{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"})]}));Nx.displayName=g7t.displayName;const rDs=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}}),aDs=()=>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)}}}),iDs=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}),oDs=()=>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:y}=await q.from("listing_leads").insert({id:g,listing_id:s,agent_id:f||t,first_name:n,last_name:r,email:a,phone:i,share_id:m,referred_by_agent_id:f,lead_type:o,preferred_date:c||null,preferred_time:d||null,showing_mode:u||null,message:h||null});if(y)throw y;const{error:v}=await q.functions.invoke("process-listing-lead",{body:{leadId:x.id}});return v&&console.error("Error processing lead:",v),x}}),lDs=()=>mt({mutationFn:async s=>{const{error:t}=await q.rpc("increment_listing_share_click",{p_share_token:s});if(t)throw t}});function T7t({title:s,subtitle:t,areaLabel:n,sections:r,agent:a,tone:i="light"}){const l=i==="dark",o=l?"text-white/65":"text-muted-foreground",c=l?"border-white/10":"border-border";return e.jsxs("div",{className:l?"text-white":"text-foreground",id:"community-guide-print",children:[e.jsxs("header",{className:`border-b ${c} pb-6 mb-8`,children:[e.jsxs("div",{className:`flex items-center gap-2 text-[11px] uppercase tracking-[0.22em] ${o} mb-3`,children:[e.jsx(Xf,{className:"h-3.5 w-3.5"}),"Insider's Community Guide"]}),e.jsx("h1",{className:"font-display text-3xl sm:text-4xl font-semibold leading-tight",children:s}),t&&e.jsx("p",{className:`mt-3 text-base leading-relaxed ${o}`,children:t}),n&&e.jsxs("p",{className:`mt-3 flex items-center gap-1.5 text-sm ${o}`,children:[e.jsx(ci,{className:"h-3.5 w-3.5"}),n]})]}),e.jsx("div",{className:"space-y-10",children:r.map((d,u)=>e.jsxs("section",{children:[e.jsxs("div",{className:"flex items-baseline gap-3 mb-2",children:[e.jsx("span",{className:"font-display text-2xl text-primary font-semibold",children:String(u+1).padStart(2,"0")}),e.jsx("h2",{className:"font-display text-xl sm:text-2xl font-semibold",children:d.heading})]}),d.intro&&e.jsx("p",{className:`text-sm sm:text-base leading-relaxed ${o} mb-4`,children:d.intro}),e.jsx("ul",{className:"space-y-3",children:(d.items??[]).map((h,m)=>e.jsxs("li",{className:`rounded-xl border ${c} ${l?"bg-white/[0.03]":"bg-muted/40"} px-4 py-3`,children:[e.jsx("p",{className:"font-medium text-sm sm:text-base",children:h.name}),h.note&&e.jsx("p",{className:`text-sm mt-1 leading-relaxed ${o}`,children:h.note})]},m))})]},u))}),(a==null?void 0:a.name)&&e.jsxs("footer",{className:`mt-10 pt-6 border-t ${c}`,children:[e.jsxs("div",{className:"flex items-center gap-4",children:[a.avatar_url?e.jsx("img",{src:a.avatar_url,alt:a.name,className:"h-14 w-14 rounded-full object-cover border border-primary/30"}):null,e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:`text-[11px] uppercase tracking-[0.2em] ${o}`,children:"Prepared for you by"}),e.jsx("p",{className:"font-display text-lg font-semibold leading-tight",children:a.name}),a.brokerage&&e.jsx("p",{className:`text-sm ${o}`,children:a.brokerage}),e.jsxs("div",{className:`flex flex-wrap gap-4 mt-1.5 text-sm ${o}`,children:[a.phone&&e.jsxs("a",{href:`tel:${a.phone}`,className:"flex items-center gap-1.5 hover:text-primary",children:[e.jsx(Da,{className:"h-3.5 w-3.5"}),a.phone]}),a.email&&e.jsxs("a",{href:`mailto:${a.email}`,className:"flex items-center gap-1.5 hover:text-primary",children:[e.jsx(mn,{className:"h-3.5 w-3.5"}),a.email]})]})]})]}),e.jsxs("p",{className:`mt-4 text-sm ${o}`,children:["Thinking about a move in ",n||"the area","? Reach out any time — happy to share what never makes it online."]})]})]})}const Rce="border-white/15 bg-white/5 text-white placeholder:text-white/40";function cDs({listingId:s}){const[t,n]=j.useState(null),[r,a]=j.useState({firstName:"",lastName:"",email:"",phone:""}),[i,l]=j.useState(!1),[o,c]=j.useState(null),[d,u]=j.useState(!1);if(j.useEffect(()=>{let m=!1;return q.functions.invoke("community-guide-public",{body:{action:"teaser",listingId:s}}).then(({data:f})=>{!m&&f&&n(f)}).catch(()=>{}),()=>{m=!0}},[s]),!(t!=null&&t.available))return null;const h=async m=>{if(m.preventDefault(),!r.firstName.trim()||!r.email.trim()){re.error("Please add your name and email.");return}l(!0);try{const{data:f,error:g}=await q.functions.invoke("community-guide-public",{body:{action:"unlock",listingId:s,...r}});if(g||f!=null&&f.error)throw new Error((f==null?void 0:f.error)||"Something went wrong.");c(f),u(!0),re.success("Your guide is ready!")}catch(f){re.error((f==null?void 0:f.message)||"We could not send your guide. Please try again.")}finally{l(!1)}};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/[0.03] p-6 backdrop-blur",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[11px] uppercase tracking-[0.2em] text-white/60 mb-3",children:[e.jsx(Xf,{className:"h-3.5 w-3.5"}),"Free Community Guide"]}),e.jsx("h3",{className:"font-display text-xl text-white font-medium leading-snug",children:t.title}),t.subtitle&&e.jsx("p",{className:"text-sm text-white/60 mt-2 leading-relaxed",children:t.subtitle}),(t.teaser??[]).length>0&&e.jsx("ul",{className:"mt-4 space-y-2",children:t.teaser.map((m,f)=>e.jsxs("li",{className:"flex gap-2 text-sm text-white/70",children:[e.jsx(ca,{className:"h-4 w-4 text-primary shrink-0 mt-0.5"}),m]},f))}),o?e.jsxs($,{className:"w-full mt-5",onClick:()=>u(!0),children:[e.jsx(Xf,{className:"h-4 w-4 mr-2"}),"Read your guide"]}):e.jsxs("form",{onSubmit:h,className:"mt-5 space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"cg-first",className:"text-xs text-white/60",children:"First name"}),e.jsx(pe,{id:"cg-first",value:r.firstName,onChange:m=>a({...r,firstName:m.target.value}),className:Rce,required:!0})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"cg-last",className:"text-xs text-white/60",children:"Last name"}),e.jsx(pe,{id:"cg-last",value:r.lastName,onChange:m=>a({...r,lastName:m.target.value}),className:Rce})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"cg-email",className:"text-xs text-white/60",children:"Email"}),e.jsx(pe,{id:"cg-email",type:"email",value:r.email,onChange:m=>a({...r,email:m.target.value}),className:Rce,required:!0})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"cg-phone",className:"text-xs text-white/60",children:"Cell phone"}),e.jsx(pe,{id:"cg-phone",type:"tel",value:r.phone,onChange:m=>a({...r,phone:m.target.value}),className:Rce})]}),e.jsxs($,{type:"submit",className:"w-full",disabled:i,children:[i?e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(xi,{className:"h-4 w-4 mr-2"}),i?"Preparing your guide…":"Get the free guide"]}),e.jsxs("p",{className:"text-[11px] text-white/50 flex items-center gap-1.5 justify-center",children:[e.jsx(pc,{className:"h-3 w-3"}),"Instant access. We never share your details."]})]})]}),e.jsx(zs,{open:d,onOpenChange:u,children:e.jsx(Os,{className:"max-w-2xl p-0 gap-0",children:e.jsx(uo,{className:"max-h-[82vh]",children:e.jsxs("div",{className:"p-6 sm:p-8",children:[e.jsx("div",{id:"community-guide-print",children:o&&e.jsx(T7t,{title:o.title,subtitle:o.subtitle,areaLabel:o.area_label,sections:o.sections??[],agent:o.agent})}),e.jsx("div",{className:"mt-8 flex justify-end print:hidden",children:e.jsxs($,{variant:"outline",onClick:()=>dDs(o==null?void 0:o.title),children:[e.jsx(xi,{className:"h-4 w-4 mr-2"}),"Save as PDF"]})})]})})})})]})}function dDs(s){const t=document.getElementById("community-guide-print");if(!t)return window.print();const n=t.cloneNode(!0);n.removeAttribute("id"),n.setAttribute("data-print-root",""),document.body.appendChild(n),document.body.classList.add("printing-doc");const r=document.title;s&&(document.title=s);let a=!1;const i=()=>{a||(a=!0,n.remove(),document.body.classList.remove("printing-doc"),document.title=r,window.removeEventListener("afterprint",i))};window.addEventListener("afterprint",i);try{window.print()}finally{setTimeout(i,1e3)}}const AL={sale:"For Sale",lease:"For Lease",sale_or_lease:"For Sale or Lease",investment:"Investment Offering"},i6={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"},uDs=["NNN","Modified Gross","Full Service","Gross","Absolute Net","Ground Lease"],hDs={sf_year:"/SF/YR",sf_month:"/SF/MO",month:"/MO"},JHe={om:"Offering Memorandum",flyer:"Flyer",rent_roll:"Rent Roll",financials:"Financials",survey:"Survey",site_plan:"Site Plan",lease:"Lease Documents",other:"Other"},Vyt={public:"Open download",email:"Email required",nda:"NDA required"},eGe={principal:"Principal / Investor",broker:"Broker",tenant:"Tenant / User",lender:"Lender",other:"Other"},l7e=[{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"}],Z4e=[{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"}],M7t=[{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 LN(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 Hyt(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`:LN(t)}function yE(s){return s==null?null:`${new Intl.NumberFormat("en-US").format(Number(s))} SF`}function TEe(s,t=2){return s==null?null:`${Number(s).toFixed(t).replace(/\.?0+$/,"")}%`}function tGe(s){if(!(s!=null&&s.lease_rate))return null;const t=hDs[s.lease_rate_unit||"sf_year"]??"";return`${s.lease_rate_unit==="month"?LN(s.lease_rate):`$${Number(s.lease_rate).toFixed(2).replace(/\.00$/,"")}`}${t}${s.lease_type?` ${s.lease_type}`:""}`}function kG(s,t){if(!s)return LN(t)??"Price on request";if(s.deal_type==="lease")return tGe(s)??"Rate on request";const n=s.asking_price??t;if(s.deal_type==="sale_or_lease"){const r=[LN(n),tGe(s)].filter(Boolean);return r.length?r.join(" · "):"Price on request"}return LN(n)??"Price on request"}function rL(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?i6[t.commercial_type]:"Commercial"} Opportunity`:s.property_address||`${s.city??""}, ${s.state??""}`}function qae(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 mDs(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 Z4e)(a[l.key]||n[l.key])&&r.push(l.key);return{done:r,total:Z4e.length,score:Math.round(r.length/Z4e.length*100)}}const Gyt={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 Wyt(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 fDs="https://commercial.relevelup.com",W4=q;function P7t(s){return st({queryKey:["commercial-details",s],queryFn:async()=>{const{data:t,error:n}=await W4.from("commercial_listing_details").select("*").eq("listing_id",s).maybeSingle();if(n)throw n;return t??null},enabled:!!s})}function I7t(){const s=Wt(),{user:t}=bs();return mt({mutationFn:async({listingId:n,values:r})=>{const{data:a,error:i}=await W4.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 pDs(s){return st({queryKey:["commercial-pitch",s],queryFn:async()=>{const{data:t,error:n}=await W4.from("commercial_pitch_details").select("*").eq("listing_id",s).maybeSingle();if(n)throw n;return t??null},enabled:!!s})}function L7t(){const s=Wt(),{user:t}=bs();return mt({mutationFn:async({listingId:n,values:r})=>{const{data:a,error:i}=await W4.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 R7t(){const s=Wt();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 W4.from("listings").update(l).eq("id",t);if(o)throw o;return(a||i)&&await W4.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 gDs(){const s=Wt();return mt({mutationFn:async({listingId:t,values:n})=>{const{error:r}=await W4.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 Ytt(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 W4.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 Ztt(s){return st({queryKey:["commercial-leads",s],queryFn:async()=>{const{data:t,error:n}=await W4.from("listing_leads").select("*").eq("listing_id",s).order("created_at",{ascending:!1});if(n)throw n;return t??[]},enabled:!!s})}const Kyt="lu_commercial_session";function D7t(){try{let s=localStorage.getItem(Kyt);return s||(s=crypto.randomUUID(),localStorage.setItem(Kyt,s)),s}catch{return"anonymous"}}async function y$(s,t,n={}){try{await W4.from("commercial_engagement_events").insert({listing_id:s,event_type:t,session_id:D7t(),source:typeof document<"u"&&document.referrer||null,metadata:n})}catch{}}const xDs={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 yDs({open:s,onOpenChange:t,listingId:n,kind:r,documentId:a,requiresNda:i,brokerName:l}){const o=xDs[r],[c,d]=j.useState({firstName:"",lastName:"",email:"",phone:"",company:"",role:"principal",message:""}),[u,h]=j.useState(!1),[m,f]=j.useState(!1),[g,x]=j.useState(null),y=async()=>{if(!c.firstName.trim()||!c.email.trim()){re.error("Name and email are required");return}if(i&&r==="om_request"&&!u){re.error("Please acknowledge the confidentiality terms");return}f(!0);try{const{data:v,error:b}=await q.functions.invoke("commercial-lead",{body:{listingId:n,documentId:a??null,leadType:r,firstName:c.firstName,lastName:c.lastName,email:c.email,phone:c.phone||null,company:c.company||null,role:c.role,message:c.message||null,ndaAccepted:u,sessionId:D7t()}});if(b)throw b;if(v!=null&&v.error)throw new Error(v.error);x({signedUrl:(v==null?void 0:v.signedUrl)??null,fileName:(v==null?void 0:v.fileName)??null}),v!=null&&v.signedUrl&&window.open(v.signedUrl,"_blank")}catch(v){re.error(v.message||"Something went wrong. Please try again.")}finally{f(!1)}};return e.jsx(zs,{open:s,onOpenChange:v=>{t(v),v||x(null)},children:e.jsxs(Os,{className:"max-w-lg overflow-hidden border-white/10 bg-[#0b0f14] p-0 text-white",children:[e.jsxs("div",{className:"border-b border-white/10 bg-gradient-to-b from-white/[0.06] to-transparent px-7 py-6",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.24em] text-white/45",children:o.eyebrow}),e.jsx("h2",{className:"mt-2 font-serif text-2xl",children:g?"Access granted":o.title}),e.jsx("p",{className:"mt-1.5 text-sm text-white/60",children:g?g.signedUrl?"Your download has opened in a new tab. The secure link expires in 30 minutes.":`Your request has been sent${l?` to ${l}`:""}. You'll hear back shortly.`:o.blurb})]}),g?e.jsxs("div",{className:"space-y-4 px-7 py-7",children:[e.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-emerald-400/20 bg-emerald-400/10 px-4 py-3",children:[e.jsx(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(hR,{label:"First name *",children:e.jsx(pe,{value:c.firstName,onChange:v=>d({...c,firstName:v.target.value}),className:"border-white/15 bg-white/5 text-white"})}),e.jsx(hR,{label:"Last name",children:e.jsx(pe,{value:c.lastName,onChange:v=>d({...c,lastName:v.target.value}),className:"border-white/15 bg-white/5 text-white"})})]}),e.jsx(hR,{label:"Email *",children:e.jsx(pe,{type:"email",value:c.email,onChange:v=>d({...c,email:v.target.value}),className:"border-white/15 bg-white/5 text-white"})}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsx(hR,{label:"Company",children:e.jsx(pe,{value:c.company,onChange:v=>d({...c,company:v.target.value}),className:"border-white/15 bg-white/5 text-white"})}),e.jsx(hR,{label:"Phone",children:e.jsx(pe,{value:c.phone,onChange:v=>d({...c,phone:v.target.value}),className:"border-white/15 bg-white/5 text-white"})})]}),e.jsx(hR,{label:"I am a *",children:e.jsxs(ms,{value:c.role,onValueChange:v=>d({...c,role:v}),children:[e.jsx(us,{className:"border-white/15 bg-white/5 text-white",children:e.jsx(fs,{})}),e.jsx(hs,{children:Object.entries(eGe).map(([v,b])=>e.jsx(Ge,{value:v,children:b},v))})]})}),r!=="om_request"&&e.jsx(hR,{label:"Message",children:e.jsx(Ls,{rows:3,value:c.message,onChange:v=>d({...c,message:v.target.value}),className:"border-white/15 bg-white/5 text-white",placeholder:r==="tour_request"?"Preferred dates and times…":"Your question…"})}),i&&r==="om_request"&&e.jsxs("label",{className:"flex cursor-pointer items-start gap-3 rounded-xl border border-white/10 bg-white/[0.04] p-3",children:[e.jsx(ai,{checked:u,onCheckedChange:v=>h(!!v),className:"mt-0.5 border-white/30"}),e.jsxs("span",{className:"text-xs leading-relaxed text-white/65",children:[e.jsx(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:y,disabled:m,children:[m?e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(pc,{className:"mr-2 h-4 w-4"}),o.cta]}),e.jsx("p",{className:"text-center text-[11px] text-white/40",children:"Your information is shared only with the listing broker."})]})]})})}function hR({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 Xtt(s){if(!s)return[];const t=[],n=(r,a)=>{a&&t.push({label:r,value:a})};return n("Cap Rate",TEe(s.cap_rate)),n("NOI",Hyt(s.noi)),n("Occupancy",s.occupancy_pct!=null?`${Math.round(Number(s.occupancy_pct))}%`:null),n("Building SF",yE(s.building_sf)),n("Available SF",yE(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?LN(s.price_per_sf,2):null),n("Price / Unit",Hyt(s.price_per_unit)),n("Lease Rate",s.deal_type!=="sale"?tGe(s):null),n("Year Built",null),n("Zoning",s.zoning??null),t}function F7t({details:s,className:t="",tone:n="light"}){const r=Xtt(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 vDs(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 bDs({slug:s}){var O,U;const{data:t,isLoading:n,error:r}=vDs(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(()=>Xtt(d).slice(0,8),[d]);if(j.useEffect(()=>{c!=null&&c.id&&y$(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=rL(c,d),y=qae(c,d),v=c.latitude&&c.longitude?`${c.latitude},${c.longitude}`:f?[d==null?void 0:d.submarket,c.city,c.state].filter(Boolean).join(", ")||null:[c.property_address,c.city,c.state].filter(Boolean).join(", ")||null,b=(O=h[0])==null?void 0:O.photo_url,w=(d==null?void 0:d.tenants)??[],S=(d==null?void 0:d.spaces)??[],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}),y$(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} | ${y}`}),e.jsx("meta",{name:"description",content:(c.description??"").slice(0,155)||`${AL[(d==null?void 0:d.deal_type)??"sale"]} — ${y}`}),f&&e.jsx("meta",{name:"robots",content:"noindex,nofollow"}),e.jsx("meta",{property:"og:title",content:x}),e.jsx("meta",{property:"og:type",content:"website"})]}),e.jsx("header",{className:"fixed inset-x-0 top-0 z-40 border-b border-white/10 bg-[#0b0f14]/80 backdrop-blur",children:e.jsxs("div",{className:"mx-auto flex max-w-7xl items-center justify-between px-6 py-3.5 md:px-10",children:[e.jsxs("a",{href:typeof window<"u"&&window.location.hostname.startsWith("commercial.")?"/":"/public/commercial",className:"flex items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.22em] text-white/70 transition-colors hover:text-white",children:[e.jsx("span",{"aria-hidden":!0,children:"←"})," All opportunities"]}),e.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-[0.22em] text-white/45",children:"LevelUp Commercial"})]})}),e.jsxs("section",{className:"relative min-h-[86vh] w-full overflow-hidden",children:[b?e.jsx("img",{src:b,alt:x,className:"absolute inset-0 h-full w-full object-cover"}):e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-[#12202b] to-[#0b0f14]"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-[#0b0f14] via-[#0b0f14]/60 to-[#0b0f14]/30"}),e.jsxs("div",{className:"relative mx-auto flex min-h-[86vh] max-w-7xl flex-col justify-end px-6 pb-16 pt-24 md:px-10",children:[e.jsxs("div",{className:"mb-5 flex flex-wrap items-center gap-2.5",children:[e.jsx("span",{className:"rounded-full border border-white/25 px-3.5 py-1 text-[10px] font-semibold uppercase tracking-[0.22em]",children:AL[(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:i6[d.commercial_type]}),f&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full border border-amber-300/30 bg-amber-300/10 px-3.5 py-1 text-[10px] font-semibold uppercase tracking-[0.22em] text-amber-200",children:[e.jsx(pc,{className:"h-3 w-3"})," Confidential offering"]})]}),e.jsx("h1",{className:"max-w-4xl font-serif text-4xl leading-[1.05] tracking-tight md:text-6xl lg:text-7xl",children:x}),e.jsxs("p",{className:"mt-4 flex items-center gap-2 text-sm uppercase tracking-[0.2em] text-white/60",children:[e.jsx(ci,{className:"h-4 w-4"})," ",y]}),e.jsxs("div",{className:"mt-8 flex flex-wrap items-end gap-x-10 gap-y-5",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.24em] text-white/45",children:(d==null?void 0:d.deal_type)==="lease"?"Lease rate":"Asking price"}),e.jsx("p",{className:"mt-1 text-3xl font-semibold tabular-nums md:text-4xl",children:kG(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:TEe(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(vM,{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(vM,{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(vM,{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),y$(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(vM,{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:LN(d==null?void 0:d.noi)},{l:"Gross income",v:LN(d==null?void 0:d.gross_income)},{l:"Operating expenses",v:LN(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?LN(d.price_per_sf,2):null},{l:"Price per unit",v:LN(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(vM,{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?yE(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(vM,{eyebrow:"Location",title:d!=null&&d.submarket?`${d.submarket} submarket`:y,children:e.jsxs("div",{className:"grid gap-8 lg:grid-cols-[1.2fr_1fr]",children:[v?e.jsx("div",{className:"overflow-hidden rounded-2xl border border-white/10",children:e.jsx("iframe",{title:"Property location",className:"h-[420px] w-full",loading:"lazy",src:`https://www.google.com/maps?q=${encodeURIComponent(v)}&z=${c.latitude&&c.longitude?15:12}&output=embed`,onLoad:()=>y$(c.id,"map_view",{})})}):e.jsx("div",{className:"flex h-[420px] items-center justify-center rounded-2xl border border-white/10 bg-white/[0.03] text-center text-sm text-white/50",children:f?"Exact location released with the Offering Memorandum.":y}),e.jsxs("div",{className:"space-y-5",children:[(d==null?void 0:d.zoning)&&e.jsx(v$,{label:"Zoning",value:d.zoning}),(d==null?void 0:d.lot_acres)!=null&&e.jsx(v$,{label:"Site size",value:`${d.lot_acres} acres`}),(d==null?void 0:d.parking_spaces)!=null&&e.jsx(v$,{label:"Parking",value:`${d.parking_spaces} spaces`}),(d==null?void 0:d.opportunity_zone)&&e.jsx(v$,{label:"Opportunity Zone",value:"Qualified"}),E.filter(W=>W.road||W.count).map((W,V)=>e.jsx(v$,{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(v$,{label:"Submarket",value:(d==null?void 0:d.submarket)||y})]})]})}),R&&e.jsx(vM,{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(([,Y])=>Y).map(([Y,X])=>e.jsxs("div",{className:"flex justify-between gap-4",children:[e.jsx("dt",{className:"text-white/50",children:Y}),e.jsx("dd",{className:"font-medium tabular-nums",children:X})]},Y))})]},W)})})}),u.length>0&&e.jsx(vM,{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(xi,{className:"h-5 w-5"}):W.gate_level==="nda"?e.jsx(Rm,{className:"h-5 w-5"}):e.jsx(pc,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate font-medium",children:W.title||JHe[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:()=>{y$(c.id,"contact_click",{}),window.location.href=`mailto:${m.email}`},children:[e.jsx(mn,{className:"mr-2 h-4 w-4"})," Email"]}),m.phone&&e.jsxs($,{variant:"outline",className:"rounded-full border-white/20 bg-transparent text-white hover:bg-white/10 hover:text-white",onClick:()=>{y$(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:[kG(d,c.price)," · ",y]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{size:"sm",variant:"outline",className:"rounded-full border-white/20 bg-transparent text-white hover:bg-white/10 hover:text-white",onClick:()=>D("tour_request"),children:"Tour"}),e.jsx($,{size:"sm",className:"rounded-full",onClick:()=>{var W;return D("om_request",((W=u.find(V=>V.doc_kind==="om"))==null?void 0:W.id)??null)},children:"Request OM"})]})]})}),e.jsx(zs,{open:a!==null,onOpenChange:W=>!W&&i(null),children:e.jsx(Os,{className:"max-w-[96vw] border-none bg-transparent p-0 shadow-none",children:a!==null&&h[a]&&e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:h[a].photo_url,alt:"",className:"max-h-[88vh] w-full rounded-xl object-contain"}),e.jsx("button",{className:"absolute right-3 top-3 rounded-full bg-black/60 p-2",onClick:()=>i(null),children:e.jsx(pr,{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(yDs,{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 vM({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 v$({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 Yyt="/assets/levelup-logo-color-BeKd2k_g.png",_Ds={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"},c7e={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"},Zyt={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"},d7e=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),SZ=s=>new Intl.NumberFormat("en-US").format(s);function Qtt({slugOverride:s}={}){var kt,Ks,wt,gs,ks,Is;const t=Wi(),n=s||t.slugOrId,[r]=gc(),{data:a,isLoading:i}=iDs(n||""),l=oDs(),o=lDs(),c=r.get("ref"),[d,u]=j.useState(""),[h,m]=j.useState(""),[f,g]=j.useState(""),[x,y]=j.useState(""),[v,b]=j.useState(""),[w,S]=j.useState(""),[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,Y]=j.useState(null),[X,ae]=j.useState(!1),[le,ne]=j.useState(!1),[te,J]=j.useState(!1),[ce,_e]=j.useState(20),[he,ue]=j.useState(6.5),[ve,Ee]=j.useState(30),Se=j.useRef(null),[Le,Fe]=j.useState(!1);j.useEffect(()=>{const Xs=()=>Fe(window.scrollY>300);return window.addEventListener("scroll",Xs,{passive:!0}),()=>window.removeEventListener("scroll",Xs)},[]),j.useEffect(()=>{c&&o.mutate(c)},[c]),j.useEffect(()=>{window.scrollTo({top:0,left:0,behavior:"auto"})},[n]);const ke=(a==null?void 0:a.photos)||[],Be=ke.find(Xs=>Xs.is_primary)||ke[0],Ne=j.useMemo(()=>{if(!(a!=null&&a.price))return 0;const Xs=a.price*(1-ce/100),ds=he/100/12,Ss=ve*12;return ds===0?Xs/Ss:Xs*ds/(1-Math.pow(1+ds,-Ss))},[a==null?void 0:a.price,ce,he,ve]),Ae=async()=>{const Xs=window.location.href;if(navigator.share)try{await navigator.share({title:document.title,url:Xs})}catch{}else await navigator.clipboard.writeText(Xs),re.success("Link copied to clipboard")},Ce=async Xs=>{if(Xs.preventDefault(),!d.trim()||!f.trim()||!a)return;const ds=R==="showing";if(ds&&!w){re.error("Please pick a preferred date for your showing");return}U(!0);try{await l.mutateAsync({listingId:a.id,agentId:a.agent_id,firstName:d.trim(),lastName:h.trim(),email:f.trim(),phone:x.trim(),shareToken:c,leadType:ds?"showing_request":"info_request",preferredDate:ds?w:null,preferredTime:ds&&A||null,showingMode:ds?I:null,message:v.trim()||null}),V(!0),re.success(ds?"Showing request sent! The agent will confirm details shortly.":"Thanks! The agent will be in touch soon.")}catch(Ss){console.error("Lead submission error:",Ss),re.error(`Failed to submit: ${Ss.message||"Please try again"}`)}finally{U(!1)}},Ve=()=>{G!==null&&Y(G===0?ke.length-1:G-1)},ze=()=>{G!==null&&Y(G===ke.length-1?0:G+1)};if((a==null?void 0:a.listing_class)==="commercial")return e.jsx(bDs,{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(wr,{to:"/public/listings",className:"flex items-center gap-2",children:e.jsx("img",{src:Yyt,alt:"LevelUp",className:"h-8"})})})}),e.jsxs("div",{className:"container mx-auto px-4 py-24 text-center",children:[e.jsx(va,{className:"h-16 w-16 mx-auto text-muted-foreground mb-4"}),e.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Listing Not Found"}),e.jsx("p",{className:"text-muted-foreground mb-6",children:"This listing may no longer be available."}),e.jsx($,{asChild:!0,children:e.jsx(wr,{to:typeof window<"u"&&window.location.host==="listings.relevelup.com"?"/":"/public/listings",children:"Browse All Listings"})})]})]});const qe=a.property_address?`${a.property_address} — ${a.city}, ${a.state}`:`${a.city}, ${a.state} Home for Sale`,dt=((Ks=(kt=a.agent)==null?void 0:kt.brokerage)==null?void 0:Ks.name)||((wt=a.agent)==null?void 0:wt.brokerage_name),Xe=((gs=a.agent)==null?void 0:gs.name)||"",at=dt||Xe||"",rt=c7e[a.status]==="Sold"?"Just Sold":c7e[a.status],Ke=rt?`${rt}: ${qe}`:qe,Je=[`${d7e(a.price)} · ${a.city}, ${a.state}`,Xe?`Presented by ${Xe}${dt?`, ${dt}`:""}.`:""].filter(Boolean).join(" · "),pt=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,gt=a.description||"",ss=gt.length>420,Yt=te||!ss?gt:gt.slice(0,420).trimEnd()+"…",ts=a.page_config||{},ys=Xs=>{var ds;return(((ds=ts.sections)==null?void 0:ds[Xs])??!0)!==!1},Bt=Array.isArray(ts.addons)?ts.addons:[],Ft=ts.custom_note||"",as=ts.accent_color||null;return e.jsxs(e.Fragment,{children:[e.jsxs(Dl,{children:[e.jsx("title",{children:at?`${qe} | ${at}`:qe}),e.jsx("meta",{name:"description",content:`${d7e(a.price)} · ${a.bedrooms||""}BD ${a.bathrooms||""}BA ${a.square_footage?a.square_footage.toLocaleString()+" sqft · ":""}${Zyt[a.property_type]} in ${a.city}, ${a.state}. ${gt.slice(0,140)}`}),e.jsx("link",{rel:"canonical",href:`https://listings.relevelup.com/${a.slug||a.id}`}),e.jsx("link",{rel:"preconnect",href:"https://fonts.googleapis.com"}),e.jsx("link",{rel:"preconnect",href:"https://fonts.gstatic.com",crossOrigin:""}),e.jsx("link",{href:"https://fonts.googleapis.com/css2?family=Fraunces:opsz,wght@9..144,300;9..144,400;9..144,500;9..144,600&display=swap",rel:"stylesheet"}),e.jsx("meta",{property:"og:title",content:Ke}),e.jsx("meta",{property:"og:description",content:Je}),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}),at&&e.jsx("meta",{property:"og:site_name",content:at}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),e.jsx("meta",{name:"twitter:title",content:Ke}),e.jsx("meta",{name:"twitter:description",content:Je}),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:gt,url:`https://listings.relevelup.com/${a.slug||a.id}`,datePosted:a.created_at,image:ke.map(Xs=>Xs.photo_url),address:{"@type":"PostalAddress",streetAddress:a.property_address||void 0,addressLocality:a.city,addressRegion:a.state,addressCountry:"US"},offers:{"@type":"Offer",price:a.price,priceCurrency:"USD",availability:a.status==="sold"?"https://schema.org/SoldOut":a.status==="under_contract"?"https://schema.org/LimitedAvailability":"https://schema.org/InStock"},numberOfRooms:a.bedrooms||void 0,numberOfBathroomsTotal:a.bathrooms||void 0,floorSize:a.square_footage?{"@type":"QuantitativeValue",value:a.square_footage,unitCode:"FTK"}:void 0,yearBuilt:a.year_built||void 0})}),e.jsx("style",{children:` .font-display { font-family: 'Fraunces', ui-serif, Georgia, serif; font-optical-sizing: auto; letter-spacing: -0.02em; } @keyframes kb-zoom { from { transform: scale(1.08); } to { transform: scale(1); } } .kb-zoom { animation: kb-zoom 12s ease-out forwards; } .noscroll::-webkit-scrollbar { display: none; } `})]}),e.jsxs("div",{className:"bg-neutral-950 text-neutral-100 min-h-screen",children:[e.jsx("header",{className:`fixed inset-x-0 top-0 z-40 transition-all duration-300 ${Le?"bg-neutral-950/85 backdrop-blur-xl border-b border-white/10 py-3":"bg-gradient-to-b from-black/60 to-transparent py-4"}`,children:e.jsxs("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 flex items-center justify-between gap-3",children:[e.jsxs(wr,{to:typeof window<"u"&&window.location.host==="listings.relevelup.com"?"/":"/public/listings",className:"flex items-center gap-2 text-white/90 hover:text-white",children:[e.jsx(Va,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm font-medium hidden sm:inline",children:"All Listings"})]}),Le&&e.jsx("div",{className:"hidden md:flex items-center gap-1 text-sm",children:[["overview","Overview"],["gallery","Gallery"],["story","The Story"],["video","Video"],["map","Location"],["payment","Payment"],["agent","Agent"]].map(([Xs,ds])=>e.jsx("a",{href:`#${Xs}`,className:"px-3 py-1.5 rounded-full text-white/70 hover:text-white hover:bg-white/10 transition",children:ds},Xs))}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(BRs,{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(Fd,{className:"h-4 w-4 text-white"})}),e.jsx($,{size:"sm",onClick:()=>ae(!0),className:"hidden sm:inline-flex bg-white text-neutral-900 hover:bg-white/90 rounded-full h-9 px-4 font-medium",children:"Request Tour"})]})]})}),e.jsxs("section",{ref:Se,id:"overview",className:"relative h-[100svh] min-h-[620px] w-full overflow-hidden",children:[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:`${_Ds[a.status]} text-white border-0 uppercase tracking-widest text-[10px] px-3 py-1 rounded-full shadow-lg`,children:c7e[a.status]}),ke.length>0&&e.jsxs("button",{onClick:()=>Y(0),className:"flex items-center gap-1.5 text-xs text-white/90 bg-black/40 backdrop-blur border border-white/20 rounded-full px-3 py-1.5 hover:bg-black/60 transition",children:[e.jsx(Sx,{className:"h-3.5 w-3.5"}),ke.length," photos"]})]}),e.jsx("div",{className:"absolute inset-x-0 bottom-0 z-10 px-4 sm:px-8 pb-10 sm:pb-14",children:e.jsxs("div",{className:"max-w-7xl mx-auto",children:[e.jsxs("div",{className:"flex items-end justify-between gap-6 flex-wrap",children:[e.jsxs("div",{className:"max-w-3xl",children:[a.neighborhood&&e.jsxs("p",{className:"text-white/70 uppercase tracking-[0.25em] text-xs mb-3 font-medium",children:[a.neighborhood," · ",a.city,", ",a.state]}),a.property_address&&e.jsx("h1",{className:"font-display text-white text-4xl sm:text-6xl md:text-7xl leading-[0.95] mb-4 font-light",children:a.property_address}),!a.property_address&&e.jsxs("h1",{className:"font-display text-white text-4xl sm:text-6xl md:text-7xl leading-[0.95] mb-4 font-light",children:[a.city,", ",a.state]}),e.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[e.jsx("p",{className:"font-display text-white text-3xl sm:text-4xl md:text-5xl font-medium",children:d7e(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:SZ(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}),dt&&e.jsx("p",{className:"text-xs text-white/60",children:dt})]}),e.jsx($,{size:"sm",onClick:()=>ae(!0),className:"bg-white text-neutral-900 hover:bg-white/90 rounded-full h-9 px-4",children:"Contact"})]})]}),e.jsxs("div",{className:"mt-10 flex items-center gap-2 text-white/50 text-xs uppercase tracking-widest",children:[e.jsx("span",{className:"h-px w-8 bg-white/30"}),"Scroll to explore"]})]})})]}),ys("stats")&&e.jsx("section",{className:"border-b border-white/10 bg-neutral-950",children:e.jsx("div",{className:"max-w-7xl mx-auto px-4 sm:px-8 py-8 grid grid-cols-2 md:grid-cols-5 gap-6",children:[a.bedrooms&&{icon:r2,label:"Bedrooms",value:a.bedrooms},a.bathrooms&&{icon:A0,label:"Bathrooms",value:a.bathrooms},a.square_footage&&{icon:j_,label:"Interior",value:`${SZ(a.square_footage)} sqft`},a.lot_size&&{icon:P4,label:"Lot Size",value:a.lot_size},a.year_built&&{icon:Ta,label:"Year Built",value:a.year_built},!a.year_built&&a.square_footage&&{icon:a2,label:"Price / sqft",value:`$${SZ(Math.round(a.price/a.square_footage))}`}].filter(Boolean).slice(0,5).map((Xs,ds)=>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(Xs.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:Xs.label}),e.jsx("p",{className:"font-display text-2xl text-white font-light",children:Xs.value})]})]},ds))})}),e.jsxs("div",{className:"max-w-7xl mx-auto px-4 sm:px-8 py-16 grid lg:grid-cols-3 gap-12",children:[e.jsxs("div",{className:"lg:col-span-2 space-y-20",children:[ys("story")&>&&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:Yt})}),ss&&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(ji,{className:"h-3 w-3 mr-1.5"}),Zyt[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(Fr,{className:"h-3.5 w-3.5 mr-1.5"})," MLS"]})})]}),(Ft||a.agent_notes&&a.agent_notes_public)&&e.jsxs("div",{className:"mt-10 rounded-2xl border border-white/10 bg-white/5 p-6",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(Nn,{className:"h-4 w-4 text-amber-300"}),e.jsx("p",{className:"text-[11px] uppercase tracking-[0.25em] text-white/60",children:"A note from the agent"})]}),e.jsxs("p",{className:"text-white/80 whitespace-pre-wrap leading-relaxed italic font-display",children:['"',Ft||a.agent_notes,'"']})]})]}),ys("gallery")&&ke.length>1&&e.jsxs("section",{id:"gallery",children:[e.jsxs("div",{className:"flex items-end justify-between mb-6",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"Gallery"}),e.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white",children:"Every angle, every detail"})]}),e.jsxs("button",{onClick:()=>Y(0),className:"text-sm text-white/60 hover:text-white underline underline-offset-4 hidden sm:inline",children:["View all ",ke.length]})]}),e.jsx("div",{className:"grid grid-cols-4 gap-2 sm:gap-3",children:ke.slice(0,7).map((Xs,ds)=>{const Ss=["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"],yn=ds===6&&ke.length>7;return e.jsxs("button",{onClick:()=>Y(ds),className:`${Ss[ds]} relative rounded-xl overflow-hidden group bg-neutral-900`,children:[e.jsx("img",{src:Xs.photo_url,alt:`Photo ${ds+1}`,className:"absolute inset-0 h-full w-full object-cover group-hover:scale-[1.04] transition-transform duration-500"}),yn&&e.jsxs("div",{className:"absolute inset-0 bg-black/60 flex flex-col items-center justify-center text-white",children:[e.jsx(Sx,{className:"h-6 w-6 mb-1"}),e.jsxs("span",{className:"font-medium",children:["+",ke.length-7," more"]})]})]},Xs.id)})})]}),ys("video")&&((ks=a.video)==null?void 0:ks.playback_url)&&e.jsxs("section",{id:"video",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"Video Tour"}),e.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:"Walk through the home"}),e.jsx("div",{className:"relative rounded-2xl overflow-hidden bg-black shadow-2xl aspect-video",children:e.jsx("iframe",{src:a.video.playback_url,className:"absolute inset-0 h-full w-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,title:"Video Tour"})})]}),ys("map")&&pt&&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:pt,className:"w-full h-full grayscale-[.2] contrast-[1.05]",loading:"lazy",title:"Map"})}),e.jsxs("div",{className:"mt-4 flex items-center gap-2 text-white/60 text-sm",children:[e.jsx(ci,{className:"h-4 w-4"}),a.property_address?`${a.property_address}, `:"",a.city,", ",a.state]})]}),ys("payment")&&e.jsxs("section",{id:"payment",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"Payment"}),e.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:"Estimate your monthly"}),e.jsxs("div",{className:"rounded-2xl border border-white/10 bg-gradient-to-br from-white/5 to-transparent p-6 sm:p-8",children:[e.jsxs("div",{className:"flex items-baseline gap-3 mb-8",children:[e.jsxs("p",{className:"font-display text-5xl sm:text-6xl font-light text-white",children:["$",SZ(Math.round(Ne))]}),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(Nx,{value:[ce],onValueChange:Xs=>_e(Xs[0]),min:0,max:50,step:1}),e.jsxs("p",{className:"text-xs text-white/50 mt-2",children:["$",SZ(Math.round(a.price*ce/100))," down"]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(ee,{className:"text-white/70 text-xs uppercase tracking-widest",children:"Interest Rate"}),e.jsxs("span",{className:"text-white font-medium",children:[he.toFixed(2),"%"]})]}),e.jsx(Nx,{value:[he],onValueChange:Xs=>ue(Xs[0]),min:2,max:10,step:.125})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(ee,{className:"text-white/70 text-xs uppercase tracking-widest",children:"Loan Term"}),e.jsxs("span",{className:"text-white font-medium",children:[ve," yr"]})]}),e.jsx(Nx,{value:[ve],onValueChange:Xs=>Ee(Xs[0]),min:10,max:30,step:5})]})]}),e.jsx("p",{className:"text-xs text-white/40 mt-6",children:"Estimated principal & interest only. Taxes, insurance, and HOA not included."})]})]}),Bt.map(Xs=>{const ds=Xs.type,Ss=Xs.data||{};if(ds==="extra_video"&&Ss.url){const yn=String(Ss.url).includes("youtu")?`https://www.youtube.com/embed/${String(Ss.url).split(/[/=]/).pop()}`:Ss.url;return e.jsxs("section",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:Ss.eyebrow||"Featured Video"}),e.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:Ss.title||"Watch"}),e.jsx("div",{className:"relative rounded-2xl overflow-hidden bg-black shadow-2xl aspect-video",children:e.jsx("iframe",{src:yn,className:"absolute inset-0 h-full w-full",allowFullScreen:!0,title:Ss.title||"Video"})})]},Xs.id)}return ds==="3d_tour"&&Ss.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:Ss.title||"Step inside"}),e.jsx("div",{className:"relative rounded-2xl overflow-hidden bg-black shadow-2xl aspect-video",children:e.jsx("iframe",{src:Ss.url,className:"absolute inset-0 h-full w-full",allowFullScreen:!0,title:"3D Tour"})})]},Xs.id):ds==="floor_plan"&&Ss.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:Ss.title||"Layout"}),e.jsx("img",{src:Ss.image_url,alt:"Floor plan",className:"w-full rounded-2xl border border-white/10"})]},Xs.id):ds==="testimonial"&&Ss.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:['"',Ss.quote,'"']}),Ss.author&&e.jsxs("p",{className:"mt-4 text-sm text-white/60",children:["— ",Ss.author]})]},Xs.id):ds==="custom_cta"&&Ss.label?e.jsxs("section",{className:"rounded-2xl p-8 text-center",style:{background:as?`${as}22`:"rgba(255,255,255,0.05)",border:`1px solid ${as||"rgba(255,255,255,0.1)"}`},children:[Ss.title&&e.jsx("h3",{className:"font-display text-3xl text-white mb-4",children:Ss.title}),e.jsx($,{asChild:!0,size:"lg",style:as?{background:as}:void 0,children:e.jsx("a",{href:Ss.url||"#agent",children:Ss.label})})]},Xs.id):null})]}),e.jsxs("aside",{id:"agent",className:"lg:sticky lg:top-24 lg:self-start space-y-6",children:[e.jsx(cDs,{listingId:a.id}),a.agent&&e.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/[0.03] p-6 backdrop-blur",children:[e.jsxs("div",{className:"flex items-start gap-4",children:[a.agent.avatar_url?e.jsx("img",{src:a.agent.avatar_url,alt:a.agent.name,className:"h-16 w-16 rounded-full object-cover border-2 border-white/20"}):e.jsx("div",{className:"h-16 w-16 rounded-full bg-white/10 flex items-center justify-center border-2 border-white/20",children:e.jsx(sl,{className:"h-7 w-7 text-white/70"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-widest text-white/50",children:"Listing Agent"}),e.jsx("p",{className:"font-display text-xl text-white font-medium leading-tight",children:a.agent.name}),dt&&e.jsx("p",{className:"text-sm text-white/60 mt-0.5",children:dt})]})]}),e.jsxs("div",{className:"mt-4 grid grid-cols-2 gap-2",children:[a.agent.phone&&e.jsx($,{asChild:!0,variant:"outline",size:"sm",className:"border-white/20 bg-white/5 text-white hover:bg-white/15",children:e.jsxs("a",{href:`tel:${a.agent.phone}`,children:[e.jsx(Da,{className:"h-3.5 w-3.5 mr-1.5"}),"Call"]})}),a.agent.email&&e.jsx($,{asChild:!0,variant:"outline",size:"sm",className:"border-white/20 bg-white/5 text-white hover:bg-white/15",children:e.jsxs("a",{href:`mailto:${a.agent.email}`,children:[e.jsx(mn,{className:"h-3.5 w-3.5 mr-1.5"}),"Email"]})})]})]}),a.co_agent_name&&e.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/[0.03] p-6 backdrop-blur",children:[e.jsxs("div",{className:"flex items-start gap-4",children:[a.co_agent_photo_url?e.jsx("img",{src:a.co_agent_photo_url,alt:a.co_agent_name,className:"h-16 w-16 rounded-full object-cover border-2 border-white/20"}):e.jsx("div",{className:"h-16 w-16 rounded-full bg-white/10 flex items-center justify-center border-2 border-white/20",children:e.jsx(sl,{className:"h-7 w-7 text-white/70"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-widest text-white/50",children:"Co-Listing Agent"}),e.jsx("p",{className:"font-display text-xl text-white font-medium leading-tight",children:a.co_agent_name}),a.co_agent_brokerage&&e.jsx("p",{className:"text-sm text-white/60 mt-0.5",children:a.co_agent_brokerage})]})]}),(a.co_agent_phone||a.co_agent_email)&&e.jsxs("div",{className:"mt-4 grid grid-cols-2 gap-2",children:[a.co_agent_phone&&e.jsx($,{asChild:!0,variant:"outline",size:"sm",className:"border-white/20 bg-white/5 text-white hover:bg-white/15",children:e.jsxs("a",{href:`tel:${a.co_agent_phone}`,children:[e.jsx(Da,{className:"h-3.5 w-3.5 mr-1.5"}),"Call"]})}),a.co_agent_email&&e.jsx($,{asChild:!0,variant:"outline",size:"sm",className:"border-white/20 bg-white/5 text-white hover:bg-white/15",children:e.jsxs("a",{href:`mailto:${a.co_agent_email}`,children:[e.jsx(mn,{className:"h-3.5 w-3.5 mr-1.5"}),"Email"]})})]})]}),e.jsx("div",{id:"contact",className:"rounded-2xl border border-white/10 bg-white text-neutral-900 p-6 shadow-2xl",children:e.jsx(Xyt,{submitted:W,activeTab:R,setActiveTab:D,firstName:d,setFirstName:u,lastName:h,setLastName:m,email:f,setEmail:g,phone:x,setPhone:y,message:v,setMessage:b,preferredDate:w,setPreferredDate:S,preferredTime: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(Cu,{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:Yyt,alt:"LevelUp",className:"h-6 opacity-80"}),e.jsxs("span",{children:["© ",new Date().getFullYear()," LevelUp"]})]}),e.jsx("a",{href:"https://relevelup.com",target:"_blank",rel:"noopener noreferrer",className:"hover:text-white",children:"relevelup.com"})]})}),e.jsx(zs,{open:G!==null,onOpenChange:()=>Y(null),children:e.jsxs(Os,{className:"max-w-6xl p-0 bg-black/95 border-0",children:[e.jsx(Us,{className:"sr-only",children:e.jsx(Bs,{children:"Photo Gallery"})}),e.jsx("button",{onClick:()=>Y(null),className:"absolute right-4 top-4 z-50 rounded-full bg-white/10 hover:bg-white/20 p-2 text-white",children:e.jsx(pr,{className:"h-5 w-5"})}),G!==null&&ke[G]&&e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:ke[G].photo_url,alt:`Photo ${G+1}`,className:"w-full max-h-[85vh] object-contain"}),ke.length>1&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:Ve,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," / ",ke.length]})]})]})]})}),e.jsx(zs,{open:X,onOpenChange:ae,children:e.jsxs(Os,{className:"max-w-md p-0 bg-white text-neutral-900",children:[e.jsx(Us,{className:"sr-only",children:e.jsx(Bs,{children:"Contact the agent"})}),e.jsx("div",{className:"p-6",children:e.jsx(Xyt,{submitted:W,activeTab:R,setActiveTab:D,firstName:d,setFirstName:u,lastName:h,setLastName:m,email:f,setEmail:g,phone:x,setPhone:y,message:v,setMessage:b,preferredDate:w,setPreferredDate:S,preferredTime:A,setPreferredTime:E,showingMode:I,setShowingMode:P,isSubmitting:O,onSubmit:Ce})})]})})]})]})}function Xyt(s){const{submitted:t,activeTab:n,setActiveTab:r,firstName:a,setFirstName:i,lastName:l,setLastName:o,email:c,setEmail:d,phone:u,setPhone:h,message:m,setMessage:f,preferredDate:g,setPreferredDate:x,preferredTime:y,setPreferredTime:v,showingMode:b,setShowingMode:w,isSubmitting:S,onSubmit: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(ca,{className:"h-7 w-7 text-emerald-600"})}),e.jsx("p",{className:"font-display text-2xl font-medium mb-1",children:n==="showing"?"Showing request sent!":"Thanks — you're all set!"}),e.jsx("p",{className:"text-sm text-neutral-600",children:n==="showing"?"The listing agent will reach out to confirm your showing time.":"The listing agent will contact you shortly with more details."})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-[0.25em] text-neutral-500 mb-1",children:"Interested?"}),e.jsx("h3",{className:"font-display text-2xl font-medium",children:"Talk to the listing agent"})]}),e.jsxs(ha,{value:n,onValueChange:E=>r(E),children:[e.jsxs(ma,{className:"grid w-full grid-cols-2 mb-4",children:[e.jsxs(Zt,{value:"info",className:"gap-1.5",children:[e.jsx(eo,{className:"h-3.5 w-3.5"})," Get Info"]}),e.jsxs(Zt,{value:"showing",className:"gap-1.5",children:[e.jsx(Cu,{className:"h-3.5 w-3.5"})," Request Tour"]})]}),e.jsxs("form",{onSubmit:A,className:"space-y-3",children:[e.jsxs(Xt,{value:"showing",className:"mt-0 space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"preferredDate",children:"Preferred Date *"}),e.jsx(pe,{id:"preferredDate",type:"date",value:g,onChange:E=>x(E.target.value),min:new Date().toISOString().split("T")[0],required:n==="showing"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"preferredTime",children:"Preferred Time"}),e.jsxs(ms,{value:y,onValueChange:v,children:[e.jsx(us,{id:"preferredTime",children:e.jsx(fs,{placeholder:"Any time"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"morning",children:"Morning (9am–12pm)"}),e.jsx(Ge,{value:"afternoon",children:"Afternoon (12pm–5pm)"}),e.jsx(Ge,{value:"evening",children:"Evening (5pm–8pm)"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"showingMode",children:"Tour Type"}),e.jsxs(ms,{value:b,onValueChange:E=>w(E),children:[e.jsx(us,{id:"showingMode",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"in_person",children:"🏡 In-person showing"}),e.jsx(Ge,{value:"video",children:"📱 Video tour (FaceTime/Zoom)"}),e.jsx(Ge,{value:"either",children:"Either works for me"})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"firstName",children:"First Name *"}),e.jsx(pe,{id:"firstName",value:a,onChange:E=>i(E.target.value),required:!0})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"lastName",children:"Last Name"}),e.jsx(pe,{id:"lastName",value:l,onChange:E=>o(E.target.value)})]})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"email",children:"Email *"}),e.jsx(pe,{id:"email",type:"email",value:c,onChange:E=>d(E.target.value),required:!0})]}),e.jsxs("div",{children:[e.jsxs(ee,{htmlFor:"phone",children:["Phone ",n==="showing"&&"*"]}),e.jsx(pe,{id:"phone",type:"tel",value:u,onChange:E=>h(E.target.value),required:n==="showing"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"message",children:n==="showing"?"Anything else?":"Message (optional)"}),e.jsx(Ls,{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 SG="/assets/levelup-logo-white-C2RAgAoG.png",wDs="/assets/listings-hero-noir-BHCJrhvU.jpg";var O7t={exports:{}};(function(s,t){(function(n,r){s.exports=r()})(Sp,function(){let n,r,a;typeof self<"u"&&(self.__mapboxImport=o=>import(o));function i(o,c){if(!n)n=c;else if(!r)r=c;else{const d={};n(void 0,d),a=c(d);const u="self.onerror = function() { console.error('An error occurred while parsing the WebWorker bundle. This is most likely due to improper transpilation by Babel; please see https://docs.mapbox.com/mapbox-gl-js/guides/install/#transpiling'); }; var sharedChunk = {}; self.__mapboxImport = (u) => import(u); ("+n+")(undefined, sharedChunk); ("+r+")(undefined, sharedChunk); self.onerror = null;";typeof window<"u"&&window&&window.URL&&window.URL.createObjectURL&&(a.workerUrl=window.URL.createObjectURL(new Blob([u],{type:"text/javascript"})))}}i(["require","exports"],function(o,c){var d="3.31.0",u=1e-6,h=typeof Float32Array<"u"?Float32Array:Array;function m(N,p){var _=p[0],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],Z=p[5],se=p[6],fe=p[7],xe=p[8],be=_[0],Te=_[1],De=_[2],Ue=_[3],Ye=_[4],nt=_[5],it=_[6],ht=_[7],ot=_[8];return N[0]=be*C+Te*z+De*se,N[1]=be*M+Te*H+De*fe,N[2]=be*F+Te*Z+De*xe,N[3]=Ue*C+Ye*z+nt*se,N[4]=Ue*M+Ye*H+nt*fe,N[5]=Ue*F+Ye*Z+nt*xe,N[6]=it*C+ht*z+ot*se,N[7]=it*M+ht*H+ot*fe,N[8]=it*F+ht*Z+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 y(){var N=new h(16);return h!=Float32Array&&(N[1]=0,N[2]=0,N[3]=0,N[4]=0,N[6]=0,N[7]=0,N[8]=0,N[9]=0,N[11]=0,N[12]=0,N[13]=0,N[14]=0),N[0]=1,N[5]=1,N[10]=1,N[15]=1,N}function v(N){var p=new h(16);return p[0]=N[0],p[1]=N[1],p[2]=N[2],p[3]=N[3],p[4]=N[4],p[5]=N[5],p[6]=N[6],p[7]=N[7],p[8]=N[8],p[9]=N[9],p[10]=N[10],p[11]=N[11],p[12]=N[12],p[13]=N[13],p[14]=N[14],p[15]=N[15],p}function b(N,p){return N[0]=p[0],N[1]=p[1],N[2]=p[2],N[3]=p[3],N[4]=p[4],N[5]=p[5],N[6]=p[6],N[7]=p[7],N[8]=p[8],N[9]=p[9],N[10]=p[10],N[11]=p[11],N[12]=p[12],N[13]=p[13],N[14]=p[14],N[15]=p[15],N}function w(N){return N[0]=1,N[1]=0,N[2]=0,N[3]=0,N[4]=0,N[5]=1,N[6]=0,N[7]=0,N[8]=0,N[9]=0,N[10]=1,N[11]=0,N[12]=0,N[13]=0,N[14]=0,N[15]=1,N}function S(N,p){if(N===p){var _=p[1],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],Z=p[6],se=p[7],fe=p[8],xe=p[9],be=p[10],Te=p[11],De=p[12],Ue=p[13],Ye=p[14],nt=p[15],it=_*H-C*z,ht=_*Z-M*z,ot=_*se-F*z,yt=C*Z-M*H,Nt=C*se-F*H,is=M*se-F*Z,At=fe*Ue-xe*De,$t=fe*Ye-be*De,Jt=fe*nt-Te*De,ns=xe*Ye-be*Ue,Ps=xe*nt-Te*Ue,Gs=be*nt-Te*Ye,pn=it*Gs-ht*Ps+ot*ns+yt*Jt-Nt*$t+is*At;return pn?(N[0]=(H*Gs-Z*Ps+se*ns)*(pn=1/pn),N[1]=(M*Ps-C*Gs-F*ns)*pn,N[2]=(Ue*is-Ye*Nt+nt*yt)*pn,N[3]=(be*Nt-xe*is-Te*yt)*pn,N[4]=(Z*Jt-z*Gs-se*$t)*pn,N[5]=(_*Gs-M*Jt+F*$t)*pn,N[6]=(Ye*ot-De*is-nt*ht)*pn,N[7]=(fe*is-be*ot+Te*ht)*pn,N[8]=(z*Ps-H*Jt+se*At)*pn,N[9]=(C*Jt-_*Ps-F*At)*pn,N[10]=(De*Nt-Ue*ot+nt*it)*pn,N[11]=(xe*ot-fe*Nt-Te*it)*pn,N[12]=(H*$t-z*ns-Z*At)*pn,N[13]=(_*ns-C*$t+M*At)*pn,N[14]=(Ue*ht-De*yt-Ye*it)*pn,N[15]=(fe*yt-xe*ht+be*it)*pn,N):null}function E(N,p,_){var C=p[0],M=p[1],F=p[2],z=p[3],H=p[4],Z=p[5],se=p[6],fe=p[7],xe=p[8],be=p[9],Te=p[10],De=p[11],Ue=p[12],Ye=p[13],nt=p[14],it=p[15],ht=_[0],ot=_[1],yt=_[2],Nt=_[3];return N[0]=ht*C+ot*H+yt*xe+Nt*Ue,N[1]=ht*M+ot*Z+yt*be+Nt*Ye,N[2]=ht*F+ot*se+yt*Te+Nt*nt,N[3]=ht*z+ot*fe+yt*De+Nt*it,N[4]=(ht=_[4])*C+(ot=_[5])*H+(yt=_[6])*xe+(Nt=_[7])*Ue,N[5]=ht*M+ot*Z+yt*be+Nt*Ye,N[6]=ht*F+ot*se+yt*Te+Nt*nt,N[7]=ht*z+ot*fe+yt*De+Nt*it,N[8]=(ht=_[8])*C+(ot=_[9])*H+(yt=_[10])*xe+(Nt=_[11])*Ue,N[9]=ht*M+ot*Z+yt*be+Nt*Ye,N[10]=ht*F+ot*se+yt*Te+Nt*nt,N[11]=ht*z+ot*fe+yt*De+Nt*it,N[12]=(ht=_[12])*C+(ot=_[13])*H+(yt=_[14])*xe+(Nt=_[15])*Ue,N[13]=ht*M+ot*Z+yt*be+Nt*Ye,N[14]=ht*F+ot*se+yt*Te+Nt*nt,N[15]=ht*z+ot*fe+yt*De+Nt*it,N}function I(N,p,_){var C,M,F,z,H,Z,se,fe,xe,be,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],Z=p[5],se=p[6],fe=p[7],xe=p[8],be=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]=Z,N[6]=se,N[7]=fe,N[8]=xe,N[9]=be,N[10]=Te,N[11]=De,N[12]=C*Ue+H*Ye+xe*nt+p[12],N[13]=M*Ue+Z*Ye+be*nt+p[13],N[14]=F*Ue+se*Ye+Te*nt+p[14],N[15]=z*Ue+fe*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],Z=p[7],se=p[8],fe=p[9],xe=p[10],be=p[11];return p!==N&&(N[0]=p[0],N[1]=p[1],N[2]=p[2],N[3]=p[3],N[12]=p[12],N[13]=p[13],N[14]=p[14],N[15]=p[15]),N[4]=F*M+se*C,N[5]=z*M+fe*C,N[6]=H*M+xe*C,N[7]=Z*M+be*C,N[8]=se*M-F*C,N[9]=fe*M-z*C,N[10]=xe*M-H*C,N[11]=be*M-Z*C,N}function D(N,p,_){var C=Math.sin(_),M=Math.cos(_),F=p[0],z=p[1],H=p[2],Z=p[3],se=p[8],fe=p[9],xe=p[10],be=p[11];return p!==N&&(N[4]=p[4],N[5]=p[5],N[6]=p[6],N[7]=p[7],N[12]=p[12],N[13]=p[13],N[14]=p[14],N[15]=p[15]),N[0]=F*M-se*C,N[1]=z*M-fe*C,N[2]=H*M-xe*C,N[3]=Z*M-be*C,N[8]=F*C+se*M,N[9]=z*C+fe*M,N[10]=H*C+xe*M,N[11]=Z*C+be*M,N}function O(N,p,_){var C=Math.sin(_),M=Math.cos(_),F=p[0],z=p[1],H=p[2],Z=p[3],se=p[4],fe=p[5],xe=p[6],be=p[7];return p!==N&&(N[8]=p[8],N[9]=p[9],N[10]=p[10],N[11]=p[11],N[12]=p[12],N[13]=p[13],N[14]=p[14],N[15]=p[15]),N[0]=F*M+se*C,N[1]=z*M+fe*C,N[2]=H*M+xe*C,N[3]=Z*M+be*C,N[4]=se*M-F*C,N[5]=fe*M-z*C,N[6]=xe*M-H*C,N[7]=be*M-Z*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],Z=_[2],se=Math.sqrt(z*z+H*H+Z*Z);return se0?(Ye=2*Math.sqrt(Ue+1),N[3]=.25*Ye,N[0]=(xe-Te)/Ye,N[1]=(be-Z)/Ye,N[2]=(H-se)/Ye):z>fe&&z>De?(Ye=2*Math.sqrt(1+z-fe-De),N[3]=(xe-Te)/Ye,N[0]=.25*Ye,N[1]=(H+se)/Ye,N[2]=(be+Z)/Ye):fe>De?(Ye=2*Math.sqrt(1+fe-z-De),N[3]=(be-Z)/Ye,N[0]=(H+se)/Ye,N[1]=.25*Ye,N[2]=(xe+Te)/Ye):(Ye=2*Math.sqrt(1+De-z-fe),N[3]=(H-se)/Ye,N[0]=(be+Z)/Ye,N[1]=(xe+Te)/Ye,N[2]=.25*Ye),N}function X(N,p){var _=p[0],C=p[1],M=p[2],F=p[3],z=_+_,H=C+C,Z=M+M,se=_*z,fe=C*z,xe=C*H,be=M*z,Te=M*H,De=M*Z,Ue=F*z,Ye=F*H,nt=F*Z;return N[0]=1-xe-De,N[1]=fe+nt,N[2]=be-Ye,N[3]=0,N[4]=fe-nt,N[5]=1-se-De,N[6]=Te+Ue,N[7]=0,N[8]=be+Ye,N[9]=Te-Ue,N[10]=1-se-xe,N[11]=0,N[12]=0,N[13]=0,N[14]=0,N[15]=1,N}var ae=function(N,p,_,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-_),Z=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*Z,N[6]=0,N[7]=0,N[8]=0,N[9]=0,N[10]=2*se,N[11]=0,N[12]=(p+_)*H,N[13]=(M+C)*Z,N[14]=(z+F)*se,N[15]=1,N},ne=E;function te(){var N=new h(3);return h!=Float32Array&&(N[0]=0,N[1]=0,N[2]=0),N}function J(N){var p=new h(3);return p[0]=N[0],p[1]=N[1],p[2]=N[2],p}function ce(N){var p=N[0],_=N[1],C=N[2];return Math.sqrt(p*p+_*_+C*C)}function _e(N,p,_){var C=new h(3);return C[0]=N,C[1]=p,C[2]=_,C}function he(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 ve(N,p,_){return N[0]=p[0]-_[0],N[1]=p[1]-_[1],N[2]=p[2]-_[2],N}function Ee(N,p,_){return N[0]=p[0]*_[0],N[1]=p[1]*_[1],N[2]=p[2]*_[2],N}function Se(N,p,_){return N[0]=Math.min(p[0],_[0]),N[1]=Math.min(p[1],_[1]),N[2]=Math.min(p[2],_[2]),N}function Le(N,p,_){return N[0]=Math.max(p[0],_[0]),N[1]=Math.max(p[1],_[1]),N[2]=Math.max(p[2],_[2]),N}function Fe(N,p,_){return N[0]=p[0]*_,N[1]=p[1]*_,N[2]=p[2]*_,N}function ke(N,p,_,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 Ne(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 Ve(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 qe(N,p,_){var C=p[0],M=p[1],F=p[2],z=_[0],H=_[1],Z=_[2];return N[0]=M*Z-F*H,N[1]=F*z-C*Z,N[2]=C*H-M*z,N}function dt(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 Xe(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],Z=p[1],se=p[2],fe=M*se-F*Z,xe=F*H-C*se,be=C*Z-M*H;return N[0]=H+z*(fe+=fe)+M*(be+=be)-F*(xe+=xe),N[1]=Z+z*xe+F*fe-C*be,N[2]=se+z*be+C*xe-M*fe,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 pt=ve,gt=Ee,ss=ce;function Yt(){var N=new h(4);return h!=Float32Array&&(N[0]=0,N[1]=0,N[2]=0,N[3]=0),N}function ts(N,p,_,C){var M=new h(4);return M[0]=N,M[1]=p,M[2]=_,M[3]=C,M}function ys(N,p,_){return N[0]=p[0]*_,N[1]=p[1]*_,N[2]=p[2]*_,N[3]=p[3]*_,N}function Bt(N,p){var _=p[0],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 as(){var N=new h(4);return h!=Float32Array&&(N[0]=0,N[1]=0,N[2]=0),N[3]=1,N}function kt(N){return N[0]=0,N[1]=0,N[2]=0,N[3]=1,N}function Ks(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 wt(N,p,_){_*=.5;var C=p[0],M=p[1],F=p[2],z=p[3],H=Math.sin(_),Z=Math.cos(_);return N[0]=C*Z+z*H,N[1]=M*Z+F*H,N[2]=F*Z-M*H,N[3]=z*Z-C*H,N}function gs(N,p,_){_*=.5;var C=p[0],M=p[1],F=p[2],z=p[3],H=Math.sin(_),Z=Math.cos(_);return N[0]=C*Z-F*H,N[1]=M*Z+z*H,N[2]=F*Z+C*H,N[3]=z*Z-M*H,N}function ks(N,p,_){_*=.5;var C=p[0],M=p[1],F=p[2],z=p[3],H=Math.sin(_),Z=Math.cos(_);return N[0]=C*Z+M*H,N[1]=M*Z-C*H,N[2]=F*Z+z*H,N[3]=z*Z-F*H,N}te(),Yt();var Is,Xs,ds,Ss=Bt,yn=(Is=te(),Xs=_e(1,0,0),ds=_e(0,1,0),function(N,p,_){var C=ze(p,_);return C<-.999999?(qe(Is,Xs,p),ss(Is)<1e-6&&qe(Is,ds,p),Ve(Is,Is),function(M,F,z){z*=.5;var H=Math.sin(z);M[0]=H*F[0],M[1]=H*F[1],M[2]=H*F[2],M[3]=Math.cos(z)}(N,Is,Math.PI),N):C>.999999?(N[0]=0,N[1]=0,N[2]=0,N[3]=1,N):(qe(Is,p,_),N[0]=Is[0],N[1]=Is[1],N[2]=Is[2],N[3]=1+C,Ss(N,N))});function Js(){var N=new h(2);return h!=Float32Array&&(N[0]=0,N[1]=0),N}function Ut(N,p){var _=new h(2);return _[0]=N,_[1]=p,_}function hn(N,p,_){return N[0]=p,N[1]=_,N}function hr(N,p,_){return N[0]=p[0]+_[0],N[1]=p[1]+_[1],N}function Rs(N,p,_){return N[0]=p[0]-_[0],N[1]=p[1]-_[1],N}function jr(N,p,_){return N[0]=p[0]*_,N[1]=p[1]*_,N}function kr(N){var p=N[0],_=N[1];return Math.sqrt(p*p+_*_)}function $n(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 kn(N,p){return N[0]*p[0]+N[1]*p[1]}as(),as(),f();var Fn=Rs;function bn(N,p,_,C){const M=3*N,F=3*(_-N)-M,z=1-M-F,H=3*p,Z=3*(C-p)-H,se=1-H-Z;return function(fe,xe=1e-6){if(fe<=0)return 0;if(fe>=1)return 1;let be=fe;for(let Ue=0;Ue<8;Ue++){const Ye=((z*be+F)*be+M)*be-fe;if(Math.abs(Ye)Ye?Te=be:De=be,be=.5*(Te+De)}return((se*be+Z)*be+H)*be}}function xs(N,p){this.x=N,this.y=p}function Lr(N,p){if(Array.isArray(N)){if(!Array.isArray(p)||N.length!==p.length)return!1;for(let _=0;__;){if(C-_>600){const Z=C-_+1,se=p-_+1,fe=Math.log(Z),xe=.5*Math.exp(2*fe/3),be=.5*Math.sqrt(fe*xe*(Z-xe)/Z)*(se-Z/2<0?-1:1);Or(N,p,Math.max(_,Math.floor(p-se*xe/Z+be)),Math.min(C,Math.floor(p+(Z-se)*xe/Z+be)),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 Qn(N,p){return Np?1:0}function Cr(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 Rn(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 Ya(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&&!(!ho(N,p,_,C)||!ho(_,C,N,p));var M,F}function zd(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 ao=bn(.25,.1,.25,1);function ta(N,p,_){return Math.min(_,Math.max(p,N))}function xc(N,p,_){return(_=ta((_-N)/(p-N),0,1))*_*(3-2*_)}function fl(N,p,_){const 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,(Z,se)=>{Z&&(F=Z),M[H]=se,--C===0&&_(F,M)})})}function fu(N,p){const _={};for(let C=0;C>p/4)).toString(16):([1e7]+-[1e3]+-4e3+-8e3+-1e11).replace(/[018]/g,N)}()}function zr(N){return N<=1?1:Math.pow(2,Math.ceil(Math.log2(N)))}function Hi(N){return!!N&&ti.test(N)}function 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 yc(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 rg(N,p){for(let _=0;_(p.y-N.y)*(_.x-N.x)}function Mh([N,p,_]){const C=Xr(p+90),M=Xr(_);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 _s(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 io(N,p,_){N[4*p+0]=_[0],N[4*p+1]=_[1],N[4*p+2]=_[2],N[4*p+3]=_[3]}function ko(N){return[Math.pow(N[0],1/2.2),Math.pow(N[1],1/2.2),Math.pow(N[2],1/2.2)]}function qi(N){return N>0?1/(1.001-N):1+N}function 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 Zg(N){return N>>>=0,N=Math.imul(2747636419^N,2654435769)>>>0,N=Math.imul(N^N>>>16,2654435769)>>>0,(N=Math.imul(N^N>>>16,2654435769)>>>0)/4294967296}let Fl,Ol,xy,Zd,Vh,cf;function Ky(){return Fl??(Fl=self.OffscreenCanvas&&!!new OffscreenCanvas(1,1).getContext("2d")&&typeof self.createImageBitmap=="function"),Fl}const ih={requestIdleCallback:N=>{if(typeof requestIdleCallback<"u")return requestIdleCallback(N);setTimeout(()=>N({didTimeout:!1,timeRemaining:()=>50}),0)},now:()=>Zd!==void 0?Zd:performance.now(),setNow(N){Zd=N},restoreNow(){Zd=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&&(xy??(xy=window.matchMedia("(prefers-reduced-motion: reduce)")),xy.matches)},hasCanvasFingerprintNoise(){if(cf!==void 0)return cf;if(!Ky())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 Ht="mapbox-tiles";let ws=500,Ts=50;const js=["language","worldview","jobid"];let Ms;function fn(){try{return caches}catch{}}function gn(){const N=fn();N&&Ms==null&&(Ms=N.open(Ht))}let vn=1/0;function Pn(N){return xt.API_URL_REGEX.test(N)}function ir(N){return N.indexOf("mapbox:")===0}function er(N){return xt.API_CDN_URL_REGEX.test(N)}function tr(N){return xt.API_SPRITE_REGEX.test(N)}function vr(N){return xt.API_STYLE_REGEX.test(N)&&!tr(N)}const yr={Unknown:"Unknown",Style:"Style",Source:"Source",Tile:"Tile",Glyphs:"Glyphs",SpriteImage:"SpriteImage",SpriteJSON:"SpriteJSON",Iconset:"Iconset",Image:"Image",Model:"Model"};Object.freeze(yr);class qa extends Error{constructor(p,_,C){super(),this.url=C,this.statusText=p,this.status=_}get message(){return this.status===401&&Pn(this.url)?`${this.statusText}: you may have provided an invalid Mapbox access token. See https://docs.mapbox.com/api/guides/#access-tokens-and-token-scopes`:this.statusText}toString(){return`${this.name}: ${this.message} (${this.status}): ${this.url}`}}function et(N){return typeof N=="object"&&N!==null&&"status"in N&&N.status===404}const Vt=Yc()?()=>self.worker.referrer:()=>(location.protocol==="blob:"?parent:self).location.href,Es=/^\w+:/,ln=/[\r\n]+/;async function tn(N,p){let _;return _=N.type==="arrayBuffer"?await p.arrayBuffer():N.type==="json"?await p.json():await p.text(),{data:_,headers:p.headers}}async function sr(N,p){return p&&p.throwIfAborted(),(_=N.url).startsWith("file:")||Vt().startsWith("file:")&&!Es.test(_)?async function(C,M){return new Promise((F,z)=>{const H=new XMLHttpRequest,Z=()=>{M.removeEventListener("abort",Z),H.abort(),z(M.reason)};M&&M.addEventListener("abort",Z),H.open(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",Z),z(new Error(H.statusText))},H.onload=()=>{if(M&&M.removeEventListener("abort",Z),(H.status>=200&&H.status<300||H.status===0)&&H.response!==null){let se=H.response;if(C.type==="json")try{se=JSON.parse(H.response)}catch(xe){return void z(xe)}const fe=new Headers;H.getAllResponseHeaders().trim().split(ln).forEach(xe=>{const be=xe.split(": "),Te=be.shift(),De=be.join(": ");Te&&fe.set(Te,De)}),F({data:se,headers:fe})}else z(new 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:Vt(),referrerPolicy:C.referrerPolicy,signal:M}),z=(H=F.url).indexOf("sku=")>0&&Pn(H);var H;if(C.type==="json"&&F.headers.set("Accept","application/json"),z){let be=null;try{be=await async function(Te){if(gn(),Ms==null)return null;const De=await Ms;let Ue=zt(Te.url,{persistentParams:js});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(ht){if(!ht)return!1;const ot=new Date(ht.headers.get("expires")||0),yt=_s(ht.headers.get("cache-control")||"");return Number(ot)>Date.now()&&!yt["no-cache"]}(nt);return De.delete(Ue).catch(ht=>Yo(ht.message)),it&&De.put(Ue,nt.clone()).catch(ht=>Yo(ht.message)),{response:nt,fresh:it}}(F)}catch(Te){Te.message!=="SecurityError"&&Yo(Te.toString())}if(be&&be.fresh)return M&&M.throwIfAborted(),tn(C,be.response)}const Z=Date.now();let se;try{se=await fetch(F)}catch(be){throw be.name==="AbortError"?be:new Error(`${be.message} ${C.url}`,{cause:be})}if(M&&M.throwIfAborted(),!se.ok)throw new qa(se.statusText,se.status,C.url);const fe=z?se.clone():null,xe=await tn(C,se);return fe&&async function(be,Te,De){if(gn(),Ms==null)return;const Ue=_s(Te.headers.get("cache-control")||"");if(Ue["no-store"])return;const Ye={status:Te.status,statusText:Te.statusText,headers:new Headers(Te.headers)};Ue["max-age"]&&Ye.headers.set("Expires",new Date(De+1e3*Ue["max-age"]).toUTCString());const nt=Ye.headers.get("expires");if(!nt||new Date(nt).getTime()-De<42e4)return;let it=zt(be.url,{persistentParams:js});if(Te.status===206){const yt=be.headers.get("Range");if(!yt)return;Ye.status=200,it=Rt(it,{range:yt})}const ht=new Response((ot=Te.status)!==200&&ot!==404&&[101,103,204,205,304].includes(ot)?null:Te.body,Ye);var ot;if(gn(),Ms!=null)try{await(await Ms).put(it,ht)}catch(yt){Yo(yt.message)}}(F,fe,Z),xe}(N,p);var _}async function nr(N,p){return sr(Object.assign(N,{type:"json"}),p)}async function Qr(N,p){return sr(Object.assign(N,{type:"arrayBuffer"}),p)}function na(N){const p=document.createElement("a");return p.href=N,p.protocol===location.protocol&&p.host===location.host}let $a,Na;$a=[],Na=0;const La="01",to={create:"create",load:"load",fullLoad:"fullLoad"},xo={mark(N){performance.mark(N)},measure(N,p,_){performance.measure(N,p,_)}};function oo(N){const p=N.name.split("?")[0];return er(p)&&p.includes("mapbox-gl.js")?"javascript":er(p)&&p.includes("mapbox-gl.css")?"css":function(_){return xt.API_FONTS_REGEX.test(_)}(p)?"fontRange":tr(p)?"sprite":vr(p)?"style":function(_){return xt.API_TILEJSON_REGEX.test(_)}(p)?"tilejson":"other"}const Lo=/(\.(png|jpg)\d*)(?=$)/,Ul=/^.+\/v4\//,po=/\.[\w]+$/,nl=/^(\/v4\/|\/(raster|rasterarrays)\/v1\/)/,Pl=/^access_token=(.*)$/,Cd="NO_ACCESS_TOKEN",au=/^(\w+):\/\/([^/?]*)(\/[^?]+)?\??(.+)?/;function qt(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 Cn(N){const p=N.params.length?`?${N.params.join("&")}`:"";return`${N.protocol}://${N.authority}${N.path}${p}`}const rr="mapbox.eventData";function ra(N){if(!N)return null;const p=N.split(".");if(!p||p.length!==3)return null;try{return JSON.parse(decodeURIComponent(atob(p[1]).split("").map(_=>"%"+("00"+_.charCodeAt(0).toString(16)).slice(-2)).join("")))}catch{return null}}function Yr(N){return!(!xt.EVENTS_URL||!N&&!xt.ACCESS_TOKEN)}let Aa;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 _=ra(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?`${rr}.${p}:${C}`:`${rr}:${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 Z=Date.now()-864e5;(!this.anonIdTimestamp||this.anonIdTimestamp=1&&localStorage.setItem(_,JSON.stringify(this.eventData)),z&&localStorage.setItem(M,z.toString())}catch{Yo("Unable to write to LocalStorage")}}processRequests(){}postEvent(p,_,C,M){if(!xt.EVENTS_URL)return;const F=qt(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,Z={url:Cn(F),headers:{"Content-Type":"text/plain"},body:JSON.stringify([H])};this.pendingRequest=!0,async function(se){return sr(Object.assign(se,{method:"POST"}),void 0)}(Z).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(!Yr(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){Yr(p)&&Array.isArray(N)&&N.some(_=>ir(_)||Pn(_))&&this.queueRequest({timestamp:Date.now()},p)}processRequests(){if(this.pendingRequest||this.queue.length===0)return;this.anonId&&this.anonIdTimestamp&&this.eventData.lastSuccess&&this.eventData.tokenU||this.fetchEventData();const N=ra(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),Z=(C-this.eventData.lastSuccess)/864e5;_=_||Z>=1||Z<-1||z.getDate()!==H.getDate()}else _=!0;if(!_)return void this.processRequests();const F={version:"2.2",sdkIdentifier:"mapbox-gl-js",sdkVersion:d,skuId:La,"enabled.telemetry":!1,userId:this.anonId,bundleFormat:"umd",bundleDistribution:Ia};Aa&&(F.sdkInfo=Aa),this.postEvent(C,F,z=>{z||(this.eventData.lastSuccess=C,this.eventData.tokenU=p)},M)}},Tu=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};Aa&&(C.sdkInfo=Aa),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(!Yr(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,()=>{},_)}},pu=Ad.postStyleLoadEvent.bind(Ad),Zc=new zo({attributes:[{name:"maps/js/layer-animations/style-with-appearances"}]}),rd=Zc.postMetricsEvent.bind(Zc),oh=new zo({attributes:[{name:"maps/js/layer-animations/runtime-appearances"}]}),Pf=oh.postMetricsEvent.bind(oh),Bd=new class extends el{constructor(){super("gljs.performance")}postPerformanceEvent(N,p){Yr(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`,ht=`${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 yt=Nt=>{De[Nt]===void 0&&(De[Nt]=0),++De[Nt]};Ye.transferSize!==void 0&&Ye.transferSize===0&&yt(ot),yt(ht)}}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,oo)),Z=window.devicePixelRatio,se=navigator.connection||navigator.mozConnection||navigator.webkitConnection,fe=se?se.effectiveType:void 0,xe={counters:[],metadata:[],attributes:[]},be=(Te,De,Ue)=>{Ue!=null&&Te.push({name:De,value:Ue.toString()})};for(const Te in H)be(xe.counters,Te,H[Te]);if(M.interactionRange[0]!==1/0&&M.interactionRange[1]!==-1/0&&(be(xe.counters,"interactionRangeMin",M.interactionRange[0]),be(xe.counters,"interactionRangeMax",M.interactionRange[1])),z)for(const Te of Object.values(to)){const De=z.find(Ue=>Ue.name===Te);De&&be(xe.counters,Te,De.startTime)}return be(xe.counters,"visibilityHidden",M.visibilityHidden),be(xe.attributes,"style",function(Te){if(Te)for(const De of Te){const Ue=De.name.split("?")[0];if(vr(Ue)){const Ye=Ue.split("/").slice(-2);if(Ye.length===2)return`mapbox://styles/${Ye[0]}/${Ye[1]}`}}}(F)),be(xe.attributes,"terrainEnabled",M.terrainEnabled?"true":"false"),be(xe.attributes,"fogEnabled",M.fogEnabled?"true":"false"),be(xe.attributes,"projection",M.projection),be(xe.attributes,"zoom",M.zoom),be(xe.metadata,"devicePixelRatio",Z),be(xe.metadata,"connectionEffectiveType",fe),be(xe.metadata,"navigatorUserAgent",navigator.userAgent),be(xe.metadata,"screenWidth",window.screen.width),be(xe.metadata,"screenHeight",window.screen.height),be(xe.metadata,"windowWidth",window.innerWidth),be(xe.metadata,"windowHeight",window.innerHeight),be(xe.metadata,"mapWidth",M.width/Z),be(xe.metadata,"mapHeight",M.height/Z),be(xe.metadata,"webglRenderer",M.renderer),be(xe.metadata,"webglVendor",M.vendor),be(xe.metadata,"sdkVersion",d),be(xe.metadata,"sdkIdentifier","mapbox-gl-js"),xe}(p);for(const M of C.metadata);for(const M of C.counters);for(const M of C.attributes);this.postEvent(N,C,()=>{},_)}},ad=Bd.postPerformanceEvent.bind(Bd),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=qt(xt.API_URL+xt.SESSION_PATH);M.params.push(`sku=${p||""}`),M.params.push(`access_token=${C||xt.ACCESS_TOKEN||""}`);const F={url:Cn(M),headers:{"Content-Type":"text/plain"}};this.pendingRequest=!0,async function(z){return sr(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),$d=new Set;function dd(N,p=0){const M=N.length,F=M-(3&M);let z,H=0|p,Z=0;for(;Z>>17,z=Math.imul(z,461845907),H^=z,H=H<<13|H>>>19,H=Math.imul(H,5)+3864292196|0;z=0;const se=3&M;return se>0&&(se>=3&&(z^=(255&N.charCodeAt(Z+2))<<16),se>=2&&(z^=(255&N.charCodeAt(Z+1))<<8),z^=255&N.charCodeAt(Z),z=Math.imul(z,3432918353),z=z<<15|z>>>17,z=Math.imul(z,461845907),H^=z),H^=M,H^=H>>>16,H=Math.imul(H,2246822507),H^=H>>>13,H=Math.imul(H,3266489909),H^=H>>>16,H>>>0}class 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 Z of F)Z.call(this,C);const z=this._oneTimeListeners[M]?this._oneTimeListeners[M].slice():[];for(const Z of z)ou(M,Z,this._oneTimeListeners),Z.call(this,C);const H=this._eventedParent;if(H){const Z=typeof this._eventedParentData=="function"?this._eventedParentData():this._eventedParentData;Object.assign(C,Z),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 Ep,Fv={},Lx=function(){if(Ep)return Fv;Ep=1;var N={transparent:[0,0,0,0],aliceblue:[240,248,255,1],antiquewhite:[250,235,215,1],aqua:[0,255,255,1],aquamarine:[127,255,212,1],azure:[240,255,255,1],beige:[245,245,220,1],bisque:[255,228,196,1],black:[0,0,0,1],blanchedalmond:[255,235,205,1],blue:[0,0,255,1],blueviolet:[138,43,226,1],brown:[165,42,42,1],burlywood:[222,184,135,1],cadetblue:[95,158,160,1],chartreuse:[127,255,0,1],chocolate:[210,105,30,1],coral:[255,127,80,1],cornflowerblue:[100,149,237,1],cornsilk:[255,248,220,1],crimson:[220,20,60,1],cyan:[0,255,255,1],darkblue:[0,0,139,1],darkcyan:[0,139,139,1],darkgoldenrod:[184,134,11,1],darkgray:[169,169,169,1],darkgreen:[0,100,0,1],darkgrey:[169,169,169,1],darkkhaki:[189,183,107,1],darkmagenta:[139,0,139,1],darkolivegreen:[85,107,47,1],darkorange:[255,140,0,1],darkorchid:[153,50,204,1],darkred:[139,0,0,1],darksalmon:[233,150,122,1],darkseagreen:[143,188,143,1],darkslateblue:[72,61,139,1],darkslategray:[47,79,79,1],darkslategrey:[47,79,79,1],darkturquoise:[0,206,209,1],darkviolet:[148,0,211,1],deeppink:[255,20,147,1],deepskyblue:[0,191,255,1],dimgray:[105,105,105,1],dimgrey:[105,105,105,1],dodgerblue:[30,144,255,1],firebrick:[178,34,34,1],floralwhite:[255,250,240,1],forestgreen:[34,139,34,1],fuchsia:[255,0,255,1],gainsboro:[220,220,220,1],ghostwhite:[248,248,255,1],gold:[255,215,0,1],goldenrod:[218,165,32,1],gray:[128,128,128,1],green:[0,128,0,1],greenyellow:[173,255,47,1],grey:[128,128,128,1],honeydew:[240,255,240,1],hotpink:[255,105,180,1],indianred:[205,92,92,1],indigo:[75,0,130,1],ivory:[255,255,240,1],khaki:[240,230,140,1],lavender:[230,230,250,1],lavenderblush:[255,240,245,1],lawngreen:[124,252,0,1],lemonchiffon:[255,250,205,1],lightblue:[173,216,230,1],lightcoral:[240,128,128,1],lightcyan:[224,255,255,1],lightgoldenrodyellow:[250,250,210,1],lightgray:[211,211,211,1],lightgreen:[144,238,144,1],lightgrey:[211,211,211,1],lightpink:[255,182,193,1],lightsalmon:[255,160,122,1],lightseagreen:[32,178,170,1],lightskyblue:[135,206,250,1],lightslategray:[119,136,153,1],lightslategrey:[119,136,153,1],lightsteelblue:[176,196,222,1],lightyellow:[255,255,224,1],lime:[0,255,0,1],limegreen:[50,205,50,1],linen:[250,240,230,1],magenta:[255,0,255,1],maroon:[128,0,0,1],mediumaquamarine:[102,205,170,1],mediumblue:[0,0,205,1],mediumorchid:[186,85,211,1],mediumpurple:[147,112,219,1],mediumseagreen:[60,179,113,1],mediumslateblue:[123,104,238,1],mediumspringgreen:[0,250,154,1],mediumturquoise:[72,209,204,1],mediumvioletred:[199,21,133,1],midnightblue:[25,25,112,1],mintcream:[245,255,250,1],mistyrose:[255,228,225,1],moccasin:[255,228,181,1],navajowhite:[255,222,173,1],navy:[0,0,128,1],oldlace:[253,245,230,1],olive:[128,128,0,1],olivedrab:[107,142,35,1],orange:[255,165,0,1],orangered:[255,69,0,1],orchid:[218,112,214,1],palegoldenrod:[238,232,170,1],palegreen:[152,251,152,1],paleturquoise:[175,238,238,1],palevioletred:[219,112,147,1],papayawhip:[255,239,213,1],peachpuff:[255,218,185,1],peru:[205,133,63,1],pink:[255,192,203,1],plum:[221,160,221,1],powderblue:[176,224,230,1],purple:[128,0,128,1],rebeccapurple:[102,51,153,1],red:[255,0,0,1],rosybrown:[188,143,143,1],royalblue:[65,105,225,1],saddlebrown:[139,69,19,1],salmon:[250,128,114,1],sandybrown:[244,164,96,1],seagreen:[46,139,87,1],seashell:[255,245,238,1],sienna:[160,82,45,1],silver:[192,192,192,1],skyblue:[135,206,235,1],slateblue:[106,90,205,1],slategray:[112,128,144,1],slategrey:[112,128,144,1],snow:[255,250,250,1],springgreen:[0,255,127,1],steelblue:[70,130,180,1],tan:[210,180,140,1],teal:[0,128,128,1],thistle:[216,191,216,1],tomato:[255,99,71,1],turquoise:[64,224,208,1],violet:[238,130,238,1],wheat:[245,222,179,1],white:[255,255,255,1],whitesmoke:[245,245,245,1],yellow:[255,255,0,1],yellowgreen:[154,205,50,1]};function p(F){return(F=Math.round(F))<0?0:F>255?255:F}function _(F){return p(F[F.length-1]==="%"?parseFloat(F)/100*255:parseInt(F))}function 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{Fv.parseCSSColor=function(F){var z,H=F.replace(/ /g,"").toLowerCase();if(H in N)return N[H].slice();if(H[0]==="#")return H.length===4?(z=parseInt(H.substr(1),16))>=0&&z<=4095?[(3840&z)>>4|(3840&z)>>8,240&z|(240&z)>>4,15&z|(15&z)<<4,1]:null:H.length===7&&(z=parseInt(H.substr(1),16))>=0&&z<=16777215?[(16711680&z)>>16,(65280&z)>>8,255&z,1]:null;var Z=H.indexOf("("),se=H.indexOf(")");if(Z!==-1&&se+1===H.length){var fe=H.substr(0,Z),xe=H.substr(Z+1,se-(Z+1)).split(","),be=1;switch(fe){case"rgba":if(xe.length!==4)return null;be=C(xe.pop());case"rgb":return xe.length!==3?null:[_(xe[0]),_(xe[1]),_(xe[2]),be];case"hsla":if(xe.length!==4)return null;be=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)),be];default:return null}}return null}}catch{}return Fv}();function ya(N,p,_){return N*(1-_)+p*_}const Yy=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 _=Yy.get(p);if(_)return _;const C=Lx.parseCSSColor(p);if(!C)return;const M=new Ci(C[0]/255,C[1]/255,C[2]/255,C[3]);return Yy.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 Rx(p,_*F,C*F,M*F,F)}clone(){return new Ci(this.r,this.g,this.b,this.a)}}class Xg{constructor(p,_,C,M,F,z=!1){if(this.premultiplied=!1,this.premultiplied=z,p){const H=p.image.height,Z=H*H;this.premultiplied?(_=F===0?0:_/F*(H-1),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(_),fe=Math.floor(C),xe=Math.floor(M),be=Math.ceil(_),Te=Math.ceil(C),De=Math.ceil(M),Ue=_-se,Ye=C-fe,nt=M-xe,it=p.image.data,ht=4*(se+fe*Z+xe*H),ot=4*(se+fe*Z+De*H),yt=4*(se+Te*Z+xe*H),Nt=4*(se+Te*Z+De*H),is=4*(be+fe*Z+xe*H),At=4*(be+fe*Z+De*H),$t=4*(be+Te*Z+xe*H),Jt=4*(be+Te*Z+De*H);this.r=ya(ya(ya(it[ht],it[ot],nt),ya(it[yt],it[Nt],nt),Ye),ya(ya(it[is],it[At],nt),ya(it[$t],it[Jt],nt),Ye),Ue)/255*(this.premultiplied?F:1),this.g=ya(ya(ya(it[ht+1],it[ot+1],nt),ya(it[yt+1],it[Nt+1],nt),Ye),ya(ya(it[is+1],it[At+1],nt),ya(it[$t+1],it[Jt+1],nt),Ye),Ue)/255*(this.premultiplied?F:1),this.b=ya(ya(ya(it[ht+2],it[ot+2],nt),ya(it[yt+2],it[Nt+2],nt),Ye),ya(ya(it[is+2],it[At+2],nt),ya(it[$t+2],it[Jt+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),Z=Math.min(F,z,H),se=Math.max(F,z,H),fe=se-Z,xe=.5*(Z+se);if(fe===0)return[0,0,100*xe,M];const be=xe>.5?fe/(2-se-Z):fe/(se+Z);let Te;switch(se){case F:Te=60*((z-H)/fe+(zya(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 gu={kind:"null"},fa={kind:"number"},Ao={kind:"string"},pl={kind:"boolean"},Qc={kind:"color"},ag={kind:"object"},Wo={kind:"value"},$0={kind:"collator"},xh={kind:"formatted"},df={kind:"resolvedImage"};function Ud(N,p){return{kind:"array",itemType:N,N:p}}function xu(N){if(N.kind==="array"){const p=xu(N.itemType);return typeof N.N=="number"?`array<${p}, ${N.N}>`:N.itemType.kind==="value"?"array":`array<${p}>`}return N.kind}const D_=[gu,fa,Ao,pl,Qc,xh,ag,Ud(Wo),df];function Ov(N,p){if(p.kind==="error")return null;if(N.kind==="array"){if(p.kind==="array"&&(p.N===0&&p.itemType.kind==="value"||!Ov(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 D_)if(!Ov(_,p))return null}}return`Expected ${xu(N)} but found ${xu(p)} instead.`}function Dx(N,p){return p.some(_=>_==="null"?N===null:_==="array"?Array.isArray(N):_==="object"?N&&!Array.isArray(N)&&typeof N=="object":_===typeof N)}function Pb(N,p){return N.kind==="array"&&p.kind==="array"?N.N===p.N&&Pb(N.itemType,p.itemType):N.kind===p.kind}class Kw{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 yu{constructor(p){this.sections=p}static fromString(p){return new yu([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 yu?p:yu.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 Kw||N instanceof yu||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 lh(N){if(N===null)return gu;if(typeof N=="string")return Ao;if(typeof N=="boolean")return pl;if(typeof N=="number")return fa;if(N instanceof Ci)return Qc;if(N instanceof Kw)return $0;if(N instanceof yu)return xh;if(N instanceof yh)return df;if(Array.isArray(N)){const p=N.length;let _;for(const C of N){const M=lh(C);if(_){if(_===M)continue;_=Wo;break}_=M}return Ud(_||Wo,p)}return ag}function np(N){return N===null?"":typeof N=="string"||typeof N=="number"||typeof N=="boolean"?String(N):N instanceof yu||N instanceof yh||N instanceof Ci?N.toString():JSON.stringify(N)}class Qg{constructor(p,_){this.type=p,this.value=_}static parse(p,_){if(p.length!==2)return _.error(`'literal' expression requires exactly one argument, but found ${p.length-1} instead.`);if(!um(p[1]))return _.error("invalid value");const C=p[1];let M=lh(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 Qg(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 yu?this.value.serialize():this.value}}class ch{constructor(p){this.name="ExpressionEvaluationError",this.message=p}toJSON(){return this.message}}const Ic={string:Ao,number:fa,boolean:pl,object:ag};class Jg{constructor(p,_){this.type=p,this.args=_}static parse(p,_){if(p.length<2)return _.error("Expected at least one argument.");let C,M=1;const F=p[0];if(F==="array"){let H,Z;if(p.length>2){const se=p[1];if(typeof se!="string"||!(se in 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);Z=p[2],M++}C=Ud(H,Z)}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 I1{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 Z=null;if(H["font-scale"]&&(Z=_.parseObjectValue(H["font-scale"],z,"font-scale",fa),!Z))return null;let se=null;if(H["text-font"]&&(se=_.parseObjectValue(H["text-font"],z,"text-font",Ud(Ao)),!se))return null;let fe=null;if(H["text-color"]&&(fe=_.parseObjectValue(H["text-color"],z,"text-color",Qc),!fe))return null;const xe=M.at(-1);xe.scale=Z,xe.font=se,xe.textColor=fe}else{const Z=_.parse(p[z],z,Wo);if(!Z)return null;const se=Z.type.kind;if(se!=="string"&&se!=="value"&&se!=="null"&&se!=="resolvedImage")return _.error("Formatted text type must be 'string', 'value', 'image' or 'null'.");F=!0,M.push({content:Z,scale:null,font:null,textColor:null})}}return new I1(M)}evaluate(p){return new yu(this.sections.map(_=>{const C=_.content.evaluate(p);return Pb(lh(C),df)?new zm("",C,null,null,null):new zm(np(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 L1{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 R1(N){return Zw(N)?"string":F_(N)?"number":Pk(N)?"boolean":Array.isArray(N)?"array":N===null?"null":Yw(N)?"object":typeof N}function Yw(N){return N!=null&&!Array.isArray(N)&&typeof N!="function"&&!(N instanceof String||N instanceof Number||N instanceof Boolean)&&typeof N=="object"}function Zw(N){return typeof N=="string"||N instanceof String}function F_(N){return typeof N=="number"||N instanceof Number}function Pk(N){return typeof N=="boolean"||N instanceof Boolean}const Ib={"to-boolean":pl,"to-color":Qc,"to-number":fa,"to-string":Ao};class zv{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=gu;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=Ud(_.expectedType.itemType,z)}else{if(!(z>0&&um(p[1][0])))return null;F=Ud(lh(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 ch(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 ch(`Could not convert ${JSON.stringify(_)} to number.`)}return this.type.kind==="formatted"?yu.fromString(np(this.args[0].evaluate(p))):this.type.kind==="resolvedImage"?yh.build(np(this.args[0].evaluate(p))):this.type.kind==="array"?this.args.map(_=>_.evaluate(p)):np(this.args[0].evaluate(p))}eachChild(p){this.args.forEach(p)}outputDefined(){return this.args.every(p=>p.outputDefined())}serialize(){if(this.type.kind==="formatted")return new I1([{content:this.args[0],scale:null,font:null,textColor:null}]).serialize();if(this.type.kind==="resolvedImage")return new L1(this.args[0]).serialize();const p=this.type.kind==="array"?[]:[`to-${this.type.kind}`];return this.eachChild(_=>{p.push(_.serialize())}),p}}const k3=["Unknown","Point","LineString","Polygon"];class V2{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"?k3[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 rp{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 _=rp.definitions[this.name];this._evaluate=Array.isArray(_)?_[2]:_.overloads[this._overloadIndex][1]}return this._evaluate(p,this.args)}eachChild(p){this.args.forEach(p)}outputDefined(){return!1}serialize(){return[this.name].concat(this.args.map(p=>p.serialize()))}static parse(p,_){const C=p[0],M=rp.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 Z=null,se=-1;for(const[fe,xe]of z){if(Array.isArray(fe)&&fe.length!==p.length-1)continue;H.push(fe),se++,Z===null?Z=_._forkForSignature():Z.errors.length=0;const be=[];let Te=!1;for(let De=1;Debe)).map(Ik).join(" | "),xe=[];for(let be=1;be_[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 C3(N,p,_,C){const M=Math.pow(2,C.z)*Bv,F=[C.x*Bv,C.y*Bv],z=[];if(!N)return z;for(const H of N)for(const Z of H){const se=[Z.x+F[0],Z.y+F[1]];LC(se,p,_,M),z.push(se)}return z}function Rb(N,p,_,C){const M=Math.pow(2,C.z)*Bv,F=[C.x*Bv,C.y*Bv],z=[];if(!N)return z;for(const Z of N){const se=[];for(const fe of Z){const xe=[fe.x+F[0],fe.y+F[1]];ii(p,xe),se.push(xe)}z.push(se)}if(p[2]-p[0]<=M/2){(H=p)[0]=H[1]=1/0,H[2]=H[3]=-1/0;for(const Z of z)for(const se of Z)LC(se,p,_,M)}var H;return z}class ip{constructor(p,_){this.type=pl,this.geojson=p,this.geometries=_}static parse(p,_){if(p.length!==2)return _.error(`'within' expression requires exactly one argument, but found ${p.length-1} instead.`);if(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 Dr=8192;function Lk(N,p,_){return[N,p,_].filter(Boolean).join("")}function RC(N,p){switch(N){case"string":return np(p);case"number":return+p;case"boolean":return!!p;case"color":return Ci.parse(p);case"formatted":return yu.fromString(np(p));case"resolvedImage":return yh.build(np(p))}return p}function tx(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 Qg))return _.error("Key name of 'config' expression must be a string literal.");let F,z=!0;const H=np(M.value);if(p.length>=3){const Z=_.parse(p[2],2);if(!(Z instanceof Qg))return _.error("Scope of 'config' expression must be a string literal.");F=np(Z.value)}if(_.options){const Z=Lk(H,F,_._scope),se=_.options.get(Z);se&&(z=F1(se.value||se.default))}return new uf(C,H,F,z)}evaluate(p){const _=Lk(this.key,this.scope,p.scope),C=p.getConfig(_);if(!C)return null;const{type:M,value:F,values:z,minValue:H,maxValue:Z,stepValue:se}=C,fe=C.default.evaluate(p);let xe=fe;if(F){const be=p.scope;p.scope=(be||"").split("").slice(1).join(""),xe=F.evaluate(p),p.scope=be}return M&&(xe=RC(M,xe)),xe===void 0||H===void 0&&Z===void 0&&se===void 0||(typeof xe=="number"?xe=tx(xe,H,Z,se):Array.isArray(xe)&&(xe=xe.map(be=>typeof be=="number"?tx(be,H,Z,se):be))),F!==void 0&&xe!==void 0&&z&&!z.includes(xe)&&(xe=fe,M&&(xe=RC(M,xe))),(M&&M!==this.type||xe!==void 0&&!Pb(lh(xe),this.type))&&(xe=RC(this.type.kind,xe)),xe}eachChild(){}outputDefined(){return!1}serialize(){const p=["config",this.key];return this.scope&&p.concat(this.scope),p}}function F1(N){if(N instanceof rp&&(N.name==="get"&&N.args.length===1||N.name==="feature-state"||N.name==="has"&&N.args.length===1||N.name==="properties"||N.name==="geometry-type"||N.name==="id"||N.name.startsWith("filter-"))||N instanceof ip||N instanceof Fi)return!1;if(N instanceof uf)return N.featureConstant;let p=!0;return N.eachChild(_=>{p&&!F1(_)&&(p=!1)}),p}function q0(N){if(N instanceof rp&&N.name==="feature-state")return!1;let p=!0;return N.eachChild(_=>{p&&!q0(_)&&(p=!1)}),p}function V0(N,p){if(N instanceof rp&&p.has(N.name))return!1;let _=!0;return N.eachChild(C=>{_&&!V0(C,p)&&(_=!1)}),_}function Ox(N,p){return V0(N,new Set(p))}const Rk=1/298.257223563,H2=Rk*(2-Rk),Dk=Math.PI/180;function Fk(N){const p=6378.137*Dk*1e3,_=Math.cos(N*Dk),C=1/(1-H2*(1-_*_)),M=Math.sqrt(C);return[p*M*_,p*M*C*(1-H2)]}function O_(N){for(;N<-180;)N+=360;for(;N>180;)N-=360;return N}function Qw(N,p,_,C){const M=O_(N[0]-p[0])*_,F=(N[1]-p[1])*C;return Math.sqrt(M*M+F*F)}function z_(N,p,_,C,M){let F=p[0],z=p[1],H=O_(_[0]-F)*C,Z=(_[1]-z)*M;if(H!==0||Z!==0){const se=(O_(N[0]-F)*C*H+(N[1]-z)*M*Z)/(H*H+Z*Z);se>1?(F=_[0],z=_[1]):se>0&&(F+=H/C*se,z+=Z/M*se)}return H=O_(N[0]-F)*C,Z=(N[1]-z)*M,Math.sqrt(H*H+Z*Z)}function DC(N,p){return p.dist-N.dist}function G2(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 _=B_(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 O1(N,p){const _=[1/0,1/0,-1/0,-1/0];if(!sx(p,N.length))return _;for(let C=p[0];C<=p[1];++C)ii(_,N[C]);return _}function Jw(N){const p=[1/0,1/0,-1/0,-1/0];for(let _=0;_p[2]&&(M=N[0]-p[2]),N[1]>p[3]&&(F=N[1]-p[3]),N[3]1?(Te=F[be+1][0],De=F[be+1][1]):nt>0&&(Te+=Ue/H*nt,De+=Ye/Z*nt)),Ue=O_(z[0]-Te)*H,Ye=(z[1]-De)*Z;const it=Ue*Ue+Ye*Ye;it=M)return M;if($i(F,z)){if(Zn(N,p))return 0}else if(Zn(p,N))return 0;let H=M;for(const Z of N)for(let se=0,fe=Z.length,xe=fe-1;se=z)continue;const xe=fe.range1;if(B_(xe)<=Z){if(!sx(xe,N.length))return NaN;if(p){const be=on(N,xe,_,C,M);if((z=Math.min(z,be))===0)return z}else for(let be=xe[0];be<=xe[1];++be){const Te=qs(N[be],_,C,M);if((z=Math.min(z,Te))===0)return z}}else{const be=FC(xe,p);if(be[0]!==null){const Te=Pe(O1(N,be[0]),se,C,M);Te=H)continue;const be=xe.range1,Te=xe.range2;if(B_(be)<=se&&B_(Te)<=fe){if(!sx(be,N.length)||!sx(Te,_.length))return NaN;if(p&&C?H=Math.min(H,As(N,be,_,Te,M,F)):p||C?p&&!C?H=Math.min(H,ls(_,Te,N,be,M,F)):!p&&C&&(H=Math.min(H,ls(N,be,_,Te,M,F))):H=Math.min(H,Ds(N,be,_,Te,M,F)),H===0)return H}else{const De=FC(be,p),Ue=FC(Te,C);Qs(Z,H,M,F,N,_,De[0],Ue[0]),Qs(Z,H,M,F,N,_,De[0],Ue[1]),Qs(Z,H,M,F,N,_,De[1],Ue[0]),Qs(Z,H,M,F,N,_,De[1],Ue[1])}}return H}function aa(N,p,_,C,M,F=1/0){let z=F;const H=O1(N,[0,N.length-1]);for(const Z of _)if(!(z!==1/0&&Pe(H,O1(Z,[0,Z.length-1]),C,M)>=z)&&(z=Math.min(z,br(N,p,Z,!0,C,M,z)),z===0))return z;return z}function ur(N,p,_,C,M,F=1/0){let z=F;const H=O1(N,[0,N.length-1]);for(const Z of _){if(z!==1/0&&Pe(H,Jw(Z),C,M)>=z)continue;const se=or(N,p,Z,C,M,z);if(isNaN(se))return se;if((z=Math.min(z,se))===0)return z}return z}function pa(N,p,_){const C=[];for(const z of N)for(const H of z)C.push(He(H,p));const[M,F]=Fk(C[0][1]);return _.type==="Point"||_.type==="MultiPoint"||_.type==="LineString"?br(C,!1,_.type==="Point"?[_.coordinates]:_.coordinates,_.type==="LineString",M,F):_.type==="MultiLineString"?aa(C,!1,_.coordinates,M,F):_.type==="Polygon"||_.type==="MultiPolygon"?ur(C,!1,_.type==="Polygon"?[_.coordinates]:_.coordinates,M,F):null}function cr(N,p,_){const C=[];for(const z of N){const H=[];for(const Z of z)H.push(He(Z,p));C.push(H)}const[M,F]=Fk(C[0][0][1]);if(_.type==="Point"||_.type==="MultiPoint"||_.type==="LineString")return aa(_.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 Z=aa(_.coordinates[H],!0,C,M,F,z);if(isNaN(Z))return Z;if((z=Math.min(z,Z))===0)return z}return z}if(_.type==="Polygon"||_.type==="MultiPolygon"){let z=1/0;for(let H=0;H`[${M}]`).join("")}`;this.errors.push(new Ro(C,p))}checkSubtype(p,_,C){const M=Ov(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 Jg(p,[N]):_==="coerce"?new zv(p,[N]):N}function Xl(N){if(N instanceof bl)return Xl(N.boundExpression);if(N instanceof rp&&N.name==="error"||N instanceof D1||N instanceof ip||N instanceof Fi||N instanceof uf)return!1;const p=N instanceof zv||N instanceof Jg;let _=!0;return N.eachChild(C=>{_=p?_&&Xl(C):_&&C instanceof Qg}),!!_&&F1(N)&&V0(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 ch("Input is not a number.");z=H-1}return 0}class bi{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,fa);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(Z,fe,F);if(!xe)return null;F=F||xe.type,M.push([H,xe])}return new bi(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,ig=$c*$c*$c,Xd=Math.PI/180,og=180/Math.PI;function Lh(N){return N>ig?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 dh(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 op={forward:dh,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,_)}}},uh={forward:function(N){const{l:p,a:_,b:C}=dh(N),M=Math.atan2(C,_)*og;return{h:M<0?M+360:M,c:Math.sqrt(_*_+C*C),l:p,alpha:N.a}},reverse:function(N){const p=N.h*Xd,_=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:uh,lab:op});class vc{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(fe=>typeof fe!="number"||fe<0||fe>1))return _.error("Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.",1);M={name:"cubic-bezier",controlPoints:se}}}if(p.length-1<4)return _.error(`Expected at least 4 arguments, but found only ${p.length-1}.`);if(p.length-1>3&&(p.length-1)%2!=0)return _.error("Expected an even number of arguments.");if(F=_.parse(F,2,fa),!F)return null;const H=[];let Z=null;C==="interpolate-hcl"||C==="interpolate-lab"?Z=Qc:_.expectedType&&_.expectedType.kind!=="value"&&(Z=_.expectedType);for(let se=0;se=fe)return _.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.',be);const De=_.parse(xe,Te,Z);if(!De)return null;Z=Z||De.type,H.push([fe,De])}return Z.kind==="number"||Z.kind==="color"||Z.kind==="array"&&Z.itemType.kind==="number"&&typeof Z.N=="number"?new vc(Z,C,M,F,H):_.error(`Type ${xu(Z)} 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=vc.interpolationFactor(this.interpolation,M,_[z],_[z+1]),Z=C[z].evaluate(p),se=C[z+1].evaluate(p);return this.operator==="interpolate"?kc[this.type.kind.toLowerCase()](Z,se,H):this.operator==="interpolate-hcl"?uh.reverse(uh.interpolate(uh.forward(Z),uh.forward(se),H)):op.reverse(op.interpolate(op.forward(Z),op.forward(se),H))}eachChild(p){p(this.input);for(const _ of this.outputs)p(_)}outputDefined(){return this.outputs.every(p=>p.outputDefined())}serialize(){let p;p=this.interpolation.name==="linear"?["linear"]:this.interpolation.name==="exponential"?this.interpolation.base===1?["linear"]:["exponential",this.interpolation.base]:["cubic-bezier",...this.interpolation.controlPoints];const _=[this.operator,p,this.input.serialize()];for(let C=0;COv(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 Mp{constructor(p,_){this.type=_.type,this.bindings=[].concat(p),this.result=_}evaluate(p){return this.result.evaluate(p)}eachChild(p){for(const _ of this.bindings)p(_[1]);p(this.result)}static parse(p,_){if(p.length<4)return _.error(`Expected at least 3 arguments, but found ${p.length-1} instead.`);const C=[];for(let F=1;F=C.length)throw new ch("Array index out of bounds: index exceeds array size");if(_!==Math.floor(_))throw new ch("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 Pp{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,fa),M=_.parse(p[2],2,Ud(_.expectedType||Wo));return C&&M?new Pp(M.type.itemType,C,M):null}evaluate(p){const _=this.index.evaluate(p),C=this.input.evaluate(p);if(_<0)throw new ch(`Array index out of bounds: ${_} < 0.`);if(_>C.length-1)throw new ch(`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 ch(`Cannot interpolate between non-number values at index ${_}.`);return ya(z,H,_-M)}eachChild(p){p(this.index),p(this.input)}outputDefined(){return!1}serialize(){return["at-interpolated",this.index.serialize(),this.input.serialize()]}}class rx{constructor(p,_,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,lh(Te),se))return null}else C=lh(Te);if(F[String(Te)]!==void 0)return _.error("Branch labels must be unique.",se);F[String(Te)]=z.length}const be=_.parse(xe,se,M);if(!be)return null;M=M||be.type,z.push(be)}const H=_.parse(p[1],1,Wo);if(!H)return null;const Z=_.parse(p.at(-1),p.length-1,M);return Z?H.type.kind!=="value"&&_.checkSubtype(C,H.type,1)?null:new rx(C,M,H,F,z,Z):null}evaluate(p){const _=this.input.evaluate(p);return(Pb(lh(_),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 Qd{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,fa);if(!C||!M)return null;if(F=C.type,![Ud(Wo),Ao,Wo].some(z=>z.kind===F.kind))return _.error(`Expected first argument to be of type array or string, but found ${xu(C.type)} instead`),null;var F;if(p.length===4){const z=_.parse(p[3],3,fa);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(!Dx(_,["string","array"]))throw new ch(`Expected first argument to be of type array or string, but found ${xu(lh(_))} 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 Vd(N,p,_){const C=N!=="=="&&N!=="!=";return class z7t{constructor(F,z,H){this.type=pl,this.lhs=F,this.rhs=z,this.collator=H,this.hasUntypedArgument=F.type.kind==="value"||z.type.kind==="value"}static parse(F,z){if(F.length!==3&&F.length!==4)return z.error("Expected two or three arguments.");const H=F[0];let Z=z.parse(F[1],1,Wo);if(!Z)return null;if(!Td(H,Z.type))return z.error(`"${H}" comparisons are not supported for type '${xu(Z.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 '${xu(se.type)}'.`,2);if(Z.type.kind!==se.type.kind&&Z.type.kind!=="value"&&se.type.kind!=="value")return z.error(`Cannot compare types '${xu(Z.type)}' and '${xu(se.type)}'.`);C&&(Z.type.kind==="value"&&se.type.kind!=="value"?Z=new Jg(se.type,[Z]):Z.type.kind!=="value"&&se.type.kind==="value"&&(se=new Jg(Z.type,[se])));let fe=null;if(F.length===4){if(Z.type.kind!=="string"&&se.type.kind!=="string"&&Z.type.kind!=="value"&&se.type.kind!=="value")return z.error("Cannot use collator to compare non-string types.");if(fe=z.parse(F[3],3,$0),!fe)return null}return new z7t(Z,se,fe)}evaluate(F){const z=this.lhs.evaluate(F),H=this.rhs.evaluate(F);if(C&&this.hasUntypedArgument){const Z=lh(z),se=lh(H);if(Z.kind!==se.kind||Z.kind!=="string"&&Z.kind!=="number")throw new ch(`Expected arguments for "${N}" to be (string, string) or (number, number), but found (${Z.kind}, ${se.kind}) instead.`)}if(this.collator&&!C&&this.hasUntypedArgument){const Z=lh(z),se=lh(H);if(Z.kind!=="string"||se.kind!=="string")return p(F,z,H)}return this.collator?_(F,z,H,this.collator.evaluate(F)):p(F,z,H)}eachChild(F){F(this.lhs),F(this.rhs),this.collator&&F(this.collator)}outputDefined(){return!0}serialize(){const F=[N];return this.eachChild(z=>{F.push(z.serialize())}),F}}}const bd=Vd("==",function(N,p,_){return p===_},Jl),Df=Vd("!=",function(N,p,_){return p!==_},function(N,p,_,C){return!Jl(0,p,_,C)}),zx=Vd("<",function(N,p,_){return p<_},function(N,p,_,C){return C.compare(p,_)<0}),z1=Vd(">",function(N,p,_){return p>_},function(N,p,_,C){return C.compare(p,_)>0}),bm=Vd("<=",function(N,p,_){return p<=_},function(N,p,_,C){return C.compare(p,_)<=0}),Ok=Vd(">=",function(N,p,_){return p>=_},function(N,p,_,C){return C.compare(p,_)>=0});class B1{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,fa);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 Z=null;if(M["min-fraction-digits"]!==void 0&&(Z=_.parseObjectValue(M["min-fraction-digits"],2,"min-fraction-digits",fa),!Z))return null;let se=null;return M["max-fraction-digits"]===void 0||(se=_.parseObjectValue(M["max-fraction-digits"],2,"max-fraction-digits",fa),se)?new B1(C,F,z,H,Z,se):null}evaluate(p){return new Intl.NumberFormat(this.locale?this.locale.evaluate(p):[],{style:(this.currency?"currency":this.unit&&"unit")||"decimal",currency:this.currency?this.currency.evaluate(p):void 0,unit:this.unit?this.unit.evaluate(p):void 0,minimumFractionDigits:this.minFractionDigits?this.minFractionDigits.evaluate(p):void 0,maximumFractionDigits:this.maxFractionDigits?this.maxFractionDigits.evaluate(p):void 0}).format(this.number.evaluate(p))}eachChild(p){p(this.number),this.locale&&p(this.locale),this.currency&&p(this.currency),this.unit&&p(this.unit),this.minFractionDigits&&p(this.minFractionDigits),this.maxFractionDigits&&p(this.maxFractionDigits)}outputDefined(){return!1}serialize(){const p={};return this.locale&&(p.locale=this.locale.serialize()),this.currency&&(p.currency=this.currency.serialize()),this.unit&&(p.unit=this.unit.serialize()),this.minFractionDigits&&(p["min-fraction-digits"]=this.minFractionDigits.serialize()),this.maxFractionDigits&&(p["max-fraction-digits"]=this.maxFractionDigits.serialize()),["number-format",this.number.serialize(),p]}}class $1{constructor(p){this.type=fa,this.input=p}static parse(p,_){if(p.length!==2)return _.error(`Expected 1 argument, but found ${p.length-1} instead.`),null;const 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 ${xu(C.type)} instead.`),null):new $1(C):null}evaluate(p){const _=this.input.evaluate(p);if(typeof _=="string"||Array.isArray(_))return _.length;throw new ch(`Expected value to be of type string or array, but found ${xu(lh(_))} instead.`)}eachChild(p){p(this.input)}outputDefined(){return!1}serialize(){const p=["length"];return this.eachChild(_=>{p.push(_.serialize())}),p}}function lg(N){return function(){N=1831565813+(N|=0)|0;let p=Math.imul(N^N>>>15,1|N);return p=p+Math.imul(p^p>>>7,61|p)^p,((p^p>>>14)>>>0)/4294967296}}const Db={"==":bd,"!=":Df,">":z1,"<":zx,">=":Ok,"<=":bm,array:Jg,at:nx,"at-interpolated":Pp,boolean:Jg,case:Qd,coalesce:Bm,collator:D1,format:I1,image:L1,interpolate:vc,"interpolate-hcl":vc,"interpolate-lab":vc,length:$1,let:Mp,literal:Qg,match:rx,number:Jg,"number-format":B1,object:Jg,slice:ff,step:bi,string:Jg,"to-boolean":zv,"to-color":zv,"to-number":zv,"to-string":zv,var:bl,within:ip,distance:Fi,config:uf};function ax(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 ch(z);return new Ci(p/255,_/255,C/255,F)}function W2(N,[p,_,C,M]){p=p.evaluate(N),_=_.evaluate(N),C=C.evaluate(N);const F=M?M.evaluate(N):1,z=function(se,fe,xe,be){return typeof se=="number"&&se>=0&&se<=360?typeof fe=="number"&&fe>=0&&fe<=100&&typeof xe=="number"&&xe>=0&&xe<=100?be===void 0||typeof be=="number"&&be>=0&&be<=1?null:`Invalid hsla value [${[se,fe,xe,be].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid hsla value [${(typeof be=="number"?[se,fe,xe,be]:[se,fe,xe]).join(", ")}]: 's', and 'l' must be between 0 and 100.`:`Invalid hsla value [${(typeof be=="number"?[se,fe,xe,be]:[se,fe,xe]).join(", ")}]: 'h' must be between 0 and 360.`}(p,_,C,F);if(z)throw new ch(z);const H=`hsla(${p}, ${_}%, ${C}%, ${F})`,Z=Ci.parse(H);if(!Z)throw new ch(`Failed to parse HSLA color: ${H}`);return Z}function zk(N,p){return N in p}function yy(N,p){const _=p[N];return _===void 0?null:_}function vy(N){return{type:N}}function ej(N,p){if(!Dx(N,["boolean","string","number","null"]))throw new ch(`Expected first argument to be of type boolean, string, number or null, but found ${xu(lh(N))} instead.`);if(!Dx(p,["string","array"]))throw new ch(`Expected second argument to be of type array or string, but found ${xu(lh(p))} instead.`)}function Fb(N){if(N instanceof uf)return new Set([N.key]);let p=new Set;return N.eachChild(_=>{p=new Set([...p,...Fb(_)])}),p}function Bx(N){if(N instanceof rp&&N.name==="is-active-floor")return!0;let p=!1;return N.eachChild(_=>{!p&&Bx(_)&&(p=!0)}),p}function U1(N){return{result:"success",value:N}}function lp(N){return{result:"error",value:N}}function $_(N,p){return!!N&&!!N.parameters&&N.parameters.includes(p)}function Zy(N){return N["property-type"]==="data-driven"}function Bk(N){return $_(N.expression,"measure-light")}function tj(N){return $_(N.expression,"zoom")}function Xy(N){return!!N.expression&&N.expression.interpolated}function cp(N){return typeof N=="object"&&N!==null&&!Array.isArray(N)}function q1(N){return N}function $x(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||(Xy(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,Z;if(F==="exponential")z=$k;else if(F==="interval")z=A3;else if(F==="categorical"){z=V1,H=Object.create(null);for(const se of N.stops)H[se[0]]=se[1];Z=typeof N.stops[0][0]}else{if(F!=="identity")throw new Error(`Unknown function type "${F}"`);z=HT}if(C){const se={},fe=[];for(let Te=0;TeTe[0]),evaluate:({zoom:Te},De)=>$k({stops:xe,base:N.base},p,Te).evaluate(Te,De)}}if(M){const se=F==="exponential"?{name:"exponential",base:N.base!==void 0?N.base:1}:null;return{kind:"camera",interpolationType:se,interpolationFactor:vc.interpolationFactor.bind(void 0,se),zoomStops:N.stops.map(fe=>fe[0]),evaluate:({zoom:fe})=>z(N,p,fe,H,Z)}}return{kind:"source",evaluate(se,fe){const xe=fe&&fe.properties?fe.properties[N.property]:void 0;return xe===void 0?dp(N.default,p.default):z(N,p,xe,H,Z)}}}function dp(N,p,_){return N!==void 0?N:p!==void 0?p:_!==void 0?_:void 0}function V1(N,p,_,C,M){return dp(typeof _===M?C[_]:void 0,N.default,p.default)}function A3(N,p,_){if(!F_(_))return dp(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 $k(N,p,_){const C=N.base!==void 0?N.base:1;if(!F_(_))return dp(N.default,p.default);const M=N.stops.length;if(M===1||_<=N.stops[0][0])return N.stops[0][1];if(_>=N.stops[M-1][0])return N.stops[M-1][1];const F=yo(N.stops.map(fe=>fe[0]),_),z=function(fe,xe,be,Te){const De=Te-be,Ue=fe-be;return De===0?0:xe===1?Ue/De:(Math.pow(xe,Ue)-1)/(Math.pow(xe,De)-1)}(_,C,N.stops[F][0],N.stops[F+1][0]),H=N.stops[F][1],Z=N.stops[F+1][1];let se=kc[p.type]||q1;if(N.colorSpace&&N.colorSpace!=="rgb"){const fe=vh[N.colorSpace];se=(xe,be)=>fe.reverse(fe.interpolate(fe.forward(xe),fe.forward(be),z))}return typeof H.evaluate=="function"?{evaluate(...fe){const xe=H.evaluate.apply(void 0,fe),be=Z.evaluate.apply(void 0,fe);if(xe!==void 0&&be!==void 0)return se(xe,be,z)}}:se(H,Z,z)}function HT(N,p,_){return p.type==="color"?_=Ci.parse(_):p.type==="formatted"?_=yu.fromString(_.toString()):p.type==="resolvedImage"?_=yh.build(_.toString()):R1(_)===p.type||p.type==="enum"&&p.values[_]||(_=void 0),dp(_,N.default,p.default)}rp.register(Db,{error:[{kind:"error"},[Ao],(N,[p])=>{throw new ch(p.evaluate(N))}],typeof:[Ao,[Wo],(N,[p])=>xu(lh(p.evaluate(N)))],"to-rgba":[Ud(fa,4),[Qc],(N,[p])=>p.evaluate(N).toNonPremultipliedRenderColor(null).toArray()],"to-hsla":[Ud(fa,4),[Qc],(N,[p])=>p.evaluate(N).toNonPremultipliedRenderColor(null).toHslaArray()],rgb:[Qc,[fa,fa,fa],ax],rgba:[Qc,[fa,fa,fa,fa],ax],hsl:[Qc,[fa,fa,fa],W2],hsla:[Qc,[fa,fa,fa,fa],W2],has:{type:pl,overloads:[[[Ao],(N,[p])=>zk(p.evaluate(N),N.properties())],[[Ao,ag],(N,[p,_])=>zk(p.evaluate(N),_.evaluate(N))]]},get:{type:Wo,overloads:[[[Ao],(N,[p])=>yy(p.evaluate(N),N.properties())],[[Ao,ag],(N,[p,_])=>yy(p.evaluate(N),_.evaluate(N))]]},"feature-state":[Wo,[Ao],(N,[p])=>yy(p.evaluate(N),N.featureState||{})],properties:[ag,[],N=>N.properties()],"geometry-type":[Ao,[],N=>N.geometryType()],worldview:[Ao,[],N=>N.globals.worldview||""],"is-active-floor":[pl,vy(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:[fa,[],N=>N.globals.zoom],pitch:[fa,[],N=>N.globals.pitch||0],"distance-from-center":[fa,[],N=>N.distanceFromCenter()],"measure-light":[fa,[Ao],(N,[p])=>N.measureLight(p.evaluate(N))],"heatmap-density":[fa,[],N=>N.globals.heatmapDensity||0],"line-progress":[fa,[],N=>N.globals.lineProgress||0],"raster-value":[fa,[],N=>N.globals.rasterValue||0],"raster-particle-speed":[fa,[],N=>N.globals.rasterParticleSpeed||0],"sky-radial-progress":[fa,[],N=>N.globals.skyRadialProgress||0],accumulated:[Wo,[],N=>N.globals.accumulated===void 0?null:N.globals.accumulated],"+":[fa,vy(fa),(N,p)=>{let _=0;for(const C of p)_+=C.evaluate(N);return _}],"*":[fa,vy(fa),(N,p)=>{let _=1;for(const C of p)_*=C.evaluate(N);return _}],"-":{type:fa,overloads:[[[fa,fa],(N,[p,_])=>p.evaluate(N)-_.evaluate(N)],[[fa],(N,[p])=>-p.evaluate(N)]]},"/":[fa,[fa,fa],(N,[p,_])=>p.evaluate(N)/_.evaluate(N)],"%":[fa,[fa,fa],(N,[p,_])=>p.evaluate(N)%_.evaluate(N)],ln2:[fa,[],()=>Math.LN2],pi:[fa,[],()=>Math.PI],e:[fa,[],()=>Math.E],"^":[fa,[fa,fa],(N,[p,_])=>Math.pow(p.evaluate(N),_.evaluate(N))],sqrt:[fa,[fa],(N,[p])=>Math.sqrt(p.evaluate(N))],log10:[fa,[fa],(N,[p])=>Math.log(p.evaluate(N))/Math.LN10],ln:[fa,[fa],(N,[p])=>Math.log(p.evaluate(N))],log2:[fa,[fa],(N,[p])=>Math.log2(p.evaluate(N))],sin:[fa,[fa],(N,[p])=>Math.sin(p.evaluate(N))],cos:[fa,[fa],(N,[p])=>Math.cos(p.evaluate(N))],tan:[fa,[fa],(N,[p])=>Math.tan(p.evaluate(N))],asin:[fa,[fa],(N,[p])=>Math.asin(p.evaluate(N))],acos:[fa,[fa],(N,[p])=>Math.acos(p.evaluate(N))],atan:[fa,[fa],(N,[p])=>Math.atan(p.evaluate(N))],min:[fa,vy(fa),(N,p)=>Math.min(...p.map(_=>_.evaluate(N)))],max:[fa,vy(fa),(N,p)=>Math.max(...p.map(_=>_.evaluate(N)))],abs:[fa,[fa],(N,[p])=>Math.abs(p.evaluate(N))],round:[fa,[fa],(N,[p])=>{const _=p.evaluate(N);return _<0?-Math.round(-_):Math.round(_)}],floor:[fa,[fa],(N,[p])=>Math.floor(p.evaluate(N))],ceil:[fa,[fa],(N,[p])=>Math.ceil(p.evaluate(N))],"filter-==":[pl,[Ao,Wo],(N,[p,_])=>N.properties()[p.value]===_.value],"filter-id-==":[pl,[Wo],(N,[p])=>N.id()===p.value],"filter-type-==":[pl,[Ao],(N,[p])=>N.geometryType()===p.value],"filter-<":[pl,[Ao,Wo],(N,[p,_])=>{const C=N.properties()[p.value],M=_.value;return typeof C==typeof M&&C{const _=N.id(),C=p.value;return typeof _==typeof C&&_":[pl,[Ao,Wo],(N,[p,_])=>{const C=N.properties()[p.value],M=_.value;return typeof C==typeof M&&C>M}],"filter-id->":[pl,[Wo],(N,[p])=>{const _=N.id(),C=p.value;return typeof _==typeof C&&_>C}],"filter-<=":[pl,[Ao,Wo],(N,[p,_])=>{const C=N.properties()[p.value],M=_.value;return typeof C==typeof M&&C<=M}],"filter-id-<=":[pl,[Wo],(N,[p])=>{const _=N.id(),C=p.value;return typeof _==typeof C&&_<=C}],"filter->=":[pl,[Ao,Wo],(N,[p,_])=>{const C=N.properties()[p.value],M=_.value;return typeof C==typeof M&&C>=M}],"filter-id->=":[pl,[Wo],(N,[p])=>{const _=N.id(),C=p.value;return typeof _==typeof C&&_>=C}],"filter-has":[pl,[Wo],(N,[p])=>p.value in N.properties()],"filter-has-id":[pl,[],N=>N.id()!==null&&N.id()!==void 0],"filter-type-in":[pl,[Ud(Ao)],(N,[p])=>p.value.includes(N.geometryType())],"filter-id-in":[pl,[Ud(Wo)],(N,[p])=>p.value.includes(N.id())],"filter-in-small":[pl,[Ao,Ud(Wo)],(N,[p,_])=>_.value.includes(N.properties()[p.value])],"filter-in-large":[pl,[Ao,Ud(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:pl,overloads:[[[pl,pl],(N,[p,_])=>p.evaluate(N)&&_.evaluate(N)],[vy(pl),(N,p)=>{for(const _ of p)if(!_.evaluate(N))return!1;return!0}]]},any:{type:pl,overloads:[[[pl,pl],(N,[p,_])=>p.evaluate(N)||_.evaluate(N)],[vy(pl),(N,p)=>{for(const _ of p)if(_.evaluate(N))return!0;return!1}]]},"!":[pl,[pl],(N,[p])=>!p.evaluate(N)],"is-supported-script":[pl,[Ao],(N,[p])=>{const _=N.globals&&N.globals.isSupportedScript;return!_||_(p.evaluate(N))}],upcase:[Ao,[Ao],(N,[p])=>p.evaluate(N).toUpperCase()],downcase:[Ao,[Ao],(N,[p])=>p.evaluate(N).toLowerCase()],concat:[Ao,vy(Wo),(N,p)=>p.map(_=>np(_.evaluate(N))).join("")],split:[Ud(Ao),[Ao,Ao],(N,[p,_])=>p.evaluate(N).split(_.evaluate(N))],in:[pl,[Wo,Wo],(N,[p,_])=>{const C=p.evaluate(N),M=_.evaluate(N);return M!=null&&(ej(C,M),M.includes(C))}],"index-of":{type:fa,overloads:[[[Wo,Wo],(N,[p,_])=>{const C=p.evaluate(N),M=_.evaluate(N);return ej(C,M),M.indexOf(C)}],[[Wo,Wo,fa],(N,[p,_,C])=>{const M=p.evaluate(N),F=_.evaluate(N),z=C.evaluate(N);return ej(M,F),F.indexOf(M,z)}]]},"resolved-locale":[Ao,[$0],(N,[p])=>p.evaluate(N).resolvedLocale()],random:[fa,[fa,fa,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 Z=0;ZJSON.stringify(xe)).join(", ")}, but found ${JSON.stringify(fe)} instead.`);return fe}catch(fe){const xe=fe;return this._warningHistory[xe.message]||(this._warningHistory[xe.message]=!0,typeof console<"u"&&console.warn(`Failed to evaluate expression "${JSON.stringify(this.expression.serialize())}". ${xe.message}`)),this._defaultValue}}}function Uv(N){return Array.isArray(N)&&N.length>0&&typeof N[0]=="string"&&Object.hasOwn(Db,N[0])}function H0(N,p,_,C,M){const F=new lo(Db,[],p?function(H){const Z={color:Qc,string:Ao,number:fa,enum:Ao,boolean:pl,formatted:xh,resolvedImage:df,object:ag};return H.type==="array"?Ud(Z[H.value]||Wo,H.length):Z[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?U1(new $v(z,p,_,C,M)):lp(F.errors)}class U_{constructor(p,_,C,M){this.kind=p,this._styleExpression=_,this.isLightConstant=C,this.isLineProgressConstant=M,this.isStateDependent=p!=="constant"&&!q0(_.expression),this.configDependencies=Fb(_.expression),this.isIndoorDependent=Bx(_.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 cg{constructor(p,_,C,M,F,z){this.kind=p,this.zoomStops=C,this._styleExpression=_,this.isStateDependent=p!=="camera"&&!q0(_.expression),this.isIndoorDependent=Bx(_.expression),this.isLightConstant=F,this.isLineProgressConstant=z,this.configDependencies=Fb(_.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?vc.interpolationFactor(this.interpolationType,p,_,C):0}}function G0(N,p,_,C,M){if((N=H0(N,p,_,C,M)).result==="error")return N;const F=N.value.expression,z=F1(F);if(!z&&!Zy(p))return lp([new Ro("","data expressions not supported")]);const H=Ox(F,["zoom","pitch","distance-from-center"]);if(!H&&!tj(p))return lp([new Ro("","zoom expressions not supported")]);const Z=Ox(F,["measure-light"]);if(!Z&&!Bk(p))return lp([new Ro("","measure-light expression not supported")]);const se=Ox(F,["line-progress"]);if(!se&&!function(be){return $_(be.expression,"line-progress")}(p))return lp([new Ro("","line-progress expression not supported")]);const fe=p.expression&&p.expression.relaxZoomRestriction,xe=up(F);return xe||H||fe?xe instanceof Ro?lp([xe]):xe instanceof vc&&!Xy(p)?lp([new Ro("",'"interpolate" expressions cannot be used with this property')]):U1(xe?new cg(z&&se?"camera":"composite",N.value,xe.labels,xe instanceof vc?xe.interpolation:void 0,Z,se):new U_(z&&se?"constant":"source",N.value,Z,se)):lp([new Ro("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression, or in the properties of atmosphere.')])}class Qy{constructor(p,_){this._parameters=p,this._specification=_,Object.assign(this,$x(this._parameters,this._specification))}static deserialize(p){return new Qy(p._parameters,p._specification)}static serialize(p){return{_parameters:p._parameters,_specification:p._specification}}}function up(N){let p=null;if(N instanceof Mp)p=up(N.result);else if(N instanceof Bm){for(const _ of N.args)if(p=up(_),p)break}else(N instanceof bi||N instanceof vc)&&N.input instanceof rp&&N.input.name==="zoom"&&(p=N);return p instanceof Ro||N.eachChild(_=>{const C=up(_);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 qv{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 fe=0;fethis.width||M<0||_>this.height)return z;const H=this._nextGen(),{boxCells:Z,circleCells:se,boxKeys:fe,circleKeys:xe,bboxes:be,circles:Te,boxSeen:De,circleSeen:Ue,xCellCount:Ye}=this,nt=this._xCell(p),it=this._yCell(_),ht=this._xCell(C),ot=this._yCell(M);for(let yt=nt;yt<=ht;yt++)for(let Nt=it;Nt<=ot;Nt++){const is=Ye*Nt+yt,At=Z[is];if(At)for(let Jt=0;Jt=Gs&&M>=pn&&(!F||F(fe[ns]))&&z.push({key:fe[ns],x1:Gs,y1:pn,x2:cn,y2:jn})}const $t=se[is];if($t)for(let Jt=0;Jt<$t.length;Jt++){const ns=$t[Jt];if(Ue[ns]===H)continue;Ue[ns]=H;const Ps=3*ns,Gs=Te[Ps],pn=Te[Ps+1],cn=Te[Ps+2];!this._circleAndRectCollide(Gs,pn,cn,p,_,C,M)||F&&!F(xe[ns])||z.push({key:xe[ns],x1:Gs-cn,y1:pn-cn,x2:Gs+cn,y2:pn+cn})}}return z}queryKeys(p,_,C,M,F){const z=[];if(C<0||p>this.width||M<0||_>this.height)return z;const H=this._nextGen(),{boxCells:Z,boxKeys:se,bboxes:fe,boxSeen:xe,xCellCount:be,xScale:Te,yScale:De}=this,Ue=this._xCell(p),Ye=this._yCell(_),nt=this._xCell(C),it=this._yCell(M);for(let ht=Ue;ht<=nt;ht++)for(let ot=Ye;ot<=it;ot++){if(F&&!F(ht/Te,ot/De,(ht+1)/Te,(ot+1)/De))continue;const yt=Z[be*ot+ht];if(yt)for(let Nt=0;Nt=$t&&M>=Jt)&&z.push(se[is])}}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:Z,boxKeys:se,circleKeys:fe,bboxes:xe,circles:be,boxSeen:Te,circleSeen:De,xCellCount:Ue}=this,Ye=this._xCell(p),nt=this._yCell(_),it=this._xCell(C),ht=this._yCell(M);for(let ot=Ye;ot<=it;ot++)for(let yt=nt;yt<=ht;yt++){const Nt=Ue*yt+ot,is=H[Nt];if(is)for(let $t=0;$t=xe[ns]&&M>=xe[ns+1]&&(!F||F(se[Jt])))return!0}const At=Z[Nt];if(At)for(let $t=0;$tthis.width||Z<0||z>this.height)return!1;const se=this._nextGen(),{boxCells:fe,circleCells:xe,boxKeys:be,circleKeys:Te,bboxes:De,circles:Ue,boxSeen:Ye,circleSeen:nt,xCellCount:it}=this,ht=this._xCell(F),ot=this._yCell(z),yt=this._xCell(H),Nt=this._yCell(Z);for(let is=ht;is<=yt;is++)for(let At=ot;At<=Nt;At++){const $t=it*At+is,Jt=fe[$t];if(Jt)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,Z=F-_,se=C+z;return se*se>H*H+Z*Z}_circleAndRectCollide(p,_,C,M,F,z,H){const Z=(z-M)/2,se=Math.abs(p-(M+Z));if(se>Z+C)return!1;const fe=(H-F)/2,xe=Math.abs(_-(F+fe));if(xe>fe+C)return!1;if(se<=Z||xe<=fe)return!0;const be=se-Z,Te=xe-fe;return be*be+Te*Te<=C*C}}const K2={};function oa(N,p,_={}){Object.defineProperty(N,"_classRegistryKey",{value:p,writable:!1}),K2[p]={klass:N,omit:_.omit||[]}}oa(Object,"Object"),oa(qv,"Grid"),delete xs.prototype.constructor,oa(Ci,"Color"),oa(yu,"Formatted"),oa(zm,"FormattedSection"),oa(yh,"ResolvedImage"),oa(Qy,"StylePropertyFunction"),oa($v,"StyleExpression",{omit:["_evaluator"]}),oa(vd,"ImageId"),oa(Ih,"ImageVariant"),oa(cg,"ZoomDependentExpression"),oa(U_,"ZoomConstantExpression"),oa(rp,"CompoundExpression",{omit:["_evaluate"]});for(const N in Db)K2[Db[N]._classRegistryKey]||oa(Db[N],`Expression${N}`);function E3(N){return N&&(N instanceof ArrayBuffer||N.constructor&&N.constructor.name==="ArrayBuffer")}const Y2={Error,TypeError,RangeError,SyntaxError,ReferenceError,URIError,EvalError},dg=new Set(["message","stack","cause","errors","name","class"]);function Vv(N,p){if(N===null)return null;const _=typeof N;if(_!=="object")return _==="bigint"?{$name:"BigInt",value:N.toString()}:N;if(Array.isArray(N)){const z=N.length,H=[];H.length=z;for(let Z=0;Zfe!==z).map(fe=>Vv(fe,p)));const se=z;for(const fe in se)Object.hasOwn(se,fe)&&(dg.has(fe)||(Z[fe]=Vv(se[fe],p)));return Z}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=K2[M].omit,H=N;for(const Z in H)Object.hasOwn(H,Z)&&(z.includes(Z)||(F[Z]=Vv(H[Z],p)))}if(F.$name)throw new Error("$name property is reserved for worker serialization logic.");return M!=="Object"&&(F.$name=M),F}function Ux(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,T3=N=>N>=2208&&N<=2303,GT=N=>N>=11904&&N<=12031,j9=N=>N>=12032&&N<=12255,N9=N=>N>=12272&&N<=12287,Uk=N=>N>=12288&&N<=12351,OC=N=>N>=12352&&N<=12447,zC=N=>N>=12448&&N<=12543,W0=N=>N>=12544&&N<=12591,WT=N=>N>=12704&&N<=12735,M3=N=>N>=12736&&N<=12783,Ob=N=>N>=12784&&N<=12799,qk=N=>N>=12800&&N<=13055,sj=N=>N>=13056&&N<=13311,Vk=N=>N>=13312&&N<=19903,BC=N=>N>=19968&&N<=40959,$C=N=>N>=40960&&N<=42127,D6=N=>N>=42128&&N<=42191,P3=N=>N>=44032&&N<=55215,F6=N=>N>=63744&&N<=64255,KT=N=>N>=64336&&N<=65023,O6=N=>N>=65040&&N<=65055,UC=N=>N>=65072&&N<=65103,k9=N=>N>=65104&&N<=65135,z6=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!(Z2(N)||_m(N)||T3(N)||KT(N)||z6(N))}function tt(N){return!(N!==746&&N!==747&&(N<4352||!(WT(N)||W0(N)||UC(N)&&!(N>=65097&&N<=65103)||F6(N)||sj(N)||GT(N)||M3(N)||!(!Uk(N)||N>=12296&&N<=12305||N>=12308&&N<=12319||N===12336)||Vk(N)||BC(N)||qk(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)||P3(N)||OC(N)||N9(N)||(p=>p>=12688&&p<=12703)(N)||j9(N)||Ob(N)||zC(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)||!(!k9(N)||N>=65112&&N<=65118||N>=65123&&N<=65126)||(p=>p>=5120&&p<=5759)(N)||(p=>p>=6320&&p<=6399)(N)||O6(N)||(p=>p>=19904&&p<=19967)(N)||$C(N)||D6(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)||Uk(p)||zC(p)||(_=>_>=57344&&_<=63743)(p)||UC(p)||k9(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||KT(N)||z6(N)}function Ws(N,p){return!(!p&&Ot(N)||N>=2304&&N<=3583||N>=3840&&N<=4255||(_=>_>=6016&&_<=6143)(N))}function mr(N){for(const p of N)if(Ot(p.charCodeAt(0)))return!0;return!1}const $r={unavailable:"unavailable",deferred:"deferred",loading:"loading",parsing:"parsing",parsed:"parsed",loaded:"loaded",error:"error"};let di=null,Mi=$r.unavailable,gl=null;const Zi=function(N){N&&(Mi=$r.error),di&&di(N)};function Hh(){hh.fire(new zl("pluginStateChange",{pluginStatus:Mi,pluginURL:gl}))}const hh=new Xc,by=function(){return Mi},q_=function(){if(Mi!==$r.deferred||!gl)throw new Error("rtl-text-plugin cannot be downloaded unless a pluginURL is specified");Mi=$r.loading,Hh(),gl&&Qr({url:gl}).then(()=>{Mi=$r.loaded,Hh()}).catch(N=>{Zi(N)})},Ur={applyArabicShaping:null,processBidirectionalText:null,processStyledBidirectionalText:null,isLoaded:()=>Mi===$r.loaded||Ur.applyArabicShaping!=null,isLoading:()=>Mi===$r.loading,setState(N){Mi=N.pluginStatus,gl=N.pluginURL},isParsing:()=>Mi===$r.parsing,isParsed:()=>Mi===$r.parsed,getPluginURL:()=>gl};class Wn{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(!Ws(M.charCodeAt(0),C))return!1;return!0}(p,Ur.isLoaded())}}class ia{constructor(p,_,C,M,F){this.property=p,this.value=_,this.expression=function(z,H,Z,se,fe){if(cp(z))return new Qy(z,H);if(Uv(z)||Array.isArray(z)&&z.length>0){const xe=G0(z,H,Z,se,fe);if(xe.result==="error")throw new Error(xe.value.map(be=>`${be.key}: ${be.message}`).join(", "));return xe.value}{let xe=z;return typeof z=="string"&&H.type==="color"&&(xe=Ci.parse(z)),{kind:"constant",configDependencies:new Set,isIndoorDependent:!1,evaluate:()=>xe}}}(_===void 0?p.specification.default:_,p.specification,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 ia(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 xl{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 ia(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 S9(N){return N instanceof Number||N instanceof String||N instanceof Boolean?N.valueOf():N}function C9(N){if(Array.isArray(N))return N.map(C9);if(N instanceof Object&&!(N instanceof Number||N instanceof String||N instanceof Boolean)){const p={},_=N;for(const C in _)p[C]=C9(_[C]);return p}return S9(N)}function B6(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(!B6(p)&&typeof p!="boolean")return!1;return!0;default:return!0}}function hY(N,p="",_=null,C="fill"){if(N==null)return{filter:()=>!0,needGeometry:!1,needFeature:!1};B6(N)||(N=$6(N));const M=N;let F=!0;try{F=function(fe){if(!YT(fe))return fe;let xe=C9(fe);return uoe(xe),xe=doe(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=Ys[`filter_${C}`];const fe=H0(F,H,p,_);if(fe.result==="error")throw new Error(fe.value.map(xe=>`${xe.key}: ${xe.message}`).join(", "));z=(xe,be,Te)=>fe.value.evaluate(xe,be,{},Te)}let Z=null,se=null;if(F!==M){const fe=H0(M,H,p,_);if(fe.result==="error")throw new Error(fe.value.map(xe=>`${xe.key}: ${xe.message}`).join(", "));Z=(xe,be,Te,De,Ue)=>fe.value.evaluate(xe,be,{},Te,void 0,void 0,De,Ue),se=!F1(fe.value.expression)}return{filter:z,dynamicFilter:Z||void 0,needGeometry:moe(F),needFeature:!!se}}function doe(N){if(!Array.isArray(N))return N;const p=function(_){if(hoe.has(_[0])){for(let C=1;C<_.length;C++)if(YT(_[C]))return!0}return _}(N);return p===!0?p:p.map(_=>doe(_))}function uoe(N){let p=!1;const _=[];if(N[0]==="case"){for(let C=1;C",">=","<","<=","to-boolean"]);function mY(N,p){return Np?1:0}function moe(N){if(!Array.isArray(N))return!1;if(N[0]==="within"||N[0]==="distance")return!0;for(let p=1;p"||p==="<="||p===">="?A9(N[1],N[2],p):p==="any"?(_=N.slice(1),["any"].concat(_.map($6))):p==="all"?["all"].concat(N.slice(1).map($6)):p==="none"?["all"].concat(N.slice(1).map($6).map(L3)):p==="in"?foe(N[1],N.slice(2)):p==="!in"?L3(foe(N[1],N.slice(2))):p==="has"?E9(N[1]):p!=="!has"||L3(E9(N[1]));var _}function A9(N,p,_){switch(N){case"$type":return[`filter-type-${_}`,p];case"$id":return[`filter-id-${_}`,p];default:return[`filter-${_}`,N,p]}}function foe(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(mY)]]:["filter-in-small",N,["literal",p]]}}function E9(N){switch(N){case"$type":return!0;case"$id":return["filter-has-id"];default:return["filter-has",N]}}function L3(N){return["!",N]}const ZT="";function U6(N,p){return p?`${N}${ZT}${p}`:N}function fY(N){const p=N.indexOf(ZT);return p>=0?N.slice(p+1):""}let poe,pY=1;const goe=()=>poe||(poe=new Wu({"icon-size":new Er(Ys.layout_symbol["icon-size"]),"icon-image":new Er(Ys.layout_symbol["icon-image"]),"icon-rotate":new Er(Ys.layout_symbol["icon-rotate"]),"icon-offset":new Er(Ys.layout_symbol["icon-offset"]),"text-size":new Er(Ys.layout_symbol["text-size"]),"text-rotate":new Er(Ys.layout_symbol["text-rotate"]),"text-offset":new Er(Ys.layout_symbol["text-offset"])}));let xoe;const yoe=()=>xoe||(xoe=new Wu({"icon-opacity":new Er(Ys.paint_symbol["icon-opacity"]),"icon-occlusion-opacity":new Er(Ys.paint_symbol["icon-occlusion-opacity"]),"icon-emissive-strength":new Er(Ys.paint_symbol["icon-emissive-strength"]),"text-emissive-strength":new Er(Ys.paint_symbol["text-emissive-strength"]),"icon-color":new Er(Ys.paint_symbol["icon-color"]),"icon-halo-color":new Er(Ys.paint_symbol["icon-halo-color"]),"icon-halo-width":new Er(Ys.paint_symbol["icon-halo-width"]),"icon-halo-blur":new Er(Ys.paint_symbol["icon-halo-blur"]),"icon-translate":new Er(Ys.paint_symbol["icon-translate"]),"text-opacity":new Er(Ys.paint_symbol["text-opacity"]),"text-occlusion-opacity":new Er(Ys.paint_symbol["text-occlusion-opacity"]),"text-color":new Er(Ys.paint_symbol["text-color"],{runtimeType:Qc,getOverride:N=>N.textColor,hasOverride:N=>!!N.textColor}),"text-halo-color":new Er(Ys.paint_symbol["text-halo-color"]),"text-halo-width":new Er(Ys.paint_symbol["text-halo-width"]),"text-halo-blur":new Er(Ys.paint_symbol["text-halo-blur"]),"text-translate":new Er(Ys.paint_symbol["text-translate"]),"symbol-z-offset":new Er(Ys.paint_symbol["symbol-z-offset"]),"placement-priority":new Er(Ys.paint_symbol["placement-priority"]),"placement-group":new Er(Ys.paint_symbol["placement-group"]),"icon-color-use-theme":new Er({type:"string",default:"default","property-type":"data-driven"}),"icon-halo-color-use-theme":new Er({type:"string",default:"default","property-type":"data-driven"}),"text-color-use-theme":new Er({type:"string",default:"default","property-type":"data-driven"}),"text-halo-color-use-theme":new Er({type:"string",default:"default","property-type":"data-driven"})}));class PFe{constructor(p,_,C,M,F,z){this._conditionSpec=p,this._propertiesSpec=C;const H=H0(p,Ys.appearance.condition);if(H.result==="success"&&(this.condition=H.value),this.name=_,C){this.layoutProperties=new Sl(goe()),this.unevaluatedLayout=new Md(goe(),M,F,z),this.paintProperties=new Sl(yoe()),this.unevaluatedPaint=new Md(yoe(),M,F,"");for(const Z in C)Z in this.unevaluatedLayout._values?this.unevaluatedLayout.setValue(Z,C[Z]):Z in this.unevaluatedPaint._values&&this.unevaluatedPaint.setValue(Z,C[Z])}}isActive(p){return!(this.condition||!p.isHidden||this.name!=="hidden")||this.condition.evaluate(p.globals,p.feature,p.featureState,p.canonical)}getCondition(){return this.condition}getName(){return this.name}getLayoutProperty(p){return this.layoutProperties.get(p)}getPaintProperty(p){return this.paintProperties.get(p)}getUnevaluatedLayoutProperties(){return this.unevaluatedLayout}getUnevaluatedLayoutProperty(p){return this.unevaluatedLayout._values[p]}getUnevaluatedPaintProperty(p){return this.unevaluatedPaint._values[p]}recalculate(p,_,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 gY="-transition",IFe=new Set(["fill","line","background","hillshade","raster"]);class Jy extends Xc{constructor(p,_,C,M,F,z){if(super(),this.id=p.id,this.fqid=U6(this.id,C),this.runtimeLayerUID=pY++,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 xl(_.paint,this.scope,F);for(const H in p.paint)this.setPaintProperty(H,p.paint[H]);for(const H in p.layout)this.setLayoutProperty(H,p.layout[H]);this._transitioningPaint=this._transitionablePaint.untransitioned(),this.paint=new Sl(_.paint)}}onAdd(p){}onRemove(p){}placeSymbols(p,_,C,M,F){}isDraped(p){return!this.is3D(!0)&&IFe.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 PFe(_.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(gY)?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(gY)){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 Z=C._values[p].value,se=Z.isDataDriven(),fe=p.endsWith("pattern")||p==="line-dasharray";return se||z||fe||this._handleOverridablePaintPropertyUpdate(p,H,Z)}_handleSpecialPaintPropertyUpdate(p){}getProgramIds(){return null}getDefaultProgramParams(p,_,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())),yc(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&&Zy(_.property.specification)&&(_.value.kind==="source"||_.value.kind==="composite")&&_.value.isStateDependent)return!0}for(const p of this.appearances)if(!q0(p.condition.expression))return!0;return!1}compileFilter(p){this._filterCompiled||(this._featureFilter=hY(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,Z,se,fe){}}function T9(N,p,_){if(!N._unevaluatedLayout)return!1;const C=N._unevaluatedLayout.getValue(p);return C!==void 0&&(typeof C!="string"||_(C))}function XT(N,p,_=2){const C=p&&p.length,M=C?p[0]*_:N.length;let F=voe(N,0,M,_,!0);const z=[];if(!F||F.next===F.prev)return z;let H,Z,se;if(C&&(F=function(fe,xe,be,Te){const De=[];for(let Ue=0,Ye=xe.length;Ue80*_){H=N[0],Z=N[1];let fe=H,xe=Z;for(let be=_;befe&&(fe=Te),De>xe&&(xe=De)}se=Math.max(fe-H,xe-Z),se=se!==0?32767/se:0}return q6(F,z,_,H,Z,se,0),z}function voe(N,p,_,C,M){let F;if(M===function(z,H,Z,se){let fe=0;for(let xe=H,be=Z-se;xe0)for(let z=p;z<_;z+=C)F=Noe(z/C|0,N[z],N[z+1],F);else for(let z=_-C;z>=p;z-=C)F=Noe(z/C|0,N[z],N[z+1],F);return F&&JT(F,F.next)&&(G6(F),F=F.next),F}function R3(N,p){if(!N)return N;p||(p=N);let _,C=N;do if(_=!1,C.steiner||!JT(C,C.next)&&Ff(C.prev,C,C.next)!==0)C=C.next;else{if(G6(C),C=p=C.prev,C===C.next)break;_=!0}while(_||C!==p);return p}function q6(N,p,_,C,M,F,z){if(!N)return;!z&&F&&function(Z,se,fe,xe){let be=Z;do be.z===0&&(be.z=I9(be.x,be.y,se,fe,xe)),be.prevZ=be.prev,be.nextZ=be.next,be=be.next;while(be!==Z);be.prevZ.nextZ=null,be.prevZ=null,function(Te){let De,Ue=1;do{let Ye,nt=Te;Te=null;let it=null;for(De=0;nt;){De++;let ht=nt,ot=0;for(let Nt=0;Nt0||yt>0&&ht;)ot!==0&&(yt===0||!ht||nt.z<=ht.z)?(Ye=nt,nt=nt.nextZ,ot--):(Ye=ht,ht=ht.nextZ,yt--),it?it.nextZ=Ye:Te=Ye,Ye.prevZ=it,it=Ye;nt=ht}it.nextZ=null,Ue*=2}while(De>1)}(be)}(N,C,M,F);let H=N;for(;N.prev!==N.next;){const Z=N.prev,se=N.next;if(F?RFe(N,C,M,F):LFe(N))p.push(Z.i,N.i,se.i),G6(N),N=se.next,H=se.next;else if((N=se)===H){z?z===1?q6(N=M9(R3(N),p),p,_,C,M,F,2):z===2&&DFe(N,p,_,C,M,F):q6(R3(N),p,_,C,M,F,1);break}}}function LFe(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,Z=_.y,se=C.y,fe=Math.min(M,F,z),xe=Math.min(H,Z,se),be=Math.max(M,F,z),Te=Math.max(H,Z,se);let De=C.next;for(;De!==p;){if(De.x>=fe&&De.x<=be&&De.y>=xe&&De.y<=Te&&QT(M,H,F,Z,z,se,De.x,De.y)&&Ff(De.prev,De,De.next)>=0)return!1;De=De.next}return!0}function RFe(N,p,_,C){const M=N.prev,F=N,z=N.next;if(Ff(M,F,z)>=0)return!1;const H=M.x,Z=F.x,se=z.x,fe=M.y,xe=F.y,be=z.y,Te=Math.min(H,Z,se),De=Math.min(fe,xe,be),Ue=Math.max(H,Z,se),Ye=Math.max(fe,xe,be),nt=I9(Te,De,p,_,C),it=I9(Ue,Ye,p,_,C);let ht=N.prevZ,ot=N.nextZ;for(;ht&&ht.z>=nt&&ot&&ot.z<=it;){if(ht.x>=Te&&ht.x<=Ue&&ht.y>=De&&ht.y<=Ye&&ht!==M&&ht!==z&&QT(H,fe,Z,xe,se,be,ht.x,ht.y)&&Ff(ht.prev,ht,ht.next)>=0||(ht=ht.prevZ,ot.x>=Te&&ot.x<=Ue&&ot.y>=De&&ot.y<=Ye&&ot!==M&&ot!==z&&QT(H,fe,Z,xe,se,be,ot.x,ot.y)&&Ff(ot.prev,ot,ot.next)>=0))return!1;ot=ot.nextZ}for(;ht&&ht.z>=nt;){if(ht.x>=Te&&ht.x<=Ue&&ht.y>=De&&ht.y<=Ye&&ht!==M&&ht!==z&&QT(H,fe,Z,xe,se,be,ht.x,ht.y)&&Ff(ht.prev,ht,ht.next)>=0)return!1;ht=ht.prevZ}for(;ot&&ot.z<=it;){if(ot.x>=Te&&ot.x<=Ue&&ot.y>=De&&ot.y<=Ye&&ot!==M&&ot!==z&&QT(H,fe,Z,xe,se,be,ot.x,ot.y)&&Ff(ot.prev,ot,ot.next)>=0)return!1;ot=ot.nextZ}return!0}function M9(N,p){let _=N;do{const C=_.prev,M=_.next.next;!JT(C,M)&&woe(C,_,_.next,M)&&H6(C,M)&&H6(M,C)&&(p.push(C.i,_.i,M.i),G6(_),G6(_.next),_=N=M),_=_.next}while(_!==N);return R3(_)}function DFe(N,p,_,C,M,F){let z=N;do{let H=z.next.next;for(;H!==z.prev;){if(z.i!==H.i&&_oe(z,H)){let Z=joe(z,H);return z=R3(z,z.next),Z=R3(Z,Z.next),q6(z,p,_,C,M,F,0),void q6(Z,p,_,C,M,F,0)}H=H.next}z=z.next}while(z!==N)}function FFe(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 P9(N,p){const _=function(M,F){let z=F;const H=M.x,Z=M.y;let se,fe=-1/0;if(JT(M,z))return z;do{if(JT(M,z.next))return z.next;if(Z<=z.y&&Z>=z.next.y&&z.next.y!==z.y){const Ue=z.x+(Z-z.y)*(z.next.x-z.x)/(z.next.y-z.y);if(Ue<=H&&Ue>fe&&(fe=Ue,se=z.x=z.x&&z.x>=be&&H!==z.x&&boe(Zse.x||z.x===se.x&&OFe(se,z)))&&(se=z,De=Ue)}z=z.next}while(z!==xe);return se}(N,p);if(!_)return p;const C=joe(_,N);return R3(C,C.next),R3(_,_.next)}function OFe(N,p){return Ff(N.prev,N,p.prev)<0&&Ff(p.next,N,N.next)<0}function I9(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 zFe(N){let p=N,_=N;do(p.x<_.x||p.x===_.x&&p.y<_.y)&&(_=p),p=p.next;while(p!==N);return _}function boe(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 QT(N,p,_,C,M,F,z,H){return!(N===z&&p===H)&&boe(N,p,_,C,M,F,z,H)}function _oe(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&&woe(M,M.next,_,C))return!0;M=M.next}while(M!==_);return!1}(N,p)&&(H6(N,p)&&H6(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))||JT(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 JT(N,p){return N.x===p.x&&N.y===p.y}function woe(N,p,_,C){const M=L9(Ff(N,p,_)),F=L9(Ff(N,p,C)),z=L9(Ff(_,C,N)),H=L9(Ff(_,C,p));return M!==F&&z!==H||!(M!==0||!V6(N,_,p))||!(F!==0||!V6(N,C,p))||!(z!==0||!V6(_,N,C))||!(H!==0||!V6(_,p,C))}function V6(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 L9(N){return N>0?1:N<0?-1:0}function H6(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 joe(N,p){const _=xY(N.i,N.x,N.y),C=xY(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 Noe(N,p,_,C){const M=xY(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 G6(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 xY(N,p,_){return{i:N,x:p,y:_,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function yY(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 W6(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),yY(H.constantOr(null),M,_)&&(F=!0)}return F}function vY(N,p,_,C,M,F){const z=F.patternDependencies;for(const H of p){const Z=H.paint.get(`${N}-pattern`).value;if(Z.kind!=="constant"){const se=yY(Z.evaluate({zoom:C},_,{},void 0,F.availableImages),z,M);if(!se)continue;const{primary:fe,secondary:xe}=se;fe&&(_.patterns[H.id]=[fe,xe].filter(Boolean))}}return _}const pf=Dr/Math.PI/2,Hk=64,bY=[Hk,32,16],Hv=-pf,V_=pf;function nj(N,p,_,C=pf){return _=Xr(_),[N*Math.sin(_)*C,-p*C,N*Math.cos(_)*C]}function D3(N,p,_){return nj(Math.cos(Xr(N)),Math.sin(Xr(N)),p,_)}const eM=63710088e-1,_Y=2*Math.PI*eM;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(fl(this.lng,-180,180),this.lat)}toArray(){return[this.lng,this.lat]}toString(){return`LngLat(${this.lng}, ${this.lat})`}distanceTo(p){const _=Math.PI/180,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 eM*Math.acos(Math.min(F,1))}toBounds(p=0){const _=360*p/40075017,C=_/Math.cos(Math.PI/180*this.lat);return new H_({lng:this.lng-C,lat:this.lat-_},{lng:this.lng+C,lat:this.lat+_})}toEcef(p){return D3(this.lat,this.lng,pf+p*pf/eM)}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 H_{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 H_))return Array.isArray(p)?p.length===4||p.every(Array.isArray)?this.extend(H_.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 H_?p:new H_(p)}}function K6(N){return _Y*Math.cos(N*Math.PI/180)}function Jd(N,p){return N/K6(p)}function koe(N,p){return N*K6(qd(p))}const L=85.051129;function k(N){return Math.cos(Xr(ta(N,-85.051129,L)))}function T(N,p){const _=ta(p,0,25.5),C=Math.pow(2,_);return k(N)*_Y/(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/Dr)/(1<=Z?(oe(N,p,_,se,fe,F,xe,H,Z),oe(N,se,fe,C,M,xe,z,H,Z)):N.push(z)}function me(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 ut(N,p,_){const C=N.loadGeometry(),M=N.extent,F=Dr/M;if(p&&_&&_.projection.isReprojectedInTileSpace){const z=1<{const Te=Fx((p.x+be.x/M)/z),De=qd((p.y+be.y/M)/z),Ue=fe.project(Te,De);be.x=(Ue.x*H-Z)*M,be.y=(Ue.y*H-se)*M};for(let be=0;be=M||De.y<0||De.y>=M||(xe(De),Te.push(De));C[be]=Te}}for(const z of C)for(const H of z)Qe(H,F);return C}function bt(N,p){return{type:N.type,id:N.id,properties:N.properties,geometry:p?ut(N):[]}}const vt={Int8:Int8Array,Uint8:Uint8Array,Int16:Int16Array,Uint16:Uint16Array,Int32:Int32Array,Uint32:Uint32Array,Float32:Float32Array};class Mt{constructor(p,_){this._structArray=p,this._pos1=_*this.size,this._pos2=this._pos1/2,this._pos4=this._pos1/4,this._pos8=this._pos1/8}}const es=new ArrayBuffer(0);class Qt{constructor(){this._reallocCount=0,this.capacity=0,this.length=0}static serialize(p,_){return p._trim(),_&&p.arrayBuffer&&_.add(p.arrayBuffer),{length:p.length,arrayBuffer:p.arrayBuffer}}static deserialize(p){const _=Object.create(this.prototype);return _.arrayBuffer=p.arrayBuffer,_.length=p.length,p.arrayBuffer?_.capacity=p.arrayBuffer.byteLength/_.bytesPerElement:(_.capacity=0,_.arrayBuffer=es),_._refreshViews(),_}_trim(){this.length!==this.capacity&&(this.capacity=this.length,this.arrayBuffer=this.arrayBuffer.slice(0,this.length*this.bytesPerElement),this._refreshViews())}clear(){this.length=0}resize(p){this.reserve(p),this.length=p}resizeExact(p){this.reserveExact(p),this.length=p}reserve(p){p>this.capacity&&this._allocate(Math.max(p,Math.floor(5*this.capacity),128))}reserveExact(p){(p>this.capacity||!this.arrayBuffer)&&this._allocate(p)}_allocate(p){this._reallocCount++,this.capacity=p,this.arrayBuffer=new ArrayBuffer(this.capacity*this.bytesPerElement);const _=this.uint8;this._refreshViews(),_&&this.uint8.set(_)}reserveForAdditional(p){this.reserve(this.length+p)}_refreshViews(){throw new Error("StructArray#_refreshViews() must be implemented by each concrete StructArray layout")}emplace(...p){throw new Error("StructArray#emplace() must be implemented by each concrete StructArray layout")}emplaceBack(...p){throw new Error("StructArray#emplaceBack() must be implemented by each concrete StructArray layout")}destroy(){this.int8=this.uint8=this.int16=this.uint16=this.int32=this.uint32=this.float32=null,this.arrayBuffer=null}}function Lt(N,p=1){let _=0,C=0;return{members:N.map(M=>{const F=vt[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 Hs extends Qt{_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}}Hs.prototype.bytesPerElement=4,oa(Hs,"StructArrayLayout2i4");class Fs extends Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(p,_,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}}Fs.prototype.bytesPerElement=6,oa(Fs,"StructArrayLayout3i6");class nn extends Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(p,_,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}}nn.prototype.bytesPerElement=8,oa(nn,"StructArrayLayout2i2ui8");class $s extends Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(p){const _=this.length;return this.resize(_+1),this.emplace(_,p)}emplace(p,_){return this.float32[1*p+0]=_,p}}$s.prototype.bytesPerElement=4,oa($s,"StructArrayLayout1f4");class rn extends Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(p,_,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}}rn.prototype.bytesPerElement=8,oa(rn,"StructArrayLayout2i1f8");class _n extends Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(p,_,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}}_n.prototype.bytesPerElement=8,oa(_n,"StructArrayLayout3i8");class Mn extends Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(p,_,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}}Mn.prototype.bytesPerElement=8,oa(Mn,"StructArrayLayout4i8");class Kn extends Qt{_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}}Kn.prototype.bytesPerElement=10,oa(Kn,"StructArrayLayout5i10");class Bn extends Qt{_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 Z=this.length;return this.resize(Z+1),this.emplace(Z,p,_,C,M,F,z,H)}emplace(p,_,C,M,F,z,H,Z){const se=6*p,fe=12*p,xe=3*p;return this.int16[se+0]=_,this.int16[se+1]=C,this.uint8[fe+4]=M,this.uint8[fe+5]=F,this.uint8[fe+6]=z,this.uint8[fe+7]=H,this.float32[xe+2]=Z,p}}Bn.prototype.bytesPerElement=12,oa(Bn,"StructArrayLayout2i4ub1f12");class On extends Qt{_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}}On.prototype.bytesPerElement=12,oa(On,"StructArrayLayout3f12");class Rr extends Qt{_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,Z=3*p;return this.uint16[H+0]=_,this.uint16[H+1]=C,this.uint16[H+2]=M,this.uint16[H+3]=F,this.float32[Z+2]=z,p}}Rr.prototype.bytesPerElement=12,oa(Rr,"StructArrayLayout4ui1f12");class An extends Qt{_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}}An.prototype.bytesPerElement=8,oa(An,"StructArrayLayout4ui8");class xr extends Qt{_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 Z=6*p;return this.int16[Z+0]=_,this.int16[Z+1]=C,this.int16[Z+2]=M,this.int16[Z+3]=F,this.int16[Z+4]=z,this.int16[Z+5]=H,p}}xr.prototype.bytesPerElement=12,oa(xr,"StructArrayLayout6i12");class sa extends Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(p,_,C,M,F,z,H,Z,se,fe,xe,be){const Te=this.length;return this.resize(Te+1),this.emplace(Te,p,_,C,M,F,z,H,Z,se,fe,xe,be)}emplace(p,_,C,M,F,z,H,Z,se,fe,xe,be,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]=Z,this.uint16[De+7]=se,this.int16[De+8]=fe,this.int16[De+9]=xe,this.int16[De+10]=be,this.int16[De+11]=Te,p}}sa.prototype.bytesPerElement=24,oa(sa,"StructArrayLayout4i4ui4i24");class ka extends Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(p,_,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 Z=10*p,se=5*p;return this.int16[Z+0]=_,this.int16[Z+1]=C,this.int16[Z+2]=M,this.float32[se+2]=F,this.float32[se+3]=z,this.float32[se+4]=H,p}}ka.prototype.bytesPerElement=20,oa(ka,"StructArrayLayout3i3f20");class Hr extends Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(p,_,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}}Hr.prototype.bytesPerElement=16,oa(Hr,"StructArrayLayout4f16");class ea extends Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer)}emplaceBack(p){const _=this.length;return this.resize(_+1),this.emplace(_,p)}emplace(p,_){return this.uint32[1*p+0]=_,p}}ea.prototype.bytesPerElement=4,oa(ea,"StructArrayLayout1ul4");class si extends Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(p,_){const 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 Wr extends Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(p,_,C,M,F,z,H,Z,se,fe,xe,be,Te){const De=this.length;return this.resize(De+1),this.emplace(De,p,_,C,M,F,z,H,Z,se,fe,xe,be,Te)}emplace(p,_,C,M,F,z,H,Z,se,fe,xe,be,Te,De){const Ue=20*p,Ye=10*p;return this.int16[Ue+0]=_,this.int16[Ue+1]=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]=Z,this.float32[Ye+5]=se,this.float32[Ye+6]=fe,this.int16[Ue+14]=xe,this.uint32[Ye+8]=be,this.uint16[Ue+18]=Te,this.uint16[Ue+19]=De,p}}Wr.prototype.bytesPerElement=40,oa(Wr,"StructArrayLayout5i4f1i1ul2ui40");class Tr extends Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(p,_,C,M,F,z,H){const Z=this.length;return this.resize(Z+1),this.emplace(Z,p,_,C,M,F,z,H)}emplace(p,_,C,M,F,z,H,Z){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]=Z,p}}Tr.prototype.bytesPerElement=16,oa(Tr,"StructArrayLayout3i2i2i16");class Gr extends Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(p,_,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,Z=8*p;return this.float32[H+0]=_,this.float32[H+1]=C,this.float32[H+2]=M,this.int16[Z+6]=F,this.int16[Z+7]=z,p}}Gr.prototype.bytesPerElement=16,oa(Gr,"StructArrayLayout2f1f2i16");class Ga extends Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(p,_,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 Z=20*p,se=5*p;return this.uint8[Z+0]=_,this.uint8[Z+1]=C,this.float32[se+1]=M,this.float32[se+2]=F,this.float32[se+3]=z,this.float32[se+4]=H,p}}Ga.prototype.bytesPerElement=20,oa(Ga,"StructArrayLayout2ub4f20");class qr extends Qt{_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}}qr.prototype.bytesPerElement=6,oa(qr,"StructArrayLayout3ui6");class Za extends Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer)}emplaceBack(p,_,C,M,F,z,H,Z,se,fe,xe,be,Te,De,Ue,Ye,nt,it,ht,ot,yt){const Nt=this.length;return this.resize(Nt+1),this.emplace(Nt,p,_,C,M,F,z,H,Z,se,fe,xe,be,Te,De,Ue,Ye,nt,it,ht,ot,yt)}emplace(p,_,C,M,F,z,H,Z,se,fe,xe,be,Te,De,Ue,Ye,nt,it,ht,ot,yt,Nt){const is=30*p,At=15*p,$t=60*p;return this.int16[is+0]=_,this.int16[is+1]=C,this.int16[is+2]=M,this.float32[At+2]=F,this.float32[At+3]=z,this.uint16[is+8]=H,this.uint16[is+9]=Z,this.uint32[At+5]=se,this.uint32[At+6]=fe,this.uint32[At+7]=xe,this.uint16[is+16]=be,this.uint16[is+17]=Te,this.uint16[is+18]=De,this.float32[At+10]=Ue,this.float32[At+11]=Ye,this.uint8[$t+48]=nt,this.uint8[$t+49]=it,this.uint8[$t+50]=ht,this.uint32[At+13]=ot,this.int16[is+28]=yt,this.uint8[$t+58]=Nt,p}}Za.prototype.bytesPerElement=60,oa(Za,"StructArrayLayout3i2f2ui3ul3ui2f3ub1ul1i1ub60");class Oi extends Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer)}emplaceBack(p,_,C,M,F,z,H,Z,se,fe,xe,be,Te,De,Ue,Ye,nt,it,ht,ot,yt,Nt,is,At,$t,Jt,ns,Ps,Gs,pn,cn,jn,Vn){const Cs=this.length;return this.resize(Cs+1),this.emplace(Cs,p,_,C,M,F,z,H,Z,se,fe,xe,be,Te,De,Ue,Ye,nt,it,ht,ot,yt,Nt,is,At,$t,Jt,ns,Ps,Gs,pn,cn,jn,Vn)}emplace(p,_,C,M,F,z,H,Z,se,fe,xe,be,Te,De,Ue,Ye,nt,it,ht,ot,yt,Nt,is,At,$t,Jt,ns,Ps,Gs,pn,cn,jn,Vn,Cs){const Zs=20*p,an=40*p,Ln=80*p;return this.float32[Zs+0]=_,this.float32[Zs+1]=C,this.int16[an+4]=M,this.int16[an+5]=F,this.int16[an+6]=z,this.int16[an+7]=H,this.int16[an+8]=Z,this.int16[an+9]=se,this.int16[an+10]=fe,this.int16[an+11]=xe,this.int16[an+12]=be,this.uint16[an+13]=Te,this.uint16[an+14]=De,this.uint16[an+15]=Ue,this.uint16[an+16]=Ye,this.uint16[an+17]=nt,this.uint16[an+18]=it,this.uint16[an+19]=ht,this.uint16[an+20]=ot,this.uint16[an+21]=yt,this.uint16[an+22]=Nt,this.uint16[an+23]=is,this.uint16[an+24]=At,this.uint16[an+25]=$t,this.uint16[an+26]=Jt,this.uint16[an+27]=ns,this.uint32[Zs+14]=Ps,this.float32[Zs+15]=Gs,this.float32[Zs+16]=pn,this.float32[Zs+17]=cn,this.float32[Zs+18]=jn,this.uint8[Ln+76]=Vn,this.uint16[an+39]=Cs,p}}Oi.prototype.bytesPerElement=80,oa(Oi,"StructArrayLayout2f9i15ui1ul4f1ub1ui80");class Do extends Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(p,_,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 Z=6*p;return this.float32[Z+0]=_,this.float32[Z+1]=C,this.float32[Z+2]=M,this.float32[Z+3]=F,this.float32[Z+4]=z,this.float32[Z+5]=H,p}}Do.prototype.bytesPerElement=24,oa(Do,"StructArrayLayout6f24");class so extends Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(p,_,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}}so.prototype.bytesPerElement=20,oa(so,"StructArrayLayout5f20");class ql extends Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(p,_,C,M,F,z,H){const Z=this.length;return this.resize(Z+1),this.emplace(Z,p,_,C,M,F,z,H)}emplace(p,_,C,M,F,z,H,Z){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]=Z,p}}ql.prototype.bytesPerElement=28,oa(ql,"StructArrayLayout7f28");class vu extends Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(p,_,C,M,F,z,H,Z,se,fe,xe){const be=this.length;return this.resize(be+1),this.emplace(be,p,_,C,M,F,z,H,Z,se,fe,xe)}emplace(p,_,C,M,F,z,H,Z,se,fe,xe,be){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]=Z,this.float32[Te+7]=se,this.float32[Te+8]=fe,this.float32[Te+9]=xe,this.float32[Te+10]=be,p}}vu.prototype.bytesPerElement=44,oa(vu,"StructArrayLayout11f44");class Uc extends Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(p,_,C,M,F,z,H,Z,se){const fe=this.length;return this.resize(fe+1),this.emplace(fe,p,_,C,M,F,z,H,Z,se)}emplace(p,_,C,M,F,z,H,Z,se,fe){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]=Z,this.float32[xe+7]=se,this.float32[xe+8]=fe,p}}Uc.prototype.bytesPerElement=36,oa(Uc,"StructArrayLayout9f36");class Ko extends Qt{_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 no extends Qt{_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}}no.prototype.bytesPerElement=12,oa(no,"StructArrayLayout1ul3ui12");class _d extends Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(p){const _=this.length;return this.resize(_+1),this.emplace(_,p)}emplace(p,_){return this.uint16[1*p+0]=_,p}}_d.prototype.bytesPerElement=2,oa(_d,"StructArrayLayout1ui2");class Gh extends Qt{_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 Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(p,_,C,M,F,z,H,Z,se,fe,xe,be,Te,De,Ue,Ye){const nt=this.length;return this.resize(nt+1),this.emplace(nt,p,_,C,M,F,z,H,Z,se,fe,xe,be,Te,De,Ue,Ye)}emplace(p,_,C,M,F,z,H,Z,se,fe,xe,be,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]=Z,this.float32[it+7]=se,this.float32[it+8]=fe,this.float32[it+9]=xe,this.float32[it+10]=be,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 Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(p){const _=this.length;return this.resize(_+1),this.emplace(_,p)}emplace(p,_){return this.int16[1*p+0]=_,p}}Vl.prototype.bytesPerElement=2,oa(Vl,"StructArrayLayout1i2");class mm extends Qt{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer)}emplaceBack(p){const _=this.length;return this.resize(_+1),this.emplace(_,p)}emplace(p,_){return this.uint8[1*p+0]=_,p}}mm.prototype.bytesPerElement=1,oa(mm,"StructArrayLayout1ub1");class bc extends Mt{get projectedAnchorX(){return this._structArray.int16[this._pos2+0]}get projectedAnchorY(){return this._structArray.int16[this._pos2+1]}get projectedAnchorZ(){return this._structArray.int16[this._pos2+2]}get tileAnchorX(){return this._structArray.int16[this._pos2+3]}get tileAnchorY(){return this._structArray.int16[this._pos2+4]}get x1(){return this._structArray.float32[this._pos4+3]}get y1(){return this._structArray.float32[this._pos4+4]}get x2(){return this._structArray.float32[this._pos4+5]}get y2(){return this._structArray.float32[this._pos4+6]}get padding(){return this._structArray.int16[this._pos2+14]}get featureIndex(){return this._structArray.uint32[this._pos4+8]}get sourceLayerIndex(){return this._structArray.uint16[this._pos2+18]}get bucketIndex(){return this._structArray.uint16[this._pos2+19]}}bc.prototype.size=40;class dc extends Wr{get(p){return new bc(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 Za{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 _c extends Oi{get(p){return new Pd(this,p)}}oa(_c,"SymbolInstanceArray");class Kh extends $s{getoffsetX(p){return this.float32[1*p+0]}}oa(Kh,"GlyphOffsetArray");class ug extends Hs{getx(p){return this.int16[2*p+0]}gety(p){return this.int16[2*p+1]}}oa(ug,"SymbolLineVertexArray");class G_ 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]}}G_.prototype.size=12;class e0 extends no{get(p){return new G_(this,p)}}oa(e0,"FeatureIndexArray");class rj extends si{geta_centroid_pos0(p){return this.uint16[2*p+0]}geta_centroid_pos1(p){return this.uint16[2*p+1]}}oa(rj,"FillExtrusionCentroidArray");class bu 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]}}bu.prototype.size=6;class id extends Fs{get(p){return new bu(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),ix=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=ta(Math.floor(N),0,255))+ta(Math.floor(p),0,255)}Li.MAX_VERTEX_ARRAY_LENGTH=Math.pow(2,16)-1,oa(Li,"SegmentVector");const hg=Lt([{name:"a_pattern",components:4,type:"Uint16"},{name:"a_pixel_ratio",components:1,type:"Float32"}]),aj=Lt([{name:"a_pattern_b",components:4,type:"Uint16"}]),ij=Lt([{name:"a_dash",components:4,type:"Uint16"}]);class zb{constructor(){this.ids=[],this.uniqueIds=[],this.positions=[],this.indexed=!1}add(p,_,C,M){this.ids.push(Bb(p)),this.positions.push(_,C,M)}eachPosition(p,_){const C=Bb(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 X2(C,M,0,C.length-1),_&&(_.add(C.buffer),_.add(M.buffer)),{ids:C,positions:M}}static deserialize(p){const _=new zb;let C;_.ids=p.ids,_.positions=p.positions;for(const M of _.ids)M!==C&&_.uniqueIds.push(M),C=M;return _.indexed=!0,_}}function Bb(N){const p=+N;return Number.isSafeInteger(p)?p:dd(String(N))}function X2(N,p,_,C){for(;_>1];let F=_-1,z=C+1;for(;;){do F++;while(N[F]M);if(F>=z)break;$b(N,F,z),$b(p,3*F,3*z),$b(p,3*F+1,3*z+1),$b(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 Y6(p):new co(p)}}class jY{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 wY(p):new co(p)}}class F3{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,Z){const se=this.paintVertexArray.length,fe=this.expression.kind==="composite"||this.expression.kind==="source"?this.expression.evaluate(new Wn(0,{brightness:z,worldview:Z}),_,{},F,M,H):this.expression.kind==="constant"&&this.expression.value,xe=D9(this.lutExpression,_,{},M,F,z,H,Z);this.paintVertexArray.resize(p),this._setPaintValue(se,p,fe,xe?null:this.context.lut)}updatePaintArray(p,_,C,M,F,z,H,Z){const se=this.expression.kind==="composite"||this.expression.kind==="source"?this.expression.evaluate({zoom:0,brightness:H,worldview:Z},C,M,void 0,F):this.expression.kind==="constant"&&this.expression.value,fe=D9(this.lutExpression,C,M,F,void 0,H,void 0,Z);this._setPaintValue(p,_,se,fe?null:this.context.lut)}_setPaintValue(p,_,C,M){if(this.type==="color"){const F=R9(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 qC{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,Z){const se=this.expression.evaluate(new Wn(this.context.zoom,{brightness:z,worldview:Z}),_,{},F,M,H),fe=this.expression.evaluate(new Wn(this.context.zoom+1,{brightness:z,worldview:Z}),_,{},F,M,H),xe=D9(this.lutExpression,_,{},M,F,z,H,Z),be=this.paintVertexArray.length;this.paintVertexArray.resize(p),this._setPaintValue(be,p,se,fe,xe?null:this.context.lut)}updatePaintArray(p,_,C,M,F,z,H,Z){const se=this.expression.evaluate({zoom:this.context.zoom,brightness:H,worldview:Z},C,M,void 0,F),fe=this.expression.evaluate({zoom:this.context.zoom+1,brightness:H,worldview:Z},C,M,void 0,F),xe=D9(this.lutExpression,C,M,F,void 0,H,void 0,Z);this._setPaintValue(p,_,se,fe,xe?null:this.context.lut)}_setPaintValue(p,_,C,M,F){if(this.type==="color"){const z=R9(C.toPremultipliedRenderColor(F)),H=R9(M.toPremultipliedRenderColor(F));for(let Z=p;Z<_;Z++)this.paintVertexArray.emplace(Z,z[0],z[1],H[0],H[1])}else{for(let z=p;z<_;z++)this.paintVertexArray.emplace(z,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=ta(this.expression.interpolationFactor(z,this.context.zoom,this.context.zoom+1),0,1);_.set(p,F,H)}getBinding(p,_){return new co(p)}}class VC{constructor(p,_,C,M,F){this.expression=p,this.layerId=F,this.paintVertexAttributes=(C==="array"?ij:hg).members;for(let z=0;z<_.length;++z);this.paintVertexArray=new M,this.paintTransitionVertexArray=new An}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:Z,pixelRatio:se}=F;for(let fe=p;fe<_;fe++)this.paintVertexArray.emplace(fe,H[0],H[1],Z[0],Z[1],se)}if(z){this.paintTransitionVertexArray.resize(this.paintVertexArray.length);const{tl:H,br:Z}=z;for(let se=p;se<_;se++)this.paintTransitionVertexArray.emplace(se,H[0],H[1],Z[0],Z[1])}}}upload(p){const _=this.expression.isStateDependent||!this.expression.isLightConstant;this.paintVertexArray&&this.paintVertexArray.arrayBuffer&&(this.paintVertexBuffer=p.createVertexBuffer(this.paintVertexArray,this.paintVertexAttributes,_)),this.paintTransitionVertexArray&&this.paintTransitionVertexArray.length&&(this.paintTransitionVertexBuffer=p.createVertexBuffer(this.paintTransitionVertexArray,aj.members,_))}destroy(){this.paintVertexBuffer&&this.paintVertexBuffer.destroy(),this.paintTransitionVertexBuffer&&this.paintTransitionVertexBuffer.destroy()}}class X6{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&&Zy(H.property.specification)))continue;const Z=$us(z,p.type),se=H.value,fe=H.property.specification.type,xe=!!H.property.useIntegerZoom,be=z==="line-dasharray"||z.endsWith("pattern"),Te=F.paint.get(`${z}-use-theme`),De=z==="line-dasharray"&&F.layout.get("line-cap").value.kind!=="constant"||Te&&Te.value.kind!=="constant";if(se.kind!=="constant"||De)if(se.kind==="source"||De||be){const Ue=tdt(z,fe,"source");this.binders[z]=be?new VC(se,Z,fe,Ue,p.id):new F3(se,Z,fe,Ue),M.push(`/a_${z}`)}else{const Ue=tdt(z,fe,"composite");this.binders[z]=new qC(se,Z,fe,xe,_,Ue),M.push(`/z_${z}`)}else this.binders[z]=be?new jY(se.value,Z):new Soe(se.value,Z,fe,_),M.push(`/u_${z}`);Te&&(this.binders[z].lutExpression=Te.value)}this.cacheKey=M.sort().join("")}updateExpressions(p){const _=p;for(const C in this.binders){const M=this.binders[C];if(M instanceof F3||M instanceof qC||M instanceof VC){const F=_.paint.get(C);M.expression=F.value}}}getMaxValue(p){const _=this.binders[p];return _ instanceof F3||_ instanceof qC?_.maxValue:0}populatePaintArrays(p,_,C,M,F,z,H,Z){for(const se in this.binders){const fe=this.binders[se];fe.context=this.context,(fe instanceof F3||fe instanceof qC||fe instanceof VC)&&fe.populatePaintArray(p,_,C,M,F,z,H,Z)}}setConstantPatternPositions(p,_){for(const C in this.binders){const M=this.binders[C];M instanceof jY&&M.setConstantPatternPositions(p,_)}}getPatternTransitionVertexBuffer(p){const _=this.binders[p];return _ instanceof VC?_.paintTransitionVertexBuffer:null}updatePaintArrays(p,_,C,M,F,z,H,Z,se,fe){let xe=!1;const be=Object.keys(p),Te=be.length!==0&&!Z,De=Te?be:_.uniqueIds;this.context.lut=F.lut;for(const Ue in this.binders){const Ye=this.binders[Ue];if(Ye.context=this.context,(Ye instanceof F3||Ye instanceof qC||Ye instanceof VC)&&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 ht=p[it.toString()];_.eachPosition(it,(ot,yt,Nt)=>{const is=M.feature(ot);Ye.updatePaintArray(yt,Nt,is,ht,z,H,se,fe)})}if(!Te)for(const it of C.uniqueIds){const ht=p[it.toString()];C.eachPosition(it,(ot,yt,Nt)=>{const is=M.feature(ot);Ye.updatePaintArray(yt,Nt,is,ht,z,H,se,fe)})}xe=!0}}return xe}defines(){const p=[];for(const _ in this.binders){const C=this.binders[_];(C instanceof Soe||C instanceof jY)&&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 Soe||M instanceof jY||M instanceof qC)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:Z}of C)this.binders[H].setUniform(p,Z,F,M.get(H),z)}updatePaintBuffers(){this._buffers=[];for(const p in this.binders){const _=this.binders[p];(_ instanceof F3||_ instanceof qC||_ instanceof VC)&&_.paintVertexBuffer&&this._buffers.push(_.paintVertexBuffer),_ instanceof VC&&_.paintTransitionVertexBuffer&&this._buffers.push(_.paintTransitionVertexBuffer)}}upload(p){for(const _ in this.binders){const C=this.binders[_];(C instanceof F3||C instanceof qC||C instanceof VC)&&C.upload(p)}this.updatePaintBuffers()}destroy(){for(const p in this.binders){const _=this.binders[p];(_ instanceof F3||_ instanceof qC||_ instanceof VC)&&_.destroy()}}}class Gk{constructor(p,_,C=()=>!0){this.programConfigurations={};for(const M of p)this.programConfigurations[M.id]=new X6(M,_,C);this.needsUpload=!1,this._featureMap=new zb,this._featureMapWithoutIds=new zb,this._bufferOffset=0,this._idlessCounter=0}populatePaintArrays(p,_,C,M,F,z,H,Z,se){for(const fe in this.programConfigurations)this.programConfigurations[fe].populatePaintArrays(p,_,M,F,z,H,Z,se);_.id!==void 0?this._featureMap.add(_.id,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,Z){for(const se of C)this.needsUpload=this.programConfigurations[se.id].updatePaintArrays(p,this._featureMap,this._featureMapWithoutIds,_,se,M,F,z,H||0,Z)||this.needsUpload}get(p){return this.programConfigurations[p]}upload(p){if(this.needsUpload){for(const _ in this.programConfigurations)this.programConfigurations[_].upload(p);this.needsUpload=!1}}destroy(){for(const p in this.programConfigurations)this.programConfigurations[p].destroy()}updateExpressions(p){const _=new Set;for(const 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 Bus={"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 $us(N,p){return Bus[N]||[N.replace(`${p}-`,"").replace(/-/g,"_")]}const Uus={"line-pattern":{source:Rr,composite:Rr},"fill-pattern":{source:Rr,composite:Rr},"fill-extrusion-pattern":{source:Rr,composite:Rr},"line-dasharray":{source:An,composite:An}},qus={color:{source:Ko,composite:Hr},number:{source:$s,composite:Ko}};function tdt(N,p,_){const C=Uus[N];return C&&C[_]||qus[p][_]}oa(Soe,"ConstantBinder"),oa(jY,"PatternConstantBinder"),oa(F3,"SourceExpressionBinder",{omit:["expression"]}),oa(VC,"PatternCompositeBinder",{omit:["expression"]}),oa(qC,"CompositeExpressionBinder",{omit:["expression"]}),oa(X6,"ProgramConfiguration",{omit:["_buffers"]}),oa(Gk,"ProgramConfigurationSet");class BFe{constructor(p,_,C){this.layoutVertexArray=new Hs,this.indexArray=new qr,this.lineIndexArray=new si,this.triangleSegments=new Li,this.lineSegments=new Li,this.programConfigurations=new Gk(p,{zoom:_,lut:C}),this.uploaded=!1}update(p,_,C,M,F,z,H,Z){this.programConfigurations.updatePaintArrays(p,_,F,C,M,z,H,Z)}isEmpty(){return this.layoutVertexArray.length===0}needsUpload(){return this.programConfigurations.needsUpload}upload(p){this.uploaded||(this.layoutVertexBuffer=p.createVertexBuffer(this.layoutVertexArray,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(BFe,"FillBufferData");class $Fe{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 BFe(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=W6("fill",this.layers,this.pixelRatio,_);const F=this.layers[0].layout.get("fill-sort-key"),z=[];for(const{feature:H,id:Z,index:se,sourceLayerIndex:fe}of p){const xe=this.layers[0]._featureFilter.needGeometry,be=bt(H,xe);if(!this.layers[0]._featureFilter.filter(new Wn(this.zoom,{worldview:this.worldview,activeFloors:_.activeFloors}),be,C))continue;const Te=F?F.evaluate(be,{},C,_.availableImages):void 0,De={id:Z,properties:H.properties,type:H.type,sourceLayerIndex:fe,index:se,geometry:xe?be.geometry:ut(H,C,M),patterns:{},sortKey:Te};z.push(De)}F&&z.sort((H,Z)=>H.sortKey-Z.sortKey);for(const H of z){const{geometry:Z,index:se,sourceLayerIndex:fe}=H;if(this.hasPattern){const xe=vY("fill",this.layers,H,this.zoom,this.pixelRatio,_);this.patternFeatures.push(xe)}else this.addFeature(H,Z,se,C,{},_.availableImages,_.brightness,_.elevationFeatures);_.featureIndex.insert(p[se].feature,Z,se,fe,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,Z){const se=this.hdExt?this.hdExt.trackFeatureFrc(p.properties):null,fe=this.bufferData.indexArray.length,xe=Pa(_,500);this.hdExt!=null&&this.hdExt.handleFeature(p,xe,C,M,Z,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,fe,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 Z=C?_:null,se=(fe,xe,be)=>{if(C!=null)if(xe.push(fe),H!=null)Z.elevatedLayoutVertexArray.emplaceBack(H),be.push(H);else{const Te=C.elevationSampler.pointElevation(fe,C.elevation,C.bias);Z.elevatedLayoutVertexArray.emplaceBack(Te),be.push(Te),F=Math.min(F,Te),z=Math.max(z,Te)}};for(const fe of p){let xe=0;for(const yt of fe)xe+=yt.length;const be=_.triangleSegments.prepareSegment(xe,_.layoutVertexArray,_.indexArray),Te=be.vertexLength,De=[],Ue=[],Ye=[],nt=[],it=[],ht=_.layoutVertexArray.length;for(const yt of fe){if(yt.length===0)continue;yt!==fe[0]&&Ue.push(De.length/2);const Nt=_.lineSegments.prepareSegment(yt.length,_.layoutVertexArray,_.lineIndexArray),is=Nt.vertexLength;C&&it.push(_.layoutVertexArray.length-ht),se(yt[0],Ye,nt),_.layoutVertexArray.emplaceBack(yt[0].x,yt[0].y),_.lineIndexArray.emplaceBack(is+yt.length-1,is),De.push(yt[0].x),De.push(yt[0].y);for(let At=1;At0&&C&&M){const yt=C.elevation.isTunnel(),Nt=C.elevation.safeArea,is=M.addVertices(Ye,nt);M.addTriangles(ot,is,yt);const At=it.length;if(At>0){for(let $t=0;$t>3,z===0)continue}if(z--,F===1)H+=p.readSVarint(),Z+=p.readSVarint(),M&&C.push(M),M=[new xs(H,Z)];else if(F===2)H+=p.readSVarint(),Z+=p.readSVarint(),M&&M.push(new xs(H,Z));else{if(F!==7)throw new Error(`unknown command ${F}`);M&&M.push(M[0].clone())}}return M&&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,Z=-1/0,se=1/0,fe=-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(),FZ&&(Z=F),zfe&&(fe=z);else if(C!==7)throw new Error(`unknown command ${C}`)}return[H,se,Z,fe]}toGeoJSON(p,_,C){const M=this.extent*Math.pow(2,C),F=this.extent*p,z=this.extent*_,H=this.loadGeometry();function Z(be){return[360*(be.x+F)/M-180,360/Math.PI*Math.atan(Math.exp((1-2*(be.y+z)/M)*Math.PI))-90]}function se(be){return be.map(Z)}let fe;if(this.type===1){const be=[];for(const De of H)be.push(De[0]);const Te=se(be);fe=be.length===1?{type:"Point",coordinates:Te[0]}:{type:"MultiPoint",coordinates:Te}}else if(this.type===2){const be=H.map(se);fe=be.length===1?{type:"LineString",coordinates:be[0]}:{type:"MultiLineString",coordinates:be}}else{if(this.type!==3)throw new Error("unknown feature type");{const be=function(De){const Ue=De.length;if(Ue<=1)return[De];const Ye=[];let nt,it;for(let ht=0;ht=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 tM(this._pbf,_,this.extent,this._keys,this._values)}}function ths(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 UFe{constructor(p,_=p.length){const C=Object.create(null);for(;p.pos<_;){const M=p.readVarint();if(M===26){const F=new ehs(p,p.readVarint()+p.pos);F.length&&(C[F.name]=F)}else p.skip(M)}this.layers=C}}function qFe(N,p){for(let _=0;_1){if(HFe(N,p))return!0;for(let C=0;C1?_:_.sub(p)._mult(M)._add(p))}function ndt(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 sM(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 KFe(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(sM(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 O9(N,p,_,C,M,F){let z=p.y-N.y,H=N.x-p.x;if(F=F||0){const Z=z*z+H*H;if(Z===0)return!0;const se=Math.sqrt(Z);z/=se,H/=se}return!((_.x-N.x)*z+(_.y-N.y)*H-F<0||(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 YFe(N,p,_,C,M,F,z){return!(O9(N,p,C,M,F,z)||O9(p,_,C,M,F,z)||O9(_,N,C,M,F,z)||O9(C,M,N,p,_,z)||O9(M,F,N,p,_,z)||O9(F,C,N,p,_,z))}class Q6 extends xs{constructor(p,_,C){super(p,_),this.z=C}}class rdt extends Q6{constructor(p,_,C,M){super(p,_,C),this.w=M}}function adt(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 idt(N,p,_,C){const M=_,F=C;for(const z of["x","y"]){let H=N,Z=p;H[z]>=Z[z]&&(H=p,Z=N),H[z]M&&adt(H,Z,z,M),H[z]F&&adt(Z,H,z,F)}}function ZFe(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+odt(nt,it,Te)*Ue,max:1},parentIndex:H,prevPoint:nt,nextPoint:it})),se.push(De),F&&(F.at(-1).progress.max=Ye+odt(nt,it,De)*Ue,F.at(-1).nextPoint=it)))))}if(F&&xe>0)for(let be=fe;bese.t-fe.t);let z=0,H=0,Z=[];for(C.push(Z);z!==N.length;){if(H===F.length){for(;z!==N.length;)Z.length!==0&&Z.at(-1).equals(N[z])||Z.push(N[z]),z++;break}F[H].t<=z?(Z.length!==0&&Z.at(-1).equals(F[H].point)||Z.push(F[H].point),Math.trunc(F[H].t),H++):(Z.length!==0&&Z.at(-1).equals(N[z])||Z.push(N[z]),z++)}}function odt(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 ldt(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 cdt(N,p,_){const{width:C,height:M}=p;C===N.width&&M===N.height||(XFe(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 XFe(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 Z=N.data,se=p.data,fe=F===4&&H;for(let xe=0;xe1&&(Z=p[++H]);const fe=Math.abs(se-Z.left),xe=Math.abs(se-Z.right),be=Math.min(fe,xe);let Te;const De=F/C*(M+1);if(Z.isDash){const Ue=M-Math.abs(De);Te=Math.sqrt(be*be+Ue*Ue)}else Te=M-Math.sqrt(be*be+De*De);this.image.data[z+se]=Math.max(0,Math.min(255,Te+128))}}}addRegularDash(p,_){for(let Z=p.length-1;Z>=0;--Z){const se=p[Z],fe=p[Z+1];se.zeroLength?p.splice(Z,1):fe&&fe.isDash===se.isDash&&(fe.left=se.left,p.splice(Z,1))}const 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 Z=0;Z1&&(H=p[++z]);const se=Math.abs(Z-H.left),fe=Math.abs(Z-H.right),xe=Math.min(se,fe);this.image.data[F+Z]=Math.max(0,Math.min(255,(H.isDash?xe:-xe)+_+128))}}addDash(p,_){const 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 fe=Math.round(se/this.width*4095);this.nextRow+=z;const xe=Math.floor(H),be={tl:[Z,F|fe<<4],br:[xe,Math.round(65535*(H-xe))]};return this.positions[C]=be,be}}oa(udt,"LineAtlas");const O3="3d_elevation_id",hdt="level",ohs=tM.types,lhs=Math.cos(Math.PI/180*37.5),chs=Math.cos(Math.PI/180*5);class QFe{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 Bn,this.layoutVertexArray2=new On,this.patternVertexArray=new On,this.indexArray=new qr,this.programConfigurations=new Gk(p.layers,{zoom:p.zoom,lut:p.lut}),this.segments=new Li,this.sourceLayerName=p.sourceLayerName||"",this.maxLineLength=0,this.zOffsetVertexArray=new Hr,this.elevationIdColVertexArray=new On,this.elevationGroundScaleVertexArray=new $s,this.stateDependentLayerIds=this.layers.filter(_=>_.isStateDependent()).map(_=>_.id),this.tessellationStep=p.tessellationStep?p.tessellationStep:128,this.worldview=p.worldview,this.hasAppearances=null}updateFootprints(p,_){}updateAppearances(p,_,C,M){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(p,_,C,M){this.showElevationIdDebug=_.showElevationIdDebug,this.terrainEnabled=_.terrainEnabled,this.hasPattern=W6("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 be=this.layers[0].layout.get("line-z-offset"),Te=be.isConstant()&&!be.constantOr(0);this.elevationType=z!=="sea"&&z!=="ground"&&Te?"none":"offset",this.elevationType==="offset"&&z==="none"&&Yo(`line-elevation-reference: ground is used for the layer ${this.layerIds[0]} because non-zero line-z-offset value was found.`),this.isSeaLevelReference=z==="sea"}const H=this.layers[0].layout.get("line-cross-slope");this.hasCrossSlope=this.elevationType==="offset"&&H!==void 0;const Z=[];for(const{feature:be,id:Te,index:De,sourceLayerIndex:Ue}of p){const Ye=this.layers[0]._featureFilter.needGeometry,nt=bt(be,Ye);if(!this.layers[0]._featureFilter.filter(new Wn(this.zoom,{worldview:this.worldview,activeFloors:_.activeFloors}),nt,C))continue;const it=F?F.evaluate(nt,{},C):void 0,ht={id:Te,properties:be.properties,type:be.type,sourceLayerIndex:Ue,index:De,geometry:Ye?nt.geometry:ut(be,C,M),patterns:{},sortKey:it};Z.push(ht)}F&&Z.sort((be,Te)=>be.sortKey-Te.sortKey);const{lineAtlas:se,featureIndex:fe}=_,xe=this.addConstantDashes(se);for(const be of Z){const{geometry:Te,index:De,sourceLayerIndex:Ue}=be;if(xe&&this.addFeatureDashes(be,se),this.hasPattern){const Ye=vY("line",this.layers,be,this.zoom,this.pixelRatio,_);this.patternFeatures.push(Ye)}else this.addFeature(be,Te,De,C,se.positions,_.availableImages,_.brightness,_.elevationFeatures,_.elevationParams,_.crossSourceElevationEnabled);fe.insert(p[De].feature,Te,De,Ue,this.index)}!this.hasPattern&&this.hdExt&&this.hdExt.buildFrcSegments(this),this.hdExt&&this.hdExt.endPopulate()}addConstantDashes(p){let _=!1;for(const 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,Z;if(F.kind==="constant"){if(H=F.value,!H)continue}else H=F.evaluate({zoom:C},p);Z=z.kind==="constant"?z.value:z.evaluate({zoom:C},p),_.addDash(H,Z),p.patterns[M.id]=[_.getKey(H,Z)]}}update(p,_,C,M,F,z,H,Z,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,Zus)),this.patternVertexArray.length!==0&&(this.patternVertexBuffer=p.createVertexBuffer(this.patternVertexArray,Qus)),!this.zOffsetVertexBuffer&&this.zOffsetVertexArray.length>0&&(this.zOffsetVertexBuffer=p.createVertexBuffer(this.zOffsetVertexArray,Hus.members,!0)),!this.elevationIdColVertexBuffer&&this.elevationIdColVertexArray.length>0&&(this.elevationIdColVertexBuffer=p.createVertexBuffer(this.elevationIdColVertexArray,Gus.members,!0)),!this.elevationGroundScaleVertexBuffer&&this.elevationGroundScaleVertexArray.length>0&&(this.elevationGroundScaleVertexBuffer=p.createVertexBuffer(this.elevationGroundScaleVertexArray,Wus.members,!0)),this.layoutVertexBuffer=p.createVertexBuffer(this.layoutVertexArray,Kus),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,Z,se,fe){const xe=this.layers[0].layout,be=this.hdExt?this.hdExt.trackFeatureFrc(p.properties):null,Te=this.indexArray.length,De=xe.get("line-join").evaluate(p,{}),Ue=xe.get("line-cap").evaluate(p,{}),Ye=xe.get("line-miter-limit"),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 ht=this.layers[0].paint,ot=ht.get("line-width").value;ot.kind!=="constant"&&ot.isLineProgressConstant===!1&&(this.variableWidthValue=ot);const yt=ht.get("line-emissive-strength").value;if(yt.kind!=="constant"&&yt.isLineProgressConstant===!1&&(this.variableEmissiveStrengthValue=yt),this.isSeaLevelReference){const Nt=xe.get("line-elevation-ground-scale").value;Nt.kind==="constant"&&Nt.value===0||(this.elevationGroundScaleValue=Nt)}if(this.hdExt==null||!this.hdExt.handleFeature(p,_,M,Z,se,!!fe,De,Ue,Ye,nt,this))for(let Nt=0;Nt<_.length;Nt++)this.addLine(_[Nt],p,M,De,Ue,Ye,nt,void 0,it&&Nt>0?Nt: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,be)}fillNonElevatedRoadSegment(p){for(let _=Math.max(p,this.zOffsetVertexArray.length);_0,be=Z&&Z.progress.max<1;if(this.lineClips){let $t={min:this.lineClips.start,max:this.lineClips.end},Jt=1;if(Z){const Gs=this.lineClips.end-this.lineClips.start;$t=function(pn,cn,jn){return{min:Zo(pn.min,cn,jn),max:Zo(pn.max,cn,jn)}}(Z.progress,{min:0,max:1},$t),Gs>0&&(Jt=($t.max-$t.min)/Gs)}const ns=+_.properties.mapbox_clip_feature_len,Ps=+_.properties.mapbox_clip_seg_len;if(Number.isNaN(ns)||Number.isNaN(Ps)){for(let pn=0;pn=2&&p[De-1].equals(p[De-2]);)De--;let Ue=0;for(;Ue0,Zs=this.overscaling<=16?122880/(512*this.overscaling):0;if(Jt&&ns==="round"){if(cnz&&(ns="bevel"),ns==="bevel"&&(cn>2&&(ns="flipbevel"),cn2*Zs){const In=nt.sub(nt.sub(it)._mult(Zs/an)._round());this.updateDistance(it,In),this.addCurrentVertex(In,ot,0,0,Ye,At),it=In}this.updateDistance(it,nt),Gs._mult(cn),this.addCurrentVertex(nt,Gs,0,0,Ye,At);const Ln=nt.dist(ht);if(Ln>2*Zs){const In=nt.add(ht.sub(nt)._mult(Zs/Ln)._round());this.updateDistance(nt,In),this.addCurrentVertex(In,yt,0,0,Ye,At),nt=In}}else Gs._mult(cn),this.addCurrentVertex(nt,Gs,0,0,Ye,At);else if(ns==="flipbevel"){if(cn>100)Gs=yt.mult(-1);else{const an=cn*ot.add(yt).mag()/ot.sub(yt).mag();Gs._perp()._mult(an*(Cs?-1:1))}this.addCurrentVertex(nt,Gs,0,0,Ye,At),this.addCurrentVertex(nt,Gs.mult(-1),0,0,Ye,At)}else if(ns==="bevel"||ns==="fakeround"){const an=nt.dist(it);let Ln=1;if(this.elevationType==="offset"&&ns==="bevel"&&this.currentLineJoinType!=="round"&&!this.patternJoinNone&&At!=null&&it&&ht){const lr=4*Zs;an1){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,ht=_.x-p.x,ot=_.y-p.y,yt=Math.sqrt(ht*ht+ot*ot);if(yt===0)return;const Nt=-ot/yt,is=ht/yt,At=Nt,$t=is,Jt=-Nt,ns=-is;for(let Ps=1;Ps=0&&this.e2>=0&&(this.indexArray.emplaceBack(this.e1,this.e2,fe),Z.primitiveLength++),z?this.e2=fe:this.e1=fe,se!=null&&(this.zOffsetVertexArray.emplaceBack(se.zOffset,se.variableWidth,se.variableWidth,se.variableEmissiveStrength),this.showElevationIdDebug&&this.elevationIdColVertexArray.emplaceBack(0,0,0)),this.elevationGroundScaleValue){const xe=se?se.elevationGroundScale:this.evaluateElevationGroundScale();this.elevationGroundScaleVertexArray.emplaceBack(xe)}}updateScaledDistance(){this.lineClips?(this.scaledDistance=this.distance/this.totalDistance,this.lineSoFar=this.totalFeatureLength*this.lineClips.start+this.distance):this.lineSoFar=this.distance}updateDistance(p,_){this.prevDistance=this.distance,this.distance+=p.dist(_),this.updateScaledDistance()}}function JFe(N,p,_){return N.x_||N.y_}oa(QFe,"LineBucket",{omit:["layers","patternFeatures","currentVertex","currentVertexIsOutside"]});const dhs=Lt([{name:"a_pos",components:2,type:"Int16"}],4),uhs=Lt([{name:"a_circle_z_offset",components:1,type:"Float32"}],4),hhs=Lt([{name:"a_pos_3",components:3,type:"Int16"},{name:"a_pos_normal_3",components:3,type:"Int16"}]);class Coe{constructor(p){this.zoom=p.zoom,this.overscaling=p.overscaling,this.layers=p.layers,this.layerIds=this.layers.map(_=>_.fqid),this.index=p.index,this.hasPattern=!1,this.projection=p.projection,this.layoutVertexArray=new Hs,this.indexArray=new qr,this.segments=new Li,this.programConfigurations=new Gk(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:fe,index:xe,sourceLayerIndex:be}of p){const Te=this.layers[0]._featureFilter.needGeometry,De=bt(se,Te);if(!this.layers[0]._featureFilter.filter(new Wn(this.zoom,{worldview:this.worldview,activeFloors:_.activeFloors}),De,C))continue;const Ue=H?H.evaluate(De,{},C):void 0,Ye={id:fe,properties:se.properties,type:se.type,sourceLayerIndex:be,index:xe,geometry:Te?De.geometry:ut(se,C,M),patterns:{},sortKey:Ue};z.push(Ye)}H&&z.sort((se,fe)=>se.sortKey-fe.sortKey);let Z=null;M.projection.name==="globe"&&(this.globeExtVertexArray=new xr,Z=M.projection);for(const se of z){const{geometry:fe,index:xe,sourceLayerIndex:be}=se,Te=p[xe].feature;this.addFeature(se,fe,xe,_.availableImages,C,Z,_.brightness,_.elevationFeatures),_.featureIndex.insert(Te,fe,xe,be,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,dhs.members),this.indexBuffer=p.createIndexBuffer(this.indexArray),this.globeExtVertexArray&&(this.globeExtVertexBuffer=p.createVertexBuffer(this.globeExtVertexArray,hhs.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,Z){this.hdExt&&this.hdExt.beginFeature(p,Z,F);for(const se of _)for(const fe of se){const xe=fe.x,be=fe.y;if(xe<0||xe>=Dr||be<0||be>=Dr)continue;if(z){const Ue=z.projectTilePoint(xe,be,F),Ye=z.upVector(F,xe,be);this.addGlobeExtVertex(Ue,Ye),this.addGlobeExtVertex(Ue,Ye),this.addGlobeExtVertex(Ue,Ye),this.addGlobeExtVertex(Ue,Ye)}const Te=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray,p.sortKey),De=Te.vertexLength;this.addCircleVertex(xe,be,-1,-1),this.addCircleVertex(xe,be,1,-1),this.addCircleVertex(xe,be,1,1),this.addCircleVertex(xe,be,-1,1),this.hdExt&&this.hdExt.writeVertexQuad(xe,be),this.indexArray.emplaceBack(De,De+1,De+2),this.indexArray.emplaceBack(De,De+2,De+3),Te.vertexLength+=4,Te.primitiveLength+=2}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,p,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(Coe,"CircleBucket",{omit:["layers"]});const mhs=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),fhs=Lt([{name:"a_globe_anchor",components:3,type:"Int16"},{name:"a_globe_normal",components:3,type:"Float32"}],4),phs=Lt([{name:"a_projected_pos",components:4,type:"Float32"}],4);Lt([{name:"a_fade_opacity",components:1,type:"Uint32"}],4);const ghs=Lt([{name:"a_auto_z_offset",components:1,type:"Float32"}],4),xhs=Lt([{name:"a_feature_index",components:1,type:"Float32"}],4),yhs=Lt([{name:"a_x_axis",components:3,type:"Float32"},{name:"a_y_axis",components:3,type:"Float32"}]),vhs=Lt([{name:"a_texb",components:2,type:"Uint16"}]),bhs=Lt([{name:"a_placed",components:2,type:"Uint8"},{name:"a_shift",components:2,type:"Float32"},{name:"a_elevation_from_sea",components:2,type:"Float32"}]),_hs=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 mdt=Lt([{name:"a_pos",components:3,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4),whs=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 fdt=new Float32Array(1),jhs=new Uint32Array(fdt.buffer);function Aoe(N){return fdt[0]=N,jhs[0]}const z9=class fU{static getBlockIndices(p){let _=fU._blockIndicesTemplate;if(!_){_=fU._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,fU.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 Z=0;Z<9;Z++)z&1<this._propsDirtyMax&&(this._propsDirtyMax=H)}rightSizeForTransfer(){const p=this._propsDirtyMax===-1?0:this._propsDirtyMax;p>>_&1?8:4);const F=fU.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,fU.getBlockIndices(this.propsDwords)),this._blockIndicesDirty=!1,C=!0),C&&_.bindBuffer(_.UNIFORM_BUFFER,null)}bind(p,_){const C=p.gl,M=(z,H,Z)=>{if(!H)return;const se=C.getUniformBlockIndex(_,z);se!==C.INVALID_INDEX&&(C.uniformBlockBinding(_,se,Z),C.bindBufferBase(C.UNIFORM_BUFFER,Z,H))},F=3*this.batchIndex;M("SymbolPaintPropertiesHeaderUniform",this.headerBuffer,F),M("SymbolPaintPropertiesUniform",this.propertiesBuffer,F+1),M("SymbolPaintPropertiesIndexUniform",this.blockIndicesBuffer,F+2)}destroy(){if(this.context){const p=this.context.gl;this.headerBuffer&&(p.deleteBuffer(this.headerBuffer),this.headerBuffer=null),this.propertiesBuffer&&(p.deleteBuffer(this.propertiesBuffer),this.propertiesBuffer=null),this.blockIndicesBuffer&&(p.deleteBuffer(this.blockIndicesBuffer),this.blockIndicesBuffer=null)}}};z9.HEADER_DWORDS=16,z9.HEADER_BYTES=64,z9.EVAL_FLAT_OFFSETS=[0,8,16,20,24,28,32,36,40],z9.EVAL_FLAT_TOTAL=48,z9._blockIndicesTemplate=null;let NY=z9;function pdt(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 gdt(N){if(!(N instanceof bh))return!1;const p=N.value;return(p.kind==="source"||p.kind==="composite")&&p.isStateDependent}oa(NY,"SymbolPropertiesUBO",{omit:["headerBuffer","propertiesBuffer","blockIndicesBuffer"]});const kY=["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(NY.EVAL_FLAT_TOTAL),Nhs=[0,0],xdt=new WeakMap;class eOe{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(NY.HEADER_DWORDS),this.updateHeader(),this.isAllConstant=this.header[0]===0;const Z=4*this.header[2];this.maxFeaturesPerBatch=Z===0?Number.MAX_SAFE_INTEGER:Math.floor(this.uboSizeDwords/Z)}updateHeader(){const p=this.layer.paint;let _=0,C=0,M=0,F=0,z=!0;const H=this._floorZoom,Z=kY[+this.isText];for(let se=0;se<9;se++){const fe=Z[se],xe=se<2,be=p.get(fe),Te=!(!be||typeof be.isConstant!="function"||be.isConstant()),De=this._appearancesHavePaintProperties(fe);if(!Te&&!De){const yt=this._layerUnevaluated(fe);yt&&yt.expression&&yt.expression.kind==="camera"&&(M|=1<{if(!se)return;this._computeZoomRange(se,_,this._zoomRangeScratch,0);const fe=this._zoomRangeScratch[0],xe=this._zoomRangeScratch[1];C?fe===z&&xe===H||(M=!0):(C=!0,z=fe,H=xe,F=se)};Z(this._zoomExprOf(this._layerUnevaluated(p)));for(const se of this.layer.getAppearances()||[])se.hasPaintProperty(p)&&Z(this._zoomExprOf(se.getUnevaluatedPaintProperty(p)));return{hasZoom:C,differs:M,representative:F}}evaluateAllProperties(p,_,C,M,F,z,H){const Z={brightness:F,worldview:this.worldview},se={feature:p,featureState:_,canonical:C,availableImages:M,params:new Wn(this.zoom,Z),paramsNext:new Wn(this.zoom+1,Z),formattedSection:z,activeAppearance:H},fe=kY[+this.isText];for(let xe=0;xe<9;xe++){const be=fe[xe],Te=xe<2,De=xe===8,Ue=this.zoomDependency[xe],Ye=Ue!==0,nt=Ue===2,it=NY.EVAL_FLAT_OFFSETS[xe],ht=it+(Te||De?4:2);Te?this._evaluateColorValue(be,xe,Ye,nt,ht,se,it):De?this._evaluateTranslateValue(be,xe,Ye,nt,ht,se,it):this._evaluateFloatValue(be,xe,Ye,nt,ht,se,it)}return jm}_resolveProp(p,_,C=!1,M){const F=this.layer.paint,z=F.get(p),H=p,Z=!(!_||!_.hasPaintProperty(H)),se=Z?M&&z&&z.property.overrides&&z.property.overrides.hasOverride(M)?z:_.paintProperties.get(H):F.get(p);if(C||!se||typeof se.isConstant!="function"||!se.isConstant())return se;const fe=Z?_.getUnevaluatedPaintProperty(H):this._layerUnevaluated(p);return this._unbakeCamera(se,fe)}_unbakeCamera(p,_){const C=_&&_.expression;if(!C||C.kind!=="camera")return p;let M=xdt.get(_);return M||(M=new bh(p.property,C,p.parameters,p.iconImageUseTheme),xdt.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 Z=this._resolveProp(p,z.activeAppearance,!1,z.formattedSection);if(this._writePropertyZoomRange(_,C,M,Z,F),!Z)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),fe=pdt(se&&typeof se!="string"?se.value:void 0,z.feature,z.featureState,z.availableImages,z.canonical,z.params.brightness,z.formattedSection,this.worldview)?null:this.lut,xe=(Z.isConstant()?Z.constantOr(Ci.transparent):this._evalAt(Z,z.params,z)||Ci.transparent).toNonPremultipliedRenderColor(fe);if(jm[H]=wm(255*xe.r,255*xe.g),jm[H+1]=wm(255*xe.b,255*xe.a),C){const be=(this._evalAt(Z,z.paramsNext,z)||Ci.transparent).toNonPremultipliedRenderColor(fe);jm[H+2]=wm(255*be.r,255*be.g),jm[H+3]=wm(255*be.b,255*be.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 Z of H)if(Z>_&&Z<_+1){F=z=Z-_;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 Z=p.endsWith("opacity")?1:0,se=this._resolveProp(p,z.activeAppearance);this._writePropertyZoomRange(_,C,M,se,F);const fe=(se?se.isConstant()?se.constantOr(Z):this._evalAt(se,z.params,z):Z)??Z;if(jm[H]=fe,C){const xe=this._evalAt(se,z.paramsNext,z);jm[H+1]=xe??Z}else jm[H+1]=fe}_evaluateTranslateValue(p,_,C,M,F,z,H){const Z=this._resolveProp(p,z.activeAppearance);this._writePropertyZoomRange(_,C,M,Z,F);const se=!!Z&&typeof Z.isConstant=="function"&&!Z.isConstant(),fe=Z?typeof Z.isConstant!="function"?Z:se?this._evalAt(Z,z.params,z):Z.constantOr(Nhs):void 0;if(jm[H]=fe?fe[0]:0,jm[H+1]=fe?fe[1]:0,C){const xe=se?this._evalAt(Z,z.paramsNext,z):fe;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=kY[+this.isText];for(const M of C)if(gdt(_.get(M)))return!0;for(const M of p.getAppearances()||[])for(const F of C){const z=F;if(M.hasPaintProperty(z)&&gdt(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],Z=_.feature(H);if(!Z)return;const se=this.allFeatureIds[p],fe=se!=null&&F[se]||{},xe={type:Z.type,id:se,properties:Z.properties||{},geometry:[]},be=this.activeAppearanceByVtIndex?this.activeAppearanceByVtIndex.get(H):void 0,Te=this.evaluateAllProperties(xe,fe,C,M,z,(this.allFormattedSections?this.allFormattedSections[p]:void 0)||void 0,be);this._writeFeatureBlock(p,Te)}_ensureRangeMaps(){if(!this.featureVertexRangesFromId){this.featureVertexRangesFromId=new Map,this.featureVertexRangesFromVtIndex=new Map;for(let p=0;p{const be=H[xe],Te=M.get(be);if(!Te)return[0,0,0,1];const De=M.get(`${be}-use-theme`),Ue=pdt(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()),Ur.applyArabicShaping&&(M=Ur.applyArabicShaping(M)),M}(C.text,p,_)}),N}const z3={horizontal:1,vertical:2,horizontalOnly:3};function ydt(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 vdt(N,p,_,C){const{horizontalAlign:M,verticalAlign:F}=ydt(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 bdt(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 Z=p.left*F,se=p.right*F;let fe,xe,be,Te;_==="width"||_==="both"?(Te=M[0]+Z-C[3],xe=M[0]+se+C[1]):(Te=M[0]+(Z+se-z.displaySize[0])/2,xe=Te+z.displaySize[0]);const De=p.top*F,Ue=p.bottom*F;return _==="height"||_==="both"?(fe=M[1]+De-C[0],be=M[1]+Ue+C[2]):(fe=M[1]+(De+Ue-z.displaySize[1])/2,be=fe+z.displaySize[1]),{imagePrimary:z,imageSecondary:void 0,top:fe,right:xe,bottom:be,left:Te,collisionPadding:H}}const SY={"!":"︕","#":"#",$:"$","%":"%","&":"&","(":"︵",")":"︶","*":"*","+":"+",",":"︐","-":"︲",".":"・","/":"/",":":"︓",";":"︔","<":"︿","=":"=",">":"﹀","?":"︖","@":"@","[":"﹇","\\":"\","]":"﹈","^":"^",_:"︳","`":"`","{":"︷","|":"―","}":"︸","~":"~","¢":"¢","£":"£","¥":"¥","¦":"¦","¬":"¬","¯":" ̄","–":"︲","—":"︱","‘":"﹃","’":"﹄","“":"﹁","”":"﹂","…":"︙","‧":"・","₩":"₩","、":"︑","。":"︒","〈":"︿","〉":"﹀","《":"︽","》":"︾","「":"﹁","」":"﹂","『":"﹃","』":"﹄","【":"︻","】":"︼","〔":"︹","〕":"︺","〖":"︗","〗":"︘","!":"︕","(":"︵",")":"︶",",":"︐","-":"︲",".":"・",":":"︓",";":"︔","<":"︿",">":"﹀","?":"︖","[":"﹇","]":"﹈","_":"︳","{":"︷","|":"―","}":"︸","⦅":"︵","⦆":"︶","。":"︒","「":"﹁","」":"﹂"};function Shs(N){return N==="︶"||N==="﹈"||N==="︸"||N==="﹄"||N==="﹂"||N==="︾"||N==="︼"||N==="︺"||N==="︘"||N==="﹀"||N==="︐"||N==="︓"||N==="︔"||N==="`"||N===" ̄"||N==="︑"||N==="︒"}function Chs(N){return N==="︵"||N==="﹇"||N==="︷"||N==="﹃"||N==="﹁"||N==="︽"||N==="︻"||N==="︹"||N==="︗"||N==="︿"}const rM=128;function $9(N,p,_,C){const{expression:M}=p;if(M.kind==="constant")return{kind:"constant",layoutSize:M.evaluate(new Wn(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(;HZ*H)}}function wdt(N,p,_,C,M,F,z){return{appearanceTextOffset:U9(N,p,_,C,"text-offset",M,([Z,se])=>[Z*B9,se*B9]),appearanceTextRotate:U9(N,p,_,C,"text-rotate",F),appearanceTextSize:U9(N,p,_,C,"text-size",z)}}function jdt(N,p,_,C,M,F,z,H,Z,se){if(!N)return;const fe=function(xe,be,Te,De,Ue,Ye,nt){if(xe.kind==="camera")return xe.maxSize;if(xe.kind==="composite"){const it=be.possiblyEvaluate(new Wn(xe.maxZoom,{worldview:Ye}),Te,nt).evaluate(Ue,{},Te,nt),ht=be.possiblyEvaluate(new Wn(xe.minZoom,{worldview:Ye}),Te,nt).evaluate(Ue,{},Te,nt);return Math.max(it,ht)}return be.possiblyEvaluate(new Wn(De,{worldview:Ye}),Te,nt).evaluate(Ue,{},Te,nt)}(p,_,C,M,F,Z,se);return N.scaleSelf(fe*H*z)}function tOe(N,p,_,C,M,F,z,H,Z,se){return{iconPrimary:jdt(N.getPrimary(),p,_,C,M,F,z,H,Z,se),iconSecondary:jdt(N.getSecondary(),p,_,C,M,F,z,H,Z,se)}}function Ndt(N,p){return N*p/24}function kdt(N,p,_,C,M,F){let z=null;return p.kind==="source"?(z=[rM*_*C],z[0]>J6&&Yo(`${N}: Value for "text-size" or "icon-size" is >= 255. Reduce your "text-size" or "icon-size".`)):p.kind==="composite"&&(z=[rM*M*C,rM*F*C],(z[0]>J6||z[1]>J6)&&Yo(`${N}: Value for "text-size" or "icon-size" is >= 255. Reduce your "text-size" or "icon-size".`)),z}const Ths=Lt([{type:"Float32",name:"a_globe_pos",components:3},{type:"Float32",name:"a_uv",components:2}]),{members:Toe}=Ths,Mhs=Lt([{name:"a_pos_3",components:3,type:"Int16"}]);var sOe=Lt([{name:"a_pos",type:"Int16",components:2}]);class Phs{constructor(p,_){this.pos=p,this.dir=_}intersectsPlane(p,_,C){const M=kn(_,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 Moe{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],ht=De[1],ot=De[2];return Math.abs(Ue-it)<=u*Math.max(1,Math.abs(Ue),Math.abs(it))&&Math.abs(Ye-ht)<=u*Math.max(1,Math.abs(Ye),Math.abs(ht))&&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],Z=this.pos[1]-p[1],se=this.pos[2]-p[2],fe=M*M+F*F+z*z,xe=2*(H*M+Z*F+se*z),be=xe*xe-4*fe*(H*H+Z*Z+se*se-_*_);if(be<0){const Te=Math.max(-xe/2,0),De=H+M*Te,Ue=Z+F*Te,Ye=se+z*Te,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(be))/(2*fe);if(Te<0){const De=Math.hypot(H,Z,se);return C[0]=H*_/De,C[1]=Z*_/De,C[2]=se*_/De,!1}return C[0]=H+M*Te,C[1]=Z+F*Te,C[2]=se+z*Te,!0}}}class nOe{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],Z=Xe(M,M,p),se=Xe(F,F,p),fe=Xe(z,z,p),xe=Xe(H,H,p);return new nOe(Z,se,fe,xe,_/C)}}function rOe(N,p,_,C){const M=p[0],F=p[1],z=p[2],H=_[0],Z=_[1],se=_[2];let fe=1/0,xe=-1/0;for(let be=0;bexe&&(xe=De)}return C[0]=fe,C[1]=xe,C}function Sdt(N,p){let _=!0;for(let C=0;C=0);if(F===0)return 0;F!==p.length&&(_=!1)}return _?2:1}const Ihs=[0,0];function Cdt(N,p){for(const _ of N.projections){const C=rOe(p,N.points[0],_.axis,Ihs);if(_.projection[1]C[1])return 0}return 1}function Adt(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 $3{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=[pt([],this.points[2],this.points[3]),pt([],this.points[0],this.points[3]),pt([],this.points[4],this.points[0]),pt([],this.points[5],this.points[1]),pt([],this.points[6],this.points[2]),pt([],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:rOe(this.points,this.points[0],M,[0,0])}),this.projections.push({axis:F,projection:rOe(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 fe=Ft([],se,p),xe=1/fe[3]/_*F;return(be=fe)[0]=(Te=fe)[0]*(De=[xe,xe,M?1/fe[3]:xe,xe])[0],be[1]=Te[1]*De[1],be[2]=Te[2]*De[2],be[3]=Te[3]*De[3],be;var be,Te,De}),H=[[0,1,2],[6,5,4],[0,3,7],[2,1,5],[3,2,6],[0,4,5]].map(se=>{const fe=Ve([],qe([],pt([],z[se[0]],z[se[1]]),pt([],z[se[2]],z[se[1]]))),xe=-ze(fe,z[se[1]]);return fe.concat(xe)}),Z=[];for(let se=0;seDe&&(De=ht)}let Ue=1/0,Ye=-1/0;for(let nt=0;ntYe&&(Ye=ht)}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)Se(_,_,M),Le(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 Poe(N){return N*pf/eM}oa(du,"Aabb");const Lhs=[new du([Hv,Hv,Hv],[V_,V_,V_]),new du([Hv,Hv,Hv],[0,0,V_]),new du([0,Hv,Hv],[V_,0,V_]),new du([Hv,0,Hv],[0,V_,V_]),new du([0,0,Hv],[V_,V_,V_])];function Edt(N,p,_,C=!0){const M=Fe([],N._camera.position,N.worldSize),F=[p,_,1,1];Ft(F,F,N.pixelMatrixInverse),ys(F,F,1/F[3]);const z=Ve([],pt([],F,M)),H=N.globeMatrix,Z=[H[12],H[13],H[14]],se=pt([],Z,M),fe=ce(se),xe=Ve([],se),be=N.worldSize/(2*Math.PI),Te=ze(xe,z),De=Math.asin(be/fe);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,ta(_,0,1))+N.center[p]}function HC(N){if(N.z<=1)return Lhs[N.z+2*N.y+N.x];const p=oOe(Ioe(N));return du.fromPoints(p)}function U3(N,p,_){return Fe(N,N,1-_),ke(N,N,p,_)}function Tdt(N,p,_){for(const C of N)Xe(C,C,p),Fe(C,C,_)}function iOe(N,p,_,C){const M=p/N.worldSize,F=N.globeMatrix;if(_.z<=1){const $t=HC(_).getCorners();return Tdt($t,F,M),du.fromPoints($t)}const z=Ioe(_,C),H=oOe(z,pf+Poe(N._tileCoverLift));Tdt(H,F,M);const Z=Number.MAX_VALUE,se=[-Z,-Z,-Z],fe=[Z,Z,Z];if(z.contains(N.center)){for(const ns of H)Se(fe,fe,ns),Le(se,se,ns);se[2]=0;const $t=N.point,Jt=[$t.x*M,$t.y*M,0];return Se(fe,fe,Jt),Le(se,se,Jt),new du(fe,se)}if(N._tileCoverLift>0){for(const $t of H)Se(fe,fe,$t),Le(se,se,$t);return new du(fe,se)}const xe=[F[12]*M,F[13]*M,F[14]*M],be=z.getCenter(),Te=ta(N.center.lat,-85.051129,L),De=ta(be.lat,-85.051129,L),Ue=ex(N.center.lng),Ye=ap(Te);let nt=Ue-ex(be.lng);const it=Ye-ap(De);nt>.5?nt-=1:nt<-.5&&(nt+=1);let ht=0;Math.abs(nt)>Math.abs(it)?ht=nt>=0?1:3:(ht=it>=0?0:2,ke(xe,xe,[F[4]*M,F[5]*M,F[6]*M],-Math.sin(Xr(it>=0?z.getSouth():z.getNorth()))*pf));const ot=H[ht],yt=H[(ht+1)%4],Nt=new Rhs(ot,yt,xe),is=[aOe(Nt,0)||ot[0],aOe(Nt,1)||ot[1],aOe(Nt,2)||ot[2]],At=q3(N.zoom);if(At>0){const $t=function({x:ns,y:Ps,z:Gs},pn,cn,jn,Vn){const Cs=1/(1<.5?qn=-1:Dn<-.5&&(qn=1),Zs=((Zs+qn)*pn-(jn*=pn))*cn+jn,an=((an+qn)*pn-jn)*cn+jn,Ln=(Ln*pn-(Vn*=pn))*cn+Vn,In=(In*pn-Vn)*cn+Vn,[[Zs,In,0],[an,In,0],[an,Ln,0],[Zs,Ln,0]]}(_,p,N._pixelsPerMercatorPixel,Ue,Ye);for(let ns=0;nsMath.PI/2*1.01}const Ldt=Xr(85),Dhs=Math.cos(Ldt),Fhs=Math.sin(Ldt);function Rdt(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 Z=F*(1/N._horizonShift);if(!N.elevation||N.elevation.exaggeration()===0){let se=Math.max(N.zoom-17,0);N.isOrthographic&&(se/=10),H*=1+se}return Math.min(1.01*H,Z)}class aM{constructor(p,_,C){this.z=p,this.x=_,this.y=C,this.key=iM(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 Z=2**H,se=2*Math.PI*6378137,fe=se*(F/Z-.5),xe=se*(.5-(z+1)/Z);return`${fe},${xe},${fe+se/Z},${xe+se/Z}`}(this.x,this.y,this.z),M=function(F,z,H){let Z,se="";for(let fe=F;fe>0;fe--)Z=1<this.canonical.z?new mg(p,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y):new mg(p,this.wrap,p,this.canonical.x>>_,this.canonical.y>>_)}calculateScaledKey(p,_=!0){if(this.overscaledZ===p&&_)return this.key;if(p>this.canonical.z)return iM(this.wrap*+_,p,this.canonical.z,this.canonical.x,this.canonical.y);{const C=this.canonical.z-p;return iM(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 mg(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 mg(_,this.wrap,_,C,M),new mg(_,this.wrap,_,C+1,M),new mg(_,this.wrap,_,C,M+1),new mg(_,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 mg(N.overscaledZ,N.wrap,N.canonical.z,N.canonical.x,(N.canonical.y===0?1<new mg(N.overscaledZ,N.wrap,N.canonical.z,N.canonical.x,N.canonical.y===(1<ht&&(ot(Nt,pn,At,$t,Ps,Gs),ot(pn,is,Ps,Gs,Jt,ns))}ot(xe,be,C,F,M,F),ot(be,Te,M,F,M,z),ot(Te,De,M,z,C,z),ot(De,xe,C,z,C,F),Ue-=ht,Ye-=ht,nt+=ht,it+=ht;const yt=1/Math.max(nt-Ue,it-Ye);return{scale:yt,x:Ue*yt,y:Ye*yt,x2:nt*yt,y2:it*yt,projection:p}}function Fdt(N,p,_,C,M,F,z,H,Z){if(Z.name==="globe")return iOe(N,p,new aM(_,C,M),!1);const se=uOe({z:_,x:C,y:M},Z);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(aM,"CanonicalTileID"),oa(mg,"OverscaledTileID",{omit:["projMatrix","expandedProjMatrix"]});const Ohs=w(new Float32Array(16));class oM{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 Jd(1,p)*_}pixelSpaceConversion(p,_,C){return 1}farthestPixelDistance(p){return Rdt(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?_<-q9+C&&(_=-q9+C):_>q9-C&&(_=q9-C);const z=F/Math.pow(zoe(_),M);let H=z*Math.sin(M*p),Z=F-z*Math.cos(M*p);return H=.5*(H/Math.PI+.5),Z=.5*(Z/Math.PI+.5),{x:H,y:this.southernCenter?Z:1-Z,z:0}}unproject(p,_){p=(2*p-.5)*Math.PI,this.southernCenter&&(_=1-_),_=(2*(1-_)-.5)*Math.PI;const{n:C,f:M}=this,F=M-_,z=Math.sign(F),H=Math.sign(C)*Math.sqrt(p*p+F*F);let Z=Math.atan2(p,Math.abs(F))*z;F*C<0&&(Z-=Math.PI*Math.sign(p)*z);const se=ta(Eo(Z/C)+this.center[0],-180,180),fe=ta(Eo(2*Math.atan(Math.pow(M/H,1/C))-q9),-85.051129,L);return new Il(se,this.southernCenter?-fe:fe)}}class Odt extends oM{constructor(p){super(p),this.wrap=!0,this.supportsWorldCopies=!0,this.supportsTerrain=!0,this.supportsFog=!0,this.supportsFreeCamera=!0,this.isReprojectedInTileSpace=!1,this.unsupportedLayers=[],this.range=null}project(p,_){return{x:ex(p),y:ap(_),z:0}}unproject(p,_){const C=Fx(p),M=qd(_);return new Il(C,M)}}const zdt=Xr(L);class qhs extends oM{project(p,_){const C=(_=Xr(_))*_,M=C*C;return{x:.5*((p=Xr(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=ta(C-F,-zdt,zdt)}while(Math.abs(F)>1e-6&&--M>0);z=C*C;const H=ta(Eo(p/(.8707+z*(z*(z*z*z*(.003971-.001529*z)-.013791)-.131979))),-180,180),Z=Eo(C);return new Il(H,Z)}}const Bdt=Xr(L);class Vhs extends oM{project(p,_){_=Xr(_),p=Xr(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,Z=.5*(_+Math.sin(_)/z)||0;return{x:.5*(H/Math.PI+.5),y:1-.5*(Z/Math.PI+1),z:0}}unproject(p,_){let C=p=(2*p-.5)*Math.PI,M=_=(2*(1-_)-1)*Math.PI,F=25;const z=1e-6;let H=0,Z=0;do{const se=Math.cos(M),fe=Math.sin(M),xe=2*fe*se,be=fe*fe,Te=se*se,De=Math.cos(C/2),Ue=Math.sin(C/2),Ye=2*De*Ue,nt=Ue*Ue,it=1-Te*De*De,ht=it?1/it:0,ot=it?Math.acos(se*De)*Math.sqrt(1/it):0,yt=.5*(2*ot*se*Ue+2*C/Math.PI)-p,Nt=.5*(ot*fe+M)-_,is=.5*ht*(Te*nt+ot*se*De*be)+1/Math.PI,At=ht*(Ye*xe/4-ot*fe*Ue),$t=.125*ht*(xe*Ue-ot*fe*Te*Ye),Jt=.5*ht*(be*De+ot*nt*se)+.5,ns=At*$t-Jt*is;H=(Nt*At-yt*Jt)/ns,Z=(yt*$t-Nt*is)/ns,C=ta(C-H,-Math.PI,Math.PI),M=ta(M-Z,-Bdt,Bdt)}while((Math.abs(H)>z||Math.abs(Z)>z)&&--F>0);return new Il(Eo(C),Eo(M))}}class $dt extends oM{constructor(p){super(p),this.center=p.center||[0,0],this.parallels=p.parallels||[0,0],this.cosPhi=Math.max(.01,Math.cos(Xr(this.parallels[0]))),this.scale=1/(2*Math.max(Math.PI*this.cosPhi,1/this.cosPhi)),this.wrap=!0,this.supportsWorldCopies=!0}project(p,_){const{scale:C,cosPhi:M}=this;return{x:Xr(p)*M*C+.5,y:-Math.sin(Xr(_))/M*C+.5,z:0}}unproject(p,_){const{scale:C,cosPhi:M}=this,F=-(_-.5)/C,z=ta(Eo((p-.5)/C)/M,-180,180),H=Math.asin(ta(F*M,-1,1)),Z=ta(Eo(H),-85.051129,L);return new Il(z,Z)}}class Hhs extends Odt{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=CY(p,_,C);return Xe(M,M,Doe(HC(C))),{x:M[0],y:M[1],z:M[2]}}locationPoint(p,_,C){const M=D3(_.lat,_.lng),F=Ve([],M),z=C?p._centerAltitude+C:p.elevation?p.elevation.getAtPointOrZero(p.locationCoordinate(_),p._centerAltitude):p._centerAltitude;ke(M,M,F,Jd(1,0)*Dr*z);const H=w(new Float64Array(16));return E(H,p.pixelMatrix,p.globeMatrix),Xe(M,M,H),new xs(M[0],M[1])}pixelsPerMeter(p,_){return Jd(1,0)*_}pixelSpaceConversion(p,_,C){const M=Jd(1,p)*_,F=ya(Jd(1,45)*_,M,C);return this.pixelsPerMeter(p,_)/F}createTileMatrix(p,_,C){const M=lOe(HC(C.canonical));return E(new Float64Array(16),p.globeMatrix,M)}createInversionMatrix(p,_){const{center:C}=p,M=Doe(HC(_));return D(M,M,Xr(C.lng)),R(M,M,Xr(C.lat)),P(M,M,[p._pixelsPerMercatorPixel,p._pixelsPerMercatorPixel,1]),Float32Array.from(M)}pointCoordinate(p,_,C,M){return Edt(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!Edt(p,_.x,_.y,!1)}farthestPixelDistance(p){const _=function(M,F){const z=M.cameraToCenterDistance,H=M._centerAltitude*F,Z=M._camera,se=M._camera.forward(),fe=ue([],Fe([],se,-z),[0,0,H]),xe=M.worldSize/(2*Math.PI),be=[0,0,-xe],Te=M.width/M.height,De=Math.tan(M.fovAboveCenter),Ue=Fe([],Z.up(),De),Ye=Fe([],Z.right(),De*Te),nt=Ve([],ue([],ue([],se,Ue),Ye)),it=[];let ht;if(new Moe(fe,nt).closestPointOnSphere(be,xe,it)){const ot=ue([],it,be),yt=pt([],ot,fe);ht=Math.cos(M.fovAboveCenter)*ce(yt)}else{const ot=pt([],fe,be),yt=pt([],be,fe);Ve(yt,yt);const Nt=ce(ot)-xe;ht=Math.sqrt(Nt*(Nt+2*xe));const is=Math.acos(ht/(xe+Nt))-Math.acos(ze(se,yt));ht*=Math.cos(is)}return 1.01*ht}(p,this.pixelsPerMeter(p.center.lat,p.worldSize)),C=q3(p.zoom);if(C>0){const M=Rdt(p,Jd(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 CY(_,C,p,1)}upVectorScale(p){return{metersToTile:Poe(Loe(HC(p)))}}}function Boe(N){const p=N.parallels,_=!!p&&Math.abs(p[0]+p[1])<.01;switch(N.name){case"mercator":return new Odt(N);case"equirectangular":return new $hs(N);case"naturalEarth":return new qhs(N);case"equalEarth":return new Bhs(N);case"winkelTripel":return new Vhs(N);case"albers":return _?new $dt(N):new zhs(N);case"lambertConformalConic":return _?new $dt(N):new Uhs(N);case"globe":return new Hhs(N)}throw new Error(`Invalid projection name: ${N.name}`)}const PY=Number.MAX_SAFE_INTEGER,Ghs=PY-1;function hOe(N,p,_,C){return N.orderp.max.x||N.max.xp.max.y||N.max.ynew xs((Z.x+F.x*Dr)*H-z.x*Dr,(Z.y+F.y*Dr)*H-z.y*Dr))}return fOe(_,M,N.indices,0,N.indices.length,0,0)}function pOe(N,p,_,C){const M=Math.pow(2,C.z-_.z);return new xs((N+_.x*Dr)*M-C.x*Dr,(p+_.y*Dr)*M-C.y*Dr)}function qoe(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(sM([M[C[3*z+0]],M[C[3*z+1]],M[C[3*z+2]]],N))return!0}return!1}const IY={None:0,Model:1,Symbol:2,FillExtrusion:4};function gOe(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 xOe{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 Z=this.getAtTileOffset(p,F,z,H),se=M.upVector(p.canonical,F.x,F.y);return Fe(se,se,Z*M.upVectorScale(p.canonical,_,C).metersToTile),se}}getForTilePoints(p,_,C,M){if(this.isUsingMockSource())return!1;const F=V9.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 Hoe{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)*bOe;return this.pos+=8,p}readSFixed64(){const p=this.dataView.getUint32(this.pos,!0)+this.dataView.getInt32(this.pos+4,!0)*bOe;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,Z){const se=Z.buf;let fe,xe;if(xe=se[Z.pos++],fe=(112&xe)>>4,xe<128||(xe=se[Z.pos++],fe|=(127&xe)<<3,xe<128)||(xe=se[Z.pos++],fe|=(127&xe)<<10,xe<128)||(xe=se[Z.pos++],fe|=(127&xe)<<17,xe<128)||(xe=se[Z.pos++],fe|=(127&xe)<<24,xe<128)||(xe=se[Z.pos++],fe|=(1&xe)<<31,xe<128))return H9(z,fe,H);throw new Error("Expected varint not more than 10 bytes")}(F,p,this))))}readSVarint(){const p=this.readVarint();return p%2==1?(p+1)/-2:p/2}readBoolean(){return!!this.readVarint()}readString(){const p=this.readVarint()+this.pos,_=this.pos;return this.pos=p,p-_>=12&&Zdt?Zdt.decode(this.buf.subarray(_,p)):function(C,M,F){let z="",H=M;for(;H239?4:Z>223?3:Z>191?2:1;if(H+Te>F)break;Te===1?Z<128&&(be=Z):Te===2?(se=C[H+1],(192&se)==128&&(be=(31&Z)<<6|63&se,be<=127&&(be=null))):Te===3?(se=C[H+1],fe=C[H+2],(192&se)==128&&(192&fe)==128&&(be=(15&Z)<<12|(63&se)<<6|63&fe,(be<=2047||be>=55296&&be<=57343)&&(be=null))):Te===4&&(se=C[H+1],fe=C[H+2],xe=C[H+3],(192&se)==128&&(192&fe)==128&&(192&xe)==128&&(be=(15&Z)<<18|(63&se)<<12|(63&fe)<<6|63&xe,(be<=65535||be>=1114112)&&(be=null))),be===null?(be=65533,Te=1):be>65535&&(be-=65536,z+=String.fromCharCode(be>>>10&1023|55296),be=56320|1023&be),z+=String.fromCharCode(be),H+=Te}return z}(this.buf,_,p)}readBytes(){const p=this.readVarint()+this.pos,_=this.buf.subarray(this.pos,p);return this.pos=p,_}readPackedVarint(p=[],_){const 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 H9(N,p,_){return _?4294967296*p+(N>>>0):4294967296*(p>>>0)+(N>>>0)}function Xdt(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 Khs(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 Yhs(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 Z=C[H];if(!(z.w>Z.w||z.h>Z.h)){if(z.x=Z.x,z.y=Z.y,F=Math.max(F,z.y+z.h),M=Math.max(M,z.x+z.w),z.w===Z.w&&z.h===Z.h){const se=C.pop();se&&Hp.id?1:N.versionp.version?1:N.sxp.sx?1:N.syp.sy?1:0}function Woe(N){let p=0;for(let _=0;_0,Jdt(p,C,this.iconDescriptors,z),Jdt(_,C,this.patternDescriptors,z),this.iconDescriptors.sort(Goe),this.patternDescriptors.sort(Goe);let H=0;H=oj(H,Woe(F)),H=oj(H,1);const Z=M?M.data:"";Z&&(H=oj(H,Woe(Z))),H=oj(H,1);for(const se of this.iconDescriptors)H=oj(H,Woe(se.id)),H=oj(H,se.version),H=oj(H,se.sx),H=oj(H,se.sy);H=oj(H,1);for(const se of this.patternDescriptors)H=oj(H,Woe(se.id)),H=oj(H,se.version),H=oj(H,se.sx),H=oj(H,se.sy);this.hash=H}subsetOf(p){return this.scope===p.scope&&this.isSubsetArray(this.iconDescriptors,p.iconDescriptors,Goe)&&this.isSubsetArray(this.patternDescriptors,p.patternDescriptors,Goe)}isSubsetArray(p,_,C){let M=0,F=0;if(p.length>_.length)return!1;for(;M0&&fe>0){const be=this.useMipmap?Math.floor(Math.log2(Math.max(se,fe)))+1:1;z.texStorage2D(z.TEXTURE_2D,be,this.format,se,fe),this.size=[se,fe]}this.size&&(xe?z.texSubImage2D(z.TEXTURE_2D,0,H,Z,wOe(this.format),jOe(this.format),p):"data"in p&&p.data&&z.texSubImage2D(z.TEXTURE_2D,0,H,Z,C,M,wOe(this.format),jOe(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 eut{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:Z}=p;Z.bindTexture(Z.TEXTURE_3D,this.texture),p.pixelStoreUnpackFlipY.set(!1),p.pixelStoreUnpack.set(1),p.pixelStoreUnpackPremultiplyAlpha.set(!1),"data"in _&&_.data&&Z.texImage3D(Z.TEXTURE_3D,0,this.format,F,z,H,0,wOe(this.format),jOe(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 RY{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:Z,content:se,sdf:fe,usvg:xe}=_;this.pixelRatio=F,this.stretchX=H,this.stretchY=Z,this.content=se,this.version=z,this.padding=C,this.sdf=fe,this.usvg=xe,this.scale=RY.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 tut(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 RY(M,p,_,C),imageVariant:C}}function NOe(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 sut{constructor(p){this.sourceAtlasHash=p}}class nut{constructor(p,_,C,M,F=""){const z=new Map,H=new Map;this.haveRenderCallbacks=[];const Z=[],se=M!==void 0,fe=se?new Map:void 0,xe=se?NOe(p,fe):p,be=se?NOe(_,fe):_;this.addImages(xe,z,1,Z),this.addImages(be,H,2,Z);const{w:Te,h:De}=Qdt(Z),Ue=new t0({width:Te||1,height:De||1});for(const[Ye,nt]of xe.entries()){const it=z.get(Ye).paddedRect;t0.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 be.entries()){const it=H.get(Ye),ht=it.paddedRect;let ot=it.padding;const yt=ht.x+ot,Nt=ht.y+ot,is=nt.data.width,At=nt.data.height;ot=ot>1?ot-1:ot,t0.copy(nt.data,Ue,{x:0,y:0},{x:yt,y:Nt},nt.data,C),t0.copy(nt.data,Ue,{x:0,y:At-ot},{x:yt,y:Nt-ot},{width:is,height:ot},C),t0.copy(nt.data,Ue,{x:0,y:0},{x:yt,y:Nt+At},{width:is,height:ot},C),t0.copy(nt.data,Ue,{x:is-ot,y:0},{x:yt-ot,y:Nt},{width:ot,height:At},C),t0.copy(nt.data,Ue,{x:0,y:0},{x:yt+is,y:Nt},{width:ot,height:At},C),t0.copy(nt.data,Ue,{x:is-ot,y:At-ot},{x:yt-ot,y:Nt-ot},{width:ot,height:ot},C),t0.copy(nt.data,Ue,{x:0,y:At-ot},{x:yt+is,y:Nt-ot},{width:ot,height:ot},C),t0.copy(nt.data,Ue,{x:0,y:0},{x:yt+is,y:Nt+At},{width:ot,height:ot},C),t0.copy(nt.data,Ue,{x:is-ot,y:0},{x:yt-ot,y:Nt+At},{width:ot,height:ot},C)}this.lut=C,this.image=Ue,this.iconPositions=z,this.patternPositions=H,se&&(this.contentDescriptor=new _Oe(xe,be,M,C,F,fe))}addImages(p,_,C,M){for(const[F,z]of p.entries()){const{bin:H,imagePosition:Z,imageVariant:se}=tut(F,z,C);_.set(F,Z),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 Z=p.getImage(F,C);this.patchUpdatedImage(this.iconPositions.get(z),Z,_,null)}}for(const z of this.patternPositions.keys()){const H=Ih.parse(z);if(vd.isEqual(H.id,F)){const Z=p.getImage(F,C);this.patchUpdatedImage(this.patternPositions.get(z),Z,_,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 Z={width:_.data.width,height:_.data.height},se=new t0(Z);t0.copy(_.data,se,{x:0,y:0},{x:0,y:0},Z,M,H),C.update(se,{position:{x:F,y:z},recreateWhenResize:!1})}else C.update(_.data,{position:{x:F,y:z},recreateWhenResize:!1})}}oa(RY,"ImagePosition"),oa(nut,"ImageAtlas",{omit:["lut"]}),oa(sut,"ImageAtlasReference");class DY{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 DY.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},Z=(se,fe,xe)=>{if(!H.callbackCalled&&(fe&&!H.firstError&&(H.firstError=fe),xe&&(z[se]=xe),H.completed++,H.completed===p.length)){H.callbackCalled=!0;const be=z.filter(De=>De!==null);if(be.length===0)return void F(H.firstError||new Error("All fonts failed to load"));const Te=this._composeGlyphs(be);F(null,Te)}};for(let se=0;se{Z(se,fe,xe)})}_loadFont(p,_,C,M,F){const z=`${p}:${_}`;if(this.cachedRanges.has(z)){const Z=this.cachedRanges.get(z);return void ih.frame(()=>F(null,Z))}const H=this.pendingRequests.get(z);H?H.push(F):(this.pendingRequests.set(z,[F]),DY.loadGlyphRange(p,_,C,M,(Z,se)=>{Z||this.cachedRanges.set(z,se||null);const fe=this.pendingRequests.get(z);if(this.pendingRequests.delete(z),fe)for(const xe of fe)xe(Z,se)}))}_composeGlyphs(p){const _={};let 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}}}DY.loadGlyphRange=async function(N,p,_,C,M){const F=256*p,z=F+255;let H;try{const Z=await C.transformRequest(C.normalizeGlyphsURL(_).replace("{fontstack}",N).replace("{range}",`${F}-${z}`),yr.Glyphs),{data:se}=await Qr(Z),fe={},xe=function(be){return function(Te){const De={glyphs:[]};let Ue;for(;Ue=Te.nextField();)Ue===1&&nms(Te,Te.readVarint()+Te.pos,De);return De}(new Hoe(be))}(se);for(const be of xe.glyphs)fe[be.id]=be;H={glyphs:fe,ascender:xe.ascender,descender:xe.descender}}catch(Z){return M(Z)}M(null,H)};const FY=1e20,kOe=new Float64Array(256);for(let N=0;N<256;N++){const p=.5-Math.pow(N/255,.45454545454545453);kOe[N]=p*Math.abs(p)}function rut(N,p,_,C,M,F,z,H,Z){for(let se=p;se-1);Z++,F[Z]=H,z[Z]=se,z[Z+1]=FY}for(let H=0,Z=0;H{if(z){M.ascender=z.ascender,M.descender=z.descender;for(const H in z.glyphs)this._doesCharSupportLocalGlyph(+H)||(M.glyphs[+H]=z.glyphs[+H]);M.ranges[_]=!0}for(const H of M.requests[_]||[])H(F,z);delete M.requests[_]}))}getGlyphs(p,_){const 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 Z=this.entries[F];Z||(Z=this.entries[F]={glyphs:{},requests:{},ranges:{},ascender:void 0,descender:void 0});let se=Z.glyphs[z];if(se!==void 0)return void H(null,{stack:F,id:z,glyph:se});if(se=this._tinySDF(Z,F,z),se)return Z.glyphs[z]=se,void H(null,{stack:F,id:z,glyph:se});const fe=Math.floor(z/256);if(256*fe>65535)return Yo("glyphs > 65535 not supported"),void H(null,{stack:F,id:z,glyph:se});if(Z.ranges[fe])return void H(null,{stack:F,id:z,glyph:se});let xe=Z.requests[fe];xe||(xe=Z.requests[fe]=[],this.glyphLoader.loadGlyphRange(F,fe,M,this.requestManager,(be,Te)=>{if(Te){Z.ascender=Te.ascender,Z.descender=Te.descender;for(const De in Te.glyphs)this._doesCharSupportLocalGlyph(+De)||(Z.glyphs[+De]=Te.glyphs[+De]);Z.ranges[fe]=!0}for(const De of xe)De(be,Te);delete Z.requests[fe]})),xe.push((be,Te)=>{be?H(be):Te&&H(null,{stack:F,id:z,glyph:Te.glyphs[z]||null})})},(F,z)=>{if(F)_(F);else if(z){const H={};for(const{stack:Z,id:se,glyph:fe}of z)H[Z]===void 0&&(H[Z]={}),H[Z].glyphs===void 0&&(H[Z].glyphs={}),H[Z].glyphs[se]=fe&&{id:fe.id,bitmap:fe.bitmap.clone(),metrics:fe.metrics},H[Z].ascender=this.entries[Z].ascender,H[Z].descender=this.entries[Z].descender;_(null,H)}})}_doesCharSupportLocalGlyph(p){return this.localGlyphMode!==SOe.none&&(this.localGlyphMode===SOe.all?!!this.localFontFamily:!!this.localFontFamily&&(BC(p)||P3(p)||OC(p)||zC(p)||Uk(p)||Vk(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";ams.test(_)?Ye="900":ims.test(_)?Ye="500":oms.test(_)&&(Ye="200"),F=p.tinySDF=new Yoe.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:Z,width:se,height:fe,glyphWidth:xe,glyphHeight:be,glyphLeft:Te,glyphTop:De,glyphAdvance:Ue}=F.draw(H);return this.localGlyphs[z][C]={id:C,bitmap:new nM({width:se,height:fe},Z),metrics:{width:xe/2,height:be/2,left:Te/2,top:De/2-27,advance:Ue/2,localGlyph:!0}}}}function iut(N,p){return N+p[1]-p[0]}function out(N,p,_,C,M=1){const F=[],z=N.imagePrimary,H=z.pixelRatio,Z=z.paddedRect.w-2,se=z.paddedRect.h-2,fe=(N.right-N.left)*M,xe=(N.bottom-N.top)*M,be=z.stretchX||[[0,Z]],Te=z.stretchY||[[0,se]],De=be.reduce(iut,0),Ue=Te.reduce(iut,0),Ye=Z-De,nt=se-Ue;let it=0,ht=De,ot=0,yt=Ue,Nt=0,is=Ye,At=0,$t=nt;if(z.content&&C){const ns=z.content;it=Zoe(be,0,ns[0]),ot=Zoe(Te,0,ns[1]),ht=Zoe(be,ns[0],ns[2]),yt=Zoe(Te,ns[1],ns[3]),Nt=ns[0]-it,At=ns[1]-ot,is=ns[2]-ns[0]-ht,$t=ns[3]-ns[1]-yt}const Jt=(ns,Ps,Gs,pn)=>{const cn=Xoe(ns.stretch-it,ht,fe,N.left*M),jn=Qoe(ns.fixed-Nt,is,ns.stretch,De),Vn=Xoe(Ps.stretch-ot,yt,xe,N.top*M),Cs=Qoe(Ps.fixed-At,$t,Ps.stretch,Ue),Zs=Xoe(Gs.stretch-it,ht,fe,N.left*M),an=Qoe(Gs.fixed-Nt,is,Gs.stretch,De),Ln=Xoe(pn.stretch-ot,yt,xe,N.top*M),In=Qoe(pn.fixed-At,$t,pn.stretch,Ue),qn=new xs(cn,Vn),Dn=new xs(Zs,Vn),ar=new xs(Zs,Ln),zn=new xs(cn,Ln),Ir=new xs(jn/H,Cs/H),lr=new xs(an/H,In/H),_r=p*Math.PI/180;if(_r){const Ni=Math.sin(_r),Fo=Math.cos(_r),rl=[Fo,-Ni,Ni,Fo];qn._matMult(rl),Dn._matMult(rl),zn._matMult(rl),ar._matMult(rl)}const Wa=ns.stretch+ns.fixed,Ka=Gs.stretch+Gs.fixed,oi=Ps.stretch+Ps.fixed,Fa=pn.stretch+pn.fixed,Ai=N.imageSecondary;return{tl:qn,tr:Dn,bl:zn,br:ar,texPrimary:{x:z.paddedRect.x+1+Wa,y:z.paddedRect.y+1+oi,w:Ka-Wa,h:Fa-oi},texSecondary:Ai?{x:Ai.paddedRect.x+1+Wa,y:Ai.paddedRect.y+1+oi,w:Ka-Wa,h:Fa-oi}:void 0,writingMode:void 0,glyphOffset:[0,0],sectionIndex:0,pixelOffsetTL:Ir,pixelOffsetBR:lr,minFontScaleX:is/H/fe,minFontScaleY:$t/H/xe,isSDF:_}};if(z.stretchX||z.stretchY){const ns=lut(be,Ye,De),Ps=lut(Te,nt,Ue);for(let Gs=0;Gs0?[it,-ht]:ot<0?[-it,ht]:it===0?[ht,it]:[ht,-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:!F1(z),stateDependent:!q0(z),zoomDependent:!Ox(z,["zoom"]),pitchDependent:!Ox(z,["pitch"]),brightnessDependent:!Ox(z,["brightness","measure-light"]),worldviewDependent:!Ox(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*G9;return this.layoutVertexArray.uint16.slice(C,C+_*G9)}restoreSymbolVertexData(p,_){this.layoutVertexArray.uint16.set(_,p*G9)}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,Z,se,fe,xe,be,Te){const De=this.layoutVertexArray.uint16,Ue=p*G9;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]=Z,De[Ue+7]=se,De[Ue+8]=fe,De[Ue+9]=xe,De[Ue+10]=be,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,mhs.members,!!z),this.indexBuffer=p.createIndexBuffer(this.indexArray,_),this.dynamicLayoutVertexBuffer=p.createVertexBuffer(this.dynamicLayoutVertexArray,phs.members,!0),this.opacityVertexBuffer=p.createVertexBuffer(this.opacityVertexArray,ums,!0),this.iconTransitioningVertexArray.length>0&&(this.iconTransitioningVertexBuffer=p.createVertexBuffer(this.iconTransitioningVertexArray,vhs.members,!0)),this.globeExtVertexArray.length>0&&(this.globeExtVertexBuffer=p.createVertexBuffer(this.globeExtVertexArray,fhs.members,!0)),!this.zOffsetVertexBuffer&&(this.zOffsetVertexArray.length>0||F)&&(this.zOffsetVertexBuffer=p.createVertexBuffer(this.zOffsetVertexArray,ghs.members,!0)),!this.orientationVertexBuffer&&this.orientationVertexArray&&this.orientationVertexArray.length>0&&(this.orientationVertexBuffer=p.createVertexBuffer(this.orientationVertexArray,yhs.members,!0)),this.opacityVertexBuffer.itemSize=1,this.featureIdArray.length>0&&(this.featureIdBuffer=p.createVertexBuffer(this.featureIdArray,xhs.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(COe,"SymbolBuffers",{omit:["cachedBatchIndices","cachedBatchSegments"]});class AOe{constructor(p,_,C){this.layoutVertexArray=new p,this.layoutAttributes=_,this.indexArray=new C,this.segments=new Li,this.collisionVertexArray=new Ga,this.collisionVertexArrayExt=new Hr}upload(p){this.layoutVertexBuffer=p.createVertexBuffer(this.layoutVertexArray,this.layoutAttributes),this.indexBuffer=p.createIndexBuffer(this.indexArray),this.collisionVertexBuffer=p.createVertexBuffer(this.collisionVertexArray,bhs.members,!0),this.collisionVertexBufferExt=p.createVertexBuffer(this.collisionVertexArrayExt,_hs.members,!0)}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy(),this.collisionVertexBuffer.destroy(),this.collisionVertexBufferExt.destroy())}}oa(AOe,"CollisionBuffers");class ele{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=$9(this.zoom,_["text-size"],this.worldview,p.availableImages),this.iconSizeData=$9(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=>z3[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 COe(new Gk(this.layers,{zoom:this.zoom,lut:this.lut},p=>p.startsWith("text")||p.startsWith("symbol"))),this.icon=new COe(new Gk(this.layers,{zoom:this.zoom,lut:this.lut},p=>p.startsWith("icon")||p.startsWith("symbol"))),this.text.uboBinder=new eOe(this.layers[0],this.zoom,this.lut,!0,"",this.maxUniformBufferBindings,this.maxUniformBlockSizeDwords),this.icon.uboBinder=new eOe(this.layers[0],this.zoom,this.lut,!1,"",this.maxUniformBufferBindings,this.maxUniformBlockSizeDwords),this.glyphOffsetArray=new Kh,this.lineVertexArray=new ug,this.symbolInstances=new _c}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 Z=SY[z];Z&&(_[Z.charCodeAt(0)]=!0)}}}calculateEffectiveAppearanceIconSize(p,_,C,M,F,z,H){if(!p.hasLayoutProperty("icon-size"))return H*z;let Z=1;const se=p.getUnevaluatedLayoutProperty("icon-size"),fe=$9(this.zoom,se,this.worldview,F),xe=B3(fe,_);if(fe.kind!=="constant"&&fe.kind!=="camera"||(Z=xe.uSize),fe.kind==="composite"){const{minZoom:be,maxZoom:Te}=fe,De=se.possiblyEvaluate(new Wn(be,{worldview:this.worldview}),M),Ue=se.possiblyEvaluate(new Wn(Te,{worldview:this.worldview}),M),Ye=De.evaluate(C,{},M,F);Z=Ye+(Ue.evaluate(C,{},M,F)-Ye)*xe.uSizeT}return fe.kind==="source"&&(Z=se.possiblyEvaluate(new Wn(this.zoom,{worldview:this.worldview}),M).evaluate(C,{},M,F)),Z*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(Z<0)return;const se=H.placedSymbolArray.get(Z),fe=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,Z,se,fe,xe,be){if(this.symbolInstances.length===0)return;if(be&&this.updateReplacement(H.tileID,be),!this.collisionArrays){if(!H.collisionBoxArray)return;this.deserializeCollisionBoxes(H.collisionBoxArray)}this.placementIdRangeStart===null&&(this.placementIdRangeStart=_.allocateRange(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(),ht=F.pitch>0,ot={collisionRules:{},insertIntoCollisionGrid:!0},yt=F.zoom,Nt=B3(this.iconSizeData,yt),is=B3(this.textSizeData,yt),At=De.paint.get("symbol-z-offset"),$t=De.layout.get("symbol-elevation-reference")==="sea",Jt=!At.isConstant(),ns=Jt?0:At.evaluate(null,{}),Ps=F.elevation,Gs=Kdt(fe),pn=zn=>{if(!zn)return Gs;const Ir=se.get(U6(zn,De.scope));return Ir!==void 0?Ir:(Yo(`global placement: placement-group "${zn}" does not match any placement-group layer; using the layer's implicit group`),Gs)},cn=De.paint.get("placement-priority"),jn=De.paint.get("placement-group"),Vn=!cn.isConstant(),Cs=!jn.isConstant(),Zs=Vn?0:cn.evaluate(null,{}),an=Cs?Gs:pn(jn.evaluate(null,{})),Ln=Vn||Cs,In=Jt||Ln?H.latestFeatureIndex:null;In&&In.loadVTLayers();const qn=In?In.sourceLayerCoder.decode(this.sourceLayerIndex):"",Dn=(zn,Ir,lr)=>{let _r;if(this.elevationType==="road")_r=$t?lr:lr+xOe.getAtTileOffset(H.tileID,new xs(zn.tileAnchorX,zn.tileAnchorY),Ps,null);else{const Ai=this.hdExt?this.hdExt.elevationFeatures[Ir.elevationFeatureIndex]:void 0;_r=$t?lr:lr+xOe.getAtTileOffset(H.tileID,new xs(zn.tileAnchorX,zn.tileAnchorY),Ps,Ai)}if(_r+=Ir.zOffset,!_r)return{x:zn.projectedAnchorX,y:zn.projectedAnchorY,z:zn.projectedAnchorZ,elevated:!1};const[Wa,Ka,oi]=Ye.upVector(H.tileID.canonical,zn.tileAnchorX,zn.tileAnchorY),Fa=Ye.upVectorScale(H.tileID.canonical,F.center.lat,F.worldSize).metersToTile;return{x:zn.projectedAnchorX+Wa*_r*Fa,y:zn.projectedAnchorY+Ka*_r*Fa,z:zn.projectedAnchorZ+oi*_r*Fa,elevated:!0}},ar=(zn,Ir,lr,_r)=>{if(!zn)return;const{x:Wa,y:Ka,z:oi,elevated:Fa}=Dn(zn,Ir,lr),Ai=function(K0,Zh,_l,Hd,mh,Vm,mo,fp,Lp){const gf=[Zh,_l,Hd,1];let qx=!1;Hd||mh.pitch>0?(Ft(gf,gf,K0),fp&&Vm.name!=="globe"&&(qx=Hdt(fp,Zh,_l,Hd,Lp,mh)>.9)):gOe(gf,gf,K0);const Vx=gf[3];return{x:(gf[0]/Vx+1)/2*mh.width,y:(-gf[1]/Vx+1)/2*mh.height,perspectiveRatio:Math.min(.5+mh.getCameraToCenterDistance(Vm)/Vx*.5,1.5),occluded:mo&&gf[2]>Vx||qx}}(M,Wa,Ka,oi,F,Ye,ht||Fa,Z,it);if(Ai.occluded||Ai.perspectiveRatio<=.55)return;const Ni=_r(),Fo=z*Ai.perspectiveRatio,rl=(zn.x1*Ni-zn.padding)*Fo+Ai.x,Bl=(zn.y1*Ni-zn.padding)*Fo+Ai.y,wc=(zn.x2*Ni+zn.padding)*Fo+Ai.x,qm=(zn.y2*Ni+zn.padding)*Fo+Ai.y;rl0||Ir.numVerticalGlyphVertices>0)){Yo("new placement: text-variable-anchor is not supported yet; skipping symbols");continue}if(Ir.numVerticalGlyphVertices>0){Yo("new placement: vertical text-writing-mode is not supported yet; skipping symbols");continue}const lr=this.collisionArrays[zn];if(!lr.iconBox&&!lr.textBox)continue;let _r=!1;for(const Fo of this.activeReplacements)if(!hOe(Fo,fe,IY.Symbol,De.scope)&&!(Fo.min.x>Ir.tileAnchorX||Ir.tileAnchorX>Fo.max.x||Fo.min.y>Ir.tileAnchorY||Ir.tileAnchorY>Fo.max.y)&&(_r=qoe(pOe(Ir.tileAnchorX,Ir.tileAnchorY,H.tileID.canonical,Fo.footprintTileId.canonical),Fo.footprint),_r))break;const Wa={symbolId:{styleLayerId:C,symbolIdOrigin:1,symbolId:Te+zn},variantIdx:0},Ka=In?In.loadFeature({featureIndex:Ir.featureIndex,sourceLayerIndex:this.sourceLayerIndex,bucketIndex:this.index,layoutVertexArrayOffset:0}):null,oi=Ln&&Ka&&In?In.getId(Ka,qn):void 0,Fa=oi!==void 0&&xe[String(oi)]||mms,Ai=Vn&&Ka?cn.evaluate(Ka,Fa):Zs,Ni=Cs&&Ka?pn(jn.evaluate(Ka,Fa)):an;if(p.startSymbolVariantProcessing(Wa,{placementSubgroupOrder:Ni,symbolPlacementPriority:Ai,symbolVariantVisibility:this.placementVariantVisible[zn]?vOe.VARIANT_VISIBLE:vOe.SYMBOL_INVISIBLE,symbolPlacementType:1,styleLayerOrder:fe,symbolDisplayOrder:0},ot),nt&&!_r){const Fo=Jt&&Ka?At.evaluate(Ka,{}):ns;ar(lr.iconBox,Ir,Fo,()=>this.getSymbolInstanceIconSize(Nt,yt,Ir.placedIconSymbolIndex)),ar(lr.textBox,Ir,Fo,()=>this.getSymbolInstanceTextSize(is,Ir,yt,zn))}p.finishVariantProcessing()}}updateReplacement(p,_){if(_.updateTime===this.replacementUpdateTime)return!1;this.replacementUpdateTime=_.updateTime;const C=_.getReplacementRegionsForTile(p.toUnwrapped(),!0);return!Uoe(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",Z=z.get("text-font"),se=z.get("text-field"),fe=z.get("icon-image"),[xe,be]=z.get("icon-size-scale-range"),Te=ta(_.scaleFactor||1,xe,be),[De,Ue]=z.get("text-size-scale-range"),Ye=ta(_.scaleFactor||1,De,Ue),nt=(se.value.kind!=="constant"||se.value.value instanceof yu&&!se.value.value.isEmpty()||se.value.value.toString().length>0)&&(Z.value.kind!=="constant"||Z.value.value.length>0),it=fe.value.kind!=="constant"||!!fe.value.value||Object.keys(fe.parameters).length>0,ht=this.hasAnyAppearanceLayoutProperty("icon-image"),ot=z.get("symbol-sort-key");if(this.features=[],this.featureAppearanceData=new Map,!nt&&!it&&!ht)return;const yt=_.iconDependencies,Nt=_.glyphDependencies,is=_.availableImages,At=new Wn(this.zoom,{worldview:this.worldview,activeFloors:_.activeFloors}),$t=Jt=>{const ns=Jt.id.toString();yt.has(ns)?yt.get(ns).push(Jt):yt.set(ns,[Jt])};for(const Jt of p){const{feature:ns,id:Ps,index:Gs,sourceLayerIndex:pn}=Jt,cn=F._featureFilter.needGeometry,jn=bt(ns,cn);if(!F._featureFilter.filter(At,jn,C))continue;if(cn||(jn.geometry=ut(ns,C,M)),H&&ns.type!==1&&C.z<=5){const Dn=jn.geometry,ar=.98078528056,zn=(Ir,lr)=>ze(CY(Ir.x,Ir.y,C,1),CY(lr.x,lr.y,C,1)){if(!Dn.getLayoutProperty("icon-image"))return;const{iconPrimary:ar,iconSecondary:zn}=this.getCombinedIconVariants(Dn,Zs,jn,C,is,In,Te);ar&&($t(ar),zn&&(this.hasAnySecondaryIcon=!0,$t(zn)))}),Vn){const Dn=Z.evaluate(jn,{},C).join(","),ar=z.get("text-rotation-alignment")==="map"&&z.get("symbol-placement")!=="point";this.allowVerticalPlacement=this.writingModes&&this.writingModes.includes(z3.vertical);for(const zn of Vn.sections)if(zn.image){const Ir=zn.image.getPrimary().scaleSelf(this.pixelRatio*Ye),lr=Ir.id.toString(),_r=yt.get(lr)||[];_r.push(Ir),yt.set(lr,_r)}else{const Ir=de(Vn.toString()),lr=zn.fontStack||Dn,_r=Nt[lr]=Nt[lr]||{};this.calculateGlyphDependencies(zn.text,_r,ar,this.allowVerticalPlacement,Ir)}}}z.get("symbol-placement")==="line"&&(this.features=function(Jt){const ns={},Ps={},Gs=[];let pn=0;function cn(Zs){Gs.push(Jt[Zs]),pn++}function jn(Zs,an,Ln){const In=Ps[Zs];return delete Ps[Zs],Ps[an]=In,Gs[In].geometry[0].pop(),Gs[In].geometry[0]=Gs[In].geometry[0].concat(Ln[0]),In}function Vn(Zs,an,Ln){const In=ns[an];return delete ns[an],ns[Zs]=In,Gs[In].geometry[0].shift(),Gs[In].geometry[0]=Ln[0].concat(Gs[In].geometry[0]),In}function Cs(Zs,an,Ln){const In=Ln?an[0].at(-1):an[0][0];return`${Zs}:${In.x}:${In.y}`}for(let Zs=0;Zs1){cn(Zs);continue}const qn=Cs(In,Ln,!1),Dn=Cs(In,Ln,!0);if(qn in Ps&&Dn in ns&&Ps[qn]!==ns[Dn]){const ar=Vn(qn,Dn,Ln),zn=jn(qn,Dn,Gs[ar].geometry);delete ns[qn],delete Ps[Dn],Ps[Cs(In,Gs[zn].geometry,!0)]=zn,Gs[ar].geometry=null}else qn in Ps?jn(qn,Dn,Ln):Dn in ns?Vn(qn,Dn,Ln):(cn(Zs),ns[qn]=pn-1,Ps[Dn]=pn-1)}return Gs.filter(Zs=>Zs.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((Jt,ns)=>Jt.sortKey-ns.sortKey)}getCombinedIconVariants(p,_,C,M,F,z,H){let Z;if(p.hasLayoutProperty("icon-image")){const se=_.getAppearanceValueAndResolveTokens(p,"icon-image",C,M,F);Z=this.getResolvedImageFromTokens(se)}else{const se=_.getValueAndResolveTokens("icon-image",C,M,F);Z=this.getResolvedImageFromTokens(se)}if(Z){const se=p.hasLayoutProperty("icon-size")?p.getUnevaluatedLayoutProperty("icon-size"):_._unevaluatedLayout._values["icon-size"],fe=$9(this.zoom,se,this.worldview,F),{iconPrimary:xe,iconSecondary:be}=tOe(Z,fe,se,M,this.zoom,z,this.pixelRatio,H,this.worldview,F);return{iconPrimary:xe,iconSecondary:be}}return{iconPrimary:void 0,iconSecondary:void 0}}getCombinedIconPrimary(p,_,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:Z,globalProperties:se,layer:fe,iconScaleFactor:xe,featureState:be,layoutIconOffset:Te,layoutIconSize:De,layoutIconRotate:Ue}=z;if(p.placedIconSymbolIndex<0)return{vertexOffsetDelta:0,hasChanges:!1};if(_.activeAppearanceIndex===C)return{vertexOffsetDelta:p.numIconVertices,hasChanges:!1};const Ye=C>=0?fe.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:ht}=this.getCombinedIconVariants(Ye,fe,M,H,Z,nt,xe);if(!it)return{vertexOffsetDelta:0,hasChanges:!1};const ot=it.toString(),yt=this.iconAtlasPositions&&this.iconAtlasPositions.get(ot);if(yt){const{appearanceIconOffset:Nt,appearanceIconRotate:is}=_dt(Ye,fe,M,H,Te,Ue,De,xe),At=fe.layout.get("icon-anchor").evaluate(M,be,H);let $t=vdt(yt,ht?this.iconAtlasPositions&&this.iconAtlasPositions.get(ht.toString()):void 0,Nt,At);const Jt=yt.sdf,ns=fe.layout.get("icon-text-fit").constantOr("none");ns!=="none"&&_.textShaping&&_.iconTextFitPadding&&_.fontScale&&($t=bdt($t,_.textShaping,ns,_.iconTextFitPadding,Nt,_.fontScale));const Ps=this.calculateEffectiveAppearanceIconSize(Ye,se.zoom,M,H,Z,xe,De),Gs=0,pn=1+(Math.min(J6,Math.round(Ps*rM))<<1),cn=out($t,is,Jt,ns!=="none",xe),jn=this.icon.iconTransitioningVertexArray.length>0;_.isUsingAppearanceIconVertexData||(_.isUsingAppearanceIconVertexData=!0,_.layoutBasedIconVertexData=this.icon.snapshotSymbolVertexData(F,p.numIconVertices),jn&&(_.layoutBasedIconTransitioningVertexData=this.icon.snapshotIconTransitioningVertexData(F,p.numIconVertices)));const Vn=Math.floor(p.numIconVertices/4),Cs=Math.min(cn.length,Vn);let Zs=F;const an=jn?this.icon.iconTransitioningVertexArray.uint16:null;for(let In=0;In0||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 yt=C>=0?Z.appearances[C]:null;if(yt&&_.textShaping){const{appearanceTextOffset:Nt,appearanceTextRotate:is,appearanceTextSize:At}=wdt(yt,Z,M,H,be,De,Te);_.fontScale=Ndt(At,_.textScaleFactor);const $t=yt.getUnevaluatedLayoutProperty("text-size");let Jt=this.textSizeData,ns=nt,Ps=it;yt.hasLayoutProperty("text-size")&&(Jt=$9(this.zoom,$t,this.worldview,ht),ns=this.textSizeData.kind==="composite"?this.textSizeData.minZoom:0,Ps=this.textSizeData.kind==="composite"?this.textSizeData.maxZoom:0);const Gs=_.textShaping.bottom-be[1],pn=_.textShaping.left-be[0],cn=_.textShaping.right-be[0];_.textShaping.top=Nt[1]+(_.textShaping.top-be[1]),_.textShaping.bottom=Nt[1]+Gs,_.textShaping.left=Nt[0]+pn,_.textShaping.right=Nt[0]+cn;const jn=dut(0,_.textShaping,Nt,Z,!1,M,fe,this.allowVerticalPlacement,is),Vn=At&&Jt.kind==="composite"?$t.possiblyEvaluate(new Wn(ns,{}),H).evaluate(M,xe,H):Ue,Cs=At&&Jt.kind==="composite"?$t.possiblyEvaluate(new Wn(Ps,{}),H).evaluate(M,xe,H):Ye,Zs=kdt(yt.name,Jt,At,se,Vn,Cs),an=Array.isArray(Zs)?Zs[1]:At,Ln=0,In=1+(Math.min(J6,Math.round(an*rM))<<1);_.isUsingAppearanceTextVertexData||(_.isUsingAppearanceTextVertexData=!0,_.layoutBasedTextVertexData=this.text.snapshotSymbolVertexData(F,p.numHorizontalGlyphVertices+p.numVerticalGlyphVertices));for(let qn=0;qn0){const se=F[0],fe=[this.text.uboBinder,this.icon.uboBinder].filter(xe=>xe&&xe.hasStateDependentPaint(se));if(fe.length>0){const xe=new Set(Object.keys(p).map(be=>{const Te=Number(be);return!isNaN(Te)&&Number.isSafeInteger(Te)&&String(Te)===be?Te:be}));for(const be of fe)be.updateFeatures(xe,se,_,Z,C,p,H)}}}}updateZOffset(){const p=(F,z,H)=>{C+=z,C>F.length&&F.resize(C);for(let Z=-z;Z<0;Z++)F.emplace(Z+C,H)},_=(F,z,H)=>{M+=z,M>F.length&&F.resize(M);for(let Z=-z;Z<0;Z++)F.emplace(Z+M,H)};if(!this.zOffsetBuffersNeedUpload)return;this.zOffsetBuffersNeedUpload=!1;let C=0,M=0;for(let F=0;F0;if((H>0||Z>0)&&(p(this.text.zOffsetVertexArray,H,fe),p(this.text.zOffsetVertexArray,Z,fe)),xe){const{placedIconSymbolIndex:be,verticalPlacedIconSymbolIndex:Te}=z;be>=0&&_(this.icon.zOffsetVertexArray,se,fe),Te>=0&&_(this.icon.zOffsetVertexArray,z.numVerticalIconVertices,fe)}}this.text.zOffsetVertexBuffer&&this.text.zOffsetVertexBuffer.updateData(this.text.zOffsetVertexArray),this.icon.zOffsetVertexBuffer&&this.icon.zOffsetVertexBuffer.updateData(this.icon.zOffsetVertexArray)}isEmpty(){return this.symbolInstances.length===0&&!this.hasRTLText}uploadPending(){return!this.uploaded||this.text.programConfigurations.needsUpload||this.icon.programConfigurations.needsUpload}upload(p,_,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 Z=_||{},se=this.icon.layoutVertexArray&&this.icon.layoutVertexArray.length>0&&this.icon.layoutVertexArray.arrayBuffer,fe=this.text.layoutVertexArray&&this.text.layoutVertexArray.length>0&&this.text.layoutVertexArray.arrayBuffer;if(!se&&!fe)return H;const xe=this.layers[0],be=xe.layout;this.featureAppearances&&this.featureAppearances.appearancesVersion===xe.appearancesVersion||(this.featureAppearances=new cms(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[is,At]=be.get("icon-size-scale-range");De=ta(1,is,At)}let it=1,ht=0,ot=!1;if(fe){const[is,At]=be.get("text-size-scale-range");it=ta(1,is,At)}const yt=new Map;if(F&&C)for(const is of C){const At=F.getImage(is,xe.scope);if(At){const $t=new Ih(is.toString());yt.set($t.toString(),At)}}const Nt=[this.text.uboBinder,this.icon.uboBinder];for(let is=0;isjn.isActive({globals:M,feature:Ps,canonical:p,featureState:ns})):-1;Gs=cn>=0?cn:-1}const pn=$t.activeAppearanceIndex!==Gs;if(fe){const cn=be.get("text-size"),jn=this.textSizeData.kind==="composite"?this.textSizeData.minZoom:0,Vn=this.textSizeData.kind==="composite"?this.textSizeData.maxZoom:0,Cs={canonical:p,layer:xe,featureState:ns,availableImages:C,textScaleFactor:it,imageMap:yt,layoutTextOffset:be.get("text-offset").evaluate(Ps,ns,p).map(an=>an*B9),layoutTextSize:cn.evaluate(Ps,ns,p),layoutTextRotate:be.get("text-rotate").evaluate(Ps,ns,p),layoutMinZoomSize:cn.evaluate(Ps,{zoom:jn},p),layoutMaxZoomSize:cn.evaluate(Ps,{zoom:Vn},p),layoutTextSizeMinZoom:jn,layoutTextSizeMaxZoom:Vn},Zs=this.updateSymbolInstanceTextVertices(At,$t,Gs,Ps,ht,Cs);ht+=Zs.vertexOffsetDelta,ot=ot||Zs.hasChanges}if(se){const cn={canonical:p,layer:xe,featureState:ns,availableImages:C,globalProperties:M,iconScaleFactor:De,layoutIconOffset:be.get("icon-offset").evaluate(Ps,ns,p),layoutIconSize:be.get("icon-size").evaluate(Ps,ns,p,C),layoutIconRotate:be.get("icon-rotate").evaluate(Ps,ns,p)},jn=this.updateSymbolInstanceIconVertices(At,$t,Gs,Ps,Ue,cn);Ue+=jn.vertexOffsetDelta,Ye=Ye||jn.hasChanges}if(pn){const cn=At.featureIndex,jn=M?M.brightness:null,Vn=ns||{},Cs=Gs>=0?xe.appearances[Gs]:null;for(const Zs of Nt)Zs&&(Zs.layer=xe,nt=Zs.updateFeaturePaintForAppearance(cn,Ps,Vn,p,C,jn,Cs)||nt)}$t.activeAppearanceIndex=Gs}return Ye&&this.icon.layoutVertexBuffer&&this.icon.layoutVertexArray.arrayBuffer!==null&&this.icon.layoutVertexArray.length===this.icon.layoutVertexBuffer.length&&this.icon.layoutVertexBuffer.updateData(this.icon.layoutVertexArray),Ye&&this.icon.iconTransitioningVertexBuffer&&this.icon.iconTransitioningVertexArray.length>0&&this.icon.iconTransitioningVertexArray.length===this.icon.iconTransitioningVertexBuffer.length&&this.icon.iconTransitioningVertexBuffer.updateData(this.icon.iconTransitioningVertexArray),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=Boe(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,Z,se,fe,xe,be,Te,De,Ue,Ye,nt,it){const ht=p.indexArray,ot=p.layoutVertexArray,yt=p.globeExtVertexArray,Nt=it,is=p.uboBinder?p.uboBinder.getCurrentBatchIndex():void 0,At=p.segments.prepareSegment(4*Nt,ot,ht,this.canOverlap?z.sortKey:void 0,is),$t=this.glyphOffsetArray.length,Jt=At.vertexLength,ns=this.allowVerticalPlacement&&H===z3.vertical?Math.PI/2:0,Ps=z.text&&z.text.sections;let Gs=ot.length,pn=-1;for(let Vn=0;Vn<_.length;Vn++){const{tl:Cs,tr:Zs,bl:an,br:Ln,texPrimary:In,texSecondary:qn,pixelOffsetTL:Dn,pixelOffsetBR:ar,minFontScaleX:zn,minFontScaleY:Ir,glyphOffset:lr,isSDF:_r,sectionIndex:Wa}=_[Vn],Ka=At.vertexLength,oi=lr[1];if(OY(ot,se.x,se.y,Cs.x,oi+Cs.y,In.x,In.y,C,_r,Dn.x,Dn.y,zn,Ir),OY(ot,se.x,se.y,Zs.x,oi+Zs.y,In.x+In.w,In.y,C,_r,ar.x,Dn.y,zn,Ir),OY(ot,se.x,se.y,an.x,oi+an.y,In.x,In.y+In.h,C,_r,Dn.x,ar.y,zn,Ir),OY(ot,se.x,se.y,Ln.x,oi+Ln.y,In.x+In.w,In.y+In.h,C,_r,ar.x,ar.y,zn,Ir),Z){const{x:Fa,y:Ai,z:Ni}=Z.anchor,[Fo,rl,Bl]=Z.up;BY(yt,Fa,Ai,Ni,Fo,rl,Bl),BY(yt,Fa,Ai,Ni,Fo,rl,Bl),BY(yt,Fa,Ai,Ni,Fo,rl,Bl),BY(yt,Fa,Ai,Ni,Fo,rl,Bl),eR(p.dynamicLayoutVertexArray,Fa,Ai,Ni,ns)}else eR(p.dynamicLayoutVertexArray,se.x,se.y,se.z,ns);if(Ye){const Fa=qn||In;zY(p.iconTransitioningVertexArray,Fa.x,Fa.y),zY(p.iconTransitioningVertexArray,Fa.x+Fa.w,Fa.y),zY(p.iconTransitioningVertexArray,Fa.x,Fa.y+Fa.h),zY(p.iconTransitioningVertexArray,Fa.x+Fa.w,Fa.y+Fa.h)}if(ht.emplaceBack(Ka,Ka+1,Ka+2),ht.emplaceBack(Ka+1,Ka+2,Ka+3),At.vertexLength+=4,At.primitiveLength+=2,this.glyphOffsetArray.emplaceBack(lr[0]),(Vn===_.length-1||Wa!==_[Vn+1].sectionIndex)&&(p.uboBinder||p.programConfigurations.populatePaintArrays(ot.length,z,z.index,{},Te,De,Ue,Ps&&Ps[Wa],this.worldview),p.uboBinder)){const Fa=p.uboBinder.populateUBO(z,z.index,De,Te,Ue,Ps&&Ps[Wa]);pn=Fa;const Ai=ot.length-Gs;for(let Ni=0;Ni=0)){const Vn=4*cn;for(let Cs=0;Cs=0?p.rightJustifiedTextSymbolIndex:p.centerJustifiedTextSymbolIndex>=0?p.centerJustifiedTextSymbolIndex:p.leftJustifiedTextSymbolIndex>=0?p.leftJustifiedTextSymbolIndex:p.verticalPlacedTextSymbolIndex>=0?p.verticalPlacedTextSymbolIndex:_}getSymbolInstanceTextSize(p,_,C,M){const F=this.defaultPlacedTextSymbolIndex(_,M),z=this.text.placedSymbolArray.get(F),H=Eoe(this.textSizeData,p,z)/B9;return this.tilePixelRatio*H}getSymbolInstanceIconSize(p,_,C){const M=this.icon.placedSymbolArray.get(C),F=Eoe(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 Z=M;Z0}hasIconData(){return this.icon.segments.get().length>0}hasDebugData(){return this.textCollisionBox&&this.iconCollisionBox}hasTextCollisionBoxData(){return this.hasDebugData()&&this.textCollisionBox.segments.get().length>0}hasIconCollisionBoxData(){return this.hasDebugData()&&this.iconCollisionBox.segments.get().length>0}hasIconTextFit(){return this.hasAnyIconTextFit}addIndicesForPlacedSymbol(p,_){const C=p.placedSymbolArray.get(_),M=C.vertexStartIndex+4*C.numGlyphs;for(let F=C.vertexStartIndex;FM[H]-M[Z]||F[Z]-F[H]),z}getSortedIndexesByZOffset(){if(!this.zOffsetSortDirty)return this.symbolInstanceIndexesSortedZOffset;if(!this.symbolInstanceIndexesSortedZOffset){this.symbolInstanceIndexesSortedZOffset=[];for(let p=0;pthis.symbolInstances.get(_).zOffset-this.symbolInstances.get(p).zOffset)}addToSortKeyRanges(p,_){const 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:Z,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),Z>=0&&this.addIndicesForPlacedSymbol(this.icon,Z),se>=0&&this.addIndicesForPlacedSymbol(this.icon,se)}this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray)}}}oa(ele,"SymbolBucket",{omit:["layers","collisionBoxArray","compareText","features"]}),ele.addDynamicAttributes=eR;class uut extends BFe{constructor(p,_,C){super(p,_,C),this.elevatedLayoutVertexArray=new $s}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(uut,"ElevatedFillBufferData");class V3{constructor(){this.portals=[]}static isOnBorder(p,_){return p<=0&&_<=0||p>=Dr&&_>=Dr}static evaluate(p){if(p.length===0)return new V3;let _=[];for(const Z of p)_.push(...Z.portals);if(_.length===0)return new V3;for(const Z of _){const se=Z.va,fe=Z.vb;(V3.isOnBorder(se.x,fe.x)||V3.isOnBorder(se.y,fe.y))&&(Z.type="border")}const C=_.filter(Z=>Z.type!=="unevaluated"),M=_.filter(Z=>Z.type==="unevaluated");if(M.length===0)return new V3;M.sort((Z,se)=>Z.hash===se.hash?Z.isTunnel===se.isTunnel?0:Z.isTunnel?-1:1:Z.hashZ.hashF!=="fill-tunnel-structure-color"),this.tunnelProgramConfigurations=new Gk(_,{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||be.x>=F.min.x&&be.x<=F.max.x&&be.y>=F.min.y&&be.y<=F.max.y||F9(xe,be,H))||this.isOnBorder(xe.x,be.x)||this.isOnBorder(xe.y,be.y))continue;const Te=H1.computeEdgeHash(this.unevalVertices[se],this.unevalVertices[fe]);let De,Ue=this.vertexHashLookup.get(H1.computePosHash(xe));Ue!=null?De=Ue.next:(Ue=this.vertexHashLookup.get(H1.computePosHash(be)),De=Ue!=null?Ue.prev:Te),this.unevalEdges.push({polygonIdx:p,a:se,b:fe,hash:Te,portalHash:De,isTunnel:M,type:"unevaluated",featureInfo:z})}}addPortalCandidates(p,_,C,M,F){if(_.length!==0){this.vertexHashLookup.clear();for(const z of _){if(z.length===0)continue;const H=z[0];let Z=H1.computeEdgeHash(H[H.length-2],H.at(-1));for(let se=0;se({vertexOffset:0,primitiveOffset:this.indexArray.length}),C=be=>{be.primitiveLength=this.indexArray.length-be.primitiveOffset},M=new fms(this.vertexPositions,this.vertexNormals,this.indexArray);this.prepareEdges(p.portals,this.unevalEdges);const F=_(),z=_(),H=_(),Z=(be,Te)=>{be.sort((Ue,Ye)=>Ue.type===Te&&Ye.type!==Te?-1:Ue.type!==Te&&Ye.type===Te?1:0);const De=be.findIndex(Ue=>Ue.type!==Te);return De>=0?De:be.length};let se=0;this.unevalEdges.length>0&&(se=Z(this.unevalEdges,"none"),this.constructBridgeStructures(M,this.unevalVertices,this.unevalHeights,this.unevalEdges,{min:0,max:se},this.tileToMeters)),C(H);const fe=_(),xe=_();if(this.unevalEdges.length>0){const be=this.unevalEdges.splice(se),Te=Z(be,"tunnel")+se;this.unevalEdges.push(...be),this.constructTunnelStructures(M,this.unevalVertices,this.unevalHeights,this.unevalEdges,{min:0,max:se},{min:se,max:Te})}C(fe),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,fe.primitiveOffset,0,fe.primitiveLength),this.shadowCasterSegments=Li.simpleSegment(0,F.primitiveOffset,0,F.primitiveLength)}update(p,_,C,M,F,z,H,Z){this.bridgeProgramConfigurations.updatePaintArrays(p,_,F,C,M,z,H,Z),this.tunnelProgramConfigurations.updatePaintArrays(p,_,F,C,M,z,H,Z)}upload(p){this.vertexBuffer||this.vertexPositions.length===0||this.vertexNormals.length===0||this.indexArray.length===0||(this.vertexBuffer=p.createVertexBuffer(this.vertexPositions,ix.members),this.vertexBufferNormal=p.createVertexBuffer(this.vertexNormals,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,Z)=>{for(let se=0;sehe(cn,_[jn].x,_[jn].y,C[jn]*Z),xe=te(),be=te(),Te=te(),De=te(),Ue=te(),Ye=(cn,jn)=>{const Vn=H.get(H1.computePosHash(_[jn])),Cs=Vn.from,Zs=Vn.to;if(!Cs||!Zs)return;fe(xe,Cs),fe(be,jn),fe(Te,Zs),Ke(De),Je(xe,be)||(pt(Ue,be,xe),Ve(De,Ue)),Je(Te,be)||(pt(Ue,Te,be),ue(De,De,Ve(Ue,Ue)));const an=ss(De);return an>0?Fe(cn,De,1/an):void 0};let nt=Number.POSITIVE_INFINITY;this.sortSubarray(M,F.min,F.max,(cn,jn)=>cn.featureInfo.featureIndex-jn.featureInfo.featureIndex);const it=te(),ht=te(),ot=te(),yt=te(),Nt=te(),is=te(),At=te(),$t=te(),Jt=te(),ns=[te(),te(),te(),te()],Ps=[te(),te(),te(),te()],Gs=[{coord:new xs(0,0),height:0},{coord:new xs(0,0),height:0}],pn=(cn,jn)=>cn>jn;for(let cn=F.min;cnnt.featureInfo.featureIndex-it.featureInfo.featureIndex;this.sortSubarray(M,F.min,F.max,Z),this.sortSubarray(M,z.min,z.max,Z);const se=nt=>Ve(nt,nt),fe=[{coord:new xs(0,0),height:0},{coord:new xs(0,0),height:0}],xe=(nt,it)=>ntH.hash===Z.hash?Z.polygonIdx-H.polygonIdx:Z.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.portalHashfe.hash?H++:fe.hash>se.portalHash?Z++:(se.type=fe.type,H++)}}}isOnBorder(p,_){return p<=0&&_<=0||p>=Dr&&_>=Dr}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(H1.computePosHash(p))<<32n|BigInt(H1.computePosHash(_))}static computePosHash(p){return((65535&p.x)<<16|65535&p.y)>>>0}}class pms{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 hut{constructor(p,_){this.featureFunc=p,this.vertexFunc=_}parseFeature(p,_,C){return this.featureFunc(p,_,C)}parseVertex(p,_,C){return this.vertexFunc(p,_,C)}}const gms=new hut((N,p,_)=>N.reset(p).require(O3,C=>{_.id=C}).optional("fixed_height_relative",C=>{_.constantHeight=C},H3.decodeRelativeHeight).geometry(C=>{_.bounds=C},zd).success(),(N,p,_)=>N.reset(p).require(O3,C=>{_.id=C}).require("elevation_idx",C=>{_.idx=C}).require("extent",C=>{_.extent=C}).require("height_relative",C=>{_.height=C},H3.decodeRelativeHeight).geometry(C=>{_.position=C},H3.getPoint).success()),xms=new hut((N,p,_)=>N.reset(p).require(O3,C=>{_.id=C}).optional("fixed_height",C=>{_.constantHeight=C},H3.decodeMetricHeight).geometry(C=>{_.bounds=C},zd).success(),(N,p,_)=>N.reset(p).require(O3,C=>{_.id=C}).require("elevation_idx",C=>{_.idx=C}).require("extent",C=>{_.extent=C}).require("height",C=>{_.height=C},H3.decodeMetricHeight).geometry(C=>{_.position=C},H3.getPoint).success());class H3{static getPoint(p){return Ut(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"?xms:void 0:gms}static parse(p){const _=[],C=[],M=p.length,F=new pms;for(let z=0;z{return H.a0?Fe(Z,Z,1/se):he(Z,0,0,1)}getSafeArea(){return this.safeArea}isTunnel(){return this.heightRange.max<=-5}getClosestEdge(p){if(this.edges.length===0)return;let _=0,C=Number.POSITIVE_INFINITY,M=0;const[F,z,H,Z,se,fe,xe]=yms;hn(xe,p.x,p.y);const be=new Phs(xe,null);for(let Te=0;Te0?kn(Z,H)/ot:0,Nt=ta(yt,0,1),is=Math.abs((yt-Nt)*this.edgeProps[Te].len);Rs(se,xe,Ye),hn(fe,Ue[1],-Ue[0]);const At=is+Math.abs(kn(se,fe));At=0;--z){const H=this.edges[z].a,Z=this.edges[z].b,{position:se,height:fe,extent:xe}=this.vertices[H],{position:be,height:Te,extent:De}=this.vertices[Z],Ue=this.vertexProps[H].dir,Ye=this.vertexProps[Z].dir;if(he(_,se[0]/p,se[1]/p,fe),he(C,be[0]/p,be[1]/p,Te),he(M,Ue[1],-Ue[0],0),Fe(M,M,xe),he(F,Ye[1],-Ye[0],0),Fe(F,F,De),this.distSqLines(_e(_[0]+.5*M[0],_[1]+.5*M[1],_[2]+.5*M[2]),_e(C[0]-.5*F[0],C[1]-.5*F[1],C[2]-.5*F[2]),_e(_[0]-.5*M[0],_[1]-.5*M[1],_[2]-.5*M[2]),_e(C[0]+.5*F[0],C[1]+.5*F[1],C[2]+.5*F[2]))<=.0025000000000000005)continue;const nt=this.vertices.length,it=hr(Js(),se,be);this.vertices.push({position:jr(it,it,.5),height:.5*(fe+Te),extent:.5*(xe+De),index:.5*((this.vertices[H].index!==void 0?this.vertices[H].index:H)+(this.vertices[Z].index!==void 0?this.vertices[Z].index:Z))});const ht=hr(Js(),Ue,Ye);this.vertexProps.push({dir:$n(ht,ht)}),this.edges.splice(z,1),this.edgeProps.splice(z,1),this.edges.push({a:H,b:nt}),this.edges.push({a:nt,b:Z});const ot=Rs(Js(),this.vertices[nt].position,se),yt=kr(ot),Nt={vec:ot,dir:jr(Js(),ot,1/yt),len:yt};this.edgeProps.push(Nt),this.edgeProps.push(Nt)}}distSqLines(p,_,C,M){const F=ve(te(),_,p),z=ve(te(),M,C),H=ve(te(),p,C),Z=ze(F,F),se=ze(F,z),fe=ze(F,H),xe=ze(z,z),be=ze(z,H),Te=Z*xe-se*se;if(Te===0)return Ne(dt(F,C,M,ze(H,z)/ze(z,z)),p);const De=(Z*be-se*fe)/Te;return Ne(dt(F,p,_,(se*be-fe*xe)/Te),dt(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:tle(F.position),height:F.height,extent:F.extent,index:F.index})),C.vertexProps=p.vertexProps.map(F=>({dir:tle(F.dir)})),C.edges=p.edges.map(F=>({a:F.a,b:F.b})),C.edgeProps=p.edgeProps.map(F=>({vec:tle(F.vec),dir:tle(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 G3(p.id,_,p.constantHeight);if(!p.vertices||p.vertices.length===0){const M=Object.create(G3.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(G3.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:sle(M.position),height:M.height,extent:M.extent,index:M.index})),C.vertexProps=(p.vertexProps||[]).map(M=>({dir:sle(M.dir)})),C.edges=(p.edges||[]).map(M=>({a:M.a,b:M.b})),C.edgeProps=(p.edgeProps||[]).map(M=>({vec:sle(M.vec),dir:sle(M.dir),len:M.len})),C}}class W9{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)*Dr,this.yOffset=(p.y*this.zScale-_.y)*Dr)}pointTransform(p){return Ut(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+_*xc(0,_,p>=0?p:Math.abs(.5*p))}}function vms(N){if(N===0)return[0,0,0];const p=lg(N);return[p(),p(),p()]}function fut(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=fut(_,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 bms(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,Z=this._root;for(;F.length!==0||Z;)if(Z)F.push(Z),Z=Z.left;else{if(Z=F.pop(),H=z(Z.key,_),H>0)break;if(z(Z.key,p)>=0&&C.call(M,Z))return this;Z=Z.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&&MOe(p,_,0,M-1,this._compare),this._root=TOe(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 EOe(C,F).load(p,_,M)}}function TOe(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=TOe(H,p,_,C,z),H.right=TOe(H,p,_,z+1,M),H}return null}function MOe(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 Z=N[z];N[z]=N[H],N[H]=Z,Z=p[z],p[z]=p[H],p[H]=Z}MOe(N,p,_,H,M),MOe(N,p,H+1,C,M)}const put=11102230246251565e-32,Ub=134217729,_ms=(3+8*put)*put;function POe(N,p,_,C,M){let F,z,H,Z,se=p[0],fe=C[0],xe=0,be=0;fe>se==fe>-se?(F=se,se=p[++xe]):(F=fe,fe=C[++be]);let Te=0;if(xese==fe>-se?(z=se+F,H=F-(z-se),se=p[++xe]):(z=fe+F,H=F-(z-fe),fe=C[++be]),F=z,H!==0&&(M[Te++]=H);xese==fe>-se?(z=F+se,Z=z-F,H=F-(z-Z)+(se-Z),se=p[++xe]):(z=F+fe,Z=z-F,H=F-(z-Z)+(fe-Z),fe=C[++be]),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 Y9(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 GC(N,p){return N[0]===p[0]&&N[1]===p[1]}function IOe(N,p,_){const C=function(M,F,z,H,Z,se){const fe=(F-se)*(z-Z),xe=(M-Z)*(H-se),be=fe-xe;if(fe===0||xe===0||fe>0!=xe>0)return be;const Te=Math.abs(fe+xe);return Math.abs(be)>=33306690738754716e-32*Te?be:-function(De,Ue,Ye,nt,it,ht,ot){let yt,Nt,is,At,$t,Jt,ns,Ps,Gs,pn,cn,jn,Vn,Cs,Zs,an,Ln,In;const qn=De-it,Dn=Ye-it,ar=Ue-ht,zn=nt-ht;Cs=qn*zn,Jt=Ub*qn,ns=Jt-(Jt-qn),Ps=qn-ns,Jt=Ub*zn,Gs=Jt-(Jt-zn),pn=zn-Gs,Zs=Ps*pn-(Cs-ns*Gs-Ps*Gs-ns*pn),an=ar*Dn,Jt=Ub*ar,ns=Jt-(Jt-ar),Ps=ar-ns,Jt=Ub*Dn,Gs=Jt-(Jt-Dn),pn=Dn-Gs,Ln=Ps*pn-(an-ns*Gs-Ps*Gs-ns*pn),cn=Zs-Ln,$t=Zs-cn,K9[0]=Zs-(cn+$t)+($t-Ln),jn=Cs+cn,$t=jn-Cs,Vn=Cs-(jn-$t)+(cn-$t),cn=Vn-an,$t=Vn-cn,K9[1]=Vn-(cn+$t)+($t-an),In=jn+cn,$t=In-jn,K9[2]=jn-(In-$t)+(cn-$t),K9[3]=In;let Ir=function(oi,Fa){let Ai=Fa[0];for(let Ni=1;Ni<4;Ni++)Ai+=Fa[Ni];return Ai}(0,K9),lr=22204460492503146e-32*ot;if(Ir>=lr||-Ir>=lr||($t=De-qn,yt=De-(qn+$t)+($t-it),$t=Ye-Dn,is=Ye-(Dn+$t)+($t-it),$t=Ue-ar,Nt=Ue-(ar+$t)+($t-ht),$t=nt-zn,At=nt-(zn+$t)+($t-ht),yt===0&&Nt===0&&is===0&&At===0)||(lr=11093356479670487e-47*ot+_ms*Math.abs(Ir),Ir+=qn*At+zn*yt-(ar*is+Dn*Nt),Ir>=lr||-Ir>=lr))return Ir;Cs=yt*zn,Jt=Ub*yt,ns=Jt-(Jt-yt),Ps=yt-ns,Jt=Ub*zn,Gs=Jt-(Jt-zn),pn=zn-Gs,Zs=Ps*pn-(Cs-ns*Gs-Ps*Gs-ns*pn),an=Nt*Dn,Jt=Ub*Nt,ns=Jt-(Jt-Nt),Ps=Nt-ns,Jt=Ub*Dn,Gs=Jt-(Jt-Dn),pn=Dn-Gs,Ln=Ps*pn-(an-ns*Gs-Ps*Gs-ns*pn),cn=Zs-Ln,$t=Zs-cn,G1[0]=Zs-(cn+$t)+($t-Ln),jn=Cs+cn,$t=jn-Cs,Vn=Cs-(jn-$t)+(cn-$t),cn=Vn-an,$t=Vn-cn,G1[1]=Vn-(cn+$t)+($t-an),In=jn+cn,$t=In-jn,G1[2]=jn-(In-$t)+(cn-$t),G1[3]=In;const _r=POe(4,K9,4,G1,gut);Cs=qn*At,Jt=Ub*qn,ns=Jt-(Jt-qn),Ps=qn-ns,Jt=Ub*At,Gs=Jt-(Jt-At),pn=At-Gs,Zs=Ps*pn-(Cs-ns*Gs-Ps*Gs-ns*pn),an=ar*is,Jt=Ub*ar,ns=Jt-(Jt-ar),Ps=ar-ns,Jt=Ub*is,Gs=Jt-(Jt-is),pn=is-Gs,Ln=Ps*pn-(an-ns*Gs-Ps*Gs-ns*pn),cn=Zs-Ln,$t=Zs-cn,G1[0]=Zs-(cn+$t)+($t-Ln),jn=Cs+cn,$t=jn-Cs,Vn=Cs-(jn-$t)+(cn-$t),cn=Vn-an,$t=Vn-cn,G1[1]=Vn-(cn+$t)+($t-an),In=jn+cn,$t=In-jn,G1[2]=jn-(In-$t)+(cn-$t),G1[3]=In;const Wa=POe(_r,gut,4,G1,xut);Cs=yt*At,Jt=Ub*yt,ns=Jt-(Jt-yt),Ps=yt-ns,Jt=Ub*At,Gs=Jt-(Jt-At),pn=At-Gs,Zs=Ps*pn-(Cs-ns*Gs-Ps*Gs-ns*pn),an=Nt*is,Jt=Ub*Nt,ns=Jt-(Jt-Nt),Ps=Nt-ns,Jt=Ub*is,Gs=Jt-(Jt-is),pn=is-Gs,Ln=Ps*pn-(an-ns*Gs-Ps*Gs-ns*pn),cn=Zs-Ln,$t=Zs-cn,G1[0]=Zs-(cn+$t)+($t-Ln),jn=Cs+cn,$t=jn-Cs,Vn=Cs-(jn-$t)+(cn-$t),cn=Vn-an,$t=Vn-cn,G1[1]=Vn-(cn+$t)+($t-an),In=jn+cn,$t=In-jn,G1[2]=jn-(In-$t)+(cn-$t),G1[3]=In;const Ka=POe(Wa,xut,4,G1,yut);return yut[Ka-1]}(M,F,z,H,Z,se,Te)}(N[0],N[1],p[0],p[1],_[0],_[1]);return C>0?-1:C<0?1:0}function lM(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:IOe(z,M.otherEvent.point,F.otherEvent.point)!==0?M.isBelow(F.otherEvent.point)?-1:1:!M.isSubject&&F.isSubject?1:-1}(N,p,_)}function cM(N,p,_){const C=new Y9(p,!1,N,N.isSubject),M=new Y9(p,!0,N.otherEvent,N.isSubject);return GC(N.point,N.otherEvent.point)&&console.warn("what is that, a collapsed segment?",N),C.contourId=M.contourId=N.contourId,lM(M,N.otherEvent)>0&&(N.otherEvent.left=!0,M.left=!1),N.otherEvent.otherEvent=M,N.otherEvent=C,_.push(M),_.push(C),_}function nle(N,p){return N[0]*p[1]-N[1]*p[0]}function LOe(N,p){return N[0]*p[0]+N[1]*p[1]}function ROe(N,p,_){const C=function(Z,se,fe,xe){const be=[se[0]-Z[0],se[1]-Z[1]],Te=[xe[0]-fe[0],xe[1]-fe[1]];function De(is,At,$t){return[is[0]+At*$t[0],is[1]+At*$t[1]]}const Ue=[fe[0]-Z[0],fe[1]-Z[1]];let Ye=nle(be,Te),nt=Ye*Ye;const it=LOe(be,be);if(nt>0){const is=nle(Ue,Te)/Ye;if(is<0||is>1)return null;const At=nle(Ue,be)/Ye;return At<0||At>1?null:is===0||is===1?[De(Z,is,be)]:At===0||At===1?[De(fe,At,Te)]:[De(Z,is,be)]}if(Ye=nle(Ue,be),nt=Ye*Ye,nt>0)return null;const ht=LOe(be,Ue)/it,ot=ht+LOe(be,Te)/it,yt=Math.min(ht,ot),Nt=Math.max(ht,ot);return yt<=1&&Nt>=0?yt===1?[De(Z,yt>0?yt:0,be)]:Nt===0?[De(Z,Nt<1?Nt:1,be)]:[De(Z,yt>0?yt:0,be),De(Z,Nt<1?Nt:1,be)]:null}(N.point,N.otherEvent.point,p.point,p.otherEvent.point),M=C?C.length:0;if(M===0||M===1&&(GC(N.point,p.point)||GC(N.otherEvent.point,p.otherEvent.point))||M===2&&N.isSubject===p.isSubject)return 0;if(M===1)return!GC(N.point,C[0])&&!GC(N.otherEvent.point,C[0])&&cM(N,C[0],_),!GC(p.point,C[0])&&!GC(p.otherEvent.point,C[0])&&cM(p,C[0],_),1;const F=[];let z=!1,H=!1;return GC(N.point,p.point)?z=!0:lM(N,p)===1?F.push(p,N):F.push(N,p),GC(N.otherEvent.point,p.otherEvent.point)?H=!0:lM(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&&cM(F[1].otherEvent,F[0].point,_),2):H?(cM(F[0],F[1].point,_),3):F[0]!==F[3].otherEvent?(cM(F[0],F[1].point,_),cM(F[1],F[2].point,_),3):(cM(F[0],F[1].point,_),cM(F[3].otherEvent,F[2].point,_),3)}function wms(N,p){if(N===p)return 0;if(IOe(N.point,N.otherEvent.point,p.point)!==0||IOe(N.point,N.otherEvent.point,p.otherEvent.point)!==0)return GC(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 lM(N,p)===1?1:-1}class jms{constructor(){this.points=[],this.holeIds=[],this.holeOf=null,this.depth=null}isExterior(){return this.holeOf==null}}function Nms(N,p,_,C){let M,F=N+1,z=p[N].point;const H=p.length;for(FC;)F--;return F}function kms(N,p,_){const C=new jms;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 but=Math.max,_ut=Math.min;let rle=0;function wut(N,p,_,C,M,F){let z,H,Z,se,fe,xe;for(z=0,H=N.length-1;z0?xe.left=!0:fe.left=!0;const be=Z[0],Te=Z[1];M[0]=_ut(M[0],be),M[1]=_ut(M[1],Te),M[2]=but(M[2],be),M[3]=but(M[3],Te),C.push(fe),C.push(xe)}}const ale=[];function jut(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(be,Te,De){let Ue=null;return be.length*Te.length===0&&(De===0?Ue=ale:De===2?Ue=be:(De===1||De===3)&&(Ue=be.length===0?Te:be)),Ue}(C,M,_);if(F)return F===ale?null:F;const z=[1/0,1/0,-1/0,-1/0],H=[1/0,1/0,-1/0,-1/0],Z=function(be,Te,De,Ue,Ye){const nt=new Xw(void 0,lM);let it,ht,ot,yt,Nt,is;for(ot=0,yt=be.length;otUe[2]||Ue[0]>De[2]||De[1]>Ue[3]||Ue[1]>De[3])&&(Ye===0?nt=ale:Ye===2?nt=be:(Ye===1||Ye===3)&&(nt=be.concat(Te))),nt}(C,M,z,H,_),F)return F===ale?null:F;const se=function(be,Te,De,Ue,Ye,nt){const it=new EOe(wms),ht=[],ot=Math.min(Ue[2],Ye[2]);let yt,Nt,is;for(;be.length!==0;){let At=be.pop();if(ht.push(At),nt===0&&At.point[0]>ot||nt===2&&At.point[0]>Ue[2])break;if(At.left){Nt=yt=it.insert(At),is=it.minNode(),yt=yt!==is?it.prev(yt):null,Nt=it.next(Nt);const $t=yt?yt.key:null;let Jt;if(qY(At,$t,nt),Nt&&ROe(At,Nt.key,be)===2&&(qY(At,$t,nt),qY(Nt.key,At,nt)),yt&&ROe(yt.key,At,be)===2){let ns=yt;ns=ns!==is?it.prev(ns):null,Jt=ns?ns.key:null,qY($t,Jt,nt),qY(At,$t,nt)}}else At=At.otherEvent,Nt=yt=it.find(At),yt&&Nt&&(yt=yt!==is?it.prev(yt):null,Nt=it.next(Nt),it.remove(At),Nt&&yt&&ROe(yt.key,Nt.key,be))}return ht}(Z,0,0,z,H,_),fe=function(be){let Te,De;const Ue=function(it){let ht,ot,yt,Nt,is;const At=[];for(ot=0,yt=it.length;ot{Ye[is]=!0,is=Ue.length)&&Ue[yt];);nt.push(ht)}return nt}(se),xe=[];for(let be=0;be0&&(M=jut(M,F,2)),kut(M,1/65536,.001)}function DOe(N,p=1){return[N.map(_=>_.map(C=>[C.x*p,C.y*p]))]}function Nut(N,p){const _=Math.floor(N)+.5;return Math.abs(N-_)<=p?Math.round(_):Math.round(N)}class Ams{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 Z=-1;Z<=1;Z++){const se=this.buckets.get(M+Z);if(se)for(let fe=-1;fe<=1;fe++){const xe=se.get(F+fe);if(xe){for(const be of xe)if(Math.abs(this.xs[be]-p)<=C&&Math.abs(this.ys[be]-_)<=C){const Te=this.ixs[be],De=this.iys[be];return this.xs[be]===p&&this.ys[be]===_||this.store(p,_,Te,De,M,F),[Te,De]}}}}const z=Nut(p,C),H=Nut(_,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 Z=this.buckets.get(F);Z||(Z=new Map,this.buckets.set(F,Z));let se=Z.get(z);se||(se=[],Z.set(z,se)),se.push(H)}}function kut(N,p=1,_){const C=_!=null?new Ams(_):null;return N.map(M=>M.map((F,z)=>{const H=F.map(Z=>{const se=Z[0]*p,fe=Z[1]*p;if(C){const[xe,be]=C.canonicalize(se,fe);return new xs(xe,be)}return new xs(Math.round(se),Math.round(fe))});return z>0&&H.reverse(),H}))}class FOe{constructor(){this.frcCoverage=new Set,this.featureTriSegments=[],this.frcPerLevel=new Map,this.frcNonRoadSegments=new Li}empty(){return this.frcCoverage.size===0}}function Sut(N,p,_){if(N.frcCoverage.size===0||N.featureTriSegments.length===0)return;const C=_.get(),M=p.uint16,F=[];N.featureTriSegments.sort((xe,be)=>xe.segIdx!==be.segIdx?xe.segIdx-be.segIdx:xe.frc===null&&be.frc===null?0:xe.frc===null?-1:be.frc===null?1:be.frc-xe.frc);const z=new Map;let H=0,Z=N.featureTriSegments[0].frc,se={vertexOffset:C[H].vertexOffset,primitiveOffset:0,vertexLength:C[H].vertexLength,primitiveLength:0,vaos:{},sortKey:void 0};const fe=()=>{se.primitiveLength>0&&(z.has(Z)||z.set(Z,[]),z.get(Z).push({...se}))};for(const xe of N.featureTriSegments){xe.segIdx!==H&&(fe(),H=xe.segIdx,Z=xe.frc,se={vertexOffset:C[H].vertexOffset,primitiveOffset:F.length/3,vertexLength:C[H].vertexLength,primitiveLength:0,vaos:{},sortKey:void 0}),xe.frc!==Z&&(fe(),Z=xe.frc,se={...se,primitiveOffset:F.length/3,primitiveLength:0});for(let be=xe.start;be0?F.length-1:0,frc:M})}buildFrcSegments(p){this.frcData&&!this.frcData.empty()&&Sut(this.frcData,p.bufferData.indexArray,p.bufferData.triangleSegments)}handleFeature(p,_,C,M,F,z){const H=new Array;if(!this.elevationMode)return!1;const Z=$Y(p,F,void 0,M);if(!Z)return!1;{const fe=this.clipPolygonsToTile(_,1);fe.length>0&&H.push({polygons:fe,elevationFeature:Z.feature,elevationTileID:Z.tileId})}const se={guardRailEnabled:z.layers[0].layout.get("fill-construct-bridge-guard-rail").evaluate(p,{},M),featureIndex:C};for(const fe of H)if(fe.elevationFeature){if(this.elevationMode==="hd-road-base"){this.elevatedStructures||(this.elevatedStructures=new H1(fe.elevationTileID,z.layers,z.zoom,z.lut));const be=fe.elevationFeature.isTunnel();let Te=0;Object.hasOwn(p.properties,hdt)&&(Te=+p.properties[hdt]),this.elevatedStructures.addPortalCandidates(fe.elevationFeature.id,fe.polygons,be,fe.elevationFeature,Te)}fe.elevationFeature.constantHeight==null&&(fe.polygons=this.prepareElevatedPolygons(fe.polygons,fe.elevationFeature,fe.elevationTileID));const xe=new W9(M,fe.elevationTileID);this.addElevatedGeometry(z,fe.polygons,xe,fe.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,Z){this.elevationBufferData&&this.elevationBufferData.update(p,_,C,M,F,z,H,Z),this.elevatedStructures&&this.elevatedStructures.update(p,_,C,M,F,z,H,Z)}updateExpressions(p){this.elevationBufferData&&this.elevationBufferData.programConfigurations.updateExpressions(p),this.elevatedStructures&&(this.elevatedStructures.bridgeProgramConfigurations.updateExpressions(p),this.elevatedStructures.tunnelProgramConfigurations.updateExpressions(p))}upload(p){this.elevationBufferData&&this.elevationBufferData.upload(p),this.elevatedStructures&&this.elevatedStructures.upload(p)}destroy(){this.elevationBufferData&&this.elevationBufferData.destroy(),this.elevatedStructures&&this.elevatedStructures.destroy()}getUnevaluatedPortalGraph(){return this.elevatedStructures?this.elevatedStructures.unevaluatedPortals:void 0}setEvaluatedPortalGraph(p,_,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 Z={elevation:M,elevationSampler:C,bias:F,index:z,featureInfo:H},[se,fe]=p.addGeometry(_,this.elevationBufferData,Z,this.elevatedStructures);this.elevationBufferData.heightRange==null?this.elevationBufferData.heightRange={min:se,max:fe}:(this.elevationBufferData.heightRange.min=Math.min(this.elevationBufferData.heightRange.min,se),this.elevationBufferData.heightRange.max=Math.max(this.elevationBufferData.heightRange.max,fe))}prepareElevatedPolygons(p,_,C){const M=1/K(C),F=[];for(const z of p){const H=Cms(z,new mut(_,M),.1);F.push(...H)}return F}clipPolygonsToTile(p,_){const C=-_,M=-_,F=Dr+_,z=Dr+_;let H=0;const Z=[],se=[];for(;H=C&&Te.max.x<=F&&Te.min.y>=M&&Te.max.y<=z?Z:se).push(be)}if(Z.length===p.length)return p;const fe=[new xs(C,M),new xs(F,M),new xs(F,z),new xs(C,z),new xs(C,M)],xe=Z;for(const be of se)xe.push(...Sms(be,fe));return xe}}function Tms(N,p){return N.nextPoint.sub(p.at(-2)).unit()}function Mms(N,p){return p[1].sub(N.prevPoint).unit()}oa(Cut,"FillHDExtension"),oa(H1,"ElevatedStructures");class Aut{constructor(p,_){this.elevationEnabled=p,this.hasDeferredElevationFeatures=!1,_&&(this.frcData=new FOe)}isEmpty(){const p=!this.elevationEnabled||this.heightRange===void 0,_=!this.frcData||this.frcData.empty();return p&&_}trackFeatureFrc(p){if(!this.frcData)return null;const _=ile(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()&&Sut(this.frcData,p.indexArray,p.segments)}handleFeature(p,_,C,M,F,z,H,Z,se,fe,xe){if(!this.elevationEnabled)return!1;if(!xe.terrainEnabled){const Ye=$Y(p,M,F?F.registry:void 0,C),nt=p.properties!=null&&Object.hasOwn(p.properties,O3)&&!Number.isNaN(+p.properties[O3]);if(!Ye&&nt&&z&&(!F||!F.allProvidersReady))return this.hasDeferredElevationFeatures=!0,!0;if(Ye){let it=Ye.feature,ht=Ye.tileId;if(!Ye.tileId.equals(C)){const Nt=this.mergedFeatureCache?this.mergedFeatureCache.get(it.id):void 0;if(Nt)it=Nt,ht=C;else{const is=function(At,$t,Jt){if(!At.properties||!$t||$t.length===0)return[];const ns=+At.properties[O3];if(Number.isNaN(ns))return[];const Ps=fut($t,ns);if(Ps<0)return[];const Gs=[];for(let pn=Ps;pn<$t.length&&$t[pn].feature.id===ns;pn++){const cn=$t[pn];(cn.tileId.isChildOf(Jt)||Jt.isChildOf(cn.tileId)||cn.feature.constantHeight!=null)&&Gs.push(cn)}return Gs}(p,F?F.registry:void 0,C);is.length>1&&(it=function(At,$t){const Jt=$t.slice().sort((Cs,Zs)=>Zs.tileId.z-Cs.tileId.z),ns=new xs(Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY),Ps=new xs(Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY),Gs=[];for(const Cs of Jt){const Zs=new W9(Cs.tileId,At);for(const Ln of Cs.feature.vertices)Gs.push({position:Zs.pointTransform(Ln.position),height:Ln.height,extent:Ln.extent,index:Ln.index});const an=Cs.feature.safeArea;tR[0]=an.min.x,tR[1]=an.min.y,sR[0]=an.max.x,sR[1]=an.max.y,Zs.pointTransformInPlace(tR),Zs.pointTransformInPlace(sR),ns.x=Math.min(ns.x,tR[0],sR[0]),ns.y=Math.min(ns.y,tR[1],sR[1]),Ps.x=Math.max(Ps.x,tR[0],sR[0]),Ps.y=Math.max(Ps.y,tR[1],sR[1])}const pn={min:ns,max:Ps};if(Jt[0].feature.constantHeight!=null)return new G3(Jt[0].feature.id,pn,Jt[0].feature.constantHeight);Gs.sort((Cs,Zs)=>Cs.index-Zs.index);const cn=[];for(const Cs of Gs)cn.length!==0&&cn.at(-1).index===Cs.index||cn.push(Cs);const jn=[];for(let Cs=1;Cs>1,xe.layoutVertexArray.int16[6*Jt+1]>>1),Ps=At.pointElevation(ns,it,.05);this.updateHeightRange(Ps),Jt0?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 W9(C,M);for(const Z of p)ihs(Z,new mut(_,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(Aut,"LineHDExtension");class Eut{constructor(){this.elevatedLayoutVertexArray=new $s,this.hasElevation=!1}beginFeature(p,_,C){const M=$Y(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,uhs.members))}destroy(){this.elevatedLayoutVertexBuffer&&this.elevatedLayoutVertexBuffer.destroy()}}oa(Eut,"CircleHDExtension");const ole=(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 Z=0;Z0||Te>0,nt=De>0,it=se.elevationFeatureIndex,ht=it=0&&ole(p.icon.orientationVertexArray,De,fe,xe),yt>=0&&ole(p.icon.orientationVertexArray,Ue,fe,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,ht,ot){const yt=it.upVector(Ye,nt.x,nt.y);return Fe(yt,yt,Ue*it.upVectorScale(Ye,ht,ot).metersToTile),[yt[0],yt[1],yt[2]]}(De!==null?De:0,M.canonical,Te,H,Z,se)},elevation:z,elevationFeature:null}:{getElevation:F,elevation:z,elevationFeature:xe}}}oa(Tut,"SymbolHDExtension",{omit:["consumerCanonical","elevationParams","crossSourceElevationEnabled","terrainEnabled","hasDeferredElevationFeatures","elevationFeatureIdToIndex"]});let Wk=null,lle=null,zOe=null,cle=null;const Mut=5120,Put=5121,Iut=5122,Lut=5123,Rut=5125,Dut=5126,Z9={[Mut]:Int8Array,[Put]:Uint8Array,[Iut]:Int16Array,[Lut]:Uint16Array,[Rut]:Uint32Array,[Dut]:Float32Array},Pms={[Mut]:"DT_INT8",[Put]:"DT_UINT8",[Iut]:"DT_INT16",[Lut]:"DT_UINT16",[Rut]:"DT_UINT32",[Dut]:"DT_FLOAT32"},X9={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16};function Fut(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 BOe="KHR_draco_mesh_compression";function Ims(N,p){const _=N.extensions&&N.extensions[BOe];if(!_)return;const C=new Wk.Decoder,M=$ut(p,_.bufferView),F=new Wk.Mesh;if(!C.DecodeArrayToMesh(M,M.byteLength,F))throw new Error("Failed to decode Draco mesh");const z=p.json.accessors[N.indices],H=Z9[z.componentType],Z=z.count*H.BYTES_PER_ELEMENT,se=Wk._malloc(Z);H===Uint16Array?C.GetTrianglesUInt16Array(F,Z,se):C.GetTrianglesUInt32Array(F,Z,se),Fut(Wk.memory.buffer.slice(se,se+Z),z,p),Wk._free(se);for(const fe of Object.keys(_.attributes)){const xe=C.GetAttributeByUniqueId(F,_.attributes[fe]),be=p.json.accessors[N.attributes[fe]],Te=Pms[be.componentType],De=be.count*X9[be.type]*Z9[be.componentType].BYTES_PER_ELEMENT,Ue=Wk._malloc(De);C.GetAttributeDataArrayForAllPoints(F,xe,Wk[Te],De,Ue),Fut(Wk.memory.buffer.slice(Ue,Ue+De),be,p),Wk._free(Ue)}C.destroy(),F.destroy(),delete N.extensions[BOe]}const dle="EXT_meshopt_compression";function Lms(N,p){if(!N.extensions||!N.extensions[dle])return;const _=N.extensions[dle],C=new Uint8Array(p.buffers[_.buffer],_.byteOffset||0,_.byteLength||0),M=new Uint8Array(_.count*_.byteStride);zOe.decodeGltfBuffer(M,_.count,_.byteStride,C,_.mode,_.filter),N.buffer=p.buffers.length,N.byteOffset=0,p.buffers[N.buffer]=M.buffer,delete N.extensions[dle]}const Out=1179937895,zut=new TextDecoder("utf8");function But(N,p){return new URL(N,p).href}async function Rms(N,p,_,C,M){const F=await fetch(But(N.uri,C),{signal:M}),z=await F.arrayBuffer();p.buffers[_]=z}function $ut(N,p){const _=N.json.bufferViews[p];return new Uint8Array(N.buffers[_.buffer],_.byteOffset||0,_.byteLength)}async function Dms(N,p,_,C,M){if(N.uri){const F=But(N.uri,C),z=await fetch(F,{signal:M}),H=await z.blob(),Z=await createImageBitmap(H);p.images[_]=Z}else if(N.bufferView!==void 0){const F=$ut(p,N.bufferView),z=new Blob([F],{type:N.mimeType}),H=await createImageBitmap(z);p.images[_]=H}}async function Uut(N,p=0,_,C){const M={json:null,images:[],buffers:[]};if(new Uint32Array(N,p,1)[0]===Out){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(zut.decode(Te.subarray(De,De+Ye))),De+=Ye,De>>0,Math.ceil(1.2*ht)),yt=Math.ceil((ot-ht)/65536);try{return Ue.grow(yt),Ye(),!0}catch{return!1}},b:nt}}).then(it=>{const{Rb:ht,Qb:ot,P:yt,T:Nt,X:is,Ja:At,La:$t,Qa:Jt,Va:ns,Wa:Ps,eb:Gs,jb:pn,f:cn,e:jn,yb:Vn,zb:Cs,Ab:Zs,Bb:an,Db:Ln,Gb:In}=it.instance.exports;Ue=jn;const qn=(()=>{let Dn=0,ar=0,zn=0,Ir=0;return lr=>{zn&&(ht(Ir),ht(Dn),ar+=zn,zn=Dn=0),Dn||(ar+=128,Dn=ot(ar));const _r=lr.length+7&-8;let Wa=Dn;_r>=ar&&(zn=_r,Wa=Ir=ot(_r));for(let Ka=0;Ka{Wk=Te,lle=null})),lle}()),be&&fe.push(function(){var Te;if(!zOe)return cle!=null||(cle=(Te=fetch(ct()),WebAssembly.instantiateStreaming(Te,{}).then(De=>{const{sbrk:Ue,memory:Ye,meshopt_decodeVertexBuffer:nt,meshopt_decodeIndexBuffer:it,meshopt_decodeIndexSequence:ht,meshopt_decodeFilterOct:ot,meshopt_decodeFilterQuat:yt,meshopt_decodeFilterExp:Nt}=De.instance.exports,is={ATTRIBUTES:nt,TRIANGLES:it,INDICES:ht},At={OCTAHEDRAL:ot,QUATERNION:yt,EXPONENTIAL:Nt};return De.instance.exports.__wasm_call_ctors(),{decodeGltfBuffer($t,Jt,ns,Ps,Gs,pn){const cn=Jt+3&-4,jn=Ue(cn*ns),Vn=Ue(Ps.length),Cs=new Uint8Array(Ye.buffer);Cs.set(Ps,Vn);const Zs=is[Gs](jn,Jt,ns,Vn,Ps.length);if(Zs===0&&At[pn]&&At[pn](jn,cn,ns),$t.set(Cs.subarray(jn,jn+Jt*ns)),Ue(jn-Ue(0)),Zs!==0)throw new Error(`Malformed buffer data: ${Zs}`)}}})).then(De=>{zOe=De,cle=null})),cle}()),z)for(let Te=0;Texe.cellIdx-be.cellIdx||xe.triIdx-be.triIdx);let fe=0;for(;fethis.max.x||this.min.x>p.x||p.y>this.max.y||this.min.y>p.y)return;const C=WC(p.x-this.min.x,this.xScale,this.cellsX),M=WC(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=WC(p.x-this.min.x,this.xScale,this.cellsX),F=WC(_.x-this.min.x,this.xScale,this.cellsX),z=WC(p.y-this.min.y,this.yScale,this.cellsY),H=WC(_.y-this.min.y,this.yScale,this.cellsY);for(let Z=z;Z<=H;Z++)for(let se=M;se<=F;se++){const fe=this.cells[Z*this.cellsX+se];if(fe)for(let xe=0;xe0){const F=function(z,H){const Z=H.worldSize,se=Jd(1,0)*Z*T(H.center.lat,H.zoom)/cOe(Z),fe=Jd(1,H.center.lat)*Z,xe=w([]);D(xe,xe,Xr(H.center.lng)),R(xe,xe,Xr(H.center.lat)),I(xe,xe,[0,0,pf]),P(xe,xe,[se,se,se*fe]);const be=H.point;return I(xe,xe,[-be.x,-be.y,0]),E(xe,xe,z),E(xe,H.globeMatrix,xe)}(N,p);return function(z,H,Z){const se=(De,Ue,Ye)=>{const nt=ce(De),it=ce(Ue),ht=U3(De,Ue,Ye);return Fe(ht,ht,1/ce(ht)*ya(nt,it,Ye))},fe=se([z[0],z[1],z[2]],[H[0],H[1],H[2]],Z),xe=se([z[4],z[5],z[6]],[H[4],H[5],H[6]],Z),be=se([z[8],z[9],z[10]],[H[8],H[9],H[10]],Z),Te=U3([z[12],z[13],z[14]],[H[12],H[13],H[14]],Z);return[fe[0],fe[1],fe[2],0,xe[0],xe[1],xe[2],0,be[0],be[1],be[2],0,Te[0],Te[1],Te[2],1]}(M,F,C)}return M}function UOe(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])&&(fe=Te)}xe=fe}while(xe!==se);return Z.length>0&&Z.push(Z[0]),Z}(M);if(qFe(N,z))return F}const nR=64,qOe=["","wall","door","roof","window","lamp","logo"],Gms=[1,1,1];function fle(N,p,_,C,M,F,z,H,Z,se=!1){const fe=_.zoom,xe=_.project(C),be=T(C.lat,fe),Te=1/be;w(N),I(N,N,[xe.x+z[0]*Te,xe.y+z[1]*Te,z[2]]);let De=1,Ue=1;const Ye=_.worldSize;if(se){if(_.projection.name==="mercator"){let ot=0;_.elevation&&(ot=_.elevation.getAtPointOrZero(new Q(xe.x/Ye,xe.y/Ye),0));const yt=Ft([],[xe.x,xe.y,ot,1],_.projMatrix)[3]/_.cameraToCenterDistance;De=yt,Ue=yt*T(_.center.lat,fe)}else if(_.projection.name==="globe"){const ot=mle(N,_),yt=[0,0,0,1];Ft(yt,yt,E([],_.projMatrix,ot));const Nt=yt[3]/_.cameraToCenterDistance,is=q3(fe),At=_.projection.pixelsPerMeter(C.lat,Ye)*T(C.lat,fe),$t=_.projection.pixelsPerMeter(_.center.lat,Ye)*T(_.center.lat,fe);De=Nt/ya(At,k(_.center.lat),is),Ue=Nt*be/At,De*=$t,Ue*=$t}}else De=Te;P(N,N,[De,De,Ue]);const nt=[...N],it=p.orientation,ht=[];if(Wut(ht,[it[0]+(M?M[0]:0),it[1]+(M?M[1]:0),it[2]+(M?M[2]:0)],F),E(N,nt,ht),H&&_.elevation){let ot=0;const yt=[];if(Z&&_.elevation){ot=function(is,At,$t,Jt,ns){const Ps=At.elevation;if(!Ps)return 0;const Gs=du.projectAabbCorners($t,Jt),pn=Jd(1,ns.lat)*At.worldSize,cn=function(zn,Ir){const lr=[0,0,1],_r=[{corners:[0,1,3,2],dotProductWithUp:0},{corners:[1,5,2,6],dotProductWithUp:0},{corners:[0,4,1,5],dotProductWithUp:0},{corners:[2,6,3,7],dotProductWithUp:0},{corners:[4,7,5,6],dotProductWithUp:0},{corners:[0,3,4,7],dotProductWithUp:0}];for(const Wa of _r){const Ka=zn[Wa.corners[0]],oi=zn[Wa.corners[1]],Fa=zn[Wa.corners[2]],Ai=[oi[0]-Ka[0],oi[1]-Ka[1],Ir*(oi[2]-Ka[2])],Ni=qe(Ai,Ai,[Fa[0]-Ka[0],Fa[1]-Ka[1],Ir*(Fa[2]-Ka[2])]);Ve(Ni,Ni),Wa.dotProductWithUp=ze(Ni,lr)}return _r.sort((Wa,Ka)=>Wa.dotProductWithUp-Ka.dotProductWithUp),_r[0].corners}(Gs,pn),jn=Gs[cn[0]],Vn=Gs[cn[1]],Cs=Gs[cn[2]],Zs=Gs[cn[3]],an=Ps.getAtPointOrZero(new Q(jn[0]/At.worldSize,jn[1]/At.worldSize),0),Ln=Ps.getAtPointOrZero(new Q(Vn[0]/At.worldSize,Vn[1]/At.worldSize),0),In=Ps.getAtPointOrZero(new Q(Cs[0]/At.worldSize,Cs[1]/At.worldSize),0),qn=Ps.getAtPointOrZero(new Q(Zs[0]/At.worldSize,Zs[1]/At.worldSize),0),Dn=(an+qn)/2,ar=(Ln+In)/2;return Dn>ar?Ln=p.gl.NEAREST_MIPMAP_NEAREST}),N.uploaded=!0,N.image=null)}function Yut(N,p,_){N.indexBuffer=p.createIndexBuffer(N.indexArray,!1,!0),N.vertexBuffer=p.createVertexBuffer(N.vertexArray,Fms.members,!1,!0),N.normalArray&&(N.normalBuffer=p.createVertexBuffer(N.normalArray,Ums.members,!1,!0)),N.texcoordArray&&(N.texcoordBuffer=p.createVertexBuffer(N.texcoordArray,(N.texcoordArray.bytesPerElement===8?Bms:$ms).members,!1,!0)),N.colorArray&&(N.colorBuffer=p.createVertexBuffer(N.colorArray,(N.colorArray.bytesPerElement===12?Oms:zms).members,!1,!0)),N.featureArray&&(N.featureBuffer=p.createVertexBuffer(N.featureArray,Vms.members,!1,!0)),N.segments=Li.simpleSegment(0,0,N.vertexArray.length,N.indexArray.length);const C=N.material;C.pbrMetallicRoughness.baseColorTexture&&HY(C.pbrMetallicRoughness.baseColorTexture,p),C.pbrMetallicRoughness.metallicRoughnessTexture&&HY(C.pbrMetallicRoughness.metallicRoughnessTexture,p),C.normalTexture&&HY(C.normalTexture,p),C.occlusionTexture&&HY(C.occlusionTexture,p,_),C.emissionTexture&&HY(C.emissionTexture,p)}function VOe(N,p,_){if(N.meshes)for(const C of N.meshes)Yut(C,p,_);if(N.lodMeshes)for(const C of N.lodMeshes)Yut(C,p,_);if(N.children)for(const C of N.children)VOe(C,p,_)}function Zut(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 ple(N){if(N.meshes)for(const p of N.meshes)Zut(p);if(N.lodMeshes)for(const p of N.lodMeshes)Zut(p);if(N.children)for(const p of N.children)ple(p)}function Xut(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 HOe(N){if(N.meshes)for(const p of N.meshes)Xut(p);if(N.lodMeshes)for(const p of N.lodMeshes)Xut(p);if(N.footprintDebugMesh&&(N.footprintDebugMesh.vertexBuffer.destroy(),N.footprintDebugMesh.indexBuffer.destroy(),N.footprintDebugMesh.segments.destroy()),N.children)for(const p of N.children)HOe(p)}function GOe(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 Wms(N,p,_,C,M,F,z,H,Z,se,fe){const xe=.5*(se[0]+fe[0]),be=.5*(se[1]+fe[1]),Te=.5*(se[2]+fe[2]),De=.5*(fe[0]-se[0]),Ue=.5*(fe[1]-se[1]),Ye=.5*(fe[2]-se[2]),nt=N-xe,it=p-be,ht=_-Te,ot=C-xe,yt=M-be,Nt=F-Te,is=z-xe,At=H-be,$t=Z-Te,Jt=ot-nt,ns=yt-it,Ps=Nt-ht,Gs=is-ot,pn=At-yt,cn=$t-Nt,jn=nt-is,Vn=it-At,Cs=ht-$t;let Zs,an,Ln,In,qn,Dn;if(Zs=ht*ns-it*Ps,an=Nt*ns-yt*Ps,Ln=$t*ns-At*Ps,In=Math.min(Zs,an,Ln),qn=Math.max(Zs,an,Ln),Dn=Math.abs(Ps)*Ue+Math.abs(ns)*Ye,In>Dn||qn<-Dn||(Zs=ht*pn-it*cn,an=Nt*pn-yt*cn,Ln=$t*pn-At*cn,In=Math.min(Zs,an,Ln),qn=Math.max(Zs,an,Ln),Dn=Math.abs(cn)*Ue+Math.abs(pn)*Ye,In>Dn||qn<-Dn)||(Zs=ht*Vn-it*Cs,an=Nt*Vn-yt*Cs,Ln=$t*Vn-At*Cs,In=Math.min(Zs,an,Ln),qn=Math.max(Zs,an,Ln),Dn=Math.abs(Cs)*Ue+Math.abs(Vn)*Ye,In>Dn||qn<-Dn)||(Zs=nt*Ps-ht*Jt,an=ot*Ps-Nt*Jt,Ln=is*Ps-$t*Jt,In=Math.min(Zs,an,Ln),qn=Math.max(Zs,an,Ln),Dn=Math.abs(Ps)*De+Math.abs(Jt)*Ye,In>Dn||qn<-Dn)||(Zs=nt*cn-ht*Gs,an=ot*cn-Nt*Gs,Ln=is*cn-$t*Gs,In=Math.min(Zs,an,Ln),qn=Math.max(Zs,an,Ln),Dn=Math.abs(cn)*De+Math.abs(Gs)*Ye,In>Dn||qn<-Dn)||(Zs=nt*Cs-ht*jn,an=ot*Cs-Nt*jn,Ln=is*Cs-$t*jn,In=Math.min(Zs,an,Ln),qn=Math.max(Zs,an,Ln),Dn=Math.abs(Cs)*De+Math.abs(jn)*Ye,In>Dn||qn<-Dn)||(Zs=it*Jt-nt*ns,an=yt*Jt-ot*ns,Ln=At*Jt-is*ns,In=Math.min(Zs,an,Ln),qn=Math.max(Zs,an,Ln),Dn=Math.abs(ns)*De+Math.abs(Jt)*Ue,In>Dn||qn<-Dn)||(Zs=it*Gs-nt*pn,an=yt*Gs-ot*pn,Ln=At*Gs-is*pn,In=Math.min(Zs,an,Ln),qn=Math.max(Zs,an,Ln),Dn=Math.abs(pn)*De+Math.abs(Gs)*Ue,In>Dn||qn<-Dn)||(Zs=it*jn-nt*Vn,an=yt*jn-ot*Vn,Ln=At*jn-is*Vn,In=Math.min(Zs,an,Ln),qn=Math.max(Zs,an,Ln),Dn=Math.abs(Vn)*De+Math.abs(jn)*Ue,In>Dn||qn<-Dn)||(In=Math.min(nt,ot,is),qn=Math.max(nt,ot,is),In>De||qn<-De)||(In=Math.min(it,yt,At),qn=Math.max(it,yt,At),In>Ue||qn<-Ue)||(In=Math.min(ht,Nt,$t),qn=Math.max(ht,Nt,$t),In>Ye||qn<-Ye))return!1;const ar=ns*cn-Ps*pn,zn=Ps*Gs-Jt*cn,Ir=Jt*pn-ns*Gs,lr=-(ar*nt+zn*it+Ir*ht);return Dn=De*Math.abs(ar)+Ue*Math.abs(zn)+Ye*Math.abs(Ir),!(Math.abs(lr)>Dn)}const Kms=[];class Qut{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 Z=0;for(let fe=0;fe0;){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 Jut(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 Q9(N,p){const _=N.json.bufferViews[p.bufferView],C=Z9[p.componentType];return new C(N.buffers[_.buffer],(p.byteOffset||0)+(_.byteOffset||0),p.count*(_.byteStride&&_.byteStride!==X9[p.type]*C.BYTES_PER_ELEMENT?_.byteStride/C.BYTES_PER_ELEMENT:X9[p.type]))}function eht(N,p,_,C){const M=Q9(N,p),F=M instanceof Float32Array?M:new Uint32Array(M.buffer,M.byteOffset,p.count),z=new si;z.reserveExact(p.count);let H=-1;for(let Z=0;Z>>16|F[Z]<<16:F[Z],fe=65535&se,xe=se>>>16;H=H<0&&(15&xe)==2?fe:H,z.emplaceBack(fe,xe)}C.featureArray=z,H>=0&&(C.doorVertexColor=H)}function WOe(N,p,_,C,M=!0){const F=Z9[p.componentType],z=X9[p.type],H=M?Jut(F):1,Z=N.json.bufferViews[p.bufferView],se=Z.byteStride?Z.byteStride/F.BYTES_PER_ELEMENT:z,fe=p.count*se;for(let xe=0,be=0;xe0){const it=p.json.accessors[M.TEXCOORD_0],ht=Q9(p,it);it.normalized&&Z9[it.componentType]===Uint16Array?(F.texcoordArray=new si,F.texcoordArray.resizeExact(it.count),WOe(p,it,F.texcoordArray.uint16,ht,!1)):(F.texcoordArray=new Ko,F.texcoordArray.resizeExact(it.count),WOe(p,it,F.texcoordArray.float32,ht))}const Ye=!(!p.json.extensionsUsed||!p.json.extensionsUsed.includes("EXT_meshopt_compression"));M._FEATURE_ID_RGBA4444!==void 0&&Ye&&eht(p,p.json.accessors[M._FEATURE_ID_RGBA4444],!1,F),M._FEATURE_RGBA4444!==void 0&&eht(p,p.json.accessors[M._FEATURE_RGBA4444],!Ye,F),F.hasFeatureData=!!F.featureArray;const nt=N.material;return F.material=function(it,ht){const{emissiveFactor:ot=[0,0,0],alphaMode:yt="OPAQUE",alphaCutoff:Nt=.5,normalTexture:is,occlusionTexture:At,emissiveTexture:$t,doubleSided:Jt,name:ns}=it,{baseColorFactor:Ps=[1,1,1,1],metallicFactor:Gs=1,roughnessFactor:pn=1,baseColorTexture:cn,metallicRoughnessTexture:jn}=it.pbrMetallicRoughness||{},Vn=At?ht[At.index]:void 0;if(At&&At.extensions&&At.extensions.KHR_texture_transform&&Vn){const Cs=At.extensions.KHR_texture_transform;Vn.offsetScale=[Cs.offset[0],Cs.offset[1],Cs.scale[0],Cs.scale[1]]}return{name:ns,pbrMetallicRoughness:{baseColorFactor:new Ci(...Ps),metallicFactor:Gs,roughnessFactor:pn,baseColorTexture:cn?ht[cn.index]:void 0,metallicRoughnessTexture:jn?ht[jn.index]:void 0},doubleSided:Jt,emissiveFactor:new Ci(...ot),alphaMode:yt,alphaCutoff:Nt,normalTexture:is?ht[is.index]:void 0,occlusionTexture:Vn,emissionTexture:$t?ht[$t.index]:void 0,defined:it.defined===void 0}}(nt!==void 0?p.json.materials[nt]:{defined:!1},_),F}function KOe(N,p,_){const{matrix:C,rotation:M,translation:F,scale:z,mesh:H,extras:Z,children:se,name:fe}=N,xe={};if(xe.name=fe,xe.localMatrix=C||function(be,Te,De,Ue){var Ye=Te[0],nt=Te[1],it=Te[2],ht=Te[3],ot=Ye+Ye,yt=nt+nt,Nt=it+it,is=Ye*ot,At=Ye*yt,$t=Ye*Nt,Jt=nt*yt,ns=nt*Nt,Ps=it*Nt,Gs=ht*ot,pn=ht*yt,cn=ht*Nt,jn=Ue[0],Vn=Ue[1],Cs=Ue[2];return be[0]=(1-(Jt+Ps))*jn,be[1]=(At+cn)*jn,be[2]=($t-pn)*jn,be[3]=0,be[4]=(At-cn)*Vn,be[5]=(1-(is+Ps))*Vn,be[6]=(ns+Gs)*Vn,be[7]=0,be[8]=($t+pn)*Cs,be[9]=(ns-Gs)*Cs,be[10]=(1-(is+Jt))*Cs,be[11]=0,be[12]=De[0],be[13]=De[1],be[14]=De[2],be[15]=1,be}([],M||[0,0,0,1],F||[0,0,0],z||[1,1,1]),xe.globalMatrix=v(xe.localMatrix),H!==void 0){xe.meshes=_[H];const be=xe.anchor=[0,0];for(const Te of xe.meshes){const{min:De,max:Ue}=Te.aabb;be[0]+=De[0]+Ue[0],be[1]+=De[1]+Ue[1]}be[0]=Math.floor(be[0]/xe.meshes.length/2),be[1]=Math.floor(be[1]/xe.meshes.length/2)}if(Z&&(Z.id&&(xe.id=Z.id),Z.lights&&(xe.lights=function(be){if(!be.length)return[];const Te=function(it){const ht=atob(it),ot=new Uint8Array(ht.length);for(let yt=0;yt=ht.length||Ye>=ht.length||nt>=ht.length||it>=ht.length)return null;const ot=ht[Ue],yt=ht[Ye],Nt=ht[nt],is=ht[it];if(ot.bufferView===void 0||yt.bufferView===void 0||Nt.bufferView===void 0||is.bufferView===void 0)return null;const At=be.json.bufferViews;if(ot.bufferView>=At.length||yt.bufferView>=At.length||Nt.bufferView>=At.length||is.bufferView>=At.length)return null;const $t=At[ot.bufferView],Jt=At[yt.bufferView],ns=At[Nt.bufferView],Ps=At[is.bufferView];if($t.buffer>=be.buffers.length||Jt.buffer>=be.buffers.length||ns.buffer>=be.buffers.length||Ps.buffer>=be.buffers.length)return null;const Gs=(qn,Dn,ar)=>qn>=0&&qn<=ar&&Dn<=ar-qn,pn=ot.byteOffset||0,cn=yt.byteOffset||0,jn=Nt.byteOffset||0,Vn=is.byteOffset||0;if(!(Gs(pn,0,$t.byteLength)&&Gs(cn,3*yt.count*4,Jt.byteLength)&&Gs(jn,3*Nt.count*4,ns.byteLength)&&Gs(Vn,4*is.count,Ps.byteLength)))return null;const Cs=new Uint8Array(be.buffers[$t.buffer],($t.byteOffset||0)+pn,$t.byteLength-pn),Zs=new Float32Array(be.buffers[Jt.buffer],(Jt.byteOffset||0)+cn,3*yt.count),an=new Float32Array(be.buffers[ns.buffer],(ns.byteOffset||0)+jn,3*Nt.count),Ln=new Uint32Array(be.buffers[Ps.buffer],(Ps.byteOffset||0)+Vn,is.count),In=new Qut;if(In.serializeFromGltf(Cs,Zs,an,Ln),De!==void 0&&be.json.meshes&&be.json.meshes[De]){const qn=be.json.meshes[De].primitives[0];if(qn&&qn.attributes.POSITION!==void 0&&qn.attributes.POSITION1&&C.at(-1).equals(C[0])&&C.pop();let M=0;for(let z=0;z0&&C.reverse();const F=XT(C.flatMap(z=>[z.x,z.y]),[]);return F.length===0?null:{vertices:C,indices:F}}function Qms(N,p){const _=[],C=[];let M=0;const F=[];for(const z of N){M=_.length;const H=z.vertexArray.float32,Z=z.indexArray.uint16;for(let se=0;se0&&([C[z+1],C[z+2]]=[C[z+2],C[z+1]])}return{vertices:_,indices:C}}function tht(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--)fe.splice(Ue[Ye],1)}})(Z,H,N.json.nodes);const se=C?tht(C,"LOD"):-1;if(se>=0){const fe=C[se].nodes,xe=new Map;for(const be of fe){const Te=KOe(F[be],N,_);Te.id&&xe.set(Te.id,Te)}for(const be of Z)if(be.id){const Te=xe.get(be.id);Te&&Te.meshes&&(be.lodMeshes=Te.meshes,Te.meshBVH&&(be.meshBVH=Te.meshBVH))}}return Z}function Jms(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=nR/(N.aabb.max[0]-_+2),F=nR/(N.aabb.max[1]-C+2);for(let z=0;zN.heightmap[se*nR+Z]&&(N.heightmap[se*nR+Z]=H)}}function sht(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,Z=[-z.normal[1],z.normal[0],0],se=Math.min(.29,.1*z.width/z.depth),fe=z.width-2*z.depth*p*(se+.01),xe=ke([],z.pos,Z,fe/2),be=ke([],z.pos,Z,-fe/2),Te=[xe[0],xe[1],xe[2]+z.height],De=[be[0],be[1],be[2]+z.height],Ue=ke([],z.normal,Z,se);Fe(Ue,Ue,H);const Ye=ke([],z.normal,Z,-se);Fe(Ye,Ye,H),ue(Ue,xe,Ue),ue(Ye,be,Ye),xe[2]+=.1,be[2]+=.1,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(be[0],be[1],be[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(be[0],be[1],be[2]),C.emplaceBack(Ue[0],Ue[1],Ue[2]),C.emplaceBack(Ye[0],Ye[1],Ye[2]);const nt=fe/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 efs(N,p,_){const C={};C.indexArray=new qr,C.vertexArray=new On,C.colorArray=new Hr,C.indexArray.reserveExact(4*N.length),C.vertexArray.reserveExact(10*N.length),C.colorArray.reserveExact(10*N.length),sht(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,Z+(xe-H)/(se-H)*(fe-Z)))}:(z,H,Z,se,fe,xe)=>{z.push(new xs(H+(xe-Z)/(fe-Z)*(se-H),xe))};for(const z of N){const H=[];for(const Z of z){if(Z.length<=2)continue;const se=[];for(let be=0;bep&&F(se,Te,De,Ue,Ye,p):nt>_?it<_&&F(se,Te,De,Ue,Ye,_):se.push(Z[be]),it=p&&F(se,Te,De,Ue,Ye,p),it>_&&nt<=_&&F(se,Te,De,Ue,Ye,_)}let fe=Z.at(-1);const xe=C===0?fe.x:fe.y;xe>=p&&xe<=_&&se.push(fe),se.length&&(fe=se.at(-1),se[0].x===fe.x&&se[0].y===fe.y||se.push(se[0]),H.push(se))}H.length&&M.push(H)}return M}const ZOe=[new xs(0,0),new xs(Dr,0),new xs(Dr,Dr),new xs(0,Dr)];function aht(N,p){const _=[];let C=[];if(!p||N.length<2)return[N];if(N.length===2)return F9(N[0],N[1],ZOe)?[N]:[];for(let M=0;M0&&(C.length>1&&_.push(C),C=[])}return C.length>1&&_.push(C),_}const XOe=tM.types,gfs=["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"],xfs=["fill-extrusion-flood-light-ground-radius"],yfs=Math.pow(2,13),vfs=Math.pow(2,15)-1,xle=new xs(0,1),W3=2147483648,yle=1073741824;function GY(N,p,_,C,M,F,z,H){N.emplaceBack((p<<1)+z,(_<<1)+F,(Math.floor(C*yfs)<<1)+M,Math.round(H))}function WY(N,p,_){N.emplaceBack(p.x*Dr,p.y*Dr,_?1:0)}function vle(N,p,_,C,M,F){N.emplaceBack(p.x,p.y,(_.x<<1)+C,(_.y<<1)+M,F)}function KY(N,p,_){N.emplaceBack(p.x,p.y,p.z,_[0]*16384,_[1]*16384,_[2]*16384)}class iht{constructor(){this.vertexOffset=0,this.vertexCount=0,this.indexOffset=0,this.indexCount=0}}class ble{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===Dr)&&_.x===C.x)!=((_.y===0||_.y===Dr)&&_.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>Dr!=p.x>Dr&&this.addBorderIntersection(1,ya(_.y,p.y,(Dr-_.x)/(p.x-_.x))),_.y<0!=p.y<0&&this.addBorderIntersection(2,ya(_.x,p.x,(0-_.y)/(p.y-_.y))),_.y>Dr!=p.y>Dr&&this.addBorderIntersection(3,ya(_.x,p.x,(Dr-_.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 oht(N,p){const _=N.add(p)._unit(),C=ta(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*vfs*((M=N).x*(F=p).y-M.y*F.x<0?-1:1)}const bfs=[N=>N.x<0,N=>N.x>Dr,N=>N.y<0,N=>N.y>Dr];function _fs(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 Z=0;Z<4;Z++)for(const se of H)if(bfs[Z](se)){M.push(Z);break}return M}class JOe{constructor(p){this.groundRadiusArray=null,this.groundRadiusBuffer=null,this.vertexArray=new Kn,this.indexArray=new qr,this.programConfigurations=new Gk(p.layers,{zoom:p.zoom,lut:p.lut},_=>xfs.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 Z;z!==this._segments.get().length-1&&(z++,this._segmentToGroundQuads[z]=[],this._segmentToRegionTriCounts[z]=[0,0,0,0,0]);{const se=p[0],fe=p[1];Z=oht(se.sub(p[F-1])._perp()._unit(),fe.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((Z,se)=>Z+se,0);let H=0;for(let Z=0;Z<=4;Z++){const se=z[Z];if(se!==0){let fe=this.regionSegments[Z];fe||(fe=this.regionSegments[Z]=new Li);const xe={vertexOffset:F.vertexOffset,primitiveOffset:F.primitiveOffset+H,vertexLength:F.vertexLength,primitiveLength:se};fe.get().push(xe)}H+=se}for(let Z=0;Z0?this.hiddenByLandmarkVertexBuffer=p.createVertexBuffer(this.hiddenByLandmarkVertexArray,mfs.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 jle{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 wle,this.footprintIndices=new qr,this.footprintVertices=new Hs,this.footprintSegments=new ble,this.layoutVertexArray=new Mn,this.centroidVertexArray=new rj,this.wallVertexArray=new id,this.indexArray=new qr,this.programConfigurations=new Gk(p.layers,{zoom:p.zoom,lut:p.lut},_=>gfs.includes(_)),this.segments=new Li,this.stateDependentLayerIds=this.layers.filter(_=>_.isStateDependent()).map(_=>_.id),this.groundEffect=new JOe(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=W6("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:Z}of p){const se=this.layers[0]._featureFilter.needGeometry,fe=bt(F,se);if(!this.layers[0]._featureFilter.filter(new Wn(this.zoom,{worldview:this.worldview,activeFloors:_.activeFloors}),fe,C))continue;const xe={id:z,sourceLayerIndex:Z,index:H,geometry:se?fe.geometry:ut(F,C,M),properties:F.properties,type:F.type,patterns:{}},be=this.layoutVertexArray.length,Te=XOe[xe.type]==="Polygon";if(this.hasPattern)this.features.push({featureId:F.id,feature:vY("fill-extrusion",this.layers,xe,this.zoom,this.pixelRatio,_)});else if(this.wallMode)for(const De of xe.geometry)for(const Ue of aht(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,Z,this.index,be)}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:Z}of this.features){const se=XOe[Z.type]==="Polygon",{geometry:fe}=Z;if(this.wallMode)for(const xe of fe)for(const be of aht(xe,se))this.addFeature(H,Z,[be],Z.index,_,C,M,F,z);else this.addFeature(H,Z,fe,Z.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,pfs),this.indexBuffer=p.createIndexBuffer(this.indexArray),this.wallVertexBuffer=p.createVertexBuffer(this.wallVertexArray,hfs.members),this.layoutVertexExtArray&&(this.layoutVertexExtBuffer=p.createVertexBuffer(this.layoutVertexExtArray,ffs.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,ufs.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,Z,se){const fe=this.layers[0].paint.get("fill-extrusion-flood-light-ground-radius").evaluate(_,{})/this.tileToMeter,xe=[new xs(0,0),new xs(Dr,Dr)],be=Z.projection,Te=be.name==="globe",De=this.wallMode||XOe[_.type]==="Polygon",Ue=new QOe;Ue.centroidDataIndex=this.centroidData.length;const Ye=new _le;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 ht;if(Ye.height=it,Ye.vertexArrayOffset=this.layoutVertexArray.length,Ye.groundVertexArrayOffset=this.groundEffect.vertexArray.length,Te&&!this.layoutVertexExtArray&&(this.layoutVertexExtArray=new xr),this.wallMode){if(Te)return void Yo("Non zero fill-extrusion-line-width is not yet supported on globe.");if(C.length!==1)return;ht=function(Jt){const ns=Jt[0].x===Jt.at(-1).x&&Jt[0].y===Jt.at(-1).y;(function(ar){let zn=0;const Ir=ar.length;for(let lr=0;lr=0})(Jt)||(Jt=Jt.reverse());const Gs={geometry:[],joinNormals:[],indices:[]},pn=[],cn=[],jn=[];let Vn=Jt.length;for(;Vn>=2&&Jt[Vn-1].equals(Jt[Vn-2]);)Vn--;if(Vn<(ns?3:2))return Gs;let Cs,Zs,an,Ln,In,qn=0;for(;qn0;let Wa="miter";const Ka=2;Wa==="miter"&&lr>Ka&&(Wa="bevel"),Wa==="bevel"&&(lr>100&&(Wa="flipbevel"),lr{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),jn.push(Ai),pn.push(rl),cn.push(Bl)};if(Wa==="miter")zn._mult(lr),oi(Cs,zn,0,0);else if(Wa==="flipbevel")zn=In.mult(-1),oi(Cs,zn,0,0),oi(Cs,zn.mult(-1),0,0);else{const Fa=-Math.sqrt(lr*lr-1),Ai=_r?Fa:0,Ni=_r?0:Fa;Zs&&oi(Cs,Ln,Ai,Ni),an&&oi(Cs,In,Ai,Ni)}}Gs.geometry=[...pn,...cn.reverse(),pn[0]],Gs.joinNormals=[...jn,...jn.reverse(),jn.at(-1)];const Dn=Gs.geometry.length-1;for(let ar=0;arJt<(ns.length-1)/2||Jt===ns.length-1,yt=this.wallMode?[C]:Pa(C,500);for(let Jt=yt.length-1;Jt>=0;Jt--){const ns=yt[Jt];(ns.length===0||Nfs(ns[0]))&&yt.splice(Jt,1)}let Nt;if(Te)Nt=fht(yt,xe,F);else{Nt=[];for(const Jt of yt)Nt.push({polygon:Jt,bounds:xe})}const is=De?this.edgeRadius:0,At=is>0&&this.zoom<17,$t=(Jt,ns)=>{if(Jt.length===0)return!1;const Ps=Jt.at(-1);return ns.x===Ps.x&&ns.y===Ps.y};for(const{polygon:Jt,bounds:ns}of Nt){let Ps=0,Gs=0;for(const Vn of Jt)De&&!Vn[0].equals(Vn.at(-1))&&Vn.push(Vn[0]),Gs+=De?Vn.length-1:Vn.length;const pn=this.segments.prepareSegment((De?5:4)*Gs,this.layoutVertexArray,this.indexArray);Ye.footprintSegIdx<0&&(Ye.footprintSegIdx=this.footprintSegments.length),Ye.polygonSegIdx<0&&(Ye.polygonSegIdx=this.polygonSegments.length);const cn={triangleArrayOffset:this.indexArray.length,triangleCount:0,triangleSegIdx:this.segments.segments.length-1},jn=new iht;if(jn.vertexOffset=this.footprintVertices.length,jn.indexOffset=3*this.footprintIndices.length,jn.ringIndices=[],De){const Vn=[],Cs=[];Ps=pn.vertexLength;for(let an=0;an4&&uht(Cs[Cs.length-2],Cs[0],Cs[1]),an=is?jfs(Cs[Cs.length-2],Cs[0],Cs[1],is):0;const Ln=[];let In,qn,Dn;qn=Cs[1].sub(Cs[0])._perp()._unit();let ar=!0;for(let zn=1,Ir=0;zn0?1:0,Ai=lr.dist(_r);if(Ir+Ai>32768&&(Ir=0),is){Dn=Nle(_r,Wa,qn);let Bl=cht(lr,_r,Wa,e8e(qn,Dn),is);isNaN(Bl)&&(Bl=0);const wc=wfs(lr,_r,new xs(0,0));lr=lr.add(wc.mult(an))._round(),_r=_r.add(wc.mult(-Bl))._round(),an=Bl,qn=Dn,nt&&this.zoom>=17&&($t(Ln,lr)||Ln.push(lr),$t(Ln,_r)||Ln.push(_r))}const Ni=pn.vertexLength,Fo=Cs.length>4&&uht(lr,_r,Wa);let rl=hht(Ir,Zs,ar);if(GY(this.layoutVertexArray,lr.x,lr.y,oi,Fa,0,0,rl),GY(this.layoutVertexArray,lr.x,lr.y,oi,Fa,0,1,rl),this.wallMode){const Bl=ot(zn-1,Cs),wc=ht.joinNormals[zn-1];WY(this.wallVertexArray,wc,Bl),WY(this.wallVertexArray,wc,Bl)}if(Ir+=Ai,rl=hht(Ir,Fo,!ar),Zs=Fo,GY(this.layoutVertexArray,_r.x,_r.y,oi,Fa,0,0,rl),GY(this.layoutVertexArray,_r.x,_r.y,oi,Fa,0,1,rl),this.wallMode){const Bl=ot(zn,Cs),wc=ht.joinNormals[zn];WY(this.wallVertexArray,wc,Bl),WY(this.wallVertexArray,wc,Bl)}if(pn.vertexLength+=4,this.indexArray.emplaceBack(Ni+0,Ni+1,Ni+2),this.indexArray.emplaceBack(Ni+1,Ni+3,Ni+2),pn.primitiveLength+=2,is){const Bl=Ps+(zn===1?Cs.length-2:zn-2),wc=zn===1?Ps:Bl+1;if(this.indexArray.emplaceBack(Ni+1,Bl,Ni+3),this.indexArray.emplaceBack(Bl,wc,Ni+3),pn.primitiveLength+=2,In===void 0&&(In=Ni),!t8e(Wa,Cs[zn],ns)){const qm=zn===Cs.length-1?In:pn.vertexLength;this.indexArray.emplaceBack(Ni+2,Ni+3,qm),this.indexArray.emplaceBack(Ni+3,qm+1,qm),this.indexArray.emplaceBack(Ni+3,wc,qm+1),pn.primitiveLength+=3}ar=!ar}if(Te){const Bl=this.layoutVertexExtArray,wc=be.projectTilePoint(lr.x,lr.y,F),qm=be.projectTilePoint(_r.x,_r.y,F),K0=be.upVector(F,lr.x,lr.y),Zh=be.upVector(F,_r.x,_r.y);KY(Bl,wc,K0),KY(Bl,wc,K0),KY(Bl,qm,Zh),KY(Bl,qm,Zh)}}De&&(Ps+=Cs.length-1),nt&&is&&this.zoom>=17&&(Ln.length!==0&&$t(Ln,Ln[0])&&Ln.pop(),this.groundEffect.addData(Ln,ns,fe,is>0))}this.footprintSegments.push(jn),cn.triangleCount=this.indexArray.length-cn.triangleArrayOffset,this.polygonSegments.push(cn),++Ye.footprintSegLen,++Ye.polygonSegLen}if(Ye.vertexCount=this.layoutVertexArray.length-Ye.vertexArrayOffset,Ye.groundVertexCount=this.groundEffect.vertexArray.length-Ye.groundVertexArrayOffset,Ye.vertexCount!==0){if(Ye.centroidXY=Ue.borders?xle:this.encodeCentroid(Ue,Ye),_.properties&&Object.hasOwn(_.properties,"building_id")){const Jt=Ye.buildingId;let ns=this.buildingGroups.get(Jt);ns||(ns={accX:0,accY:0,accCount:0,mergedMin:new xs(Number.MAX_VALUE,Number.MAX_VALUE),mergedMax:new xs(-Number.MAX_VALUE,-Number.MAX_VALUE),partIndices:[]},this.buildingGroups.set(Jt,ns)),ns.accX+=Ue.acc.x,ns.accY+=Ue.acc.y,ns.accCount+=Ue.accCount,ns.mergedMin.x=Math.min(ns.mergedMin.x,Ye.min.x),ns.mergedMin.y=Math.min(ns.mergedMin.y,Ye.min.y),ns.mergedMax.x=Math.max(ns.mergedMax.x,Ye.max.x),ns.mergedMax.y=Math.max(ns.mergedMax.y,Ye.max.y),ns.partIndices.push(this.centroidData.length)}if(this.centroidData.push(Ye),Ue.borders){this.featuresOnBorder.push(Ue);const Jt=this.featuresOnBorder.length-1;for(let ns=0;nsthis.featuresOnBorder[_].borders[p][0]-this.featuresOnBorder[C].borders[p][0])}splitToSubtiles(){const p=[];for(let H=0;HDr),fe=2*se+(+(Z.min.x+Z.max.x>Dr)^se);for(let xe=0;xeH.triangleSegmentIdx===Z.triangleSegmentIdx?H.subtile-Z.subtile:H.triangleSegmentIdx-Z.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,Z=M,se=M;for(let fe=Z;fe0&&this.triangleSubSegments.push({segment:Te,min:xe,max:be}),Z=se;for(let De=Z;De[ya(Ue[0],Ye[0],nt[0]),ya(Ue[1],Ye[1],nt[1])],Te=[],De=[];for(const Ue of this.triangleSubSegments){Te[0]=Ue.min.x/Dr,Te[1]=Ue.min.y/Dr,De[0]=Ue.max.x/Dr,De[1]=Ue.max.y/Dr;const Ye=be(fe,xe,Te),nt=be(fe,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(ta(C.x,1,8191)<<3|F,ta(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&=W3,_!=="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(ta(C.groupCentroidPos.x,1,8191)<<3|F,ta(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?xle:p.centroidXY,F=this.centroidVertexArray.geta_centroid_pos0(_);if(this.centroidVertexArray.geta_centroid_pos1(_)!==M.y||F!==M.x){for(let z=_;zZ.max.x||Z.min.x>z.max.x||z.min.y>Z.max.y||Z.min.y>z.max.y||z.footprint.buildingIds.has(Z.buildingId)&&(Z.flags|=z.clipMask!==IY.None?-1073741824:W3);else for(const Z of this.centroidData)if(!(Z.flags&W3||Z.flags&yle||z.min.x>Z.max.x||Z.min.x>z.max.x||z.min.y>Z.max.y||Z.min.y>z.max.y))for(let se=0;se_!=Te>_&&p<(this.footprintVertices.int16[2*(fe+z.vertexOffset)+0]-xe)*(_-be)/(Te-be)+xe&&(M=!M)}H=Z}}return M}getHeightAtTileCoord(p,_){let C=Number.NEGATIVE_INFINITY,M=!0;const F=4*(p+Dr)*Dr+(_+Dr);if(Object.hasOwn(this.partLookup,F)){const Z=this.partLookup[F];return Z?{height:Z.height,hidden:!!(Z.flags&W3)}:void 0}const z=this.centroidData.buffer,H=this.centroidData.length;for(let Z=0;Zz[se+4]||z[se+2]>p||_>z[se+5]||z[se+3]>_)continue;const fe=z[se+13];if(fe<=C)continue;const xe=this.centroidData.get(Z);this.footprintContainsPoint(p,_,xe)&&(C=fe,this.partLookup[F]=xe,M=!!(xe.flags&W3))}if(C!==Number.NEGATIVE_INFINITY)return{height:C,hidden:M};this.partLookup[F]=void 0}}function wfs(N,p,_){return N.equals(p)?_:p.sub(N)._unit()}function Nle(N,p,_){return N.equals(p)?_:p.sub(N)._perp()._unit()}function lht(N,p){const _=N.add(p),C=_.mag();return C===0?N:_.div(C)}function e8e(N,p){const _=lht(N,p);return N.x*_.x+N.y*_.y}function jfs(N,p,_,C){let M,F;return N.equals(p)?(F=Nle(p,_,new xs(0,0)),M=F):(M=p.sub(N)._perp()._unit(),F=Nle(p,_,M)),cht(N,p,_,e8e(M,F),C)}function cht(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 t8e(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 dht(N,p){return N.xp[1].x||N.yp[1].y}function Nfs(N){return N.every(p=>p.x<=0)||N.every(p=>p.x>=Dr)||N.every(p=>p.y<=0)||N.every(p=>p.y>=Dr)}function uht(N,p,_){if(N.x<0||N.x>=Dr||p.x<0||p.x>=Dr||_.x<0||_.x>=Dr)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 hht(N,p,_){const C=p?2|N:-3&N;return _?1|C:-2&C}function mht(){const N=Math.PI/32,p=Math.tan(N),_=eM;return _*Math.sqrt(1+2*p*p)-_}function fht(N,p,_){const C=1<<_.z,M=Fx(_.x/C),F=Fx((_.x+1)/C),z=qd(_.y/C),H=qd((_.y+1)/C);return function(Z,se,fe,xe,be=0,Te){const De=[];if(!Z.length||!fe||!xe)return De;const Ue=(Nt,is)=>{for(const At of Nt)De.push({polygon:At,bounds:is})},Ye=Math.ceil(Math.log2(fe)),nt=Math.ceil(Math.log2(xe)),it=Ye-nt,ht=[];for(let Nt=0;Nt0?0:1);for(let Nt=0;Ntis+1?yt.push({polygons:pn,bounds:jn,depth:is+1}):Ue(pn,jn)}if(cn.length){const jn=[new xs(At===0?Gs:$t.x,At===1?Gs:$t.y),Jt];ht.length>is+1?yt.push({polygons:cn,bounds:jn,depth:is+1}):Ue(cn,jn)}}return De}(N,p,Math.ceil((F-M)/11.25),Math.ceil((z-H)/11.25),1,(Z,se,fe)=>{if(Z===0)return .5*(se+fe);{const xe=qd((_.y+se/Dr)/C);return(ap(.5*(qd((_.y+fe/Dr)/C)+xe))*C-_.y)*Dr}})}function kfs(N,p,_,C,M,F){const z=Math.pow(2,C.z-M.z);for(let H=0;H<_;H++){let Z=N.int16[2*(H+p)+0],se=N.int16[2*(H+p)+1];Z=(Z+M.x*Dr)*z-C.x*Dr,se=(se+M.y*Dr)*z-C.y*Dr,F.push(new xs(Z,se))}}oa(jle,"FillExtrusionBucket",{omit:["layers","features"]}),oa(_le,"PartData"),oa(wle,"PartDataArray"),oa(ble,"FootprintSegmentArray"),oa(QOe,"BorderCentroidData"),oa(JOe,"GroundEffect");const s8e=4096;class Sfs{constructor(p){this.module=p,this.memoryStack=this.module.malloc(s8e),this.memoryStackNextFree=this.memoryStack}createIntArray(p){const _=this.memoryStackNextFree;return this.memoryStackNextFree+=p.length*Int32Array.BYTES_PER_ELEMENT,this.memoryStackNextFree-this.memoryStack>s8e?-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>s8e?-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 Z=this.createIntArray(H.ringIndices),se=this.createFloatArray(H.coordinates);if(Z===-1||se===-1)return`building_gen: Out of stack memory: ${this.memoryStackNextFree-this.memoryStack}/4096`;this.module.addFeature(H.id,H.sourceId,H.minHeight,H.height,H.roofType,se,Z,H.ringIndices.length-1)}for(const H of _){let Z;Z=H.entrances?JSON.parse(H.entrances):[];const se=this.createFloatArray(Z),fe=this.createFloatArray(H.coordinates);if(se===-1||fe===-1)return`building_gen: Out of stack memory: ${this.memoryStackNextFree-this.memoryStack}/4096`;this.module.addFacade(H.sourceId,H.crossPerc,H.distanceToRoad,se,Z.length,fe,H.coordinates.length)}if(!this.module.generateMesh()){const H=this.module.getLastError();return this.readStringBuffer(H)}const C=this.module.getMeshCount(),M=new Array(C);for(let H=0;H_||M.y<-p||M.y>_)return!1;return!0}function Afs(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 ght,xht,J9=null,yht=null,lj=null;class n8e{constructor(){this.layoutVertexArray=new On,this.layoutAttenuationArray=new Hr,this.layoutColorArray=new si,this.indexArray=new qr,this.indexArrayForConflation=new qr,this.segmentsBucket=new Li}}class r8e{constructor(p){this.layoutFacadePaintArray=null,this.layoutFacadeDataArray=null,this.layoutFacadeVerticalRangeArray=null,this.segmentsBucket=new Li,this.entranceBloom=new n8e;const _=66560;this.layoutVertexArray=new On,this.layoutVertexArray.reserve(_),this.layoutNormalArray=new Fs,this.layoutNormalArray.reserve(_),this.layoutCentroidArray=new Fs,this.layoutCentroidArray.reserve(_),this.layoutColorArray=new si,this.layoutColorArray.reserve(_),this.layoutFloodLightDataArray=new Vl,this.layoutFloodLightDataArray.reserve(_),this.layoutAOArray=new mm,this.layoutAOArray.reserve(_),this.indexArray=new qr,this.indexArray.reserve(66560),this.indexArrayForConflation=new qr,this.segmentsBucket=new Li,this.entranceBloom=new n8e,p&&(this.layoutFacadePaintArray=new si,this.layoutFacadeDataArray=new An,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 vht{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 r8e(!1),this.buildingWithFacade=new r8e(!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 Gk(p.layers,{zoom:p.zoom,lut:p.lut}),this.stateDependentLayerIds=this.layers.filter(_=>_.isStateDependent()).map(_=>_.id),this.projection=p.projection,this.groundEffect=new JOe(p),this.groundEffect.groundRadiusArray=new $s,this.hasAppearances=null}updateFootprints(p,_){const C=new ule([],[],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(!lj)return;const F=K(C);this.tileToMeter=F,this.brightness=_.brightness,lj.setStyle({normalScale:[1,-1,F],tileToMeters:F}),lj.setAOOptions(!1,.3),lj.setMetricOptions(!1,16),lj.setStructuralOptions(!0),lj.setFacadeClassifierOptions(3);const z=new Map,H=new Map;let Z=0;for(const{feature:Ye}of p){if(pht[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 Wn(this.zoom),Ye,C))continue;const it=bt(Ye,nt);if(!nt&&!this.layers[0]._featureFilter.filter(new Wn(this.zoom),it,C))continue;const ht=nt?it.geometry:ut(Ye,C,M),ot=[];for(const At of ht)for(const $t of At)ot.push($t.x),ot.push($t.y);const yt={coordinates:ot,crossPerc:Ye.properties.cross_perc,distanceToRoad:Ye.properties.distance_to_road,entrances:Ye.properties.entrances,sourceId:0},Nt=Ye.properties.source_id;let is=H.get(Nt);is||(is=[],H.set(Nt,is)),is.push(yt),++Z}this.maxHeight=0;const se=new Array,fe=new Set,xe=Ye=>{Ye!=null&&fe.add(Ye)},be=(Ye,nt)=>{Ye!=null&&se.push({buildingId:Ye,footprintIndex:nt})},Te=64*(p.length-Z),De=Te/2;this.buildingWithFacade.reserve(Te,De,!0),this.buildingWithoutFacade.reserve(2*Te,2*De,!1),this.footprintsIndices.reserve(16*(p.length-Z)),this.footprintsVertices.reserve(8*(p.length-Z));for(const{feature:Ye,id:nt,index:it,sourceLayerIndex:ht}of p){if(pht[Ye.type]==="LineString")continue;const ot=this.layers[0]._featureFilter.needGeometry;if(ot&&!this.layers[0]._featureFilter.filter(new Wn(this.zoom),Ye,C))continue;let yt=null;if(Ye.properties&&Object.hasOwn(Ye.properties,"building_id")&&(yt=Number(Ye.properties.building_id),fe.has(yt)))continue;const Nt=bt(Ye,ot);if(!ot&&!this.layers[0]._featureFilter.filter(new Wn(this.zoom),Nt,C))continue;const is=ot?Nt.geometry:ut(Ye,C,M),At=Pa(is,500);let $t=!1;for(const wo of At)if(wo.length!==1){$t=!0;break}if($t){xe(yt);continue}if(!Cfs(is,163)){xe(yt);continue}const Jt=this.layers[0],ns=Afs(Jt.layout.get("building-roof-shape").evaluate(Ye,{},C)),Ps=Jt.layout.get("building-base").evaluate(Ye,{},C),Gs=Jt.layout.get("building-height").evaluate(Ye,{},C),pn=Jt.layout.get("building-flood-light-ground-radius").evaluate(Ye,{},C),cn=Jt.paint.get("building-ambient-occlusion-intensity"),jn=pn/this.tileToMeter;Ye.properties["building-part"]="roof";const Vn=Jt.paint.get("building-color").evaluate(Ye,{},this.canonical).toPremultipliedRenderColor(this.lut),Cs=Jt.paint.get("building-emissive-strength").evaluate(Ye,{},this.canonical);Ye.properties["building-part"]="wall";const Zs=Jt.paint.get("building-color").evaluate(Ye,{},this.canonical).toPremultipliedRenderColor(this.lut),an=Jt.paint.get("building-emissive-strength").evaluate(Ye,{},this.canonical);Ye.properties["building-part"]="window";const Ln=Jt.paint.get("building-color").evaluate(Ye,{},this.canonical).toPremultipliedRenderColor(this.lut),In=Jt.paint.get("building-emissive-strength").evaluate(Ye,{},this.canonical);Ye.properties["building-part"]="door";const qn=Jt.paint.get("building-color").evaluate(Ye,{},this.canonical).toPremultipliedRenderColor(this.lut),Dn=Jt.paint.get("building-emissive-strength").evaluate(Ye,{},this.canonical);let ar=Jt.layout.get("building-flood-light-wall-radius").evaluate(Ye,{},C);ar=ta(ar,0,2048);const zn=ar/2048*kle,Ir=z.get(nt),lr=H.get(Ir)||[],_r=lr.length!==0&&Jt.layout.get("building-facade").evaluate(Ye,{},C);lj.setFacadeOptions(4,!0),lj.setFauxFacadeOptions(_r,!1,1);let Wa=0,Ka=0,oi=0,Fa=0,Ai=0,Ni=0,Fo=0,rl=0,Bl=0,wc=0,qm=0;if(_r){let wo=Math.round(Jt.layout.get("building-facade-floors").evaluate(Ye,{},C));if(Ps===0){wo=Math.max(1,wo-(lr.length>0?1:0));let Mu=4;if(Gs>100){const Hm=[10,13,15];Mu=Hm[Ye.id?Ye.id%Hm.length:0]}else Gs<=10&&(Mu=3);lj.setFacadeOptions(Mu,!0),Ai=(Gs<15?1.3:1.61803)*Mu/F}else Ai=Ps/F;Ni=Gs/F,Ai=Math.min(Ai,Ni),oi=Jt.layout.get("building-facade-unit-width").evaluate(Ye,{},C)/F,Fa=(Ni-Ai)/wo,lj.setFauxFacadeOptions(!0,!0,oi);const pg=Jt.layout.get("building-facade-window").evaluate(Ye,{},C);Wa=pg[0],Ka=pg[1],Fo=Math.floor(65535*Math.min(1,Ai/Dr)),rl=Math.floor(65535*Math.min(1,Ni/Dr)),Bl=Math.floor(255*Wa)<<8|Math.floor(255*Ka),wc=Math.floor(65535*Math.min(1,oi/Dr)),qm=Math.floor(65535*Math.min(1,Fa/Dr))}const K0=Array(At.length),Zh={x:1/0,y:1/0},_l={x:-1/0,y:-1/0},Hd={x:0,y:0};let mh=0;for(let wo=0;wo0){const Mu=[],Hm=Array(pg.length+1);Hm[0]=0;for(let Y_=0;Y_Dr||Zh.y<0||_l.y>Dr)&&this.featuresOnBorder.push({featureId:Ye.id,footprintIndex:this.footprints.length});{const wo=XT(Zk,null,2);this.footprintsIndices.resize(this.footprintsIndices.length+wo.length),this.footprintsIndices.uint16.set(wo,Hb),this.buildingIds.add(yt??Ye.id),this.footprintsMin.x=Math.min(this.footprintsMin.x,K_.x),this.footprintsMin.y=Math.min(this.footprintsMin.y,K_.y),this.footprintsMax.x=Math.max(this.footprintsMax.x,Y0.x),this.footprintsMax.y=Math.max(this.footprintsMax.y,Y0.y);const pg={footprintVertexOffset:fg,footprintVertexLength:this.footprintsVertices.length-fg,footprintIndexOffset:Hb,footprintIndexLength:this.footprintsIndices.length-Hb,min:K_,max:Y0,hiddenFlags:0,indicesOffset:ky,indicesLength:Vb,bloomIndicesOffset:Vx,bloomIndicesLength:qb,groundEffectVertexOffset:ZC,groundEffectVertexLength:oR,hasFauxFacade:_r,height:Wv,promoteId:nt,feature:Nt,parts:gf,buildingBloom:qx},Mu=this.footprints.length;Ye.id!==void 0&&this.featureFootprintLookup.set(Ye.id,Mu),be(yt,Mu),this.footprints.push(pg)}this.programConfigurations.populatePaintArrays(mo.layoutVertexArray.length,Ye,it,{},_.availableImages,C,_.brightness),this.groundEffect.addPaintPropertiesData(Ye,it,{},_.availableImages,C,_.brightness),_.featureIndex.insert(Ye,is,it,ht,this.index,Ny)}se.forEach(({buildingId:Ye,footprintIndex:nt})=>{fe.has(Ye)&&(this.footprints[nt].hiddenFlags|=4)});const Ue=new Set;this.buildingIds.forEach((Ye,nt,it)=>{fe.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,nht.members),C.layoutNormalBuffer=p.createVertexBuffer(C.layoutNormalArray,tfs.members),C.layoutCentroidBuffer=p.createVertexBuffer(C.layoutCentroidArray,sfs.members),C.layoutFloodLightDataBuffer=p.createVertexBuffer(C.layoutFloodLightDataArray,ofs.members),C.layoutFacadeDataArray&&C.layoutFacadeDataArray.length&&(C.layoutFacadeDataBuffer=p.createVertexBuffer(C.layoutFacadeDataArray,rfs.members)),C.layoutFacadeVerticalRangeArray&&C.layoutFacadeVerticalRangeArray.length&&(C.layoutFacadeVerticalRangeBuffer=p.createVertexBuffer(C.layoutFacadeVerticalRangeArray,afs.members)),C.entranceBloom.layoutVertexArray.length&&(C.entranceBloom.layoutVertexBuffer=p.createVertexBuffer(C.entranceBloom.layoutVertexArray,nht.members),C.entranceBloom.layoutAttenuationBuffer=p.createVertexBuffer(C.entranceBloom.layoutAttenuationArray,ifs.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 Z=this.footprints[H],se=Z.hiddenFlags&z|F;Z.hiddenFlags!==se&&(Z.hiddenFlags=se,M=!0,this.groundEffect.updateHiddenByLandmarkRange(Z.groundEffectVertexOffset,Z.groundEffectVertexLength,Z.hiddenFlags!==0))}return M&&(this.indexArrayForConflationUploaded=!1),M}uploadUpdatedIndexBuffer(p){if(this.groundEffect.uploadHiddenByLandmark(p),this.indexArrayForConflationUploaded)return;const _=M=>{M.indexArray.length!==0&&(M.indexArrayForConflation.resize(M.indexArray.length),M.indexArrayForConflation.uint16.set(M.indexArray.uint16),M.entranceBloom.indexArrayForConflation.resize(M.entranceBloom.indexArray.length),M.entranceBloom.indexArrayForConflation.uint16.set(M.entranceBloom.indexArray.uint16))};_(this.buildingWithoutFacade),_(this.buildingWithFacade);for(const M of this.footprints){const F=M.hasFauxFacade?this.buildingWithFacade:this.buildingWithoutFacade,z=M.indicesOffset+M.indicesLength;if(M.hiddenFlags!==0){for(let Z=M.indicesOffset;Z{M.indexArray.length!==0&&(M.indexBuffer?M.indexBuffer.updateData(M.indexArrayForConflation):M.indexBuffer=p.createIndexBuffer(M.indexArrayForConflation,!0),M.entranceBloom.indexBuffer?M.entranceBloom.indexBuffer.updateData(M.entranceBloom.indexArrayForConflation):M.entranceBloom.indexBuffer=p.createIndexBuffer(M.entranceBloom.indexArrayForConflation,!0))};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,rht.members,!0),C.layoutFacadePaintArray&&(C.layoutFacadePaintBuffer?C.layoutFacadePaintBuffer.updateData(C.layoutFacadePaintArray):C.layoutFacadePaintBuffer=p.createVertexBuffer(C.layoutFacadePaintArray,nfs.members,!0)),C.entranceBloom.layoutColorBuffer?C.entranceBloom.layoutColorBuffer.updateData(C.entranceBloom.layoutColorArray):C.entranceBloom.layoutColorBuffer=p.createVertexBuffer(C.entranceBloom.layoutColorArray,rht.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),Z=p.paint.get("building-emissive-strength").evaluate(z,F,this.canonical);z.properties["building-part"]="wall";const se=p.paint.get("building-color").evaluate(z,F,this.canonical).toPremultipliedRenderColor(this.lut),fe=p.paint.get("building-emissive-strength").evaluate(z,F,this.canonical);z.properties["building-part"]="window";const xe=p.paint.get("building-color").evaluate(z,F,this.canonical).toPremultipliedRenderColor(this.lut),be=p.paint.get("building-emissive-strength").evaluate(z,F,this.canonical);z.properties["building-part"]="door";const Te=p.paint.get("building-color").evaluate(z,F,this.canonical).toPremultipliedRenderColor(this.lut),De=p.paint.get("building-emissive-strength").evaluate(z,F,this.canonical),Ue=M.hasFauxFacade?this.buildingWithFacade:this.buildingWithoutFacade;for(const nt of M.parts){let it,ht=H;nt.part===1?(ht=H,it=Z):nt.part===0?(ht=se,it=fe):nt.part===2?(ht=xe,it=be):nt.part===3&&(ht=Te,it=De),it=ta(it,0,1);for(let ot=0;otz.max.x||Z.max.xz.max.y||Z.max.yH.max.x||H.min.x>p||_>H.max.y||H.min.y>_||H.height<=C||Efs(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 Efs(N,p,_){for(let C=0;C<_.length;C+=3){const M=_[C],F=_[C+1],z=_[C+2],H=p[2*M+0],Z=p[2*M+1],se=p[2*F+0],fe=p[2*F+1],xe=p[2*z+0],be=p[2*z+1],Te=(H-xe)*(N.y-be)-(Z-be)*(N.x-xe),De=(se-H)*(N.y-Z)-(fe-Z)*(N.x-H);if(Te<0!=De<0&&Te!==0&&De!==0)continue;const Ue=(xe-se)*(N.y-fe)-(be-fe)*(N.x-se);if(Ue===0||Ue<0==Te+De<=0)return!0}return!1}function Tfs(N,p,_,C,M,F){const z=Math.pow(2,C.z-M.z);for(let H=0;H<_;H++){let Z=N.float32[2*(H+p)+0],se=N.float32[2*(H+p)+1];Z=(Z+M.x*Dr)*z-C.x*Dr,se=(se+M.y*Dr)*z-C.y*Dr,F.push(new xs(Z,se))}}oa(vht,"BuildingBucket",{omit:["layers"]}),oa(r8e,"BuildingGeometry"),oa(n8e,"BuildingBloomGeometry");class bht{constructor(p=0,_=[]){this.frcMask=p,this.rings=_}hasGeometry(){return this.rings.length>0&&this.rings[0].length>0}}async function Sle(){}function e$(N,p,_){const C=p.paint.get(N).value;return C.kind==="constant"?C.value:_.programConfigurations.get(p.id).getMaxValue(N)}function Cle(N){return Math.sqrt(N[0]*N[0]+N[1]*N[1])}function _ht(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 Nht(N,p,_,C,M,F,z,H,Z){if(F&&N.queryGeometry.isAboveHorizon)return!1;F&&(Z*=N.pixelToTileUnitsFactor);const se=N.tileID.canonical,fe=_.projection.upVectorScale(se,_.center.lat,_.worldSize).metersToTile;for(const xe of p)for(const be of xe){const Te=be.add(H),De=M&&_.elevation?_.elevation.exaggeration()*M.getElevationAt(Te.x,Te.y,!0):0,Ue=_.projection.projectTilePoint(Te.x,Te.y,se);if(De>0){const ht=_.projection.upVector(se,Te.x,Te.y);Ue.x+=ht[0]*fe*De,Ue.y+=ht[1]*fe*De,Ue.z+=ht[2]*fe*De}const Ye=F?Te:Pfs(Ue.x,Ue.y,Ue.z,C),nt=F?N.tilespaceRays.map(ht=>Lfs(ht,De)):N.queryGeometry.screenGeometry,it=Ft([],[Ue.x,Ue.y,Ue.z,1],C);if(!z&&F?Z*=it[3]/_.cameraToCenterDistance:z&&!F&&(Z*=_.cameraToCenterDistance/it[3]),F){const ht=qd((be.y/Dr+se.y)/(1<ya(p,_,C==="log"?(Math.pow(10,N)-1)/9:N);function YY(N){const{expression:p,evaluationKey:_,resolution:C=256,clips:M,scale:F="linear",lut:z=null}=N,H=M?M.length:1,Z=N.image||new t0({width:C,height:H}),se={},fe=(xe,be,Te)=>{se[_]=Te;const De=p.evaluate(se),Ue=(De==null?void 0:De.toNonPremultipliedRenderColor(z))??null;Ue&&(Z.data[xe+be+0]=Math.floor(255*Ue.r),Z.data[xe+be+1]=Math.floor(255*Ue.g),Z.data[xe+be+2]=Math.floor(255*Ue.b),Z.data[xe+be+3]=Math.floor(255*Ue.a))};for(let xe=0,be=0;xe_.fqid),this.index=p.index,this.hasPattern=!1,this.stateDependentLayerIds=this.layers.filter(_=>_.isStateDependent()).map(_=>_.id),this.footprints=[],this.worldview=p.worldview,this.hasAppearances=null}updateFootprints(p,_){for(const 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:Z,sourceLayerIndex:se}of p){const fe=this.layers[0]._featureFilter.needGeometry,xe=bt(z,fe);if(!this.layers[0]._featureFilter.filter(new Wn(this.zoom,{worldview:this.worldview,activeFloors:_.activeFloors}),xe,C))continue;const be={id:H,properties:z.properties,type:z.type,sourceLayerIndex:se,index:Z,geometry:fe?xe.geometry:ut(z,C,M),patterns:{}};F.push(be)}for(const z of F){const{geometry:H,index:Z,sourceLayerIndex:se}=z;this.addFeature(z,H,Z,C,{},_.availableImages,_.brightness),_.featureIndex.insert(p[Z].feature,H,Z,se,this.index)}}isEmpty(){return this.footprints.length===0}uploadPending(){return!1}upload(p){}update(p,_,C,M,F,z,H){}destroy(){}addFeature(p,_,C,M,F,z=[],H){for(const Z of Pa(_,2)){const se=[],fe=[],xe=[],be=new xs(1/0,1/0),Te=new xs(-1/0,-1/0);for(const Ye of Z)if(Ye.length!==0){Ye!==Z[0]&&xe.push(fe.length/2);for(let nt=0;nt{Gs[0]=pn,Gs[1]=cn,Gs[2]=jn,Gs[3]=1},Ps=mht();Te>0&&(Te+=Ps),De+=Ps;for(const Gs of be){const pn=[],cn=[];for(const jn of Gs){const Vn=jn.x+Ue.x,Cs=jn.y+Ue.y,Zs=xe.projection.projectTilePoint(Vn,Cs,yt),an=xe.projection.upVector(yt,jn.x,jn.y);let Ln=Te,In=De;if(nt){const qn=Hht(Vn,Cs,Te,De,nt,it,ht,ot);Ln+=qn.base,In+=qn.top}Te!==0?ns($t,Zs.x+an[0]*At*Ln,Zs.y+an[1]*At*Ln,Zs.z+an[2]*At*Ln):ns($t,Zs.x,Zs.y,Zs.z),ns(Jt,Zs.x+an[0]*At*In,Zs.y+an[1]*At*In,Zs.z+an[2]*At*In),Xe($t,$t,Ye),Xe(Jt,Jt,Ye),pn.push(new Q6($t[0],$t[1],$t[2])),cn.push(new Q6(Jt[0],Jt[1],Jt[2]))}Nt.push(pn),is.push(cn)}return[Nt,is]}(N,p,_,C,M,F,z,H,Z,se,fe):z?function(xe,be,Te,De,Ue,Ye,nt,it,ht){const ot=[],yt=[],Nt=[0,0,0,1];for(const is of xe){const At=[],$t=[];for(const Jt of is){const ns=Jt.x+De.x,Ps=Jt.y+De.y,Gs=Hht(ns,Ps,be,Te,Ye,nt,it,ht);Nt[0]=ns,Nt[1]=Ps,Nt[2]=Gs.base,Nt[3]=1,Ft(Nt,Nt,Ue),Nt[3]=Math.max(Nt[3],1e-5);const pn=new Q6(Nt[0]/Nt[3],Nt[1]/Nt[3],Nt[2]/Nt[3]);Nt[0]=ns,Nt[1]=Ps,Nt[2]=Gs.top,Nt[3]=1,Ft(Nt,Nt,Ue),Nt[3]=Math.max(Nt[3],1e-5);const cn=new Q6(Nt[0]/Nt[3],Nt[1]/Nt[3],Nt[2]/Nt[3]);At.push(pn),$t.push(cn)}ot.push(At),yt.push($t)}return[ot,yt]}(p,_,C,M,F,z,H,Z,se):function(xe,be,Te,De,Ue){const Ye=[],nt=[],it=Ue[8]*be,ht=Ue[9]*be,ot=Ue[10]*be,yt=Ue[11]*be,Nt=Ue[8]*Te,is=Ue[9]*Te,At=Ue[10]*Te,$t=Ue[11]*Te;for(const Jt of xe){const ns=[],Ps=[];for(const Gs of Jt){const pn=Gs.x+De.x,cn=Gs.y+De.y,jn=Ue[0]*pn+Ue[4]*cn+Ue[12],Vn=Ue[1]*pn+Ue[5]*cn+Ue[13],Cs=Ue[2]*pn+Ue[6]*cn+Ue[14],Zs=Ue[3]*pn+Ue[7]*cn+Ue[15],an=jn+it,Ln=Vn+ht,In=Cs+ot,qn=Math.max(Zs+yt,1e-5),Dn=jn+Nt,ar=Vn+is,zn=Cs+At,Ir=Math.max(Zs+$t,1e-5);ns.push(new Q6(an/qn,Ln/qn,In/qn)),Ps.push(new Q6(Dn/Ir,ar/Ir,zn/Ir))}Ye.push(ns),nt.push(Ps)}return[Ye,nt]}(p,_,C,M,F)}function Hht(N,p,_,C,M,F,z,H){const Z=z*M.getElevationAt(N,p,!0,!0),se=F[0]!==0,fe=se?F[1]===0?z*(F[0]/7-450):z*function(xe,be,Te){const De=Math.floor(be[0]/8),Ue=Math.floor(be[1]/8),Ye=10*(be[0]-8*De),nt=10*(be[1]-8*Ue),it=xe.getElevationAt(De,Ue,!0,!0),ht=xe.getMeterToDEM(Te),ot=Math.floor(.5*(Ye*ht-1)),yt=Math.floor(.5*(nt*ht-1)),Nt=xe.tileCoordToPixel(De,Ue),is=2*ot+1,At=2*yt+1,$t=function(cn,jn,Vn,Cs,Zs){return[cn.getElevationAtPixel(jn,Vn,!0),cn.getElevationAtPixel(jn+Zs,Vn,!0),cn.getElevationAtPixel(jn,Vn+Zs,!0),cn.getElevationAtPixel(jn+Cs,Vn+Zs,!0)]}(xe,Nt.x-ot,Nt.y-yt,is,At),Jt=Math.abs($t[0]-$t[1]),ns=Math.abs($t[2]-$t[3]),Ps=Math.abs($t[0]-$t[2])+Math.abs($t[1]-$t[3]),Gs=Math.min(.25,.5*ht*(Jt+ns)/is),pn=Math.min(.25,.5*ht*Ps/At);return it+Math.max(Gs*Ye,pn*nt)}(M,F,H):Z;return{base:Z+(_===0?-1:_),top:se?Math.max(fe+C,Z+_+2):Z+C}}function XY(N,p,_){return p*(Dr/(N.tileSize*Math.pow(2,_-N.tileID.overscaledZ)))}function Ght(N,p){return 1/XY(N,1,p.tileZoom)}function Wht(N,p,_,C){return N.translatePosMatrix(C||p.tileID.projMatrix,p,_.paint.get("line-translate"),_.paint.get("line-translate-anchor"))}oa($ht,"ClipBucket",{omit:["layers"]});const Kht=N=>{const p=[];Yht(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 Yht(N){const p=N.paint.get("line-dasharray").value;return p.kind!=="constant"||p.value}let a8e;const Zht=()=>a8e||(a8e={layout:zht||(zht=new Wu({"line-cap":new Er(Ys.layout_line["line-cap"]),"line-join":new Er(Ys.layout_line["line-join"]),"line-miter-limit":new gr(Ys.layout_line["line-miter-limit"]),"line-round-limit":new gr(Ys.layout_line["line-round-limit"]),"line-sort-key":new Er(Ys.layout_line["line-sort-key"]),"line-z-offset":new Er(Ys.layout_line["line-z-offset"]),"line-elevation-reference":new gr(Ys.layout_line["line-elevation-reference"]),"line-cross-slope":new gr(Ys.layout_line["line-cross-slope"]),visibility:new gr(Ys.layout_line.visibility),"line-width-unit":new gr(Ys.layout_line["line-width-unit"]),"line-elevation-ground-scale":new Er(Ys.layout_line["line-elevation-ground-scale"])})),paint:Bht||(Bht=new Wu({"line-opacity":new Er(Ys.paint_line["line-opacity"]),"line-color":new Er(Ys.paint_line["line-color"]),"line-translate":new gr(Ys.paint_line["line-translate"]),"line-translate-anchor":new gr(Ys.paint_line["line-translate-anchor"]),"line-width":new Er(Ys.paint_line["line-width"]),"line-gap-width":new Er(Ys.paint_line["line-gap-width"]),"line-offset":new Er(Ys.paint_line["line-offset"]),"line-blur":new Er(Ys.paint_line["line-blur"]),"line-dasharray":new Er(Ys.paint_line["line-dasharray"]),"line-pattern":new Er(Ys.paint_line["line-pattern"]),"line-pattern-cross-fade":new gr(Ys.paint_line["line-pattern-cross-fade"]),"line-gradient":new I3(Ys.paint_line["line-gradient"]),"line-trim-offset":new gr(Ys.paint_line["line-trim-offset"]),"line-trim-fade-range":new gr(Ys.paint_line["line-trim-fade-range"]),"line-trim-color":new gr(Ys.paint_line["line-trim-color"]),"line-emissive-strength":new Er(Ys.paint_line["line-emissive-strength"]),"line-border-width":new Er(Ys.paint_line["line-border-width"]),"line-border-color":new Er(Ys.paint_line["line-border-color"]),"line-border-gradient":new I3(Ys.paint_line["line-border-gradient"]),"line-occlusion-opacity":new gr(Ys.paint_line["line-occlusion-opacity"]),"line-blend-mode":new gr(Ys.paint_line["line-blend-mode"]),"line-blend-additive-clamp":new gr(Ys.paint_line["line-blend-additive-clamp"]),"line-cutout-depth":new gr(Ys.paint_line["line-cutout-depth"]),"line-color-use-theme":new Er({type:"string",default:"default","property-type":"data-driven"}),"line-gradient-use-theme":new Er({type:"string",default:"default","property-type":"data-driven"}),"line-trim-color-use-theme":new Er({type:"string",default:"default","property-type":"data-driven"}),"line-border-color-use-theme":new Er({type:"string",default:"default","property-type":"data-driven"}),"line-border-gradient-use-theme":new Er({type:"string",default:"default","property-type":"data-driven"})}))},a8e);class Dfs extends Er{possiblyEvaluate(p,_){return _=new Wn(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 QY,Xht,Qht,i8e;function Jht(N,p){return p>0?p+2*N:N}function emt(N,p){return p.replace(/{([^{}]+)}/g,(_,C)=>C in N?String(N[C]):"")}class tmt{constructor(p){this.type=p.property.overrides?p.property.overrides.runtimeType:gu,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(tmt,"FormatSectionOverride",{omit:["defaultValue"]});const Ffs={};function smt(N){return N.value.kind!=="constant"&&N.value.isStateDependent}const o8e=()=>i8e||(i8e={layout:Xht||(Xht=new Wu({"symbol-placement":new gr(Ys.layout_symbol["symbol-placement"]),"symbol-spacing":new gr(Ys.layout_symbol["symbol-spacing"]),"symbol-avoid-edges":new gr(Ys.layout_symbol["symbol-avoid-edges"]),"symbol-sort-key":new Er(Ys.layout_symbol["symbol-sort-key"]),"symbol-z-order":new gr(Ys.layout_symbol["symbol-z-order"]),"symbol-z-elevate":new gr(Ys.layout_symbol["symbol-z-elevate"]),"symbol-elevation-reference":new gr(Ys.layout_symbol["symbol-elevation-reference"]),"icon-allow-overlap":new gr(Ys.layout_symbol["icon-allow-overlap"]),"icon-ignore-placement":new gr(Ys.layout_symbol["icon-ignore-placement"]),"icon-optional":new gr(Ys.layout_symbol["icon-optional"]),"icon-rotation-alignment":new gr(Ys.layout_symbol["icon-rotation-alignment"]),"icon-size":new Er(Ys.layout_symbol["icon-size"]),"icon-size-scale-range":new gr(Ys.layout_symbol["icon-size-scale-range"]),"icon-text-fit":new Er(Ys.layout_symbol["icon-text-fit"]),"icon-text-fit-padding":new Er(Ys.layout_symbol["icon-text-fit-padding"]),"icon-image":new Er(Ys.layout_symbol["icon-image"]),"icon-image-use-theme":new gr({type:"string",default:"default","property-type":"data-constant"}),"icon-rotate":new Er(Ys.layout_symbol["icon-rotate"]),"icon-padding":new gr(Ys.layout_symbol["icon-padding"]),"icon-keep-upright":new gr(Ys.layout_symbol["icon-keep-upright"]),"icon-offset":new Er(Ys.layout_symbol["icon-offset"]),"icon-anchor":new Er(Ys.layout_symbol["icon-anchor"]),"icon-pitch-alignment":new gr(Ys.layout_symbol["icon-pitch-alignment"]),"text-pitch-alignment":new gr(Ys.layout_symbol["text-pitch-alignment"]),"text-rotation-alignment":new gr(Ys.layout_symbol["text-rotation-alignment"]),"text-field":new Er(Ys.layout_symbol["text-field"]),"text-font":new Er(Ys.layout_symbol["text-font"]),"text-size":new Er(Ys.layout_symbol["text-size"]),"text-size-scale-range":new gr(Ys.layout_symbol["text-size-scale-range"]),"text-max-width":new Er(Ys.layout_symbol["text-max-width"]),"text-line-height":new Er(Ys.layout_symbol["text-line-height"]),"text-letter-spacing":new Er(Ys.layout_symbol["text-letter-spacing"]),"text-justify":new Er(Ys.layout_symbol["text-justify"]),"text-radial-offset":new Er(Ys.layout_symbol["text-radial-offset"]),"text-variable-anchor":new gr(Ys.layout_symbol["text-variable-anchor"]),"text-anchor":new Er(Ys.layout_symbol["text-anchor"]),"text-max-angle":new gr(Ys.layout_symbol["text-max-angle"]),"text-writing-mode":new gr(Ys.layout_symbol["text-writing-mode"]),"text-rotate":new Er(Ys.layout_symbol["text-rotate"]),"text-padding":new gr(Ys.layout_symbol["text-padding"]),"text-keep-upright":new gr(Ys.layout_symbol["text-keep-upright"]),"text-transform":new Er(Ys.layout_symbol["text-transform"]),"text-offset":new Er(Ys.layout_symbol["text-offset"]),"text-allow-overlap":new gr(Ys.layout_symbol["text-allow-overlap"]),"text-ignore-placement":new gr(Ys.layout_symbol["text-ignore-placement"]),"text-optional":new gr(Ys.layout_symbol["text-optional"]),visibility:new gr(Ys.layout_symbol.visibility)})),paint:Qht||(Qht=new Wu({"icon-opacity":new Er(Ys.paint_symbol["icon-opacity"]),"icon-occlusion-opacity":new Er(Ys.paint_symbol["icon-occlusion-opacity"]),"icon-emissive-strength":new Er(Ys.paint_symbol["icon-emissive-strength"]),"text-emissive-strength":new Er(Ys.paint_symbol["text-emissive-strength"]),"icon-color":new Er(Ys.paint_symbol["icon-color"]),"icon-halo-color":new Er(Ys.paint_symbol["icon-halo-color"]),"icon-halo-width":new Er(Ys.paint_symbol["icon-halo-width"]),"icon-halo-blur":new Er(Ys.paint_symbol["icon-halo-blur"]),"icon-translate":new gr(Ys.paint_symbol["icon-translate"]),"icon-translate-anchor":new gr(Ys.paint_symbol["icon-translate-anchor"]),"icon-image-cross-fade":new gr(Ys.paint_symbol["icon-image-cross-fade"]),"text-opacity":new Er(Ys.paint_symbol["text-opacity"]),"text-occlusion-opacity":new Er(Ys.paint_symbol["text-occlusion-opacity"]),"text-color":new Er(Ys.paint_symbol["text-color"],{runtimeType:Qc,getOverride:N=>N.textColor,hasOverride:N=>!!N.textColor}),"text-halo-color":new Er(Ys.paint_symbol["text-halo-color"]),"text-halo-width":new Er(Ys.paint_symbol["text-halo-width"]),"text-halo-blur":new Er(Ys.paint_symbol["text-halo-blur"]),"text-translate":new gr(Ys.paint_symbol["text-translate"]),"text-translate-anchor":new gr(Ys.paint_symbol["text-translate-anchor"]),"icon-color-saturation":new gr(Ys.paint_symbol["icon-color-saturation"]),"icon-color-contrast":new gr(Ys.paint_symbol["icon-color-contrast"]),"icon-color-brightness-min":new gr(Ys.paint_symbol["icon-color-brightness-min"]),"icon-color-brightness-max":new gr(Ys.paint_symbol["icon-color-brightness-max"]),"symbol-z-offset":new Er(Ys.paint_symbol["symbol-z-offset"]),"placement-priority":new Er(Ys.paint_symbol["placement-priority"]),"placement-group":new Er(Ys.paint_symbol["placement-group"]),"icon-color-use-theme":new Er({type:"string",default:"default","property-type":"data-driven"}),"icon-halo-color-use-theme":new Er({type:"string",default:"default","property-type":"data-driven"}),"text-color-use-theme":new Er({type:"string",default:"default","property-type":"data-driven"}),"text-halo-color-use-theme":new Er({type:"string",default:"default","property-type":"data-driven"})}))},i8e);class Ale extends Jy{constructor(p,_,C,M){super(p,o8e(),_,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,Z){F=cm(F),z=qi(z);const se=y(),fe=F/3,xe=1-2*fe,be=[xe,fe,fe,0,fe,xe,fe,0,fe,fe,xe,0,0,0,0,1],Te=.5-.5*z,De=Z-H;return E(se,[De,0,0,0,0,De,0,0,0,0,De,0,H,H,H,1],[z,0,0,0,0,z,0,0,0,0,z,0,Te,Te,Te,1]),E(se,se,be),se}(p,_,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()||Uv(z.value)||!F?F:emt(_.properties,F)}getAppearanceValueAndResolveTokens(p,_,C,M,F){const z=p.getLayoutProperty(_);if(!z)return;const H=z.evaluate(C,{},M,F),Z=p.getUnevaluatedLayoutProperties()._values[_];return Z.isDataDriven()||Uv(Z.value)||!H||typeof H!="string"?H:emt(C.properties,H)}createBucket(p){return new ele(p)}placeSymbols(p,_,C,M,F){const{globalPlacement:z,idRangeAllocator:H,transform:Z,buildingIndex:se,fogState:fe,groupOrders:xe,replacementSource:be}=p,Te=this.runtimeLayerUID,De=smt(this.paint.get("placement-group"))||smt(this.paint.get("placement-priority"))?M._state.getState(this.sourceLayer||"_geojsonTileLayer"):Ffs;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=Wdt(Ue.tileID,Ye.getProjection(),Z,Z.projection.name);Ye.addToPlacement(z,H,Te,nt,Z,Ue.tileSize/Dr,Ue,fe,xe,C,De,F?be:null),z.finishSourceProcessing()}}queryRadius(){return 0}queryIntersectsFeature(){return!1}_setPaintOverrides(){for(const p of o8e().paint.overridableProperties){if(!Ale.hasPaintOverride(this.layout,p))continue;const _=this.paint.get(p),C=new tmt(_),M=new $v(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 U_("source",M):new cg("composite",M,_.value.zoomStops,_.value.interpolationType),this.paint._values[p]=new bh(_.property,F,_.parameters)}}_handleOverridablePaintPropertyUpdate(p,_,C){return!(!this.layout||_.isDataDriven()||C.isDataDriven())&&Ale.hasPaintOverride(this.layout,p)}static hasPaintOverride(p,_){const C=p.get("text-field"),M=o8e().paint.properties[_];let F=!1;const z=H=>{for(const Z of H)if(M.overrides&&M.overrides.hasOverride(Z))return void(F=!0)};if(C.value.kind==="constant"&&C.value.value instanceof yu)z(C.value.value.sections);else if(C.value.kind==="source"){const H=se=>{F||(se instanceof Qg&&lh(se.value)===xh?z(se.value.sections):se instanceof I1?z(se.sections):se.eachChild(H))},Z=C.value;Z._styleExpression&&H(Z._styleExpression.expression)}return F}getProgramIds(){return["symbol"]}getDefaultProgramParams(p,_,C){return{config:new X6(this,{zoom:_,lut:C}),overrideFog:!1}}hasElevation(){return this.layout&&this.layout.get("symbol-elevation-reference")==="hd-road-markup"}mayUse(p){return p==="HD"&&T9(this,"symbol-elevation-reference",_=>_==="hd-road-markup")}prepare(){return this.mayUse("HD")?Sle():Promise.resolve()}}let nmt,rmt,amt,imt;const l8e=1024,Ofs=(Math.pow(l8e,2)-1)/268170240;class omt extends Jy{constructor(p,_,C,M){super(p,{layout:amt||(amt=new Wu({visibility:new gr(Ys.layout_raster.visibility)})),paint:imt||(imt=new Wu({"raster-opacity":new gr(Ys.paint_raster["raster-opacity"]),"raster-color":new I3(Ys.paint_raster["raster-color"]),"raster-color-mix":new gr(Ys.paint_raster["raster-color-mix"]),"raster-color-range":new gr(Ys.paint_raster["raster-color-range"]),"raster-color-scale":new gr(Ys.paint_raster["raster-color-scale"]),"raster-hue-rotate":new gr(Ys.paint_raster["raster-hue-rotate"]),"raster-brightness-min":new gr(Ys.paint_raster["raster-brightness-min"]),"raster-brightness-max":new gr(Ys.paint_raster["raster-brightness-max"]),"raster-saturation":new gr(Ys.paint_raster["raster-saturation"]),"raster-contrast":new gr(Ys.paint_raster["raster-contrast"]),"raster-resampling":new gr(Ys.paint_raster["raster-resampling"]),"raster-fade-duration":new gr(Ys.paint_raster["raster-fade-duration"]),"raster-emissive-strength":new gr(Ys.paint_raster["raster-emissive-strength"]),"raster-array-band":new gr(Ys.paint_raster["raster-array-band"]),"raster-elevation":new gr(Ys.paint_raster["raster-elevation"]),"raster-elevation-reference":new gr(Ys.paint_raster["raster-elevation-reference"]),"raster-color-use-theme":new Er({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=YY({expression:_,evaluationKey:"rasterValue",image:this.colorRamp,clips:[{start:C,end:M}],resolution:l8e,scale:F}),this.colorRampTexture=null,this._curRampRange=[C,M]}is3D(p){return this.paint.get("raster-elevation")>0}}let lmt,cmt,dmt,umt,hmt,mmt,fmt,pmt;class gmt extends Jy{constructor(p,_,C,M){super(p,{layout:lmt||(lmt=new Wu({visibility:new gr(Ys["layout_raster-particle"].visibility)})),paint:cmt||(cmt=new Wu({"raster-particle-array-band":new gr(Ys["paint_raster-particle"]["raster-particle-array-band"]),"raster-particle-count":new gr(Ys["paint_raster-particle"]["raster-particle-count"]),"raster-particle-color":new I3(Ys["paint_raster-particle"]["raster-particle-color"]),"raster-particle-max-speed":new gr(Ys["paint_raster-particle"]["raster-particle-max-speed"]),"raster-particle-speed-factor":new gr(Ys["paint_raster-particle"]["raster-particle-speed-factor"]),"raster-particle-fade-opacity-factor":new gr(Ys["paint_raster-particle"]["raster-particle-fade-opacity-factor"]),"raster-particle-reset-rate-factor":new gr(Ys["paint_raster-particle"]["raster-particle-reset-rate-factor"]),"raster-particle-elevation":new gr(Ys["paint_raster-particle"]["raster-particle-elevation"]),"raster-particle-color-use-theme":new Er({type:"string",default:"default","property-type":"data-driven"})}))},_,C,M),this._updateColorRamp(),this.lastInvalidatedAt=ih.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=YY({expression:p,evaluationKey:"rasterParticleSpeed",image:this.colorRamp,clips:[{start:0,end:_}],resolution:256}),this.colorRampTexture=null}_invalidateAnimationState(){this.lastInvalidatedAt=ih.now()}tileCoverLift(){return this.paint.get("raster-particle-elevation")}}class zfs extends Jy{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 c8e(N,p,_){const C=[0,0,1],M=kt([]);return gs(M,M,_?-Xr(N)+Math.PI:Xr(N)),wt(M,M,-Xr(p)),rt(C,C,M),Ve(C,C)}class xmt{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 ymt{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>Dr?M-Dr: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 d8e{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:Z,index:se,sourceLayerIndex:fe}of p){const xe=Z??(H.properties&&Object.hasOwn(H.properties,"id")?H.properties.id:void 0),be=bt(H,F);if(!this.layers[0]._featureFilter.filter(new Wn(this.zoom,{worldview:this.worldview,activeFloors:_.activeFloors}),be,C))continue;const Te={id:xe,sourceLayerIndex:fe,index:se,geometry:F?be.geometry:ut(H,C,M),properties:H.properties,type:H.type,patterns:{}},De=this.addFeature(Te,Te.geometry,be,z,C);De&&_.featureIndex.insert(H,Te.geometry,se,fe,this.index,this.instancesPerModel[De].instancedDataArray.length,256)}this.lookup=null}evaluateQueryRenderedFeaturePadding(){const p=this.layers[0].modelManager,_=this.layers[0].scope;let 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,Z=Math.min(Dr,Math.max(H/this.tileToMeter,256));C=Math.max(Z,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,Z=F.paint.get("model-rotation").evaluate(z,{},H),se=F.paint.get("model-scale").evaluate(z,{},H),fe=F.paint.get("model-translation").evaluate(z,{},H);Je(M.rotation,Z)&&Je(M.scale,se)&&Je(M.translation,fe)||(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(Uoe(this.activeReplacements,F))return!1;this.activeReplacements=F;let z=!1;for(const H in this.instancesPerModel){const Z=this.instancesPerModel[H],se=Z.instancedDataArray;for(const fe of Z.features){const xe=fe.instancedDataOffset,be=fe.instancedDataCount;for(let Te=0;TeDr;Ue=Ye?Ue-Dr:Ue;const nt=Math.floor(Ue),it=Math.floor(se.float32[De+1]);let ht=!1;for(const ot of this.activeReplacements)if(!hOe(ot,C,IY.Model,M)&&!(ot.min.x>nt||nt>ot.max.x||ot.min.y>it||it>ot.max.y)&&(ht=qoe(pOe(nt,it,p.canonical,ot.footprintTileId.canonical),ot.footprint),ht))break;se.float32[De]=ht?Ue+Dr:Ue,z=z||ht!==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,qms.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"),Z=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 ymt);const fe=this.instancesPerModel[se],xe=fe.instancedDataArray,be=new xmt(C,xe.length);let Te;if(M){const De=$Y(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>=Dr||Ue.y<0||Ue.y>=Dr)continue;if(this.lookupDim!==0&&Z){const nt=(this.lookupDim-1)/Dr,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){fe.instancesRoadElevation||(fe.instancesRoadElevation=[]);const nt=Te?Te.pointElevation(new xs(Ue.x,Ue.y)):0;fe.instancesRoadElevation.push(nt)}fe.instancesEvaluatedElevation.push(0),xe.float32[16*Ye]=Ue.x,xe.float32[16*Ye+1]=Ue.y}return be.instancedDataCount=fe.instancedDataArray.length-be.instancedDataOffset,be.instancedDataCount>0&&(p.id&&(fe.idToFeaturesIndex[p.id]=fe.features.length),fe.features.push(be),this.evaluate(be,{},fe,!1)),se}getModelUris(){return this.modelUris}evaluate(p,_,C,M){const F=this.layers[0],z=p.feature,H=this.canonical,Z=p.rotation=F.paint.get("model-rotation").evaluate(z,_,H),se=p.scale=F.paint.get("model-scale").evaluate(z,_,H),fe=p.translation=F.paint.get("model-translation").evaluate(z,_,H),{r:xe,g:be,b:Te}=F.paint.get("model-color").evaluate(z,_,H),De=F.paint.get("model-color-mix-intensity").evaluate(z,_,H),Ue=[];this.maxVerticalOffset0?Math.sqrt(Ye):0;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])),Wut(Ue,Z,se);const it=Math.round(100*De)+Te/1.05;for(let ht=0;ht10?this.tileToMeter:K(H,At)),Nt[yt+4]=fe[0],Nt[yt+5]=fe[1],Nt[yt+6]=fe[2]+(C.instancesRoadElevation?C.instancesRoadElevation[ot]:0)+is,Nt[yt+7]=Ue[0],Nt[yt+8]=Ue[1],Nt[yt+9]=Ue[2],Nt[yt+10]=Ue[4],Nt[yt+11]=Ue[5],Nt[yt+12]=Ue[6],Nt[yt+13]=Ue[8],Nt[yt+14]=Ue[9],Nt[yt+15]=Ue[10],C.instancesEvaluatedElevation[ot]=fe[2]}}}oa(d8e,"ModelBucket",{omit:["layers"]}),oa(ymt,"PerModelAttributes"),oa(xmt,"ModelFeature");const vmt=new WeakMap;class Bfs{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=vmt.get(_);if(C===void 0){const F=p.gl,z=F.getUniformBlockIndex(_,"ModelPartStyleUniform");C=z!==F.INVALID_INDEX,C&&F.uniformBlockBinding(_,z,0),vmt.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 u8e=new Float32Array(262144),rR=new Uint8Array(262144),Ele=[0,0,0],Tle=[0,0,0];function bmt(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,bmt(_));return p}function _mt(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)_mt(C,p,_)}class wmt{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:bmt(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 jmt{constructor(p,_,C,M,F,z,H,Z){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=Z,this.dirty=!0,this.needsPartStyleUBOs=!1,this.filter=null,this.nodesInfo=[];for(const se of _)this.nodesInfo.push(new wmt(se)),_mt(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(!Lr(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 _)VOe(C.node,p,!0);for(const C of _)ple(C.node);this.uploaded=!0}}createPartStyleUBOs(p){for(const _ of this.getNodesInfo())_.needsPartStyleUBO&&(_.partStyleUBO=new Bfs(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||JY(C.paint.get("model-color").value,z)||JY(C.paint.get("model-color-mix-intensity").value,z)||JY(C.paint.get("model-roughness").value,z)||JY(C.paint.get("model-emissive-strength").value,z)||JY(C.paint.get("model-height-based-emissive-strength-multiplier").value,z)){this.projection=M,this.brightness=F;const H=this.getNodesInfo();for(const Z of H)Z.state=null;return!0}return!1}evaluateTransform(p,_){if(p.transform.zoom===this.zoom)return;this.zoom=p.transform.zoom;const 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(Lr(z,M.state))continue;M.state=structuredClone(z);const H=M.node.meshes&&M.node.meshes[0].hasFeatureData,Z=this.id.canonical;if(M.hasTranslucentParts=!1,H){for(let se=0;se=Nt)continue;const Vn=u8e[jn],Cs=Math.abs(Vn);Cs>ns&&(Jt=Vn,ns=Cs,Ps=cn,Gs=pn)}if(ns>.1){const pn=1-(Nt+.5*Math.abs(Ps*Gs))/De;let cn=_._dem.get(At,is)+Jt*pn;const jn=_._dem.get(At+Ps,is+Gs),Vn=_._dem.get(At-Ps,is-Gs,!0);(cn-jn)*(cn-Vn)>0&&(cn=(jn+Vn)/2),u8e[$t]=_._dem.set(At,is,cn),rR[$t]=Nt}}}}}H&&(_._demTile.needsDEMTextureUpload=!0,_._dem._timestamp=ih.now())}setFilter(p){this.filter=p?hY(p):null}getNodesInfo(){return this.filter?this.nodesInfo.filter(p=>this.filter.filter(new Wn(this.id.overscaledZ,{worldview:this.worldview}),p.feature,this.id.canonical)):this.nodesInfo}destroy(){const p=this.getNodesInfo();for(const _ of p)ple(_.node),HOe(_.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,Xe(C,C,M),F.node.meshBVH){const xe=C[0],be=C[1];Ele[0]=xe-1,Ele[1]=be-1,Ele[2]=-1e3,Tle[0]=xe+1,Tle[1]=be+1,Tle[2]=1e3;const Te=F.node.meshBVH.findHighestPoint(Ele,Tle);if(Te!==null)return{height:Te,maxHeight:F.feature.properties.height,hidden:F.hiddenByReplacement,verticalScale:F.evaluatedScale[2]};continue}if(!z.heightmap)continue;const Z=(C[0]-z.aabb.min[0])/(z.aabb.max[0]-z.aabb.min[0])*nR|0,se=Math.min(63,(C[1]-z.aabb.min[1])/(z.aabb.max[1]-z.aabb.min[1])*nR|0)*nR+Math.min(63,Z),fe=z.heightmap[se];if(fe<0&&F.node.footprint){const xe=[];if(F.node.footprint.grid.query(new xs(p,_),new xs(p,_),xe),xe.length>0)return{height:void 0,maxHeight:F.feature.properties.height,hidden:F.hiddenByReplacement,verticalScale:F.evaluatedScale[2]};continue}return F.hiddenByReplacement?void 0:{height:fe,maxHeight:F.feature.properties.height,hidden:!1,verticalScale:F.evaluatedScale[2]}}}}function JY(N,p){return N instanceof U_&&!N.isLightConstant&&p}function $fs(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 Ufs(N){const p=N.partStyle;for(let _=0;_{let ht=kmt,ot=0,yt=kmt;if(!it){const $t=M.style.light,Jt=$t.properties.get("position");if(ht=[-Jt.x,-Jt.y,Jt.z],$t.properties.get("anchor")==="viewport"){const Ps=f();x(Ps,-M.transform.angle),at(ht,ht,Ps)}const ns=$t.properties.get("color").toNonPremultipliedRenderColor(null);ot=$t.properties.get("intensity"),yt=[ns.r,ns.g,ns.b]}const Nt=fe.alphaMode==="MASK",is=be.paint.get("model-ambient-occlusion-intensity"),At=be.paint.get("model-color").constantOr(Ci.white).toNonPremultipliedRenderColor(null);return At.a=be.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||h8e,u_lightpos:ht,u_lightintensity:ot,u_lightcolor:yt,u_camera_pos:Te,u_opacity:F,u_baseTextureIsAlpha:0,u_alphaMask:+Nt,u_alphaCutoff:fe.alphaCutoff,u_baseColorFactor:z.toNonPremultipliedRenderColor(null).toArray01(),u_emissiveFactor:H.toNonPremultipliedRenderColor(null).toArray01(),u_metallicFactor:Z,u_roughnessFactor:se,u_baseColorTexture:Gv.BaseColor,u_metallicRoughnessTexture:Gv.MetallicRoughness,u_normalTexture:Gv.Normal,u_occlusionTexture:Gv.Occlusion,u_emissionTexture:Gv.Emission,u_lutTexture:Gv.LUT,u_color_mix:At.toArray01(),u_aoIntensity:is,u_emissive_strength:xe,u_occlusionTextureTransform:De||[0,0,0,0],u_dithered_discard_threshold:nt,u_model_mesh_params:[0,1,0,0]}},Smt=(N,p=h8e,_=h8e)=>({u_matrix:N,u_instance:p,u_node_matrix:_}),f8e=7680;class cj{constructor(p,_,C,M,F,z){this.test=p,this.ref=_,this.mask=C,this.fail=M,this.depthFail=F,this.pass=z}}cj.disabled=new cj({func:519,mask:0},0,0,f8e,f8e,f8e);const Mle=770,t$=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,t$,1,t$],Ci.transparent,[!0,!0,!0,!0]),wh.alphaBlendedNonPremultiplied=new wh([Mle,t$,Mle,t$],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,t$],Ci.transparent,[!0,!0,!0,!0]),wh.additive=new wh([1,1,1,1],Ci.transparent,[!0,!0,!0,!0]),wh.additiveAlphaWeighted=new wh([Mle,1,773,1],Ci.transparent,[!0,!0,!0,!0]),wh.additiveAlphaWeightedUnboundedAlpha=new wh([Mle,1,1,1],Ci.transparent,[!0,!0,!0,!0]);class wy{constructor(p,_,C){this.func=p,this.mask=_,this.range=C}}wy.ReadOnly=!1,wy.ReadWrite=!0,wy.disabled=new wy(519,wy.ReadOnly,[0,1]);const p8e=1029,g8e=2305;class jy{constructor(p,_,C){this.enable=p,this.mode=_,this.frontFace=C}}jy.disabled=new jy(!1,p8e,g8e),jy.backCCW=new jy(!0,p8e,g8e),jy.backCW=new jy(!0,p8e,2304),jy.frontCW=new jy(!0,1028,2304),jy.frontCCW=new jy(!0,1028,g8e);class x8e{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(ta((this.left+p-this.right)/2,0,p),ta((this.top+_-this.bottom)/2,0,_))}equals(p){return this.top===p.top&&this.bottom===p.bottom&&this.left===p.left&&this.right===p.right}clone(){return new x8e(this.top,this.bottom,this.left,this.right)}toJSON(){return{top:this.top,bottom:this.bottom,left:this.left,right:this.right}}}function Cmt(N,p){const _=Ba(N,3);X(N,p),io(N,3,_)}function y8e(N,p){const _=kt([]);return ks(_,_,-p),wt(_,_,-N),_}function Amt(N,p){const _=[N[0],N[1],0],C=[p[0],p[1],0];if(ce(_)>=1e-15){const z=Ve([],_);Fe(C,z,ze(C,z)),p[0]=C[0],p[1]=C[1]}const M=qe([],p,N);if(ss(M)<1e-15)return null;const F=Math.atan2(-M[1],M[0]);return y8e(Math.atan2(Math.sqrt(N[0]*N[0]+N[1]*N[1]),-N[2]),F)}class Emt{constructor(p,_){this.position=p,this.orientation=_}get position(){return this._position}set position(p){if(p){const _=p instanceof Q?p:new Q(p[0],p[1],p[2]);this._renderWorldCopies&&(_.x=fl(_.x,0,1)),this._position=_}else this._position=null}lookAtPoint(p,_,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=Amt(H,_)}setPitchBearing(p,_){this.orientation=y8e(Xr(p),Xr(-_))}}class Ple{constructor(p,_){this._transform=w([]),this.orientation=_,this.position=p}get mercatorPosition(){const p=this.position;return new Q(p[0],p[1],p[2])}get position(){const p=Ba(this._transform,3);return[p[0],p[1],p[2]]}set position(p){var _;p&&io(this._transform,3,[(_=p)[0],_[1],_[2],1])}get orientation(){return this._orientation}set orientation(p){this._orientation=p||kt([]),p&&Cmt(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=y8e(p,_),Cmt(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:Jd(p,_?qd(this.position[1]):this.position[1]),M=this.forward();return(C-this.position[2])/M[2]}clone(){return new Ple([...this.position],[...this.orientation])}}const Vfs=Math.tan(85*Math.PI/180);function v8e(N,p,_,C,M,F,z){const H=y();if(_)if(F.name==="globe"){const Z=function(se,fe){const{x:xe,y:be}=se.point,Te=Pdt(xe,be,se.worldSize/se._pixelsPerMercatorPixel,0,0);return E(Te,Te,lOe(HC(fe)))}(M,p);E(H,H,Z)}else{const Z=m([],z);H[0]=Z[0],H[1]=Z[1],H[4]=Z[2],H[5]=Z[3],C||O(H,H,M.angle)}else E(H,M.labelPlaneMatrix,N);return H}function uM(N,p,_,C){const M=[N,p,_,1];_?Ft(M,M,C):gOe(M,M,C);const F=M[3];return M[0]/=F,M[1]/=F,M[2]/=F,M}function Tmt(N,p){return Math.min(.5+N/p*.5,1.5)}function Hfs(N,p){const _=N[0]/N[3],C=N[1]/N[3];return _>=-p[0]&&_<=p[0]&&C>=-p[1]&&C<=p[1]}function Mmt(N,p,_,C,M,F,z,H,Z,se,fe,xe,be,Te,De,Ue,Ye,nt){const{lineStartIndex:it,glyphStartIndex:ht,segment:ot}=H,yt=ht+H.numGlyphs,Nt=it+H.lineLength,is=p.getoffsetX(ht),At=p.getoffsetX(yt-1),$t=Ile(N*is,_,C,M,F,z,ot,it,Nt,Z,se,fe,xe,be,!0,Te,De,Ue,Ye,nt);if(!$t)return null;const Jt=Ile(N*At,_,C,M,F,z,ot,it,Nt,Z,se,fe,xe,be,!0,Te,De,Ue,Ye,nt);return Jt?{first:$t,last:Jt}:null}function Pmt(N,p,_,C){return N===z3.horizontal&&Math.abs(C)>Math.abs(_)?{useVertical:!0}:N===z3.vertical?C>0?{needsFlipping:!0}:null:p!==0&&function(M,F){return M===0||Math.abs(F/M)>Vfs}(_,C)?p===1?{needsFlipping:!0}:null:_<0?{needsFlipping:!0}:null}function Imt(N,p,_,C,M,F,z,H,Z,se,fe,xe,be,Te,De,Ue,Ye,nt,it,ht,ot){const yt=p/24,Nt=N.lineOffsetX*yt,is=N.lineOffsetY*yt,{lineStartIndex:At,glyphStartIndex:$t,numGlyphs:Jt,segment:ns,writingMode:Ps,flipState:Gs}=N,pn=At+N.lineLength,cn=jn=>{if(fe){const[an,Ln,In]=jn.up,qn=se.length;Joe(fe,qn+0,an,Ln,In),Joe(fe,qn+1,an,Ln,In),Joe(fe,qn+2,an,Ln,In),Joe(fe,qn+3,an,Ln,In)}const[Vn,Cs,Zs]=jn.point;eR(se,Vn,Cs,Zs,jn.angle)};if(Jt>1){const jn=Mmt(yt,H,Nt,is,_,xe,be,N,Z,F,Te,Ue,!1,Ye,nt,it,ht,ot);if(!jn)return{notEnoughRoom:!0};if(C&&!_){let[Vn,Cs,Zs]=jn.first.point,[an,Ln,In]=jn.last.point;[Vn,Cs]=uM(Vn,Cs,Zs,z),[an,Ln]=uM(an,Ln,In,z);const qn=Pmt(Ps,Gs,(an-Vn)*De,Ln-Cs);if(N.flipState=qn&&qn.needsFlipping?1:2,qn)return qn}cn(jn.first);for(let Vn=$t+1;Vn<$t+Jt-1;Vn++){const Cs=Ile(yt*H.getoffsetX(Vn),Nt,is,_,xe,be,ns,At,pn,Z,F,Te,Ue,!1,!1,Ye,nt,it,ht,ot);if(!Cs)return se.length-=4*(Vn-$t),{notEnoughRoom:!0};cn(Cs)}cn(jn.last)}else{if(C&&!_){const Vn=uM(be.x,be.y,0,M),Cs=At+ns+1,Zs=new xs(Z.getx(Cs),Z.gety(Cs)),an=uM(Zs.x,Zs.y,0,M),Ln=an[3]>0?an:Dmt(be,Zs,Vn,1,M,void 0,Ye,nt.canonical),In=Pmt(Ps,Gs,(Ln[0]-Vn[0])*De,Ln[1]-Vn[1]);if(N.flipState=In&&In.needsFlipping?1:2,In)return In}const jn=Ile(yt*H.getoffsetX($t),Nt,is,_,xe,be,ns,At,pn,Z,F,Te,Ue,!1,!1,Ye,nt,it,ht,ot);if(!jn)return{notEnoughRoom:!0};cn(jn)}return{}}function Lmt(N,p,_){const C=1<0?1:-1,Nt=0;C&&(yt*=-1,Nt=Math.PI),yt<0&&(Nt+=Math.PI);let is=H+z+(yt>0?0:1)|0,At=M,$t=M,Jt=0,ns=0;const Ps=Math.abs(ot),Gs=[],pn=[];let cn=F,jn=cn,Vn=Ke([]);const Cs=()=>Dmt(jn,cn,$t,Ps-Jt+1,fe,be,Ue,Ye.canonical,ht);for(;Jt+ns<=Ps;){if(is+=yt,is=Z)return null;if($t=At,jn=cn,Gs.push($t),Te&&pn.push(jn),cn=new xs(se.getx(is),se.gety(is)),At=xe[is],!At){const lr=Rmt(cn,Ye.canonical,fe,Ue,be,ht);At=lr[3]>0?xe[is]=lr:Cs()}Jt+=ns;const zn=pt([],At,$t),Ir=Be($t,At);if(_&&Ir>0&&ns>0&&ze(Vn,zn)/(ns*Ir)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)),Z=p.pointCoordinate(H);if(!Z)continue;const se=1/Math.hypot(Z[0]-this._camera.position[0],Z[1]-this._camera.position[1]);M+=Z[3]*se,F+=se}return F===0?NaN:M/F}get center(){return this._center}set center(p){p.lat===this._center.lat&&p.lng===this._center.lng||(this._unmodified=!1,this._center=p,this._terrainEnabled()&&(this.cameraElevationReference==="ground"?this._updateCameraOnTerrain():this._updateZoomFromElevation()),this._constrain(),this._calcMatrices())}_updateZoomFromElevation(){if(this._seaLevelZoom==null||!this._elevation)return;const p=this._seaLevelZoom,_=this._elevation.getAtPointOrZero(this.locationCoordinate(this.center)),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=iM(be,xe,Te,De,Ue);Z.has(Ye)||(F.push(new mg(xe,be,Te,De,Ue)),Z.add(Ye))};for(let xe=0;xebe.canonical.z)continue;const Te=be.canonical,De=be.overscaledZ,Ue=be.wrap,Ye=1<0,ht=Te.y+10,yt=be.wrap-(it?0:1),Nt=be.wrap+(nt?0:1),is=it?Te.x-1:Ye-1,At=nt?Te.x+1:0;if(z)C[0]<0?(se(De,Nt,Te.z,At,Te.y),C[1]<0&&ht&&(se(De,Ue,Te.z,Te.x,Te.y+1),se(De,Nt,Te.z,At,Te.y+1)),C[1]>0&&ot&&(se(De,Ue,Te.z,Te.x,Te.y-1),se(De,Nt,Te.z,At,Te.y-1))):C[0]>0?(se(De,yt,Te.z,is,Te.y),C[1]<0&&ht&&(se(De,Ue,Te.z,Te.x,Te.y+1),se(De,yt,Te.z,is,Te.y+1)),C[1]>0&&ot&&(se(De,Ue,Te.z,Te.x,Te.y-1),se(De,yt,Te.z,is,Te.y-1))):C[1]<0&&ht?se(De,Ue,Te.z,Te.x,Te.y+1):ot&&se(De,Ue,Te.z,Te.x,Te.y-1);else{const $t=be.visibleQuadrants;1&$t&&(se(De,yt,Te.z,is,Te.y),ot&&(se(De,Ue,Te.z,Te.x,Te.y-1),se(De,yt,Te.z,is,Te.y-1))),2&$t&&(se(De,Nt,Te.z,At,Te.y),ot&&(se(De,Ue,Te.z,Te.x,Te.y-1),se(De,Nt,Te.z,At,Te.y-1))),4&$t&&(se(De,yt,Te.z,is,Te.y),ht&&(se(De,Ue,Te.z,Te.x,Te.y+1),se(De,yt,Te.z,is,Te.y+1))),8&$t&&(se(De,Nt,Te.z,At,Te.y),ht&&(se(De,Ue,Te.z,Te.x,Te.y+1),se(De,Nt,Te.z,At,Te.y+1)))}}const fe=[];for(const xe of F)F.some(be=>xe.isChildOf(be))||fe.push(xe);if(F=fe.filter(xe=>!p.some(be=>!!(xe.overscaledZ<_&&be.isChildOf(xe))||xe.equals(be)||xe.isChildOf(be))),H){const xe=1<<_,be=this.projection.name==="globe"?this._camera.mercatorPosition:this.pointCoordinate(this.getCameraPoint()),Te=[xe*be.x,xe*be.y],De=4,Ue=De*De;F=F.filter(Ye=>{const nt=Ye.canonical.x+.5-Te[0],it=Ye.canonical.y+.5-Te[1];return nt*nt+it*it{const is=iM(ht,it,ot,yt,Nt);F.has(is)||(M.push(new mg(it,ht,ot,yt,Nt)),F.add(is))},H=p.reduce((it,ht)=>Math.max(it,ht.overscaledZ),C),Z=1<{const ot=Math.floor(it[0]),yt=Math.floor(it[1]),Nt=(it[0]-ot)*Dr,is=(it[1]-yt)*Dr,At=Math.floor(ht[0]),$t=Math.floor(ht[1]),Jt=(ht[0]-At)*Dr,ns=(ht[1]-$t)*Dr;for(let Ps=-1;Ps<=1;Ps++){const Gs=ot+Ps;if(!(Gs<0||Gs>=Z)){fe.x=Nt-Ps*Dr,xe.x=Jt-(Gs-At)*Dr;for(let pn=-1;pn<=1;pn++){const cn=yt+pn;fe.y=is-pn*Dr,xe.y=ns-(cn-$t)*Dr,F9(fe,xe,se)&&z(H,0,C,Gs,cn)}}}},Te=_.points,De=Te[3],Ue=Te[2],Ye=this._projectToGround(De,Te[7]),nt=this._projectToGround(Ue,Te[6]);return be(De,Ye),be(Ue,nt),M}_projectToGround(p,_){return dt(te(),p,_,p[2]/(p[2]-_[2]))}_projectToZ(p,_,C){const M=p[2]-_[2];return Math.abs(M)<1e-6?J(p):dt(te(),p,_,(p[2]-C)/M)}extendTileCoverForTunnels(p,_,C,M){if(C<18)return[];const F=_.points,z=F[0],H=F[1],Z=F[4],se=F[5];if(Z[2]>=0&&se[2]>=0||z[2]<=0||H[2]<=0)return[];const fe=Z[2]<0?this._projectToZ(z,Z,0):Z,xe=se[2]<0?this._projectToZ(H,se,0):se,be=-M,Te=Z[2]3&&(Ue.length=3),Ue}_findExtensionTilesInQuad(p,_,C,M){const F=[],z=new Set;for(const At of p)z.add(At.key);const H=p.reduce((At,$t)=>Math.max(At,$t.overscaledZ),_),Z=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])],fe=C[0][0],xe=C[1][0],be=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(fe,xe,be,Te))),ht=Math.min(Z-1,Math.ceil(Math.max(fe,xe,be,Te))-1),ot=Math.max(0,Math.floor(Math.min(De,Ue,Ye,nt))),yt=Math.min(Z-1,Math.ceil(Math.max(De,Ue,Ye,nt))-1);for(let At=ot;At<=yt;At++)for(let $t=it;$t<=ht;$t++){if(!KFe(se,$t,At,$t+1,At+1))continue;const Jt=iM(0,H,_,$t,At);z.has(Jt)||(F.push(new mg(H,0,_,$t,At)),z.add(Jt))}const Nt=M[0],is=M[1];return F.sort((At,$t)=>{const Jt=At.canonical.x+.5-Nt,ns=At.canonical.y+.5-is,Ps=$t.canonical.x+.5-Nt,Gs=$t.canonical.y+.5-is;return Jt*Jt+ns*ns-(Ps*Ps+Gs*Gs)||At.canonical.x-$t.canonical.x||At.canonical.y-$t.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),Z=this.center.lat,se=1<<_,fe=[se*H.x,se*H.y,0],xe=this.projection.name==="globe",be=!xe,Te=$3.fromInvProjectionMatrix(this.invProjMatrix,this.worldSize,_,be),De=xe?this._camera.mercatorPosition:this.pointCoordinate(this.getCameraPoint()),Ue=se*Jd(1,this.center.lat),Ye=this._camera.position[2]/Jd(1,this.center.lat),nt=[se*De.x,se*De.y,Ye*(be?1:Ue)],it=xe||M,ht=this.cameraToCenterDistance/p.tileSize*(p.roundZoom?1:.502),ot=this.isLODDisabled(!0)?_:0;let yt;if(this._elevation&&p.isTerrainDEM)yt=1e4*this._elevation.exaggeration();else if(this._elevation){const Cs=this._elevation.getMinMaxForVisibleTiles();yt=Cs?Cs.max:this._centerAltitude}else yt=this._centerAltitude;const Nt=p.isTerrainDEM?-yt:this._elevation?this._elevation.getMinElevationBelowMSL():0,is=this.projection.isReprojectedInTileSpace?Hut(this):1,At=Cs=>{const an=new Q(Cs.x+25e-6,Cs.y,Cs.z),Ln=new Q(Cs.x,Cs.y+25e-6,Cs.z),In=Cs.toLngLat(),qn=an.toLngLat(),Dn=Ln.toLngLat(),ar=this.locationCoordinate(In),zn=this.locationCoordinate(qn),Ir=this.locationCoordinate(Dn),lr=Math.hypot(zn.x-ar.x,zn.y-ar.y),_r=Math.hypot(Ir.x-ar.x,Ir.y-ar.y);return Math.sqrt(lr*_r)*is/25e-6},$t=Cs=>{const Zs=yt,an=Nt;return{aabb:Fdt(this,se,0,0,0,Cs,an,Zs,this.projection),zoom:0,x:0,y:0,minZ:an,maxZ:Zs,wrap:Cs,fullyVisible:!1}},Jt=[];let ns=[];const Ps=_,Gs=p.reparseOverscaled?C:_,pn=(Ye-this._centerAltitude)*Ue,cn=Cs=>{if(!this._elevation||!Cs.tileID||!z)return;const Zs=this._elevation.getMinMaxForTile(Cs.tileID),an=Cs.aabb;Zs?(an.min[2]=Zs.min,an.max[2]=Zs.max,an.center[2]=(an.min[2]+an.max[2])/2):(Cs.shouldSplit=Vn(Cs),Cs.shouldSplit||(an.min[2]=an.max[2]=an.center[2]=this._centerAltitude))},jn=(Cs,Zs)=>{if(.707*Zs{if(Cs.zoom=.9)return!0}else if(F&&(Ln=Cs.aabb.distanceZ(nt)*Ue),this.projection.isReprojectedInTileSpace&&C<=5){const _r=Math.pow(2,Cs.zoom),Wa=At(new Q((Cs.x+.5)/_r,(Cs.y+.5)/_r));In=Wa>.85?1:Wa}if(!z&&!xe){const _r=Math.sqrt(Zs*Zs+an*an+Ln*Ln);let Wa=(1<0;){const Cs=Jt.pop(),Zs=Cs.x,an=Cs.y;let Ln=Cs.fullyVisible;const In=()=>this.projection.name==="globe"&&(Cs.y===0||Cs.y===(1<qn)continue;let Dn=0;if(!Ln){let lr=it?Cs.aabb.intersectsPrecise(Te):Cs.aabb.intersectsPreciseFlat(Te);if(lr===0&&In()){const _r=new aM(Cs.zoom,Zs,an);lr=iOe(this,se,_r,!0).intersectsPrecise(Te)}if(lr===0)continue;if(p.calculateQuadrantVisibility)if(Te.containsPoint(Cs.aabb.center))Dn=15;else for(let _r=0;_r<4;_r++)Cs.aabb.quadrant(_r).intersects(Te)!==0&&(Dn|=1<<_r)}const ar=fe[0]-(.5+Zs+(Cs.wrap<>1),zn={aabb:z?Cs.aabb.quadrant(qn):Fdt(this,se,Cs.zoom+1,Dn,ar,Cs.wrap,Cs.minZ,Cs.maxZ,this.projection),zoom:Cs.zoom+1,x:Dn,y:ar,wrap:Cs.wrap,fullyVisible:Ln,tileID:void 0,shouldSplit:void 0,minZ:Cs.minZ,maxZ:Cs.maxZ};F&&!xe&&(zn.tileID=new mg(Cs.zoom+1===Ps?Gs:Cs.zoom+1,Cs.wrap,Cs.zoom+1,Dn,ar),cn(zn)),Jt.push(zn)}}if(this.fogCullDistSq){const Cs=this.fogCullDistSq,Zs=this.horizonLineFromTop();ns=ns.filter(an=>{const Ln=[0,0,0,1],In=[Dr,Dr,0,1],qn=this.calculateFogTileMatrix(an.tileID.toUnwrapped());Ft(Ln,Ln,qn),Ft(In,In,qn);const Dn=(lr=Ln,_r=In,(Ir=[])[0]=Math.min(lr[0],_r[0]),Ir[1]=Math.min(lr[1],_r[1]),Ir[2]=Math.min(lr[2],_r[2]),Ir[3]=Math.min(lr[3],_r[3]),Ir),ar=function(oi,Fa,Ai){return oi[0]=Math.max(Fa[0],Ai[0]),oi[1]=Math.max(Fa[1],Ai[1]),oi[2]=Math.max(Fa[2],Ai[2]),oi[3]=Math.max(Fa[3],Ai[3]),oi}([],Ln,In),zn=function(oi,Fa){let Ai=0;for(let Ni=0;Ni<2;++Ni)oi[Ni]>0&&(Ai+=(oi[Ni]-0)*(oi[Ni]-0)),Fa[Ni]<0&&(Ai+=(0-Fa[Ni])*(0-Fa[Ni]));return Ai}(Dn,ar);var Ir,lr,_r;if(zn===0)return!0;let Wa=!1;const Ka=this._elevation;if(Ka&&zn>Cs&&Zs!==0){const oi=this.calculateProjMatrix(an.tileID.toUnwrapped());let Fa;p.isTerrainDEM||(Fa=Ka.getMinMaxForTile(an.tileID)),Fa||(Fa={min:Nt,max:yt});const Ai=function(Fo){const rl=Math.round((Fo+45+360)%360/90)%4;return Th[rl]}(this.rotation),Ni=[Ai[0]*Dr,Ai[1]*Dr,Fa.max];Xe(Ni,Ni,oi),Wa=(1-Ni[1])*this.height*.5Cs.distanceSq-Zs.distanceSq).map(Cs=>Cs.tileID)}resize(p,_){this.width=p,this.height=_,this.pixelsToGLUnits=[2/p,-2/_],this._constrain(),this._calcMatrices()}get unmodified(){return this._unmodified}zoomScale(p){return Math.pow(2,p)}scaleZoom(p){return Math.log2(p)}project(p){const _=ta(p.lat,-85.051129,L),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/Jd(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(_),Z=this.pointCoordinate(F);C=H.x-Z.x,M=H.y-Z.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=_?Jd(_,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];ys(M,M,1/M[3]),ys(F,F,1/z);const H=M[2],Z=F[2];return{p0:M,p1:F,t:H===Z?0:(C-H)/(Z-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),ys(_,_,1/_[3]),ys(C,C,1/C[3]),_[2]=Jd(_[2],this._center.lat)*this.worldSize,C[2]=Jd(C[2],this._center.lat)*this.worldSize,ys(_,_,1/this.worldSize),ys(C,C,1/this.worldSize),new Moe([_[0],_[1],_[2]],Ve([],pt([],C,_)))}rayIntersectionCoordinate(p){const{p0:_,p1:C,t:M}=p,F=Jd(_[2],this._center.lat),z=Jd(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 Z=0;Z<10&&F-M>z;Z++){H.y=ya(M,F,.66);const se=this.projection.pointCoordinate3D(this,H.x,H.y);se?(F=H.y,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)),Z=this.pointLocation3D(new xs(_,C));let se=Math.min(F.lng,z.lng,H.lng,Z.lng),fe=Math.max(F.lng,z.lng,H.lng,Z.lng),xe=Math.min(F.lat,z.lat,H.lat,Z.lat),be=Math.max(F.lat,z.lat,H.lat,Z.lat);const Te=Math.pow(2,-this.zoom)/16*270,De=this.projection.name==="globe"?1:4,Ue=(Ye,nt,it,ht,ot)=>{const yt=(Ye+it)/2,Nt=(nt+ht)/2,is=new xs(yt,Nt),{lng:At,lat:$t}=this.pointLocation3D(is),Jt=Math.max(0,se-At,xe-$t,At-fe,$t-be);se=Math.min(se,At),fe=Math.max(fe,At),xe=Math.min(xe,$t),be=Math.max(be,$t),(otTe)&&(Ue(Ye,nt,yt,Nt,ot+1),Ue(yt,Nt,it,ht,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 ht=w(new Float64Array(16));E(ht,it.pixelMatrix,it.globeMatrix);const ot=[0,Hv,0],yt=[0,V_,0];return Xe(ot,ot,ht),Xe(yt,yt,ht),[ot[0]>0&&ot[0]<=it.width&&ot[1]>0&&ot[1]<=it.height&&!dOe(it,new Il(it.center.lat,90)),yt[0]>0&&yt[0]<=it.width&&yt[1]>0&&yt[1]<=it.height&&!dOe(it,new Il(it.center.lat,-90))]}(this);Ye?(be=90,fe=180,se=-180):nt&&(xe=-90,fe=180,se=-180)}return new H_(new Il(se,xe),new Il(fe,be))}_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),Z=new xs(z,C),se=new xs(z,F),fe=new xs(M,F);let xe=this.pointCoordinate(H,p),be=this.pointCoordinate(Z,p);const Te=this.pointCoordinate(se,_),De=this.pointCoordinate(fe,_),Ue=(Ye,nt)=>(nt.y-Ye.y)/(nt.x-Ye.x);return xe.y>1&&be.y>=0?xe=new Q((1-De.y)/Ue(De,xe)+De.x,1):xe.y<0&&be.y<=1&&(xe=new Q(-De.y/Ue(De,xe)+De.x,0)),be.y>1&&xe.y>=0?be=new Q((1-Te.y)/Ue(Te,be)+Te.x,1):be.y<0&&xe.y<=1&&(be=new Q(-Te.y/Ue(Te,be)+Te.x,0)),new H_().extend(this.coordinateLocation(xe)).extend(this.coordinateLocation(be)).extend(this.coordinateLocation(De)).extend(this.coordinateLocation(Te))}_getBoundsRectangularTerrain(){const p=this.elevation;if(!p.visibleDemTiles.length||p.isUsingMockSource())return this._getBoundsRectangular(0,0);const _=p.visibleDemTiles.reduce((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-feTe&&(z=Te-Z),Te-be{for(let Gs=0;Gs<16;Gs++)$t[Gs]=ya(Jt[Gs],ns[Gs],Ps)})(H,H,Z,vo(this.pitch>=s$?1:this.pitch/s$))}else H=Z;const se=ne([],Z,z),fe=ne([],H,z);if(this.projection.isReprojectedInTileSpace){const yt=this.locationCoordinate(this.center);w(this._mat4Scratch);const Nt=this._mat4Scratch;I(Nt,Nt,[yt.x*this.worldSize,yt.y*this.worldSize,0]),E(Nt,Nt,Vut(this)),I(Nt,Nt,[-yt.x*this.worldSize,-yt.y*this.worldSize,0]),E(fe,fe,Nt),E(se,se,Nt),this.inverseAdjustmentMatrix=function(is){const At=Vut(is,!0);return m([],[At[0],At[1],At[4],At[5]])}(this)}else this.inverseAdjustmentMatrix=[1,0,0,1];if(P(this.mercatorMatrix,fe,[this.worldSize,this.worldSize,this.worldSize/F,1]),this.projMatrix=fe,A(this.invProjMatrix,this.projMatrix),_){const yt=this._camera.getCameraToClipPerspective(this._fov,this.width/this.height,this._nearZ,1/0);yt[8]=2*-p.x/this.width,yt[9]=2*p.y/this.height,ne(this._expandedFarZProjMatrixBuf,yt,z),this.expandedFarZProjMatrix=this._expandedFarZProjMatrixBuf}else this.expandedFarZProjMatrix=this.projMatrix;A(this._mat4Scratch,H),this.frustumCorners=nOe.fromInvProjectionMatrix(this._mat4Scratch,this.horizonLineFromTop(),this.height),this.cameraFrustum=$3.fromInvProjectionMatrix(this.invProjMatrix,this.worldSize,0,!_),W(this.skyboxMatrix,[1,-1,1]),R(this.skyboxMatrix,this.skyboxMatrix,this._pitch),O(this.skyboxMatrix,this.skyboxMatrix,this.angle),ae(this.starsProjMatrix,this._fov,this.width/this.height,this._nearZ,this._farZ);const xe=(Math.PI/2-this._pitch)*(this.height/this._fov)*this._horizonShift;b(this._mat4Scratch,this.starsProjMatrix),this._mat4Scratch[8]=2*-p.x/this.width,this._mat4Scratch[9]=2*(p.y+xe)/this.height,E(this.skyboxMatrix,this._mat4Scratch,this.skyboxMatrix);const be=this.point,Te=be.x,De=be.y,Ue=this.width%2/2,Ye=this.height%2/2,nt=Math.cos(this.angle),it=Math.sin(this.angle),ht=Te-Math.round(Te)+nt*Ue+it*Ye,ot=De-Math.round(De)+nt*Ye+it*Ue;if(b(this.alignedProjMatrix,fe),I(this.alignedProjMatrix,this.alignedProjMatrix,[ht>.5?ht-1:ht,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(Nt){const{x:is,y:At}=Nt.point,{lng:$t,lat:Jt}=Nt._center;return Pdt(is,At,Nt.worldSize,$t,Jt)}(this);const yt=[this.globeMatrix[12],this.globeMatrix[13],this.globeMatrix[14]];this.globeCenterInViewSpace=Xe(yt,yt,z),this.globeRadius=this.worldSize/2/Math.PI-1}else this.globeMatrix=this.pixelMatrixInverse;this._projMatrixCache={},this._alignedProjMatrixCache={},this._pixelsToTileUnitsCache={},this._expandedProjMatrixCache={}}_calcFogMatrices(){this._fogTileMatrixCache={};const p=this.cameraWorldSizeForFog,_=this.cameraPixelsPerMeter,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=ke([],this._camera.position,p,F),this._updateStateFromCamera()}_updateStateFromCamera(){const p=this._camera.position,_=this._camera.forward(),{pitch:C,bearing:M}=this._camera.getPitchBearing(),F=Jd(this._centerAltitude,this.center.lat)*this._pixelsPerMercatorPixel,z=this._mercatorZfromZoom(this._maxZoom)*Math.cos(Xr(this._maxPitch)),H=Math.max((p[2]-F)/Math.cos(C),z),Z=this._zoomFromMercatorZ(H);ke(p,p,_,H),this._pitch=ta(C,Xr(this.minPitch),Xr(this.maxPitch)),this.angle=fl(M,-Math.PI,Math.PI),this._setZoom(ta(Z,this._minZoom,this._maxZoom)),this._updateSeaLevelZoom(),this._center=this.coordinateLocation(new Q(p[0],p[1],p[2])),this._unmodified=!1,this._constrain(),this._calcMatrices()}_worldSizeFromZoom(p){return Math.pow(2,p)*this.tileSize}_mercatorZfromZoom(p){return this.cameraToCenterDistance/this._worldSizeFromZoom(p)}_minimumHeightOverTerrain(){const p=Math.min(this._seaLevelZoom??this._zoom,this._maxZoom)+4;return this._mercatorZfromZoom(p)}_zoomFromMercatorZ(p){return this.scaleZoom(this.cameraToCenterDistance/(Math.max(0,p)*this.tileSize))}zoomFromMercatorZAdjusted(p){let _=0,C=6,M=0,F=1/0;for(;C-_>1e-6&&C>_;){const z=_+.5*(C-_),H=this.tileSize*Math.pow(2,z),Z=this.getCameraToCenterDistance(this.projection,z,H),se=this.scaleZoom(Z/(Math.max(0,p)*this.tileSize)),fe=Math.abs(z-se);fese||be.y>1)return!0}return!1}isHorizonVisible(){return this.pitch+Eo(this.fovAboveCenter)>88||this.anyCornerOffEdge(new xs(0,0),new xs(this.width,this.height))}zoomDeltaToMovement(p,_){const C=ce(pt([],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=VY(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>=s$?1:this.pitch/s$))),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 $3.fromInvProjectionMatrix(this.invProjMatrix,this.worldSize,p,this.projection.zAxisUnit==="meters")}}const n$=(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,(fe-_._nearZ)/F,(fe-xe-_._nearZ)/F]}}};function _8e(N,p,_,C){const M=1<({u_matrix:N,u_color:p,u_overlay:0,u_overlay_scale:_}),KC=new Float64Array(16),hM=new Float64Array(16),Omt=new Float64Array(16),w8e=new Float64Array(16),j8e=new Float64Array(16),Lle=new Float64Array(16),Gfs=new Float64Array(16),Rle=[0,0,0],Wfs=new Float32Array(16),Dle=[0,0,0],Kfs=[0,0,0],N8e=[];function zmt(N,p,_){const C=_.cameraWorldSizeForFog/_.worldSize;return P(N,_.worldToFogMatrix,[C,C,1]),E(N,N,p),N}function tZ(N,p,_,C){return I(N,p,_),Je(C,Gms)||P(N,N,C),N}function Yfs(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 Zfs(N,p){return p.featureBuffer?N.partStyleUBO:null}function k8e(N,p,_,C,M,F=null){const z=_.material,H=C.context,{baseColorTexture:Z,metallicRoughnessTexture:se}=z.pbrMetallicRoughness,{normalTexture:fe,occlusionTexture:xe,emissionTexture:be}=z;function Te(Ue,Ye,nt){if(Ue&&(N.push(Ye),H.activeTexture.set(H.gl.TEXTURE0+nt),Ue.gfxTexture)){const{minFilter:it,magFilter:ht,wrapS:ot,wrapT:yt}=Ue.sampler;Ue.gfxTexture.bindExtraParam(it,ht,ot,yt)}}Te(Z,"HAS_TEXTURE_u_baseColorTexture",Gv.BaseColor),Te(se,"HAS_TEXTURE_u_metallicRoughnessTexture",Gv.MetallicRoughness),Te(fe,"HAS_TEXTURE_u_normalTexture",Gv.Normal),Te(xe,"HAS_TEXTURE_u_occlusionTexture",Gv.Occlusion),Te(be,"HAS_TEXTURE_u_emissionTexture",Gv.Emission),M&&(M.texture||(M.texture=new eut(C.context,M.image,[M.image.height,M.image.height,M.image.height],H.gl.RGBA8)),H.activeTexture.set(H.gl.TEXTURE0+Gv.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 S8e(N,p,_,C,M,F){const z=N.modelOpacity,H=p.context,Z=new wy(p.context.gl.LEQUAL,N.isLightMesh?wy.ReadOnly:wy.ReadWrite,p.depthRangeFor3D),se=p.transform,fe=N.mesh,xe=fe.material,be=xe.pbrMetallicRoughness,Te=p.style.fog;p.transform.projection.zAxisUnit==="pixels"?KC.set(N.nodeModelMatrix):E(KC,C.zScaleMatrix,N.nodeModelMatrix),E(KC,C.negCameraPosMatrix,KC),A(hM,KC),S(hM,hM);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),k8e(Ye.defines,nt,fe,p,De?null:_.lut);let ht=null;if(Te&&(ht=zmt(Omt,N.nodeModelMatrix,p.transform),se.projection.name!=="globe")){const is=fe.aabb.min,At=fe.aabb.max,[$t,Jt]=Te.getOpacityForBounds(ht,is[0],is[1],At[0],At[1]);Ye.overrideFog=$t>=LY||Jt>=LY}const ot=n$(p,_.paint.get("model-cutoff-fade-range"));ot.shouldRenderCutoff&&Ye.defines.push("RENDER_CUTOFF");const yt=p.getOrCreateProgram("model",Ye),Nt=m8e(N.worldViewProjection,KC,hM,null,p,z,be.baseColorFactor,xe.emissiveFactor,be.metallicFactor,be.roughnessFactor,xe,Ue,_,void 0,void 0,N.materialOverride,N.modelColor,1,yt.fixedDefines.includes("LIGHTING_3D_MODE"));p.uploadCommonUniforms(H,yt,null,ht,ot,N.lightOverrides),p.renderPass!=="shadow"&&it&&it.setupShadowsFromMatrix(N.nodeModelMatrix,yt),yt.draw(p,H.gl.TRIANGLES,Z,M,F,fe.material.doubleSided?jy.disabled:jy.backCCW,Nt,_.id,fe.vertexBuffer,fe.indexBuffer,fe.segments,_.paint,p.transform.zoom,void 0,nt)}function Bmt(N,p){return N.style._importedAsBasemap?"basemap":p.scope}function C8e(N,p,_,C,M,F,z,H,Z,se,fe){const xe=N.transform,be=!!p.isGeometryBloom&&p.isGeometryBloom;if(p.minZoom!==void 0&&N.transform.zoomp.maxZoom||be&&N.renderPass==="shadow")return;const Te=xe.projection.name==="globe"?mle(_,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:be,materialOverride:Ye,modelOpacity:Z,modelColor:se,lightOverrides:fe,node:p,modelMatrix:_});continue}const nt=Xe([],Ue.centroid,De);!xe.isOrthographic&&nt[2]<=0||F.push({mesh:Ue,depth:nt[2],modelIndex:M,worldViewProjection:De,nodeModelMatrix:Te,isLightMesh:be,materialOverride:Ye,modelOpacity:Z,modelColor:se,lightOverrides:fe,node:p,modelMatrix:_})}if(p.children)for(const Ue of p.children)C8e(N,Ue,_,C,M,F,z,H,Z,se,fe)}function sZ(N,p,_,C,M){const F=_.shadowRenderer;if(!F)return;const z=F.getShadowPassDepthMode(),H=M||F.calculateShadowPassMatrixFromMatrix(p),Z=Smt(H);_.getOrCreateProgram("modelDepth").draw(_,_.context.gl.TRIANGLES,z,cj.disabled,wh.disabled,jy.disabled,Z,C.id,N.vertexBuffer,N.indexBuffer,N.segments,C.paint,_.transform.zoom,void 0,void 0)}function $mt(N,p,_,C){const M=function(fe,xe){if(xe.footprintDebugMesh)return xe.footprintDebugMesh;if(!xe.footprint)return null;const be=fe.context,Te=xe.footprint.vertices,De=xe.footprint.indices,Ue=new Hs;Ue.reserve(Te.length);for(const Jt of Te)Ue.emplaceBack(Jt.x,Jt.y);const Ye=new qr;Ye.reserve(De.length);for(let Jt=0;Jt0){const be=F.terrain,Te=be.findDEMTileFor(H);Te&&Te.dem?Z=V9.create(be,H,Te):xe=0}if(xe===0&&(z.terrainElevationMin=0,z.terrainElevationMax=0),xe===z.validForExaggeration&&(xe===0||Z&&Z._demTile&&Z._demTile.tileID===z.validForDEMTile.id&&Z._dem._timestamp===z.validForDEMTile.timestamp))return!1;for(const be in z.instancesPerModel){const Te=z.instancesPerModel[be];for(let De=0;Dese&&(se=Te.max)}const fe=ta(C.x,F,z)-C.x,xe=ta(C.y,H,Z)-C.y,be=Jd(se,p.center.lat)-C.z;return p._zoomFromMercatorZ(Math.sqrt(fe*fe+xe*xe+be*be))}function qmt(N,p,_,C,M,F,z){const H=N.context,Z=N.renderPass==="shadow",se=N.shadowRenderer,fe=Z&&se?se.getShadowPassDepthMode():new wy(H.gl.LEQUAL,wy.ReadWrite,N.depthRangeFor3D),xe=N.isTileAffectedByFog(F),be=N.transform.projection.name==="globe";if(_.meshes)for(const Te of _.meshes){const De=be?[]:["MODEL_POSITION_ON_GPU"],Ue=[];let Ye,nt,it;const ht=!be&&C.instancedDataArray.length>20;ht&&De.push("INSTANCED_ARRAYS");const ot=n$(N,p.paint.get("model-cutoff-fade-range"));if(ot.shouldRenderCutoff&&De.push("RENDER_CUTOFF"),Z&&se)Ye=N.getOrCreateProgram("modelDepth",{defines:De}),nt=Smt(z.shadowTileMatrix,z.shadowTileMatrix,_.globalMatrix),it=wh.disabled;else{k8e(De,Ue,Te,N,p.paint.get("model-color-use-theme").constantOr("default")==="none"?null:p.lut),Ye=N.getOrCreateProgram("model",{defines:De,overrideFog:xe});const Nt=Te.material,is=Nt.pbrMetallicRoughness,At=p.paint.get("model-opacity").constantOr(1),$t=p.paint.get("model-emissive-strength").constantOr(0);nt=m8e(F.expandedProjMatrix,_.globalMatrix,Wfs,null,N,At,is.baseColorFactor,Nt.emissiveFactor,is.metallicFactor,is.roughnessFactor,Nt,$t,p,M,void 0,void 0,void 0,1,Ye.fixedDefines.includes("LIGHTING_3D_MODE")),se&&(z.shadowUniformsInitialized?Ye.setShadowUniformValues(H,se.getShadowUniformValues()):(se.setupShadows(F.toUnwrapped(),Ye,"model-tile"),z.shadowUniformsInitialized=!0)),it=ot.shouldRenderCutoff||At<1||Nt.alphaMode!=="OPAQUE"?wh.alphaBlended:wh.unblended}N.uploadCommonUniforms(H,Ye,F.toUnwrapped(),null,ot);const yt=Te.material.doubleSided?jy.disabled:jy.backCCW;if(ht)Ue.push(C.instancedDataBuffer),Ye.draw(N,H.gl.TRIANGLES,fe,cj.disabled,it,yt,nt,p.id,Te.vertexBuffer,Te.indexBuffer,Te.segments,p.paint,N.transform.zoom,void 0,Ue,C.instancedDataArray.length);else{const Nt=Z?"u_instance":"u_normal_matrix";for(let is=0;is0)if(N.targetLod<0)N.targetLod=p>C?1:0;else{const z=M>0?_/1e3/M:1;N.targetLod=ta(p>C?N.targetLod+z:N.targetLod-z,0,1)}else N.targetLod=0}function sps(N,p,_,C){if(!_.modelManager)return!0;const M=_.modelManager;if(!_.shadowRenderer)return!0;const F=_.shadowRenderer,z=p.aabb;let H=!0,Z=N.maxHeight;if(Z===0){let fe=0;for(const xe in N.instancesPerModel){const be=M.getModel(xe,C);be?fe=Math.max(fe,Math.max(Math.max(be.aabb.max[0],be.aabb.max[1]),be.aabb.max[2])):H=!1}Z=N.maxScale*fe*1.41+N.maxVerticalOffset,H&&(N.maxHeight=Z)}z.max[2]=Z,z.min[2]+=N.terrainElevationMin,z.max[2]+=N.terrainElevationMax,Xe(z.min,z.min,p.tileMatrix),Xe(z.max,z.max,p.tileMatrix);const se=z.intersects(F.getCurrentCascadeFrustum());return _.currentShadowCascade===0&&(N.isInsideFirstShadowMapFrustum=se===2),se===0}function nps(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:ta(((p-_)/(C-_)-M)/(F-M),0,1)}function rps(N,p,_,C){if(p.pitch<20)return 1;const M=p.getWorldToCameraMatrix();E(M,M,N);const F=ts(_.min[0],_.min[1],_.min[2],1);let z=Ft(Yt(),F,M),H=z,Z=z;F[1]=_.max[1],z=Ft(Yt(),F,M),H=z[1]Z[1]?z:Z,F[0]=_.max[0],z=Ft(Yt(),F,M),H=z[1]Z[1]?z:Z,F[1]=_.min[1],z=Ft(Yt(),F,M),H=z[1]Z[1]?z:Z;const se=ta(C[0],0,1),fe=100*p.pixelsPerMeter*ta(C[1],0,1),xe=ta(C[2],0,1),be=(Ue=Yt(),ot=(Ye=H)[1],yt=Ye[2],Nt=Ye[3],Ue[0]=(ht=Ye[0])+(it=se)*((nt=Z)[0]-ht),Ue[1]=ot+it*(nt[1]-ot),Ue[2]=yt+it*(nt[2]-yt),Ue[3]=Nt+it*(nt[3]-Nt),Ue),Te=Math.tan(.5*p.fovX),De=-be[2]*Te;var Ue,Ye,nt,it,ht,ot,yt,Nt;if(fe===0)return be[1]<-Math.abs(De)?xe:1;const is=ta(ya(1,xe,(-Math.abs(De)-be[1])/fe),xe,1);return ya(1,is,ta((p.pitch-20)/20,0,1))}var A8e=` #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`,Vmt=` #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 }`,Hmt=` #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 `,Gmt="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;}",Wmt=` #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`,Kmt=`#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`,Ymt=`#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`,E8e=` #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`,Zmt=`#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`,Xmt=`#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`,Qmt=`#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 Jmt=/^#include\s+"([^"]+)"\s*\r?\n/gm,eft=/#pragma mapbox: ([\w\-]+) ([\w]+) ([\w]+) ([\w]+)/g,aps=/\b[A-Za-z_][A-Za-z0-9_]*\b/g,ips=new Set(["ifdef","ifndef","elif","if","defined"]),Fle=new Set;r$(A8e,Fle),r$(Hmt,Fle),r$(Vmt,Fle);const tft={"_prelude_fog.vertex.glsl":Kmt,"_prelude_terrain.vertex.glsl":Wmt,"_prelude_shadow.vertex.glsl":Xmt,"_prelude_material_table.vertex.glsl":"","_prelude_fog.fragment.glsl":Ymt,"_prelude_shadow.fragment.glsl":Qmt,"_prelude_lighting.glsl":E8e,"_prelude_raster_array.glsl":Zmt,"_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) `},Ole={},sft="precision highp float;",nft="precision mediump float;",rft=` #if defined(GL_EXT_blend_func_extended) && defined(DUAL_SOURCE_BLENDING) #extension GL_EXT_blend_func_extended : require #endif`,aft={preludeTerrain:hd("",Wmt),preludeFog:hd(Ymt,Kmt),preludeShadow:hd(Qmt,Xmt),preludeRasterArray:hd(Zmt,""),preludeLighting:hd(E8e,E8e),preludePrecisionQualifiers:hd(nft,sft),prelude:hd(Vmt,Hmt),preludeExtensions:hd(rft,"")},ops=[rft,nft,A8e,aft.prelude.fragmentSource].join(` `),lps=[sft,A8e,aft.prelude.vertexSource].join(` `);var cps={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 }`,Gmt),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 }`,Gmt),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 r$(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(aps);if(M)for(const F of M)ips.has(F)||p.add(F)}}function ift(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(Jmt,(z,H)=>(M.push(H),"")),p=p.replace(Jmt,(z,H)=>(C.push(H),""));let F=new Set(Fle);r$(N,F),r$(p,F);for(const z of[...C,...M])Ole[z]||(Ole[z]=new Set,r$(tft[z],Ole[z])),F=new Set([...F,...Ole[z]]);return{fragmentSource:N=N.replace(eft,(z,H,Z,se,fe)=>(_.add(fe),H==="define"?` #ifndef HAS_UNIFORM_u_${fe} ${ift(se)?"flat ":""}in ${Z} ${se} ${fe}; #else uniform ${Z} ${se} u_${fe}; #endif `:H==="initialize"?` #ifdef HAS_UNIFORM_u_${fe} ${Z} ${se} ${fe} = u_${fe}; #endif `:H==="define-attribute"?` #ifdef HAS_ATTRIBUTE_a_${fe} in ${Z} ${se} ${fe}; #endif `:H==="initialize-attribute"?"":void 0)),vertexSource:p=p.replace(eft,(z,H,Z,se,fe)=>{const xe=`MATERIAL_ATTRIBUTE_OFFSET_${fe}`,be=se==="float"?"vec2":se,Te=`GET_ATTRIBUTE_${be}(a_${fe}, materialInfo, ${xe})`,De=fe.includes("color")?"color":be;return H==="define-attribute-vertex-shader-only"?` #ifdef HAS_ATTRIBUTE_a_${fe} in ${Z} ${se} a_${fe}; #endif `:_.has(fe)?H==="define"?` #ifndef HAS_UNIFORM_u_${fe} uniform lowp float u_${fe}_t; #if !defined(${xe}) in ${Z} ${be} a_${fe}; #endif ${ift(se)?"flat ":""}out ${Z} ${se} ${fe}; #else uniform ${Z} ${se} u_${fe}; #endif `:H==="initialize"?De==="vec4"||De==="uvec4"?` #ifndef HAS_UNIFORM_u_${fe} ${fe} = a_${fe}; #else ${Z} ${se} ${fe} = u_${fe}; #endif `:` #if !defined(HAS_UNIFORM_u_${fe}) #ifdef ${xe} ${fe} = unpack_mix_${De}(${Te}, u_${fe}_t); #else ${fe} = unpack_mix_${De}(a_${fe}, u_${fe}_t); #endif #else ${Z} ${se} ${fe} = u_${fe}; #endif `:H==="define-attribute"?` #ifdef HAS_ATTRIBUTE_a_${fe} in ${Z} ${se} a_${fe}; out ${Z} ${se} ${fe}; #endif `:H==="initialize-attribute"?` #ifdef HAS_ATTRIBUTE_a_${fe} ${fe} = a_${fe}; #endif `:void 0:H==="define"?` #ifndef HAS_UNIFORM_u_${fe} uniform lowp float u_${fe}_t; #if !defined(${xe}) in ${Z} ${be} a_${fe}; #endif #else uniform ${Z} ${se} u_${fe}; #endif `:H==="define-instanced"?De==="mat4"?` #ifdef INSTANCED_ARRAYS in vec4 a_${fe}0; in vec4 a_${fe}1; in vec4 a_${fe}2; in vec4 a_${fe}3; #else uniform ${Z} ${se} u_${fe}; #endif `:` #ifdef INSTANCED_ARRAYS in ${Z} ${be} a_${fe}; #else uniform ${Z} ${se} u_${fe}; #endif `:H==="initialize-attribute-custom"?` #ifdef HAS_ATTRIBUTE_a_${fe} ${Z} ${se} ${fe} = a_${fe}; #endif `:De==="vec4"||De==="uvec4"?` #ifndef HAS_UNIFORM_u_${fe} #ifdef ${xe} ${Z} ${se} ${fe} = ${Te}; #else ${Z} ${se} ${fe} = a_${fe}; #endif #else ${Z} ${se} ${fe} = u_${fe}; #endif `:` #ifndef HAS_UNIFORM_u_${fe} #ifdef ${xe} ${Z} ${se} ${fe} = unpack_mix_${De}(${Te}, u_${fe}_t); #else ${Z} ${se} ${fe} = unpack_mix_${De}(a_${fe}, u_${fe}_t); #endif #else ${Z} ${se} ${fe} = u_${fe}; #endif `}),usedDefines:F,vertexIncludes:C,fragmentIncludes:M}}var dps={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 ups=(N,p)=>({u_matrix:N,u_ground_shadow_factor:p});function oft(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/XY(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 zle={terrain:0,flat:1},hps=y(),lft=[0,0,0],cft=(N,p,_,C,M,F,z,H,Z,se,fe,xe,be,Te,De,Ue,Ye,nt,it=[0,0,1],ht=!1)=>{let ot=lft,yt=0,Nt=lft;if(!ht){const $t=p.style.light,Jt=$t.properties.get("position");if(ot=[Jt.x,Jt.y,Jt.z],$t.properties.get("anchor")==="viewport"){const Ps=f();x(Ps,-p.transform.angle),at(ot,ot,Ps)}const ns=$t.properties.get("color").toPremultipliedRenderColor(null);yt=$t.properties.get("intensity"),Nt=[ns.r,ns.g,ns.b]}const is=p.transform,At={u_matrix:N,u_lightpos:ot,u_lightintensity:yt,u_lightcolor:Nt,u_vertical_gradient:+_,u_opacity:C,u_tile_id:[0,0,0],u_zoom_transition:0,u_inv_rot_matrix:hps,u_merc_center:[0,0],u_up_dir:[0,0,0],u_height_lift:0,u_height_type:zle[se],u_base_type:zle[fe],u_ao:M,u_edge_radius:F,u_width_scale:z,u_flood_light_color:De,u_vertical_scale:Ue,u_flood_light_intensity:Ye,u_ground_shadow_factor:nt,u_front_cutoff_params:it};return is.projection.name==="globe"&&(At.u_tile_id=[H.canonical.x,H.canonical.y,1<{let an=$t;jn.groundRadiusBuffer!=null&&(an=$t.concat("HAS_ATTRIBUTE_a_flood_light_ground_radius"));const Ln=jn.programConfigurations.get(C.id),In=p.isTileAffectedByFog(cn),qn=p.getOrCreateProgram("fillExtrusionGroundEffect",{config:Ln,defines:an,overrideFog:In}),Dn=((zn,Ir,lr,_r,Wa,Ka,oi,Fa,Ai,Ni)=>({u_matrix:zn,u_opacity:Ir,u_ao_pass:lr?1:0,u_meter_to_tile:_r,u_ao:Wa,u_flood_light_intensity:Ka,u_flood_light_color:oi,u_attenuation:Fa,u_edge_radius:Ai,u_fb:0,u_fb_size:Ni,u_dynamic_offset:1}))(Cs,xe,se,Zs,[be,Te*Zs],De,Ue,Ye,At>=17?0:Ps*Zs,ht?ht.size[0]:0),ar=[];nt&&ar.push(jn.hiddenByLandmarkVertexBuffer),jn.groundRadiusBuffer!=null&&ar.push(jn.groundRadiusBuffer),p.uploadCommonUniforms(yt,qn,cn.toUnwrapped(),null,Gs),qn.draw(p,yt.gl.TRIANGLES,F,z,H,Z,Dn,C.id,jn.vertexBuffer,jn.indexBuffer,Vn,C.paint,At,Ln,ar)};for(const cn of M){const jn=_.getTile(cn),Vn=jn.getBucket(C);if(!Vn||Vn.projection.name!==is.projection.name||!Vn.groundEffect||Vn.groundEffect&&!Vn.groundEffect.hasData())continue;const Cs=Vn.groundEffect,Zs=1/Vn.tileToMeter;{const an=p.translatePosMatrix(cn.projMatrix,jn,Jt,ns),Ln=Cs.getDefaultSegment();pn(cn,Cs,Ln,an,Zs)}if(it)for(let an=0;an<4;an++){const Ln=Ddt[an](cn),In=_.getTile(Ln);if(!In)continue;const qn=In.getBucket(C);if(!qn||qn.projection.name!==is.projection.name||!qn.groundEffect||qn.groundEffect&&!qn.groundEffect.hasData())continue;const Dn=qn.groundEffect;let ar,zn;an===0?(ar=[-8192,0,0],zn=1):an===1?(ar=[Dr,0,0],zn=0):an===2?(ar=[0,-8192,0],zn=3):(ar=[0,Dr,0],zn=2);const Ir=Dn.regionSegments[zn];Ir&&(I(dft,cn.projMatrix,ar),pn(cn,Dn,Ir,p.translatePosMatrix(dft,jn,Jt,ns),Zs))}}}const mps={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 co(N),u_lightcolor:new Um(N),u_camera_pos:new Um(N),u_opacity:new co(N),u_baseColorFactor:new W_(N),u_emissiveFactor:new W_(N),u_metallicFactor:new co(N),u_roughnessFactor:new co(N),u_baseTextureIsAlpha:new $m(N),u_alphaMask:new $m(N),u_alphaCutoff:new co(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 W_(N),u_aoIntensity:new co(N),u_emissive_strength:new co(N),u_occlusionTextureTransform:new W_(N),u_dithered_discard_threshold:new co(N),u_model_mesh_params:new W_(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 co(N),u_width_scale:new co(N),u_vertical_scale:new co(N),u_height_type:new $m(N),u_base_type:new $m(N)}),fillExtrusionGroundEffect:N=>({u_matrix:new Of(N),u_opacity:new co(N),u_ao_pass:new co(N),u_meter_to_tile:new co(N),u_ao:new hp(N),u_flood_light_intensity:new co(N),u_flood_light_color:new Um(N),u_attenuation:new co(N),u_edge_radius:new co(N),u_fb:new $m(N),u_fb_size:new co(N),u_dynamic_offset:new co(N)})};function hft(N){const p=N.properties.get("direction"),_=lm(p.x,p.y,p.z);_[2]=ta(_[2],0,75);const C=Mh([_[0],_[1],_[2]]);return _e(C.x,C.y,C.z)}function mft(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],Z=_.properties.get("color-use-theme")==="none",se=_.properties.get("color"),fe=_.properties.get("intensity"),xe=Math.max(ze([0,0,1],H),0),be=[0,0,0];Fe(be,se.toPremultipliedRenderColor(Z?null:N.getLut(p.scope)).toArray01Linear().slice(0,3),fe);const Te=[0,0,0];return Fe(Te,M.toPremultipliedRenderColor(C?null:N.getLut(_.scope)).toArray01Linear().slice(0,3),xe*F),ko([be[0]>0?be[0]/(be[0]+Te[0]):0,be[1]>0?be[1]/(be[1]+Te[1]):0,be[2]>0?be[2]/(be[2]+Te[2]):0])}const Ble=[];function fft(N){return Ble[N]=Ble[N]||new Float64Array(16)}const $le=[],fps=new Float32Array(16);class pps{constructor(p,_){this.aabb=p,this.lastCascade=_}}class gps{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 pps(_,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 Z=H.aabb.getCorners();for(let se=0;se1||be[1]<-1||be[1]>1){fe=!1;break}}if(H.lastCascade=se,F=Math.max(F,se),fe)break}}return F+1}}function Ule(N,p,_){const C=qe([],pt([],_,p),pt([],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 xps(N,p,_,C,M,F){const z=N.zoom,H=N.scale,Z=N.worldSize,se=1/Z,fe=N.aspect,xe=Math.sqrt(1+fe*fe)*Math.tan(.5*N.fovX),be=xe*xe,Te=C-_,De=C+_;let Ue,Ye;be>Te/De?(Ue=C,Ye=C*xe):(Ue=.5*De*(1+be),Ye=.5*Math.sqrt(Te*Te+2*(C*C+_*_)*be+De*De*be*be));const nt=N.projection.pixelsPerMeter(N.center.lat,Z),it=[0,0,-Ue*se];Xe(it,it,N._camera.getCameraToWorldMercator());let ht=Ye*se;const ot=function(Zs){return Zs[0]/=H,Zs[1]/=H,Zs[2]=Jd(Zs[2],N._center.lat),Zs},yt=N._edgeInsets;if(!(yt.left===0&&yt.top===0&&yt.right===0&&yt.bottom===0||yt.left===yt.right&&yt.top===yt.bottom)){const Zs=N._camera.getWorldToCamera(N.worldSize,N.projection.zAxisUnit==="meters"?nt:1),an=N._camera.getCameraToClipPerspective(N._fov,N.width/N.height,_,C);an[8]=2*-N.centerOffset.x/N.width,an[9]=2*N.centerOffset.y/N.height;const Ln=new Float64Array(16);ne(Ln,an,Zs);const In=new Float64Array(16);A(In,Ln);const qn=$3.fromInvProjectionMatrix(In,Z,z,!0);for(const Dn of qn.points){const ar=ot(Dn);ht=Math.max(ht,ss(ve([],it,ar)))}}ht*=M/(M-1);const Nt=Math.acos(p[2]),is=Math.atan2(-p[0],-p[1]),At=new Ple;At.position=it,At.setPitchBearing(Nt,is);const $t=At.getWorldToCamera(Z,nt),Jt=ht*Z,ns=Math.min(N._mercatorZfromZoom(17)*Z*-2,-2*Jt),Ps=At.getCameraToClipOrthographic(-Jt,Jt,-Jt,Jt,ns,(Jt+F*nt)/p[2]),Gs=new Float64Array(16);E(Gs,Ps,$t);const pn=.5*M,cn=[0,0,0];Xe(cn,_e(Math.floor(1e6*it[0])/1e6*Z,Math.floor(1e6*it[1])/1e6*Z,0),Gs),Fe(cn,cn,pn);const jn=[Math.floor(cn[0]),Math.floor(cn[1]),Math.floor(cn[2])],Vn=[0,0,0];pt(Vn,cn,jn),Fe(Vn,Vn,-1/pn);const Cs=new Float64Array(16);return w(Cs),I(Cs,Cs,Vn),E(Gs,Cs,Gs),[Gs,Jt]}class K3 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 qut((await this.map._requestManager.transformRequest(p,yr.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=YOe(M),H=F.modelSpec,Z=new Kut(p,H.uri,H.position,H.orientation,z);K3.applyModelSpecification(Z,H),Z.computeBoundsAndApplyParent(),this.models.push(Z),F.model=Z}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],K3.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&&K3.convertNodeOverrides(p,_.nodeOverrides),_.materialOverrides&&K3.convertMaterialOverrides(p,_.materialOverrides),_.nodeOverrideNames&&(p.nodeOverrideNames=[..._.nodeOverrideNames]),_.materialOverrideNames&&(p.materialOverrideNames=[..._.materialOverrideNames]),_.featureProperties&&(p.featureProperties=_.featureProperties),_.lightOverrides){const C=_.lightOverrides,M=K3.arrayFromColorSpecification(C["light-ambient-color"]),F=K3.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=K3.arrayFromColorSpecification(M["model-color"]),z={color:F!==void 0?new Ci(F[0],F[1],F[2]):new Ci(1,1,1),colorMix:0,emissionStrength:0,opacity:1},H=M["model-color-mix-intensity"];H!==void 0&&(z.colorMix=H);const Z=M["model-emissive-strength"];Z!==void 0&&(z.emissionStrength=Z);const se=M["model-opacity"];se!==void 0&&(z.opacity=se),p.materialOverrides.set(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=U6(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 pft(N,p,_){try{p=function(M){if(!M.variants)return M;if(!Array.isArray(M.variants))throw new Error("variants must be an array");let F=null,z=null;for(const Z of M.variants){if(Z==null||typeof Z!="object"||Z.constructor!==Object)throw new Error("variant must be an object");if(!Array.isArray(Z.capabilities))throw new Error("capabilities must be an array");Z.capabilities.length===1&&(Z.capabilities[0]==="meshopt-v2+lod"?z=Z:Z.capabilities[0]==="meshopt"&&(F=Z))}const H=z!==null?z:F;return H!==null?Object.assign(M,H):M}(p)}catch(M){return new Error("Failed to process TileJSON variants",{cause:M})}const C=fu({...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 gft(N,p,_,C,M){const F=function(H,Z){if(H)return M(H);if(Z){N.url&&Z.tiles&&N.tiles&&delete N.tiles;const se=pft(N,Z,p);if(se instanceof Error)return M(se);M(null,se)}},z=function(H,Z,se){if(!H)return null;if(!Z&&!se)return H;se=se||H.worldview_default;const fe=Object.values(H.language||{});if(fe.length===0)return null;const xe=Object.values(H.worldview||{});if(xe.length===0)return null;const be=fe.every(De=>De===Z),Te=xe.every(De=>De===se);return be&&Te?H:Z in(H.language_options||{})||se in(H.worldview_options||{})?null:H.language_options&&H.worldview_options?H:null}(N.data,_,C);if(z)return ih.frame(()=>F(null,z));if(N.url){const H=new AbortController;return(async()=>{const Z=await p.transformRequest(p.normalizeSourceURL(N.url,null,_,C),yr.Source,H.signal),{data:se}=await nr(Z,H.signal);F(null,se)})().catch(Z=>{H.signal.aborted||F(Z)}),{cancel:()=>H.abort()}}return ih.frame(()=>{const{data:H,...Z}=N;F(null,Z)})}function xft(N,p){const _=Math.pow(2,p.z),C=Math.floor(ex(N.getWest())*_),M=Math.floor(ap(N.getNorth())*_),F=Math.ceil(ex(N.getEast())*_),z=Math.ceil(ap(N.getSouth())*_);return p.x>=C&&p.x=M&&p.ythis.maxzoom||p.z{se&&(se.useNormalOffset=!0,fe||(se.enabled=!0))},be=p.getSource();if(N.renderPass==="light-beam"&&be.type!=="batched-model")return;if(be.type==="vector"||be.type==="geojson")return function(ot,yt,Nt,is,At){const $t=ot.transform,Jt=$t.projection.name==="globe",ns=$t.getFreeCameraOptions().position;if(!ot.modelManager)return;const Ps=ot.modelManager;Nt.modelManager=Ps;const Gs=ot.shadowRenderer;if(!Object.hasOwn(Nt._unevaluatedLayout._values,"model-id"))return;const pn=Nt._unevaluatedLayout._values["model-id"],cn={...Nt.layout.get("model-id").parameters},jn=ot.style.order.indexOf(Nt.fqid),Vn=Nt.paint.get("model-opacity").constantOr(1);for(const Cs of is){const Zs=yt.getTile(Cs).getBucket(Nt);if(!Zs||Zs.projection.name!==$t.projection.name)continue;const an=Zs.getModelUris();if(an&&!Zs.modelsRequested&&(Ps.addModelsFromBucket(an,At),Zs.modelsRequested=!0),Jt)cn.zoom=Cs.overscaledZ;else{const lr=eps(Cs,$t);cn.zoom=lr}const Ln=pn.possiblyEvaluate(cn);if(Jfs(ot,Zs,Cs),YC.shadowUniformsInitialized=!1,YC.useSingleShadowCascade=!!Gs&&Gs.getMaxCascadeForTile(Cs.toUnwrapped())===0,ot.renderPass==="shadow"&&Gs){if(ot.currentShadowCascade===1&&Zs.isInsideFirstShadowMapFrustum)continue;const lr=$t.calculatePosMatrix(Cs.toUnwrapped(),$t.worldSize);if(YC.tileMatrix.set(lr),YC.shadowTileMatrix.set(Gs.calculateShadowPassMatrixFromMatrix(lr)),YC.aabb.min=[0,0,0],YC.aabb.max[0]=YC.aabb.max[1]=Dr,YC.aabb.max[2]=0,sps(Zs,YC,ot,Nt.scope))continue}const In=1<0&&ot.style.isLayerClipped(Nt,yt.getSource())&&Zs.updateReplacement(Cs,ot.replacementSource,jn,Nt.scope)&&(Zs.uploaded=!1,Zs.upload(ot.context));let Dn=0;const ar=new Array,zn=new Array,Ir=new Array;for(let lr in Zs.instancesPerModel){const _r=Zs.instancesPerModel[lr];_r.features.length>0&&!Jt&&(lr=Ln.evaluate(_r.features[0].feature,{}));const Wa=Ps.getModel(lr,At);if(Wa||Ps.hasURLBeenRequested(lr)||Zs.modelUris.includes(lr)||(Zs.modelUris.push(lr),Zs.modelsRequested=!1),Wa&&Wa.uploaded)if(Jt){const Ka=Fe([],[ns.x,ns.y,ns.z],ot.transform.worldSize);Ce(Ka,Ka);for(let oi=0;oi<_r.instancedDataArray.length;++oi){const Fa=[0,0,0],Ai=[1,1,1],Ni=as(),Fo=_r.tileCoordinatesForInstance(oi),rl=_r.transformForInstance(oi);G(Ai,rl),Y(Ni,rl),Ks(Fa,Ni);const Bl=_r.translationForInstance(oi),wc=new Il(0,0);_8e(Zs.canonical,wc,Fo.x,Fo.y);const qm=y();fle(qm,Wa,ot.transform,wc,Fa,Ai,Bl,!0,!1,!1);const K0=_r.colorForInstance(oi),Zh=U([],Ka),_l=W([],[1,1,1/T(wc.lat,ot.transform.zoom)]);Ir.push({zScaleMatrix:_l,negCameraPosMatrix:Zh});for(const Hd of Wa.nodes)C8e(ot,Hd,qm,ot.transform.expandedFarZProjMatrix,Dn,ar,zn,Wa.materialOverrides,Vn,K0);++Dn}}else for(const Ka of Wa.nodes)qmt(ot,Nt,Ka,_r,qn,Cs,YC)}if(Jt)if(ot.renderPass==="shadow"){for(const lr of zn)sZ(lr.mesh,lr.nodeModelMatrix,ot,Nt);for(const lr of ar)sZ(lr.mesh,lr.nodeModelMatrix,ot,Nt)}else Umt(ot,Nt,ar,zn,Ir)}}(N,p,_,C,Bmt(N,_)),void xe();if(!be.loaded())return;if(be.type==="batched-model")return function(ot,yt,Nt,is){Nt.resetLayerRenderingStats(ot);const At=ot.context,$t=ot.transform,Jt=ot.style.fog,ns=ot.shadowRenderer;if($t.projection.name!=="mercator")return void Yo(`Drawing 3D landmark models for ${$t.projection.name} projection is not yet implemented`);const Ps=ot.transform.getFreeCameraOptions().position,Gs=Fe([],[Ps.x,Ps.y,Ps.z],ot.transform.worldSize),pn=U([],Ce([],Gs)),cn=T($t.center.lat,$t.zoom),jn=E([],pn,W([],[1,1,1/cn])),Vn=Nt.paint.get("model-opacity").constantOr(1),Cs=new wy(At.gl.LEQUAL,wy.ReadWrite,ot.depthRangeFor3D),Zs=new wy(At.gl.LEQUAL,wy.ReadOnly,ot.depthRangeFor3D),an=new du([1/0,1/0,1/0],[-1/0,-1/0,-1/0]),Ln=ot.renderPass==="shadow",In=ot.renderPass==="light-beam",qn=Nt.paint.get("model-color-use-theme").constantOr("default")==="none",Dn=Ln&&ns?ns.getCurrentCascadeFrustum():$t.getFrustum($t.scaleZoom($t.worldSize)),ar=Nt.paint.get("model-front-cutoff"),zn=ar[2]<1,Ir=n$(ot,Nt.paint.get("model-cutoff-fade-range")),lr=Nt.getLayerRenderingStats();(function(_r,Wa,Ka,oi){const Fa=_r.terrain?_r.terrain.exaggeration():0,Ai=_r.transform.zoom;for(const Ni of oi){const Fo=Wa.getTile(Ni).getBucket(Ka);Fo&&(Fo.setFilter(Ka.filter),_r.conflationActive&&Fo.updateReplacement(Ni,_r.replacementSource),Fo.evaluateTransform(_r,Ka),_r.terrain&&Fa>0&&Fo.elevationUpdate(_r.terrain,Fa,Ni,Ka.source),Fo.needsReEvaluation(_r,Ai,Ka)&&Fo.evaluate(Ka))}})(ot,yt,Nt,is),function(){const _r=new Map;let Wa,Ka,oi;zn?(Wa=is.length-1,Ka=-1,oi=-1):(Wa=0,Ka=is.length,oi=1);const Fa=te(),Ai=new xs(0,0);for(let Ni=Wa;Ni!==Ka;Ni+=oi){const Fo=is[Ni],rl=yt.getTile(Fo).getBucket(Nt);if(!rl||!rl.uploaded)continue;let Bl=!1;ns&&(Bl=ns.getMaxCascadeForTile(Fo.toUnwrapped())===0);const wc=$t.calculatePosMatrix(Fo.toUnwrapped(),$t.worldSize),qm=!!(4&rl.modelTraits);E(w8e,jn,wc),E(j8e,$t.expandedFarZProjMatrix,wc),A(Lle,w8e),S(Lle,Lle);const K0=!Ln&&ns&&ns.enabled?ns.computeCascadeTileMatrices(wc):null;!Ln&&zn&&(A(hM,wc),Xe(Fa,Gs,hM),Ai.x=Fa[0],Ai.y=Fa[1]);const Zh=[];rl.setFilter(Nt.filter);for(const _l of rl.getNodesInfo()){if(_l.hiddenByReplacement||!_l.node.meshes)continue;const Hd=_l.node;let mh=0;ot.terrain&&Hd.elevation&&(mh=Hd.elevation*ot.terrain.exaggeration());const Vm=()=>{const Yu=_l.aabb,Vb=an.min,Hb=an.max;return Vb[0]=Yu.min[0],Vb[1]=Yu.min[1],Vb[2]=Yu.min[2]+mh,Hb[0]=Yu.max[0],Hb[1]=Yu.max[1],Hb[2]=Yu.max[2]+mh,Xe(Vb,Vb,wc),Xe(Hb,Hb,wc),an},mo=Vm(),fp=_l.evaluatedScale;if(fp[0]<=1&&fp[1]<=1&&fp[2]<=1&&mo.intersects(Dn)===0)continue;if(!Ln){const Yu=mo.min,Vb=mo.max;Dle[0]=.5*(Yu[0]+Vb[0]),Dle[1]=.5*(Yu[1]+Vb[1]),Dle[2]=.5*(Yu[2]+Vb[2]);const Hb=Be(Gs,Dle)*cn,fg=ot._debugParams.lodSwitchDistance,Zk=fg>=0;if(Zk&&fg>=9999)_l.targetLod=0;else{let K_;if(Zk)K_=fg;else{const Y0=(Vb[2]-Yu[2])*cn*fp[2],Y3=Math.max(Vb[0]-Yu[0],Vb[1]-Yu[1])*cn*Math.max(fp[0],fp[1]);let ZC;ZC=Y0>=30?1:Y3>=80?.5:Math.max(Y0,Y3)>=20?.25:0,K_=2e3+3e3*ZC}tps(_l,Hb,Math.min(ot.frameTimeDelta,1e3/30),K_,ot._debugParams.lodSwitchFadeDuration)}}if(!Ln&&zn){const Yu=.16666666666666666;_l.cameraCollisionOpacity=Gs[0]>mo.min[0]&&Gs[0]mo.min[1]&&Gs[1]!zn||_l.opacity===1&&Hd.opacity===1?_l.depthHd.depth?-1:1);for(const _l of Zh){const Hd=_l.nodeInfo,mh=Hd.node;let Vm=null;if(ot._debugParams.show3DModelFootprints&&mh.footprint){const ky=mh.id||mh.name||"footprint";if(!_r.has(ky)){const Wv=tZ(new Float64Array(16),j8e,_l.tileTranslation,_l.nodeInfo.evaluatedScale);_r.set(ky,{node:mh,mvp:Wv})}}const mo=_l.nodeInfo.evaluatedScale;tZ(KC,w8e,_l.tileTranslation,mo),Rle[0]=1/mo[0],Rle[1]=-1/mo[1],Rle[2]=1/mo[2],P(hM,Lle,Rle),E(KC,KC,mh.globalMatrix);const fp=qm?0:Hd.evaluatedRMEA[0][2],Lp=Hd.targetLod,gf=mh.lodMeshes&&mh.lodMeshes.length>0,qx=gf&&Lp>0&&Lp<1;if(Ln&&gf&&Math.round(Lp)===1)continue;const Vx=!Ln&&Jt?zmt(Omt,_l.nodeModelMatrix,ot.transform):null,qb=Ln&&ns?ns.calculateShadowPassMatrixFromMatrix(_l.nodeModelMatrix):null,Ny=qx?2:1,Hx=gf&&Math.round(Lp)===1;for(let ky=0;ky=LY||O8e>=LY}const wo=fg.material;let pg;wo.occlusionTexture&&wo.occlusionTexture.offsetScale&&(pg=wo.occlusionTexture.offsetScale,Y0.defines.push("OCCLUSION_TEXTURE_TRANSFORM")),qx&&Y0.defines.push("DITHERED_DISCARD");const Mu=ot.getOrCreateProgram("model",Y0);if(!Ln&&ns&&ns.enabled)if(Vm!==ZC){for(let Gx=0;Gx0){const Ni=Array.from(_r.keys()).sort();for(const Fo of Ni){const{node:rl,mvp:Bl}=_r.get(Fo);$mt(ot,0,rl,Bl)}}}()}(N,p,_,C),void xe();if(be.type!=="model")return;const Te=be.getModels(),De=[],Ue=N.transform.getFreeCameraOptions().position,Ye=Fe([],[Ue.x,Ue.y,Ue.z],N.transform.worldSize);Ce(Ye,Ye);const nt=[],it=[];let ht=0;for(const ot of Te){const yt=p.getFeatureState("",ot.id),Nt={type:"Unknown",id:ot.id,properties:ot.featureProperties},is=_.paint.get("model-rotation").evaluate(Nt,yt),At=_.paint.get("model-scale").evaluate(Nt,yt),$t=_.paint.get("model-translation").evaluate(Nt,yt),Jt=_.paint.get("model-opacity").evaluate(Nt,yt);Xfs(_,ot.id,yt,ot.featureProperties,ot.nodeOverrideNames,ot.nodeOverrides),Qfs(_,ot.id,yt,ot.featureProperties,ot.materialOverrideNames,ot.materialOverrides),ot.nodeOverrides.size>0&&ot.computeBoundsAndApplyParent(),ot.computeModelMatrix(N,is,At,$t,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 Gs of ot.nodes)C8e(N,Gs,ot.matrix,N.transform.expandedFarZProjMatrix,ht,nt,it,ot.materialOverrides,Jt,void 0,ot.lightOverrides);ht++}if(nt.sort((ot,yt)=>yt.depth-ot.depth),N.renderPass!=="shadow"){if(N._debugParams.show3DModelFootprints){const ot=N.transform.projMatrix,yt=new Map,Nt=(At,$t)=>{if(At.footprint){const Jt=At.id||At.name||"footprint";if(!yt.has(Jt)){const ns=E([],ot,$t);yt.set(Jt,{node:At,mvp:ns})}}};for(const At of it)Nt(At.node,At.modelMatrix);for(const At of nt)Nt(At.node,At.modelMatrix);const is=Array.from(yt.keys()).sort();for(const At of is){const{node:$t,mvp:Jt}=yt.get(At);$mt(N,0,$t,Jt)}}Umt(N,_,nt,it,De),xe()}else{for(const ot of it)sZ(ot.mesh,ot.nodeModelMatrix,N,_);for(const ot of nt)sZ(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(_,Bmt(_,N)));if(C.type==="batched-model"||C.type!=="model")return;const M=C.getModels();for(const F of M)F.upload(_.context)},shaders:dps,programUniforms:mps,ShadowRenderer:class{constructor(N){this.painter=N,this._enabled=!1,this._drawShadowAfterLayer=-1,this._numCascadesToRender=0,this._cascades=[],this._groundShadowTiles=[],this._receivers=new gps,this._depthMode=new wy(N.context.gl.LEQUAL,wy.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 Z=C.context,se=this._shadowParameters.shadowMapResolution,fe=this._shadowParameters.shadowMapResolution;if(this._cascades.length===0||this._shadowParameters.shadowMapResolution!==this._cascades[0].texture.size[0]){this._cascades=[];for(let nt=0;ntht.dem).forEach(ht=>{const ot=ht.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 be=1.5*N.cameraToCenterDistance,Te=3*be,De=new Float64Array(16);for(let nt=0;nt=0)return{};const M=function(H,Z,se){const fe=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=[Ule(M[1],M[0],M[4]),Ule(M[2],M[1],M[5]),Ule(M[3],M[2],M[6]),Ule(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:uft,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 Z=0;for(const se of F.models){const fe=_.getFeatureState(N.sourceLayer,se.id),xe={type:"Unknown",id:se.id,properties:se.featureProperties},be=N.paint.get("model-rotation").evaluate(xe,fe),Te=N.paint.get("model-scale").evaluate(xe,fe),De=N.paint.get("model-translation").evaluate(xe,fe),Ue=N.paint.get("model-elevation-reference");let Ye=[];fle(Ye,se,C,se.position,be,Te,De,Ue==="ground",Ue==="ground",!1),C.projection.name==="globe"&&(Ye=mle(Ye,C));const nt=E([],C.projMatrix,Ye),it=UOe(p.isPointQuery()?p.screenBounds:p.screenGeometry,C,nt,se.aabb);if(it!=null){const ht=new aR(void 0,0,0,0,se.id);ht.layer=N.layer,ht.properties=structuredClone(se.featureProperties),ht.properties.layer=N.id,ht.properties.uri=se.uri,ht.properties.orientation=se.orientation,ht.sourceLayer=N.sourceLayer,ht.geometry={type:"Point",coordinates:[se.position.lng,se.position.lat]},ht.state=fe,ht.source=N.source,H.push({featureIndex:Z,feature:ht,intersectionZ:it})}++Z}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 d8e))return!1;for(const Z in H.instancesPerModel){const se=H.instancesPerModel[Z],fe=_.id!==void 0?_.id:_.properties&&Object.hasOwn(_.properties,"id")?_.properties.id:void 0;if(Object.hasOwn(se.idToFeaturesIndex,fe)){const xe=se.features[se.idToFeaturesIndex[fe]],be=z.getModel(Z,F||N.scope);if(!be)return!1;let Te=[];const De=new 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=gft(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 qle(M.bounds,this.minzoom,this.maxzoom)),Tu(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 Z of H)Z.dirty=!0;return void(N.state="loaded")}}const M=C?"loadTile":"reloadTile",F=new AbortController;N.request=F;const z=(H,Z)=>(delete N.request,N.aborted?p(null):H&&!et(H)?p(H):(this.map._refreshExpiredTiles&&Z&&N.setExpiryData(Xa(Z.headers)),N.loadModelData(Z,this.map.painter),N.state="loaded",p(null),void(N.reloadCallback&&(this.loadTile(N,N.reloadCallback),N.reloadCallback=null))));try{const H=await this.map._requestManager.transformRequest(_,yr.Tile,F.signal);if(F.signal.aborted)return p(null);const Z={request:H,data:void 0,uid:N.uid,tileID:N.tileID,tileZoom:N.tileZoom,zoom:N.tileID.overscaledZ,tileSize:this.tileSize*N.tileID.overscaleFactor(),type:this.type,source:this.id,scope:this.scope,showCollisionBoxes:this.map.showCollisionBoxes,renderSourceType:N.renderSourceType,brightness:this.map.style&&this.map.style.getBrightness()||0,pixelRatio:ih.devicePixelRatio,promoteId:this.promoteId};N.request=N.actor.sendCancelable(M,Z,{},z)}catch(H){if(F.signal.aborted)return p(null);p(H)}}abortTile(N){N.request&&(N.request.abort(),delete N.request),N.actor&&N.actor.notify("abortTile",{uid:N.uid,type:this.type,source:this.id,scope:this.scope})}serialize(){return{...this._options}}},loadModel:async function(N,p,_){const C=await qut(N),M=new Kut(p,_,void 0,void 0,YOe(C));return M.computeBoundsAndApplyParent(),M}};class yft{constructor(p,_){this.tileID=p,this.x=p.canonical.x,this.y=p.canonical.y,this.z=p.canonical.z,this.grid=new qv(Dr,Dr,512),this.featureIndexArray=new e0,this.promoteId=_,this.is3DTile=!1,this.serializedLayersCache=new Map}insert(p,_,C,M,F,z=0,H=0){const Z=this.featureIndexArray.length;this.featureIndexArray.emplaceBack(C,M,F,z);const se=this.grid;for(let fe=0;fe<_.length;fe++){const xe=_[fe],be=[1/0,1/0,-1/0,-1/0];for(let Te=0;Te=0&&be[3]>=0&&se.insert(Z,be[0],be[1],be[2],be[3])}}loadVTLayers(){if(!this.vtLayers){this.vtLayers=new UFe(new Hoe(this.rawTileData)).layers,this.sourceLayerCoder=new Nmt(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:Z}=_;this.loadVTLayers(),this.serializedLayersCache.clear();const se=_.queryRadius?_.queryRadius:0,fe=C.bufferedTilespaceBounds,xe=this.grid.queryKeys(fe.min.x,fe.min.y,fe.max.x,fe.max.y,(Ue,Ye,nt,it)=>KFe(C.bufferedTilespaceGeometry,Ue-se,Ye-se,nt+se,it+se));xe.sort(yps);let be=null;M.elevation&&xe.length>0&&(be=V9.create(M.elevation,this.tileID));const Te={};let De;for(let Ue=0;Ue(it||(it=ut(ht,this.tileID.canonical,F)),ot.queryIntersectsFeature(C,ht,yt,it,this.z,M,z,be,Nt,_.scope)))}return Te}loadMatchingFeature(p,_,C,M,F,z){const{featureIndex:H,bucketIndex:Z,sourceLayerIndex:se,layoutVertexArrayOffset:fe}=_,xe=this.bucketLayerIDs[Z],be=C.layers,Te=Object.keys(be);if(Te.length&&!rg(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 vft(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 yps(N,p){return p-N}async function bft(){return Promise.resolve()}oa(yft,"FeatureIndex",{omit:["rawTileData","sourceLayerCoder"]});const vps={circle:class extends Jy{constructor(N,p,_,C){super(N,{layout:ght||(ght=new Wu({"circle-sort-key":new Er(Ys.layout_circle["circle-sort-key"]),"circle-elevation-reference":new gr(Ys.layout_circle["circle-elevation-reference"]),visibility:new gr(Ys.layout_circle.visibility)})),paint:xht||(xht=new Wu({"circle-radius":new Er(Ys.paint_circle["circle-radius"]),"circle-color":new Er(Ys.paint_circle["circle-color"]),"circle-blur":new Er(Ys.paint_circle["circle-blur"]),"circle-opacity":new Er(Ys.paint_circle["circle-opacity"]),"circle-translate":new gr(Ys.paint_circle["circle-translate"]),"circle-translate-anchor":new gr(Ys.paint_circle["circle-translate-anchor"]),"circle-pitch-scale":new gr(Ys.paint_circle["circle-pitch-scale"]),"circle-pitch-alignment":new gr(Ys.paint_circle["circle-pitch-alignment"]),"circle-stroke-width":new Er(Ys.paint_circle["circle-stroke-width"]),"circle-stroke-color":new Er(Ys.paint_circle["circle-stroke-color"]),"circle-stroke-opacity":new Er(Ys.paint_circle["circle-stroke-opacity"]),"circle-emissive-strength":new gr(Ys.paint_circle["circle-emissive-strength"]),"circle-color-use-theme":new Er({type:"string",default:"default","property-type":"data-driven"}),"circle-stroke-color-use-theme":new Er({type:"string",default:"default","property-type":"data-driven"})}))},p,_,C)}createBucket(N){return new Coe(N)}queryRadius(N){const p=N;return e$("circle-radius",this,p)+e$("circle-stroke-width",this,p)+Cle(this.paint.get("circle-translate"))}queryIntersectsFeature(N,p,_,C,M,F,z,H){const Z=wht(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 Nht(N,C,F,z,H,this.paint.get("circle-pitch-alignment")==="map",this.paint.get("circle-pitch-scale")==="map",Z,se)}getProgramIds(){return["circle"]}getDefaultProgramParams(N,p,_){const C=jht(this);return{config:new X6(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"&&T9(this,"circle-elevation-reference",p=>p==="hd-road-markup")}prepare(){return this.mayUse("HD")?Sle():Promise.resolve()}},heatmap:class extends Jy{createBucket(N){return new Sht(N)}constructor(N,p,_,C){super(N,{layout:Cht||(Cht=new Wu({visibility:new gr(Ys.layout_heatmap.visibility)})),paint:Aht||(Aht=new Wu({"heatmap-radius":new Er(Ys.paint_heatmap["heatmap-radius"]),"heatmap-weight":new Er(Ys.paint_heatmap["heatmap-weight"]),"heatmap-intensity":new gr(Ys.paint_heatmap["heatmap-intensity"]),"heatmap-color":new I3(Ys.paint_heatmap["heatmap-color"]),"heatmap-opacity":new gr(Ys.paint_heatmap["heatmap-opacity"]),"heatmap-color-use-theme":new Er({type:"string",default:"default","property-type":"data-driven"})}))},p,_,C),this._updateColorRamp()}_handleSpecialPaintPropertyUpdate(N){N==="heatmap-color"&&this._updateColorRamp()}_updateColorRamp(){this.colorRamp=YY({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 e$("heatmap-radius",this,N)}queryIntersectsFeature(N,p,_,C,M,F,z,H){const Z=this.paint.get("heatmap-radius").evaluate(p,_);return Nht(N,C,F,z,H,!0,!0,new xs(0,0),Z)}hasOffscreenPass(){return this.paint.get("heatmap-opacity")!==0&&this.visibility!=="none"}getProgramIds(){return["heatmap","heatmapTexture"]}getDefaultProgramParams(N,p,_){return N==="heatmap"?{config:new X6(this,{zoom:p,lut:_}),overrideFog:!1}:{}}},hillshade:class extends Jy{constructor(N,p,_,C){super(N,{layout:Eht||(Eht=new Wu({visibility:new gr(Ys.layout_hillshade.visibility)})),paint:Tht||(Tht=new Wu({"hillshade-illumination-direction":new gr(Ys.paint_hillshade["hillshade-illumination-direction"]),"hillshade-illumination-anchor":new gr(Ys.paint_hillshade["hillshade-illumination-anchor"]),"hillshade-exaggeration":new gr(Ys.paint_hillshade["hillshade-exaggeration"]),"hillshade-shadow-color":new gr(Ys.paint_hillshade["hillshade-shadow-color"]),"hillshade-highlight-color":new gr(Ys.paint_hillshade["hillshade-highlight-color"]),"hillshade-accent-color":new gr(Ys.paint_hillshade["hillshade-accent-color"]),"hillshade-emissive-strength":new gr(Ys.paint_hillshade["hillshade-emissive-strength"]),"hillshade-shadow-color-use-theme":new Er({type:"string",default:"default","property-type":"data-driven"}),"hillshade-highlight-color-use-theme":new Er({type:"string",default:"default","property-type":"data-driven"}),"hillshade-accent-color-use-theme":new Er({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 Jy{constructor(N,p,_,C){super(N,{layout:Mht||(Mht=new Wu({"fill-sort-key":new Er(Ys.layout_fill["fill-sort-key"]),visibility:new gr(Ys.layout_fill.visibility),"fill-elevation-reference":new gr(Ys.layout_fill["fill-elevation-reference"]),"fill-construct-bridge-guard-rail":new Er(Ys.layout_fill["fill-construct-bridge-guard-rail"])})),paint:Pht||(Pht=new Wu({"fill-antialias":new gr(Ys.paint_fill["fill-antialias"]),"fill-opacity":new Er(Ys.paint_fill["fill-opacity"]),"fill-color":new Er(Ys.paint_fill["fill-color"]),"fill-outline-color":new Er(Ys.paint_fill["fill-outline-color"]),"fill-translate":new gr(Ys.paint_fill["fill-translate"]),"fill-translate-anchor":new gr(Ys.paint_fill["fill-translate-anchor"]),"fill-pattern":new Er(Ys.paint_fill["fill-pattern"]),"fill-pattern-cross-fade":new gr(Ys.paint_fill["fill-pattern-cross-fade"]),"fill-emissive-strength":new gr(Ys.paint_fill["fill-emissive-strength"]),"fill-z-offset":new Er(Ys.paint_fill["fill-z-offset"]),"fill-bridge-guard-rail-color":new Er(Ys.paint_fill["fill-bridge-guard-rail-color"]),"fill-tunnel-structure-color":new Er(Ys.paint_fill["fill-tunnel-structure-color"]),"fill-color-use-theme":new Er({type:"string",default:"default","property-type":"data-driven"}),"fill-outline-color-use-theme":new Er({type:"string",default:"default","property-type":"data-driven"}),"fill-bridge-guard-rail-color-use-theme":new Er({type:"string",default:"default","property-type":"data-driven"}),"fill-tunnel-structure-color-use-theme":new Er({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 X6(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 $Fe(N)}queryRadius(){return Cle(this.paint.get("fill-translate"))}queryIntersectsFeature(N,p,_,C,M,F){return!N.queryGeometry.isAboveHorizon&&VFe(_ht(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"&&T9(this,"fill-elevation-reference",p=>p!=="none")}prepare(){return this.mayUse("HD")?Sle():Promise.resolve()}hasShadowPass(){return this.layout&&this.layout.get("fill-elevation-reference")!=="none"}},"fill-extrusion":class extends Jy{constructor(N,p,_,C){super(N,{layout:Rht||(Rht=new Wu({visibility:new gr(Ys["layout_fill-extrusion"].visibility),"fill-extrusion-edge-radius":new gr(Ys["layout_fill-extrusion"]["fill-extrusion-edge-radius"]),"source-max-zoom":new gr(Ys["layout_fill-extrusion"]["source-max-zoom"])})),paint:Dht||(Dht=new Wu({"fill-extrusion-opacity":new gr(Ys["paint_fill-extrusion"]["fill-extrusion-opacity"]),"fill-extrusion-color":new Er(Ys["paint_fill-extrusion"]["fill-extrusion-color"]),"fill-extrusion-translate":new gr(Ys["paint_fill-extrusion"]["fill-extrusion-translate"]),"fill-extrusion-translate-anchor":new gr(Ys["paint_fill-extrusion"]["fill-extrusion-translate-anchor"]),"fill-extrusion-pattern":new Er(Ys["paint_fill-extrusion"]["fill-extrusion-pattern"]),"fill-extrusion-pattern-cross-fade":new gr(Ys["paint_fill-extrusion"]["fill-extrusion-pattern-cross-fade"]),"fill-extrusion-height":new Er(Ys["paint_fill-extrusion"]["fill-extrusion-height"]),"fill-extrusion-base":new Er(Ys["paint_fill-extrusion"]["fill-extrusion-base"]),"fill-extrusion-height-alignment":new gr(Ys["paint_fill-extrusion"]["fill-extrusion-height-alignment"]),"fill-extrusion-base-alignment":new gr(Ys["paint_fill-extrusion"]["fill-extrusion-base-alignment"]),"fill-extrusion-vertical-gradient":new gr(Ys["paint_fill-extrusion"]["fill-extrusion-vertical-gradient"]),"fill-extrusion-ambient-occlusion-intensity":new gr(Ys["paint_fill-extrusion"]["fill-extrusion-ambient-occlusion-intensity"]),"fill-extrusion-ambient-occlusion-radius":new gr(Ys["paint_fill-extrusion"]["fill-extrusion-ambient-occlusion-radius"]),"fill-extrusion-ambient-occlusion-wall-radius":new gr(Ys["paint_fill-extrusion"]["fill-extrusion-ambient-occlusion-wall-radius"]),"fill-extrusion-ambient-occlusion-ground-radius":new gr(Ys["paint_fill-extrusion"]["fill-extrusion-ambient-occlusion-ground-radius"]),"fill-extrusion-ambient-occlusion-ground-attenuation":new gr(Ys["paint_fill-extrusion"]["fill-extrusion-ambient-occlusion-ground-attenuation"]),"fill-extrusion-flood-light-color":new gr(Ys["paint_fill-extrusion"]["fill-extrusion-flood-light-color"]),"fill-extrusion-flood-light-intensity":new gr(Ys["paint_fill-extrusion"]["fill-extrusion-flood-light-intensity"]),"fill-extrusion-flood-light-wall-radius":new Er(Ys["paint_fill-extrusion"]["fill-extrusion-flood-light-wall-radius"]),"fill-extrusion-flood-light-ground-radius":new Er(Ys["paint_fill-extrusion"]["fill-extrusion-flood-light-ground-radius"]),"fill-extrusion-flood-light-ground-attenuation":new gr(Ys["paint_fill-extrusion"]["fill-extrusion-flood-light-ground-attenuation"]),"fill-extrusion-vertical-scale":new gr(Ys["paint_fill-extrusion"]["fill-extrusion-vertical-scale"]),"fill-extrusion-rounded-roof":new gr(Ys["paint_fill-extrusion"]["fill-extrusion-rounded-roof"]),"fill-extrusion-cutoff-fade-range":new gr(Ys["paint_fill-extrusion"]["fill-extrusion-cutoff-fade-range"]),"fill-extrusion-front-cutoff":new gr(Ys["paint_fill-extrusion"]["fill-extrusion-front-cutoff"]),"fill-extrusion-emissive-strength":new Er(Ys["paint_fill-extrusion"]["fill-extrusion-emissive-strength"]),"fill-extrusion-line-width":new Er(Ys["paint_fill-extrusion"]["fill-extrusion-line-width"]),"fill-extrusion-cast-shadows":new gr(Ys["paint_fill-extrusion"]["fill-extrusion-cast-shadows"]),"fill-extrusion-color-use-theme":new Er({type:"string",default:"default","property-type":"data-driven"}),"fill-extrusion-flood-light-color-use-theme":new Er({type:"string",default:"default","property-type":"data-driven"})}))},p,_,C),this._stats={numRenderedVerticesInShadowPass:0,numRenderedVerticesInTransparentPass:0}}createBucket(N){return new jle(N)}queryRadius(){return Cle(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,Z){const se=wht(this.paint.get("fill-extrusion-translate"),this.paint.get("fill-extrusion-translate-anchor"),F.angle,N.pixelToTileUnitsFactor),fe=this.paint.get("fill-extrusion-height").evaluate(p,_),xe=this.paint.get("fill-extrusion-base").evaluate(p,_),be=[0,0],Te=H&&F.elevation,De=F.elevation?F.elevation.exaggeration():1,Ue=N.tile.getBucket(this);if(Ue instanceof jle){const ot=Ue.centroidData.find(yt=>Z>=yt.vertexArrayOffset&&Zot.polygon).flat());const Ye=Te?H:null,[nt,it]=Vht(F,C,xe,fe,se,z,Ye,be,De,F.center.lat,N.tileID.canonical),ht=N.queryGeometry;return qht(nt,it,ht.isPointQuery()?ht.screenBounds:ht.screenGeometry)}},building:class extends Jy{constructor(N,p,_,C){super(N,{layout:Fht||(Fht=new Wu({visibility:new gr(Ys.layout_building.visibility),"building-facade":new Er(Ys.layout_building["building-facade"]),"building-facade-floors":new Er(Ys.layout_building["building-facade-floors"]),"building-facade-unit-width":new Er(Ys.layout_building["building-facade-unit-width"]),"building-facade-window":new Er(Ys.layout_building["building-facade-window"]),"building-roof-shape":new Er(Ys.layout_building["building-roof-shape"]),"building-height":new Er(Ys.layout_building["building-height"]),"building-base":new Er(Ys.layout_building["building-base"]),"building-flood-light-wall-radius":new Er(Ys.layout_building["building-flood-light-wall-radius"]),"building-flood-light-ground-radius":new Er(Ys.layout_building["building-flood-light-ground-radius"]),"building-flip-roof-orientation":new Er(Ys.layout_building["building-flip-roof-orientation"])})),paint:Oht||(Oht=new Wu({"building-opacity":new gr(Ys.paint_building["building-opacity"]),"building-ambient-occlusion-intensity":new gr(Ys.paint_building["building-ambient-occlusion-intensity"]),"building-ambient-occlusion-ground-intensity":new gr(Ys.paint_building["building-ambient-occlusion-ground-intensity"]),"building-ambient-occlusion-ground-radius":new gr(Ys.paint_building["building-ambient-occlusion-ground-radius"]),"building-ambient-occlusion-ground-attenuation":new gr(Ys.paint_building["building-ambient-occlusion-ground-attenuation"]),"building-vertical-scale":new gr(Ys.paint_building["building-vertical-scale"]),"building-cast-shadows":new gr(Ys.paint_building["building-cast-shadows"]),"building-color":new Er(Ys.paint_building["building-color"]),"building-emissive-strength":new Er(Ys.paint_building["building-emissive-strength"]),"building-facade-emissive-chance":new gr(Ys.paint_building["building-facade-emissive-chance"]),"building-cutoff-fade-range":new gr(Ys.paint_building["building-cutoff-fade-range"]),"building-front-cutoff":new gr(Ys.paint_building["building-front-cutoff"]),"building-flood-light-color":new gr(Ys.paint_building["building-flood-light-color"]),"building-flood-light-intensity":new gr(Ys.paint_building["building-flood-light-intensity"]),"building-flood-light-ground-attenuation":new gr(Ys.paint_building["building-flood-light-ground-attenuation"]),"building-color-use-theme":new Er({type:"string",default:"default","property-type":"data-driven"}),"building-flood-light-color-use-theme":new Er({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)||lj!=null||yht!=null)return null;if(J9!=null)return J9;const N=fetch(jt());return J9=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 Z(){throw new Error("Unexpected BuildingGen error.")}const se=()=>{},fe={a:{a:Z,f:function(xe){const be=_.length,Te=Math.max(xe>>>0,Math.ceil(1.2*be)),De=Math.ceil((Te-be)/65536);try{return z.grow(De),H(),!0}catch{return!1}},g:Z,b:se,c:se,d:se,e:se}};return(WebAssembly.instantiateStreaming?WebAssembly.instantiateStreaming(p,fe):p.then(xe=>xe.arrayBuffer()).then(xe=>WebAssembly.instantiate(xe,fe))).then(xe=>{const be=xe.instance.exports;return(0,be.g)(),z=be.f,H(),new Sfs({setStyle:be.h,setAOOptions:be.i,setMetricOptions:be.j,setStructuralOptions:be.k,setFacadeOptions:be.l,setFauxFacadeOptions:be.m,setFacadeClassifierOptions:be.n,addFeature:be.o,addFacade:be.p,generateMesh:be.q,getLastError:be.r,getOuterRingLength:be.s,getMeshCount:be.t,getPositionsPtr:be.u,getPositionsLength:be.v,getNormalsPtr:be.w,getNormalsLength:be.x,getAOPtr:be.y,getAOLength:be.z,getUVPtr:be.A,getUVLength:be.B,getFauxFacadePtr:be.C,getFauxFacadeLength:be.D,getIndicesPtr:be.E,getIndicesLength:be.F,getBuildingPart:be.G,getRingCount:be.H,getRingPtr:be.I,getRingLength:be.J,malloc:be.K,free:be.L,heapU8:_,heap16:C,heap32:M,heapF32:F})})}(N).then(p=>{J9=null,lj=p}).catch(p=>{Yo("Could not load building-gen"),J9=null,yht=p}),J9}()}()}createBucket(N){return new vht(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,Z,se){let fe=this.layout.get("building-height").evaluate(p,_);const xe=this.layout.get("building-base").evaluate(p,_),be=N.tile.getBucket(this).getFootprint(p);if(be){if(be.hiddenFlags!==0)return!1;fe=be.height}const[Te,De]=Vht(F,C,xe,fe,new xs(0,0),z,null,[0,0],1,F.center.lat,N.tileID.canonical),Ue=N.queryGeometry;return qht(Te,De,Ue.isPointQuery()?Ue.screenBounds:Ue.screenGeometry)}},line:class extends Jy{constructor(N,p,_,C){const M=Zht();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 bi,this.gradientVersion=(this.gradientVersion+1)%Number.MAX_SAFE_INTEGER}else if(N==="line-gradient-use-theme")this.gradientVersion=(this.gradientVersion+1)%Number.MAX_SAFE_INTEGER;else if(N==="line-border-gradient"){const p=this._transitionablePaint._values["line-border-gradient"].value.expression;this.borderStepInterpolant=p._styleExpression&&p._styleExpression.expression instanceof bi,this.borderGradientVersion=(this.borderGradientVersion+1)%Number.MAX_SAFE_INTEGER}else N==="line-border-gradient-use-theme"&&(this.borderGradientVersion=(this.borderGradientVersion+1)%Number.MAX_SAFE_INTEGER)}gradientExpression(){return this._transitionablePaint._values["line-gradient"].value.expression}borderGradientExpression(){return this._transitionablePaint._values["line-border-gradient"].value.expression}widthExpression(){return this._transitionablePaint._values["line-width"].value.expression}emissiveStrengthExpression(){return this._transitionablePaint._values["line-emissive-strength"].value.expression}recalculate(N,p){super.recalculate(N,p),this.paint._values["line-floorwidth"]=(()=>{if(QY)return QY;const _=Zht();return QY=new Dfs(_.paint.properties["line-width"].specification),QY.useIntegerZoom=!0,QY})().possiblyEvaluate(this._transitioningPaint._values["line-width"].value,N)}createBucket(N){return new QFe(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=Kht(this);return{config:new X6(this,{zoom:p,lut:_}),defines:C,overrideFog:!1}}queryRadius(N){const p=N,_=Jht(e$("line-width",this,p),e$("line-gap-width",this,p)),C=e$("line-offset",this,p);return _/2+Math.abs(C)+Cle(this.paint.get("line-translate"))}queryIntersectsFeature(N,p,_,C,M,F){if(N.queryGeometry.isAboveHorizon)return!1;const z=_ht(N.tilespaceGeometry,this.paint.get("line-translate"),this.paint.get("line-translate-anchor"),F.angle,N.pixelToTileUnitsFactor),H=N.pixelToTileUnitsFactor/2*Jht(this.paint.get("line-width").evaluate(p,_),this.paint.get("line-gap-width").evaluate(p,_)),Z=this.paint.get("line-offset").evaluate(p,_);return Z&&(C=function(se,fe){const xe=[],be=new xs(0,0);for(let Te=0;Te=3){for(let De=0;Dep==="hd-road-markup"):N==="Lite"&&function(p){if(!p._unevaluatedLayout)return!1;const _=p._unevaluatedLayout.getValue("line-elevation-reference");if(_!==void 0&&(typeof _!="string"||_!=="none"))return!0;const C=p._unevaluatedLayout.getValue("line-z-offset");return C!==void 0&&(typeof C!="number"||C!==0)}(this)}prepare(){return this.mayUse("HD")?Sle():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:Ale,background:class extends Jy{constructor(N,p,_,C){super(N,{layout:nmt||(nmt=new Wu({visibility:new gr(Ys.layout_background.visibility)})),paint:rmt||(rmt=new Wu({"background-pitch-alignment":new gr(Ys.paint_background["background-pitch-alignment"]),"background-color":new gr(Ys.paint_background["background-color"]),"background-pattern":new gr(Ys.paint_background["background-pattern"]),"background-opacity":new gr(Ys.paint_background["background-opacity"]),"background-emissive-strength":new gr(Ys.paint_background["background-emissive-strength"]),"background-color-use-theme":new Er({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:omt,"raster-particle":gmt,sky:class extends Jy{constructor(N,p,_,C){super(N,{layout:dmt||(dmt=new Wu({visibility:new gr(Ys.layout_sky.visibility)})),paint:umt||(umt=new Wu({"sky-type":new gr(Ys.paint_sky["sky-type"]),"sky-atmosphere-sun":new gr(Ys.paint_sky["sky-atmosphere-sun"]),"sky-atmosphere-sun-intensity":new gr(Ys.paint_sky["sky-atmosphere-sun-intensity"]),"sky-gradient-center":new gr(Ys.paint_sky["sky-gradient-center"]),"sky-gradient-radius":new gr(Ys.paint_sky["sky-gradient-radius"]),"sky-gradient":new I3(Ys.paint_sky["sky-gradient"]),"sky-atmosphere-halo-color":new gr(Ys.paint_sky["sky-atmosphere-halo-color"]),"sky-atmosphere-color":new gr(Ys.paint_sky["sky-atmosphere-color"]),"sky-opacity":new gr(Ys.paint_sky["sky-opacity"]),"sky-gradient-use-theme":new Er({type:"string",default:"default","property-type":"data-driven"}),"sky-atmosphere-halo-color-use-theme":new Er({type:"string",default:"default","property-type":"data-driven"}),"sky-atmosphere-color-use-theme":new Er({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=YY({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?c8e(z.azimuthal,90-z.polar,p):c8e(C[0],90-C[1],p)}const _=this.paint.get("sky-gradient-center");return c8e(_[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 Jy{constructor(N,p,_,C){super(N,{paint:hmt||(hmt=new Wu({}))},p,null)}},"placement-group":class extends Jy{constructor(N,p,_,C){super(N,{paint:mmt||(mmt=new Wu({}))},p,_,C)}},model:class extends Jy{constructor(N,p,_,C){super(N,{layout:fmt||(fmt=new Wu({visibility:new gr(Ys.layout_model.visibility),"model-id":new Er(Ys.layout_model["model-id"]),"model-allow-density-reduction":new gr(Ys.layout_model["model-allow-density-reduction"])})),paint:pmt||(pmt=new Wu({"model-opacity":new Er(Ys.paint_model["model-opacity"]),"model-rotation":new Er(Ys.paint_model["model-rotation"]),"model-scale":new Er(Ys.paint_model["model-scale"]),"model-translation":new Er(Ys.paint_model["model-translation"]),"model-color":new Er(Ys.paint_model["model-color"]),"model-color-mix-intensity":new Er(Ys.paint_model["model-color-mix-intensity"]),"model-type":new gr(Ys.paint_model["model-type"]),"model-cast-shadows":new gr(Ys.paint_model["model-cast-shadows"]),"model-receive-shadows":new gr(Ys.paint_model["model-receive-shadows"]),"model-ambient-occlusion-intensity":new gr(Ys.paint_model["model-ambient-occlusion-intensity"]),"model-emissive-strength":new Er(Ys.paint_model["model-emissive-strength"]),"model-roughness":new Er(Ys.paint_model["model-roughness"]),"model-height-based-emissive-strength-multiplier":new Er(Ys.paint_model["model-height-based-emissive-strength-multiplier"]),"model-cutoff-fade-range":new gr(Ys.paint_model["model-cutoff-fade-range"]),"model-front-cutoff":new gr(Ys.paint_model["model-front-cutoff"]),"model-elevation-reference":new gr(Ys.paint_model["model-elevation-reference"]),"model-line-cutout-mode":new gr(Ys.paint_model["model-line-cutout-mode"]),"model-color-use-theme":new Er({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 bft()}createBucket(N){return new d8e(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 iR.queryModelLayerRendered?iR.queryModelLayerRendered(this,N,p,_):{}}queryIntersectsFeature(N,p,_,C,M,F,z,H,Z,se){return!!iR.queryModelLayerIntersectsFeature&&iR.queryModelLayerIntersectsFeature(this,N,p,_,F,se)}_handleOverridablePaintPropertyUpdate(N,p,_){return!(!this.layout||p.isDataDriven()||_.isDataDriven()||N!=="model-color"&&N!=="model-color-mix-intensity"&&N!=="model-rotation"&&N!=="model-scale"&&N!=="model-translation"&&N!=="model-emissive-strength")}_isPropertyZoomDependent(N){const p=this._transitionablePaint._values[N];return p!=null&&p.value!=null&&p.value.expression!=null&&p.value.expression instanceof cg}isZoomDependent(){return this._isPropertyZoomDependent("model-scale")||this._isPropertyZoomDependent("model-rotation")||this._isPropertyZoomDependent("model-translation")}},clip:class extends Jy{constructor(N,p,_,C){super(N,{layout:Iht||(Iht=new Wu({"clip-layer-types":new gr(Ys.layout_clip["clip-layer-types"]),"clip-layer-scope":new gr(Ys.layout_clip["clip-layer-scope"]),visibility:new gr(Ys.layout_clip.visibility)})),paint:Lht||(Lht=new Wu({}))},p,_,C)}recalculate(N,p){super.recalculate(N,p)}createBucket(N){return new $ht(N)}is3D(N){return!0}}};class T8e{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(T8e,"LRUCache");class bps{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 _ft={Other:0,Symbol:1,FillExtrusion:2,HdRoadCoverage:3};class _ps{constructor(){this.tasks=new Map,zc(["process"],this),this.invoker=new bps(this.process),this.nextId=0}add(p,_){const C=this.nextId++,M=function({type:F,renderSourceType:z,zoom:H}){H=H||0;const Z=z===_ft.Symbol;return F==="message"?0:F!=="maybePrepare"||Z?F!=="parseTile"||Z?F==="parseTile"&&Z?300-H:F==="maybePrepare"&&Z?400-H:500:200-H:100-H}(_);if(M===0){try{p()}finally{}return null}return this.tasks.set(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 wft={type:"message"},M8e=new Map,jft=new Map;class Nft{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 kft(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 Z=(N[z]-_[z])*H,se=(p[z]-_[z])*H;if(Z>se){const fe=Z;Z=se,se=fe}if(Z>M&&(M=Z),seF)return null}return M}function Sft(N,p,_,C,M,F,z,H,Z,se,fe){const xe=C-N,be=M-p,Te=F-_,De=z-N,Ue=H-p,Ye=Z-_,nt=fe[1]*Ye-fe[2]*Ue,it=fe[2]*De-fe[0]*Ye,ht=fe[0]*Ue-fe[1]*De,ot=xe*nt+be*it+Te*ht;if(Math.abs(ot)<1e-15)return null;const yt=1/ot,Nt=se[0]-N,is=se[1]-p,At=se[2]-_,$t=(Nt*nt+is*it+At*ht)*yt;if($t<0||$t>1)return null;const Jt=is*Te-At*be,ns=At*xe-Nt*Te,Ps=Nt*be-is*xe,Gs=(fe[0]*Jt+fe[1]*ns+fe[2]*Ps)*yt;return Gs<0||$t+Gs>1?null:(De*Jt+Ue*ns+Ye*Ps)*yt}function Cft(N,p,_,C,M,F,z,H,Z){const se=1<<_,fe=F-C,xe=z-M,be=(N+1)/se*fe+C,Te=(p+0)/se*xe+M,De=(p+1)/se*xe+M;H[0]=(N+0)/se*fe+C,H[1]=Te,Z[0]=be,Z[1]=De}class Aft{constructor(p){if(this.maximums=[],this.minimums=[],this.leaves=[],this.childOffsets=[],this.nodeCount=0,this.dem=p,this._siblingOffset=[[0,0],[1,0],[0,1],[1,1]],!this.dem)return;const _=function(F){const z=F.dim,H=Math.ceil(Math.log2(z/8)),Z=[];let se=Math.ceil(Math.pow(2,H));const fe=(Ye,nt,it,ht,ot)=>{const yt=ht?1:0,Nt=(Ye+1)*it-yt,is=nt*it,At=(nt+1)*it-yt;ot[0]=Ye*it,ot[1]=is,ot[2]=Nt,ot[3]=At};let xe=new Nft(se);const be=1/se,{floatView:Te,stride:De}=F,Ue=[];for(let Ye=0;YePs&&(Ps=jn)}}xe.minimums.push(is),xe.maximums.push(Ps),xe.leaves.push(1)}for(Z.push(xe),se/=2;se>=1;se/=2){const Ye=Z.at(-1);xe=new Nft(se);for(let nt=0;nt0;){const{idx:De,t:Ue,nodex:Ye,nodey:nt,depth:it}=Te.pop();if(this.leaves[De]){Cft(Ye,nt,it,p,_,C,M,xe,be);const ot=1<1e-10,ar=Math.abs(z[1])>1e-10,zn=z[0]>=0?1:-1,Ir=z[1]>=0?1:-1;let lr=Math.max(0,Math.min(cn-1,Math.floor((In-Vn)/Zs))),_r=Math.max(0,Math.min(jn-1,Math.floor((qn-Cs)/an)));const Wa=Dn?Math.abs(Zs/z[0]):Number.MAX_VALUE,Ka=ar?Math.abs(an/z[1]):Number.MAX_VALUE;let oi=Dn?Ln+(Vn+(z[0]>=0?lr+1:lr)*Zs-In)/z[0]:Number.MAX_VALUE,Fa=ar?Ln+(Cs+(z[1]>=0?_r+1:_r)*an-qn)/z[1]:Number.MAX_VALUE;const Ai=(Vm,mo)=>Jt[(mo+1)*ns+Vm+1]*H;let Ni=Ai(Ps+lr,pn+_r),Fo=Ai(Ps+lr+1,pn+_r),rl=Ai(Ps+lr,pn+_r+1),Bl=Ai(Ps+lr+1,pn+_r+1),wc=null;for(let Vm=0;Vm=0||F[2]+z[2]*mo<=Math.max(Ni,Fo,rl,Bl)){const Lp=Vn+lr*Zs,gf=Lp+Zs,qx=Cs+_r*an,Vx=qx+an,qb=Sft(gf,qx,Fo,Lp,qx,Ni,Lp,Vx,rl,F,z),Ny=Sft(Lp,Vx,rl,gf,Vx,Bl,gf,qx,Fo,F,z);qb!=null&&qb>=0&&(wc===null||qb=0&&(wc===null||Ny=cn||_r<0||_r>=jn||wc!==null&&mo>wc)break;fp?zn>0?(Ni=Fo,rl=Bl,Fo=Ai(Ps+lr+1,pn+_r),Bl=Ai(Ps+lr+1,pn+_r+1)):(Fo=Ni,Bl=rl,Ni=Ai(Ps+lr,pn+_r),rl=Ai(Ps+lr,pn+_r+1)):Ir>0?(Ni=rl,Fo=Bl,rl=Ai(Ps+lr,pn+_r+1),Bl=Ai(Ps+lr+1,pn+_r+1)):(rl=Ni,Bl=Fo,Ni=Ai(Ps+lr,pn+_r),Fo=Ai(Ps+lr+1,pn+_r))}if(wc!==null)return wc||0;const qm=ke([],F,z,Ue),K0=(qm[0]-xe[0])/(be[0]-xe[0]),Zh=(qm[1]-xe[1])/(be[1]-xe[1]),_l=mM(yt,is,this.dem)*H,Hd=mM(Nt,is,this.dem)*H,mh=mM(Nt,At,this.dem)*H;if(Eft(_l,Hd,mM(yt,At,this.dem)*H,mh,K0,Zh)>=qm[2])return Ue;continue}let ht=0;for(let ot=0;ot=se[fe[At]]&&(fe.splice(At,0,ot),is=!0);is||(fe[ht]=ot),ht++}}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=Vle.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 ddt({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 Z=-_*this.dim,se=-C*this.dim;for(let fe=z;fe=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 Ips(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(Vle,"DEMData"),oa(Aft,"DemMinMaxQuadTree",{omit:["dem"]});var dj=Uint8Array,nZ=Uint16Array,Lps=Int32Array,Tft=new dj([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]),Mft=new dj([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]),Rps=new dj([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Pft=function(N,p){for(var _=new nZ(31),C=0;C<31;++C)_[C]=p+=1<>1|(21845&mp)<<1;Rft[mp]=((65280&(a$=(61680&(a$=(52428&a$)>>2|(13107&a$)<<2))>>4|(3855&a$)<<4))>>8|(255&a$)<<8)>>1}var rZ=function(N,p,_){for(var C=N.length,M=0,F=new nZ(p);M>Z]=se;return z},aZ=new dj(288);for(mp=0;mp<144;++mp)aZ[mp]=8;for(mp=144;mp<256;++mp)aZ[mp]=9;for(mp=256;mp<280;++mp)aZ[mp]=7;for(mp=280;mp<288;++mp)aZ[mp]=8;var Dft=new dj(32);for(mp=0;mp<32;++mp)Dft[mp]=5;var Ops=rZ(aZ,9),zps=rZ(Dft,5),P8e=function(N){for(var p=N[0],_=1;_p&&(p=N[_]);return p},Kk=function(N,p,_){var C=p/8|0;return(N[C]|N[C+1]<<8)>>(7&p)&_},I8e=function(N,p){var _=p/8|0;return(N[_]|N[_+1]<<8|N[_+2]<<16)>>(7&p)},Bps=function(N){return(N+7)/8|0},$ps=["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"],Yk=function(N,p,_){var C=new Error(p||$ps[N]);if(C.code=N,Error.captureStackTrace&&Error.captureStackTrace(C,Yk),!_)throw C;return C},Ups=new dj(0),qps=typeof TextDecoder<"u"&&new TextDecoder;try{qps.decode(Ups,{stream:!0})}catch{}const Vps={gzip_data:"gzip"};class Q2 extends Error{constructor(p){super(p),this.name="MRTError"}}const Hps={0:"uint32",1:"uint32",2:"uint16",3:"uint8"},Fft={uint32:1,uint16:2,uint8:4},Gps={uint32:Uint32Array,uint16:Uint16Array,uint8:Uint8Array};let L8e;class Hle{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 Q2(`Layer '${p}' not found`);return _}getHeaderLength(p){const _=new Uint8Array(p),C=new DataView(p);if(_[0]!==13)throw new Q2("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(Eps(F,F.readVarint()+F.pos));return z}(new L8e(_.subarray(0,C)));if(!isNaN(this.x)&&(this.x!==M.x||this.y!==M.y||this.z!==M.z))throw new Q2(`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 Oft(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 Z={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(Z)}return new zft(_,()=>{_.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 Oft{constructor({version:p,name:_,units:C,tileSize:M,pixelFormat:F,buffer:z,dataIndex:H},Z){if(this.version=p,this.version!==1)throw new Q2(`Cannot parse raster layer encoded with MRT version ${p}`);this.name=_,this.units=C,this.tileSize=M,this.buffer=z,this.pixelFormat=Hps[F],this.dataIndex=H,this.bandShape=[M+2*z,M+2*z,Fft[this.pixelFormat]],this._decodedBlocks=new T8e(Z?Z.cacheSize:5),this._blocksInProgress=new Set}get dimension(){return Fft[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 Q2(`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 Q2(`Invalid band: ${JSON.stringify(z)}`);const Z=this.dataIndex[H];M.includes(H)||M.push(H),F.add(H),_=Math.min(_,Z.firstByte),C=Math.max(C,Z.lastByte)}if(F.size>this.cacheSize)throw new Q2(`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 Q2(`Band not found: ${JSON.stringify(p)}`);const M=this._decodedBlocks.get(_.toString());if(!M)throw new Q2(`Data for band ${JSON.stringify(p)} of layer "${this.name}" not decoded.`);const F=this.dataIndex[_],z=this.bandShape.reduce((se,fe)=>se*fe,1),H=C*z,Z=M.subarray(H,H+z);return{data:Z,bytes:new Uint8Array(Z.buffer).subarray(Z.byteOffset,Z.byteOffset+Z.byteLength),tileSize:this.tileSize,buffer:this.buffer,pixelFormat:this.pixelFormat,dimension:this.dimension,offset:F.offset,scale:F.scale}}}Hle.setPbf=function(N){L8e=N};class zft{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)}}Hle.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:Z,blockIndex:se,filters:fe,codec:xe}=C,be=_.subarray(F,z+1),Te=new Uint32Array(Z[0]*Z[1]*Z[2]);let De;if(xe!=="gzip_data")throw new Q2(`Unhandled codec: ${xe}`);return De=function(Ue,Ye){if(!globalThis.DecompressionStream&&Ye==="gzip_data")return Promise.resolve((yt=function(At){At[0]==31&&At[1]==139&&At[2]==8||Yk(6,"invalid gzip data");var $t=At[3],Jt=10;4&$t&&(Jt+=2+(At[10]|At[11]<<8));for(var ns=($t>>3&1)+($t>>4&1);ns>0;ns-=!At[Jt++]);return Jt+(2&$t)}(nt=Ue),yt+8>nt.length&&Yk(6,"invalid gzip data"),function(At,$t,Jt,ns){var Ps=At.length;if(!Ps||$t.f&&!$t.l)return Jt||new dj(0);var Gs=!Jt,pn=Gs||$t.i!=2,cn=$t.i;Gs&&(Jt=new dj(3*Ps));var jn=function(Ny){var Hx=Jt.length;if(Ny>Hx){var ky=new dj(Math.max(2*Hx,Ny));ky.set(Jt),Jt=ky}},Vn=$t.f||0,Cs=$t.p||0,Zs=$t.b||0,an=$t.l,Ln=$t.d,In=$t.m,qn=$t.n,Dn=8*Ps;do{if(!an){Vn=Kk(At,Cs,1);var ar=Kk(At,Cs+1,3);if(Cs+=3,!ar){var zn=At[(rl=Bps(Cs)+4)-4]|At[rl-3]<<8,Ir=rl+zn;if(Ir>Ps){cn&&Yk(0);break}pn&&jn(Zs+zn),Jt.set(At.subarray(rl,Ir),Zs),$t.b=Zs+=zn,$t.p=Cs=8*Ir,$t.f=Vn;continue}if(ar==1)an=Ops,Ln=zps,In=9,qn=5;else if(ar==2){var lr=Kk(At,Cs,31)+257,_r=Kk(At,Cs+10,15)+4,Wa=lr+Kk(At,Cs+5,31)+1;Cs+=14;for(var Ka=new dj(Wa),oi=new dj(19),Fa=0;Fa<_r;++Fa)oi[Rps[Fa]]=Kk(At,Cs+3*Fa,7);Cs+=3*_r;var Ai=P8e(oi),Ni=(1<>4)<16)Ka[Fa++]=rl;else{var wc=0,qm=0;for(rl==16?(qm=3+Kk(At,Cs,3),Cs+=2,wc=Ka[Fa-1]):rl==17?(qm=3+Kk(At,Cs,7),Cs+=3):rl==18&&(qm=11+Kk(At,Cs,127),Cs+=7);qm--;)Ka[Fa++]=wc}}var K0=Ka.subarray(0,lr),Zh=Ka.subarray(lr);In=P8e(K0),qn=P8e(Zh),an=rZ(K0,In),Ln=rZ(Zh,qn)}else Yk(1);if(Cs>Dn){cn&&Yk(0);break}}pn&&jn(Zs+131072);for(var _l=(1<>4;if((Cs+=15&wc)>Dn){cn&&Yk(0);break}if(wc||Yk(2),Vm<256)Jt[Zs++]=Vm;else{if(Vm==256){mh=Cs,an=null;break}var mo=Vm-254;Vm>264&&(mo=Kk(At,Cs,(1<<(gf=Tft[Fa=Vm-257]))-1)+Lft[Fa],Cs+=gf);var fp=Ln[I8e(At,Cs)&Hd],Lp=fp>>4;if(fp||Yk(3),Cs+=15&fp,Zh=Fps[Lp],Lp>3){var gf=Mft[Lp];Zh+=I8e(At,Cs)&(1<Dn){cn&&Yk(0);break}pn&&jn(Zs+131072);var qx=Zs+mo;if(ZsNy.length)&&(ky=Ny.length),new dj(Ny.subarray(0,ky))}(Jt,0,Zs):Jt.subarray(0,Zs)}(nt.subarray(yt,-8),{i:2},new dj(((ht=nt)[(ot=ht.length)-4]|ht[ot-3]<<8|ht[ot-2]<<16|ht[ot-1]<<24)>>>0),it)));var nt,it,ht,ot,yt;const Nt=Vps[Ye];if(!Nt)throw new Error(`Unhandled codec: ${Ye}`);const is=new globalThis.DecompressionStream(Nt);return new Response(new Blob([Ue]).stream().pipeThrough(is)).arrayBuffer().then(At=>new Uint8Array(At))}(be,xe).then(Ue=>(function(Ye,nt){let it;for(;it=Ye.nextField();)if(it===2)Tps(Ye,Ye.readVarint()+Ye.pos,nt);else if(it===3)throw new Error("Not implemented")}(new L8e(Ue),Te),new Gps[H](Te.buffer))),De.then(Ue=>{for(let Ye=fe.length-1;Ye>=0;Ye--)switch(fe[Ye]){case"delta_filter":Mps(Ue,Z);break;case"zigzag_filter":Pps(Ue);break;case"bitshuffle_filter":Ips(Ue,H);break;default:throw new Q2(`Unhandled filter "${fe[Ye]}"`)}return{layerName:M,blockIndex:se,data:Ue}}).catch(Ue=>{throw Ue})}))},oa(zft,"MRTDecodingBatch",{omit:["_onCancel","_onComplete"]}),oa(Hle,"MapboxRasterTile"),oa(Oft,"MapboxRasterLayer",{omit:["_blocksInProgress"]});const Bft=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array],Ip=new Uint32Array(96);class R8e{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=Bft[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 R8e(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=Bft.indexOf(this.ArrayType),H=2*p*this.ArrayType.BYTES_PER_ELEMENT,Z=p*this.IndexArrayType.BYTES_PER_ELEMENT,se=(8-Z%8)%8;if(z<0)throw new Error(`Unexpected typed array class: ${C}.`);if(F)this.data=F,this.ids=new this.IndexArrayType(F,8,p),this.coords=new C(F,8+Z+se,2*p),this._pos=2*p,this._finished=!0;else{const fe=this.data=new M(8+H+Z+se);this.ids=new this.IndexArrayType(fe,8,p),this.coords=new C(fe,8+Z+se,2*p),this._pos=0,this._finished=!1,new Uint8Array(fe,0,2).set([219,16+z]),new Uint16Array(fe,2,1)[0]=_,new Uint32Array(fe,4,1)[0]=p}}add(p,_){const 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 D8e(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;Ip[0]=0,Ip[1]=F.length-1,Ip[2]=0;let Z=3;const se=[];for(;Z>0;){const fe=Ip[--Z],xe=Ip[--Z],be=Ip[--Z];if(xe-be<=H){for(let Ye=be;Ye<=xe;Ye++){const nt=z[2*Ye],it=z[2*Ye+1];nt>=p&&nt<=C&&it>=_&&it<=M&&se.push(F[Ye])}continue}const Te=be+xe>>1,De=z[2*Te],Ue=z[2*Te+1];De>=p&&De<=C&&Ue>=_&&Ue<=M&&se.push(F[Te]),(fe===0?p<=De:_<=Ue)&&(Ip[Z++]=be,Ip[Z++]=Te-1,Ip[Z++]=1-fe),(fe===0?C>=De:M>=Ue)&&(Ip[Z++]=Te+1,Ip[Z++]=xe,Ip[Z++]=1-fe)}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;Ip[0]=0,Ip[1]=F.length-1,Ip[2]=0;let Z=3,se=0;const fe=C*C;for(;Z>0;){const xe=Ip[--Z],be=Ip[--Z],Te=Ip[--Z];if(be-Te<=H){for(let nt=Te;nt<=be;nt++)Uft(z[2*nt],z[2*nt+1],p,_)<=fe&&(M[se++]=F[nt]);continue}const De=Te+be>>1,Ue=z[2*De],Ye=z[2*De+1];Uft(Ue,Ye,p,_)<=fe&&(M[se++]=F[De]),(xe===0?p-C<=Ue:_-C<=Ye)&&(Ip[Z++]=Te,Ip[Z++]=De-1,Ip[Z++]=1-xe),(xe===0?p+C>=Ue:_+C>=Ye)&&(Ip[Z++]=De+1,Ip[Z++]=be,Ip[Z++]=1-xe)}return se}}function D8e(N,p,_,C,M,F){if(M-C<=_)return;const z=C+M>>1;$ft(N,p,z,C,M,F),D8e(N,p,_,C,z-1,1-F),D8e(N,p,_,z+1,M,1-F)}function $ft(N,p,_,C,M,F){for(;M>C;){if(M-C>600){const se=M-C+1,fe=_-C+1,xe=Math.log(se),be=.5*Math.exp(2*xe/3),Te=.5*Math.sqrt(xe*be*(se-be)/se)*(fe-se/2<0?-1:1);$ft(N,p,_,Math.max(C,Math.floor(_-fe*be/se+Te)),Math.min(M,Math.floor(_+(se-fe)*be/se+Te)),F)}const z=p[2*_+F];let H=C,Z=M;for(iZ(N,p,C,_),p[2*M+F]>z&&iZ(N,p,C,M);Hz;)Z--}p[2*C+F]===z?iZ(N,p,C,Z):(Z++,iZ(N,p,Z,M)),Z<=_&&(C=Z+1),_<=Z&&(M=Z-1)}}function iZ(N,p,_,C){F8e(N,_,C),F8e(p,2*_,2*C),F8e(p,2*_+1,2*C+1)}function F8e(N,p,_){const C=N[p];N[p]=N[_],N[_]=C}function Uft(N,p,_,C){const M=N-_,F=p-C;return M*M+F*F}c.$=jy,c.A=q0,c.B=Ox,c.C=Ci,c.D=F1,c.E=Xc,c.F=rp,c.G=Pk,c.H=Zw,c.I=vd,c.J=B6,c.K=/^(.*)-transition$/,c.L=T8e,c.M=cp,c.N=Bk,c.O=Lr,c.P=xs,c.Q=v,c.R=yr,c.S=q3,c.T=Koe,c.U=/^(.*)-use-theme$/,c.V=function(N,p){const _=q3(p.zoom);if(_===0)return HC(N);const C=Ioe(N),M=oOe(C),F=ex(C.getWest())*p.worldSize,z=ex(C.getEast())*p.worldSize,H=ap(C.getNorth())*p.worldSize,Z=ap(C.getSouth())*p.worldSize,se=[F,H,0],fe=[z,H,0],xe=[F,Z,0],be=[z,Z,0],Te=A([],p.globeMatrix);return Xe(se,se,Te),Xe(fe,fe,Te),Xe(xe,xe,Te),Xe(be,be,Te),M[0]=U3(M[0],xe,_),M[1]=U3(M[1],be,_),M[2]=U3(M[2],fe,_),M[3]=U3(M[3],se,_),du.fromPoints(M)},c.W=lOe,c.X=E,c.Y=y,c.Z=wy,c._=cj,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",Z),M(z)},Z=()=>{const se=$a.indexOf(H);se!==-1&&$a.splice(se,1),F(C.reason)};C&&C.addEventListener("abort",Z),$a.push(H)})}(p);try{const{data:C,headers:M}=await Qr(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=Fmt,c.a1=wh,c.a2=hp,c.a3=co,c.a4=Of,c.a5=Um,c.a6=Dr,c.a7=ex,c.a8=ap,c.a9=function(N,p,_){if(p.projection.name===_.projection.name)return N.projMatrix;const C=_.clone();return C.setProjection(p.projection),yOe(C,p.getProjection(),N)},c.aA=$3,c.aB=T,c.aC=Ddt,c.aD=jle,c.aE=mht,c.aF=n$,c.aG=mft,c.aH=yh,c.aI=(N,p,_,C,M,F,z,H,Z,se,fe,xe,be,Te,De,Ue,Ye,nt,it=!1)=>{const ht=cft(N,p,_,C,M,F,z,H,se,fe,xe,be,Te,De,Ue,Ye,1,[0,0,0],[0,0,1],it),ot={u_height_factor:-Math.pow(2,H.overscaledZ)/Z.tileSize/8};return Object.assign(ht,oft(p,Z,nt),ot)},c.aJ=cft,c.aK=W3,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:zle[M],u_base_type:zle[F]}),c.aO=P,c.aP=A,c.aQ=S,c.aR=uft,c.aS=4,c.aT=2,c.aU=qFe,c.aV=VFe,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 Z of Object.values(N))for(const[se,fe]of Object.entries(Z.floors)){F.add(se),fe.isDefault&&z.add(se),fe.conflicts&&M.set(se,fe.conflicts);const xe=se===p,be=fe.connections&&p&&fe.connections.has(p);(xe||be)&&C.add(se)}const H=Z=>{const se=M.get(Z)||new Set;for(const fe of C)if((M.get(fe)||new Set).has(Z)||se.has(fe))return!0;return!1};if(_)for(const Z of _)F.has(Z)&&(H(Z)||C.add(Z));for(const Z of z)C.has(Z)||H(Z)||C.add(Z);return C}},c.aY=$m,c.aZ=W_,c.a_=class extends _y{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=ne,c.ab=Gr,c.ac=whs,c.ad=Li,c.ae=qr,c.af=xl,c.ag=Wu,c.ah=gr,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=Wn,c.ak=cg,c.al=Sl,c.am=ya,c.an=xc,c.ao=65,c.ap=45,c.aq=function(N,p,_){const C=Q.fromLngLat(p),M=_.elevation?_.elevation.getAtPointOrZero(C):0;return Gdt(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 Z=Number.MAX_VALUE,se=-Number.MAX_VALUE;for(const fe of H){const xe=ce(Xe([],fe,p));Z=Math.min(Z,xe),se=Math.max(se,xe)}return[Voe(N,Z,z.pitch),Voe(N,se,z.pitch)]},c.as=Gu,c.at=Gdt,c.au=LY,c.av=Xr,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 _ps}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:Vv(p,H)},[...H]),new Promise((Z,se)=>{const fe={resolve:Z,reject:se,metadata:F||wft};if(C){const xe=()=>{this.pendingResponses.delete(z),se(C.reason)};C.addEventListener("abort",xe,{once:!0}),fe.detach=()=>C.removeEventListener("abort",xe)}this.pendingResponses.set(z,fe)}))}notify(N,p,_){const{targetMapId:C}=_||{},M=new Set;this.target.postMessage({type:N,targetMapId:C,sourceMapId:this.mapId,data:Vv(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||wft)}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(Ux(p.error)):M.resolve(Ux(p.data))}catch(F){M.reject(F)}}return}const _=new Set,C=Ux(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:Vv(M,_)},[..._])}catch(M){this.target.postMessage({id:N,type:"",sourceMapId:this.mapId,error:Vv(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=iR,c.b=t0,c.b$=ah,c.b0=Vl,c.b1=ta,c.b2=6,c.b3=Ioe,c.b4=function(N){const p=80.051129;N=ta(N,-80.051129,p)/p*90;const _=Math.pow(Math.abs(Math.sin(Xr(N))),3);return Math.round(_*(bY.length-1))},c.b5=Doe,c.b6=HC,c.b7=function(N){const p=N.pixelsPerMeter,_=p/Jd(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(),Z=1<0){const De=180/C;g(Te,Te,[De/se+1,0,0,0,De/fe+1,0,-.5*De/xe,.5*De/be,1])}return Te[2]=Z,Te[5]=N.x,Te[8]=N.y,Te},c.b9=Zg,c.bA=QFe,c.bB=$Fe,c.bC=ut,c.bD=Hs,c.bE=_d,c.bF=sOe,c.bG=XT,c.bH=CY,c.bI=Xe,c.bJ=U3,c.bK=Fs,c.bL=Mhs,c.bM=W,c.bN=I,c.bO=function(){Ur.isLoading()||Ur.isLoaded()||by()!=="deferred"||q_()},c.bP=et,c.bQ=mg,c.bR=function(N,p){const _=[];for(const C in N)C in p||_.push(C);return _},c.bS=_ft,c.bT=Q,c.bU=Co,c.bV="hd_road_coverage",c.bW=aM,c.bX=Foe,c.bY=Y6,c.bZ=le,c.b_=lm,c.ba=256,c.bb=tft,c.bc=hd,c.bd=Ko,c.be=kt,c.bf=wt,c.bg=ks,c.bh=X,c.bi=_e,c.bj=lg,c.bk=eM,c.bl=Uc,c.bm=vu,c.bn=koe,c.bo=s$,c.bp=vo,c.bq=uOe,c.br=Fx,c.bs=qd,c.bt=nn,c.bu=dc,c.bv=ele,c.bw=hY,c.bx=bt,c.by=aR,c.bz=_s,c.c=H0,c.c$=Hoe,c.c0=function(N,p,_){const C=q3(_.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=gft,c.cF=qle,c.cG=ir,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 Qr(N.request,F.signal).then(({data:z,headers:H})=>{M(null,{rawData:z,vectorTile:_?void 0:new UFe(new Hoe(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){vn++,vn>Ts&&(N.getActor().notify("enforceCacheSizeLimit",ws),vn=0)},c.cK=Tu,c.cL=async function(N,p,_){const C=N.url&&!N.tiles?await p.transformRequest(N.url,yr.Source,_):void 0;return{request:C,options:C?{...N,url:C.url}:N}},c.cM=function(N,p,_){return p?pft(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 _=jft.get(N);if(_)return _;const C=M8e.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 jft.set(N,z),z}).finally(()=>{M8e.delete(N)});return M8e.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=omt,c.cY=gmt,c.cZ=Il,c.c_=Hle,c.ca=ke,c.cb=oft,c.cc=Mdt,c.cd=XY,c.ce=l8e,c.cf=qi,c.cg=cm,c.ch=function(N,p){const _=[0,0,0];return Xe(_,_,Doe(HC(p.canonical))),Xe(_,_,N),_},c.ci=Gv,c.cj=function(N,p,_,C,M,F){const{width:z,height:H}=C.imageManager.getPixelSize(p),Z=Math.pow(2,F.tileID.overscaledZ),se=F.tileSize*Math.pow(2,C.transform.tileZoom)/Z,fe=se*(F.tileID.canonical.x+F.tileID.wrap*Z),xe=se*F.tileID.canonical.y;return{u_image:0,u_pattern_tl:_.tl,u_pattern_br:_.br,u_texsize:[z,H],u_pattern_size:_.displaySize,u_pattern_units_to_pixels:M?[C.transform.width,-1*C.transform.height]:[1/XY(F,1,C.transform.tileZoom),1/XY(F,1,C.transform.tileZoom)],u_pixel_coord_upper:[fe>>16,xe>>16],u_pixel_coord_lower:[65535&fe,65535&xe]}},c.ck=N=>({u_matrix:new Of(N),u_texsize:new hp(N),u_pixels_to_tile_units:new Z6(N),u_device_pixel_ratio:new co(N),u_width_scale:new co(N),u_floor_width_scale:new co(N),u_image:new $m(N),u_units_to_pixels:new hp(N),u_tile_units_to_pixels:new co(N),u_alpha_discard_threshold:new co(N),u_trim_offset:new hp(N),u_trim_fade_range:new hp(N),u_trim_gradient_mix_range:new hp(N),u_trim_color:new W_(N),u_zbias_factor:new co(N),u_tile_to_meter:new co(N),u_ground_shadow_factor:new Um(N),u_pattern_transition:new co(N),u_opacity_multiplier:new co(N)}),c.cl=N=>({u_matrix:new Of(N),u_pixels_to_tile_units:new Z6(N),u_device_pixel_ratio:new co(N),u_width_scale:new co(N),u_floor_width_scale:new co(N),u_units_to_pixels:new hp(N),u_dash_image:new $m(N),u_gradient_image:new $m(N),u_border_gradient_image:new $m(N),u_image_height:new co(N),u_texsize:new hp(N),u_tile_units_to_pixels:new co(N),u_alpha_discard_threshold:new co(N),u_trim_offset:new hp(N),u_trim_fade_range:new hp(N),u_trim_gradient_mix_range:new hp(N),u_trim_color:new W_(N),u_zbias_factor:new co(N),u_road_view_depth_bias:new co(N),u_road_clip_to_view:new W_(N),u_tile_to_meter:new co(N),u_ground_shadow_factor:new Um(N),u_opacity_multiplier:new co(N)}),c.cm=N=>({u_color:new Y6(N),u_matrix:new Of(N),u_overlay:new $m(N),u_overlay_scale:new co(N)}),c.cn=N=>({u_camera_to_center_distance:new co(N),u_extrude_scale:new Z6(N),u_device_pixel_ratio:new co(N),u_matrix:new Of(N),u_inv_rot_matrix:new Of(N),u_merc_center:new hp(N),u_tile_id:new Um(N),u_zoom_transition:new co(N),u_up_dir:new Um(N),u_emissive_strength:new co(N)}),c.co=N=>({u_matrix:new Of(N),u_lightpos:new Um(N),u_lightintensity:new co(N),u_lightcolor:new Um(N),u_vertical_gradient:new co(N),u_height_factor:new co(N),u_edge_radius:new co(N),u_width_scale:new co(N),u_ao:new hp(N),u_height_type:new $m(N),u_base_type:new $m(N),u_tile_id:new Um(N),u_zoom_transition:new co(N),u_inv_rot_matrix:new Of(N),u_merc_center:new hp(N),u_up_dir:new Um(N),u_height_lift:new co(N),u_image:new $m(N),u_texsize:new hp(N),u_pixel_coord_upper:new hp(N),u_pixel_coord_lower:new hp(N),u_tile_units_to_pixels:new co(N),u_opacity:new co(N),u_pattern_transition:new co(N)}),c.cp=N=>({u_matrix:new Of(N),u_lightpos:new Um(N),u_lightintensity:new co(N),u_lightcolor:new Um(N),u_vertical_gradient:new co(N),u_opacity:new co(N),u_edge_radius:new co(N),u_width_scale:new co(N),u_ao:new hp(N),u_height_type:new $m(N),u_base_type:new $m(N),u_tile_id:new Um(N),u_zoom_transition:new co(N),u_inv_rot_matrix:new Of(N),u_merc_center:new hp(N),u_up_dir:new Um(N),u_height_lift:new co(N),u_flood_light_color:new Um(N),u_vertical_scale:new co(N),u_flood_light_intensity:new co(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 Koe(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 W_(N)}),c.d0=Qr,c.d1=["type","source","source-layer","minzoom","maxzoom","filter","layout"],c.d2=qv,c.d3=Ut,c.d4=jr,c.d5=hr,c.d6=Fn,c.d7=fl,c.d8=ts,c.d9=.55,c.dA=Vt,c.dB=Yoe,c.dC=SOe,c.dD=Zi,c.dE=zt,c.dF=dd,c.dG=$l,c.dH=function(N){const p=N.indexOf(ZT);return p>=0?N.slice(0,p):N},c.dI=function(N){return N.includes(ZT)},c.dJ=function(N){const p=N.lastIndexOf(ZT);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 H0(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 zfs(N,p):new vps[N.type](N,p,_,C)},c.dN=yc,c.dO=fY,c.dP=class extends aR{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=hh,c.dR=hft,c.dS=Kdt,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=ops,c.d_=lps,c.da=uM,c.db=Mmt,c.dc=ZFe,c.dd=Hdt,c.de=gOe,c.df=w,c.dg=B9,c.dh=.9,c.di=Wdt,c.dj=function(N,p,_,C,M,F,z){const H=v8e(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=v8e(N,p,_,C,M,F,z);return A(H,H),E(H,N,H),H}{const H=v(N),[Z,se,fe,xe]=z,[be,Te,De,Ue,Ye,nt,it,ht]=H;return H[0]=Z*be+se*Ye,H[1]=Z*Te+se*nt,H[2]=Z*De+se*it,H[3]=Z*Ue+se*ht,H[4]=fe*be+xe*Ye,H[5]=fe*Te+xe*nt,H[6]=fe*De+xe*it,H[7]=fe*Ue+xe*ht,C||O(H,H,-M.angle),H}}return M.glCoordMatrix},c.dl=B3,c.dm=hOe,c.dn=IY,c.dp=pOe,c.dq=qoe,c.dr=Yt,c.ds=Eoe,c.dt=z3,c.du=ydt,c.dv=function(N,[p,_]){let C=0,M=0;if(_===Ahs){p<0&&(p=0);const F=p/Ehs;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=R8e,c.dy=vOe,c.dz=function(N){return N({pluginStatus:Mi,pluginURL:gl}),hh.on("pluginStateChange",N),N},c.e=ih,c.e$=Cd,c.e0=N=>({u_light_matrix_0:new Of(N),u_light_matrix_1:new Of(N),u_fade_range:new hp(N),u_shadow_normal_offset:new Um(N),u_shadow_intensity:new co(N),u_shadow_texel_size:new co(N),u_shadow_map_resolution:new co(N),u_shadow_direction:new 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:yOe(_,p,N)},c.e2=v8e,c.e3=eZ,c.e4=Tmt,c.e5=eR,c.e6=function(N,p,_,C,M,F,z,H,Z,se,fe=1){const xe=_.transform,be=C?N.textSizeData:N.iconSizeData,Te=B3(be,_.transform.zoom,fe),De=xe.projection.name==="globe",Ue=(()=>{if(!De)return null;const At=q3(xe.zoom);return At===0?null:{t:At,invMatrix:xe.projection.createInversionMatrix(xe,se.canonical),mercCenter:[ex(xe.center.lng),ap(xe.center.lat)]}})(),Ye=[256/_.width*2+1,256/_.height*2+1],nt=C?N.text.dynamicLayoutVertexArray:N.icon.dynamicLayoutVertexArray;nt.clear();let it=null;De&&(it=C?N.text.globeExtVertexArray:N.icon.globeExtVertexArray);const ht=N.lineVertexArray,ot=C?N.text.placedSymbolArray:N.icon.placedSymbolArray,yt=_.transform.width/_.transform.height;let Nt,is=!1;for(let At=0;At{const z=N.transform,H=z.projection.name==="globe";let Z;if(F.paint.get("circle-pitch-alignment")==="map")if(H){const fe=Mdt(z.zoom,p.canonical)*z._pixelsPerMercatorPixel;Z=Float32Array.from([fe,0,0,fe])}else Z=z.calculatePixelsToTileUnitsMatrix(_);else Z=new Float32Array([z.pixelsToGLUnits[0],0,0,z.pixelsToGLUnits[1]]);const se={u_camera_to_center_distance:N.transform.getCameraToCenterDistance(z.projection),u_matrix:N.translatePosMatrix(p.projMatrix,_,F.paint.get("circle-translate"),F.paint.get("circle-translate-anchor")),u_device_pixel_ratio:ih.devicePixelRatio,u_extrude_scale:Z,u_inv_rot_matrix:Mfs,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(!ir(N))return N;const _=qt(N);return _.params.push(`sdk=js-${d}`),_.path=`/styles/v1${_.path}`,this._makeAPIURL(_,this._customAccessToken||p)}normalizeGlyphsURL(N,p){if(!ir(N))return N;const _=qt(N);return _.path=`/fonts/v1${_.path}`,this._makeAPIURL(_,this._customAccessToken||p)}normalizeModelURL(N,p){if(!ir(N))return N;const _=qt(N);return _.path=`/models/v1${_.path}`,this._makeAPIURL(_,this._customAccessToken||p)}normalizeSourceURL(N,p,_,C){if(!ir(N))return N;const M=qt(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 _=qt(N);return ir(N)?(_.path=`/styles/v1${_.path}/iconset.pbf`,this._makeAPIURL(_,this._customAccessToken||p)):Cn(_)}normalizeSpriteURL(N,p,_,C){const M=qt(N);return ir(N)?(M.path=`/styles/v1${M.path}/sprite${p}${_}`,this._makeAPIURL(M,this._customAccessToken||C)):(M.path+=`${p}${_}`,Cn(M))}normalizeTileURL(N,p,_){if(this._isSkuTokenExpired()&&this._createSkuToken(),N&&!ir(N))return N;const C=qt(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 _=qt(N);if(!nl.test(_.path)||!po.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&&ir(p),C=[];for(const M of N.tiles||[])Pn(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=qt(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 Cn(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||""}`),Cn(N)}},c.eX=ra,c.eY=function(N,p){p?$d.add(N):$d.delete(N)},c.eZ=ad,c.e_=Hu,c.ea=Kht,c.eb=(N,p,_,C,M,F,z,H,Z,se)=>{const fe=N.transform,xe=fe.pitch<15?ya(.07,.7,ta((14-fe.zoom)/5,0,1)):.07,be=_.paint.get("line-trim-color-use-theme").constantOr("default")==="none";return{u_matrix:Wht(N,p,_,C),u_texsize:p.imageAtlasTexture?p.imageAtlasTexture.size:[0,0],u_pixels_to_tile_units:fe.calculatePixelsToTileUnitsMatrix(p),u_device_pixel_ratio:M,u_width_scale:F,u_floor_width_scale:z,u_image:0,u_tile_units_to_pixels:Ght(p,fe),u_units_to_pixels:[1/fe.pixelsToGLUnits[0],1/fe.pixelsToGLUnits[1]],u_alpha_discard_threshold:0,u_trim_offset:H,u_trim_fade_range:_.paint.get("line-trim-fade-range"),u_trim_gradient_mix_range:[1,1],u_trim_color:_.paint.get("line-trim-color").toPremultipliedRenderColor(be?null:_.lut).toArray01(),u_zbias_factor:xe,u_tile_to_meter:K(p.tileID.canonical,0),u_ground_shadow_factor:Z,u_pattern_transition:se,u_opacity_multiplier:1}},c.ec=(N,p,_,C,M,F,z,H,Z,se)=>{const fe=N.transform,xe=fe.calculatePixelsToTileUnitsMatrix(p),be=_.paint.get("line-trim-color-use-theme").constantOr("default")==="none",Te=fe.pitch<15?ya(.07,.7,ta((14-fe.zoom)/5,0,1)):.07;return{u_matrix:Wht(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/fe.pixelsToGLUnits[0],1/fe.pixelsToGLUnits[1]],u_dash_image:0,u_gradient_image:1,u_border_gradient_image:2,u_image_height:M,u_texsize:Yht(_)&&p.lineAtlasTexture?p.lineAtlasTexture.size:[0,0],u_tile_units_to_pixels:Ght(p,N.transform),u_alpha_discard_threshold:0,u_trim_offset:Z,u_trim_fade_range:_.paint.get("line-trim-fade-range"),u_trim_gradient_mix_range:[1,1],u_trim_color:_.paint.get("line-trim-color").toPremultipliedRenderColor(be?null:_.lut).toArray01(),u_zbias_factor:Te,u_road_view_depth_bias:0,u_road_clip_to_view:[0,0,0,0],u_tile_to_meter:K(p.tileID.canonical,0),u_ground_shadow_factor:se,u_opacity_multiplier:1}},c.ed=zr,c.ee=YY,c.ef=5,c.eg=Ofs,c.eh=On,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=so,c.en=1,c.eo=t$,c.ep=0,c.eq=ql,c.er=function(N,p,_,C,M){return ta((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],Z=p[6],se=p[7],fe=p[8],xe=fe*z-H*se,be=-fe*F+H*Z,Te=se*F-z*Z,De=_*xe+C*be+M*Te;return De?(N[0]=xe*(De=1/De),N[1]=(-fe*C+M*se)*De,N[2]=(H*C-M*z)*De,N[3]=be*De,N[4]=(fe*_-M*Z)*De,N[5]=(-H*_+M*F)*De,N[6]=Te*De,N[7]=(-se*_+C*Z)*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 _=qdt(new xs(0,0),new xs(Dr,Dr),N),C=[];if(p&&!mOe(_,this._globalClipBounds))return C;for(const M of this._activeRegions){if(M.hiddenByOverlap||!mOe(_,M))continue;const F=Whs(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=qdt(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||$oe(p.min,_.min)||$oe(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||!Udt(_,C)||_.order!==C.order||_.clipMask!==C.clipMask||!Lr(_.clipScope,C.clipScope),this._activeRegions[p].hiddenByOverlap=C.hiddenByOverlap,++p}}if(N){++this._updateTime;for(const _ of this._activeRegions)_.order!==PY&&(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=PY,c.ey=class{constructor(N){this._createGrid(N),this._createPoles(N)}destroy(){this._poleIndexBuffer.destroy(),this._gridBuffer.destroy(),this._gridIndexBuffer.destroy(),this._poleNorthVertexBuffer.destroy(),this._poleSouthVertexBuffer.destroy();for(const N of this._poleSegments)N.destroy();for(const N of this._gridSegments)N.withSkirts.destroy(),N.withoutSkirts.destroy()}_fillGridMeshWithLods(N,p){const _=new Hs,C=new qr,M=[],F=N+1+2,z=p[0]+1,H=p[0]+1+(1+p.length),Z=(se,fe,xe)=>{let be=se===F-1?se-2:se===0?se:se-1;return be+=xe?24575:0,[be,fe]};for(let se=0;se0&&OOe(p,N.layers[0].source,N.sourceLayerName);(C||M)&&(N.hdExt=new Cut(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&&OOe(p,N.layers[0].source,N.sourceLayerName);(_||C)&&(N.hdExt=new Aut(_,C))},c.fD=Coe,c.fE=function(N){const p=N.layers[0];p.type==="circle"&&p.layout.get("circle-elevation-reference")==="hd-road-markup"&&(N.hdExt=new Eut)},c.fF=function(N){N.layers[0].layout.get("symbol-elevation-reference")==="hd-road-markup"&&(N.hdExt=new Tut)},c.fG=yft,c.fH=function(N){let p=0;if(new Uint32Array(N,0,1)[0]!==Out){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 Uut(N,p)},c.fI=function(N,p){const _=YOe(N);for(const C of _){if(!C.meshBVH)for(const M of C.meshes)Jms(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(efs(C.lights,p,M))}}return _},c.fJ=K,c.fK=jmt,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=Xw,c.fU=sdt,c.fV=O3,c.fW=function(N){for(const p of N)if(!Oe(p.charCodeAt(0)))return!1;return!0},c.fX=de,c.fY=tOe,c.fZ=vdt,c.f_=Ndt,c.fa=Eo,c.fb=Idt,c.fc=function(N){const p=[0,0,0],_=w(new Float64Array(16));return E(_,N.pixelMatrix,N.globeMatrix),Xe(p,p,_),new xs(p[0],p[1])},c.fd=function(N){Ia=N},c.fe=er,c.ff=Emt,c.fg=function(N,p){if(!N||!p)throw new Error("TileProvider name and URL are required");xt.TILE_PROVIDER_URLS[N]=ih.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.`):Aa=N},c.fi=by,c.fj=function(N,p,_=!1){if(Mi===$r.deferred||Mi===$r.loading||Mi===$r.loaded)throw new Error("setRTLTextPlugin cannot be called multiple times.");gl=ih.resolveURL(N),Mi=$r.deferred,di=p,Hh(),_||q_()},c.fk=function(N){xt.BUILDING_GEN_URL=ih.resolveURL(N)},c.fl=jt,c.fm=function(N){const p=ih.resolveURL(N);xt.MESHOPT_URL=p,xt.MESHOPT_SIMD_URL=p},c.fn=ct,c.fo=function(N){xt.DRACO_URL=ih.resolveURL(N)},c.fp=We,c.fq=function(N){const p=fn();if(!p)return;const _=p.delete(Ht);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 _=H3.parse(N);if(!_)return[];let{vertices:C,features:M}=_;const F=1/K(p);M.sort((se,fe)=>se.id-fe.id),C.sort((se,fe)=>se.id-fe.id||se.idx-fe.idx),C=C.filter((se,fe,xe)=>fe===xe.findIndex(be=>be.id===se.id&&be.idx===se.idx));const z=new Array;let H=0;const Z=C.length;for(const se of M){if(se.constantHeight){z.push(new G3(se.id,se.bounds,se.constantHeight));continue}for(;H!==Z&&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,Z=0;Z55295&&z<57344){if(!H){z>56319||Z+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&&Xdt(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&&Xdt(_,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,Khs,p)}writePackedSVarint(N,p){p.length&&this.writeMessage(N,Yhs,p)}writePackedBoolean(N,p){p.length&&this.writeMessage(N,Qhs,p)}writePackedFloat(N,p){p.length&&this.writeMessage(N,Zhs,p)}writePackedDouble(N,p){p.length&&this.writeMessage(N,Xhs,p)}writePackedFixed32(N,p){p.length&&this.writeMessage(N,Jhs,p)}writePackedSFixed32(N,p){p.length&&this.writeMessage(N,ems,p)}writePackedFixed64(N,p){p.length&&this.writeMessage(N,tms,p)}writePackedSFixed64(N,p){p.length&&this.writeMessage(N,sms,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=Boe,c.gs=$r,c.gt=bft,c.gu=function(N){gn(),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=RY,c.l=Yw,c.m=U6,c.n=R1,c.o=Ky,c.p=Qdt,c.q=F_,c.r=Xy,c.s=Ys,c.t=Zy,c.u=S9,c.v=tj,c.w=Yo,c.x=Uv,c.y=C9,c.z=G0}),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:jt,options:Rt}){if(!Rt.elevationFeatures||Rt.elevationFeatures.length===0)return;const zt=[];for(const ws of Object.values(xt))if(ws instanceof c.bB&&ws.hdExt){const Ts=ws.hdExt.getUnevaluatedPortalGraph();Ts&&zt.push(Ts)}const Ht=c.fw.evaluate(zt);for(const ws of Object.values(xt))if(ws instanceof c.bB&&ws.hdExt){const Ts=We.layers[ct.decode(ws.sourceLayerIndex)];ws.hdExt.setEvaluatedPortalGraph(Ht,Ts,jt,Rt.availableImages,Rt.brightness,ws.worldview)}}function m(xt){const We=[];for(let ct=0;ct0){let Ts=!1;for(const js of Ht[0])if(js.x<0||js.x>c.a6||js.y<0||js.y>c.a6){Ts=!0;break}if(Ts)continue}const ws=Ht.length===1&&Ht[0].length===5&&Ht[0].some(Ts=>Ts.x<=0&&Ts.y<=0)&&Ht[0].some(Ts=>Ts.x>=c.a6&&Ts.y<=0)&&Ht[0].some(Ts=>Ts.x>=c.a6&&Ts.y>=c.a6)&&Ht[0].some(Ts=>Ts.x<=0&&Ts.y>=c.a6);We.push(new c.fx(zt,ws?[]:Ht))}return We}function f(xt,We,ct,jt,Rt){const zt=c.fy(We);if(zt===null)return!1;let Ht=ct.x,ws=ct.y;const Ts=Rt??jt.z;if(jt.z!==Ts){const js=1<fn.map(gn=>[gn.x,gn.y]));if(c.fz([Ht,ws],Ms))return!0}return!1}function g(xt,We,ct,jt){const Rt=We.indoorState.activeFloorsVisible;if(!We.sourceLayers)return Rt?We.indoorState.activeFloors:void 0;const zt=function(Ts,js){if(!Ts)return c.w("No source layers defined in indoor specification"),js;if(Ts.size===0)return js;const Ms=Ts.difference(js);for(const fn of Ms)c.w(`Missing source layer required in indoor specification: ${fn}`);return js.intersection(js)}(We.sourceLayers,new Set(Object.keys(xt.layers))),Ht=We.indoorState,ws=function(Ts,js,Ms,fn,gn){const vn={};for(const Pn of js){const ir=Ts.layers[Pn];if(ir)for(let er=0;erPn.map(ir=>c.fA(ir,fn,Ms.extent)));return vn.length===0?void 0:{type:"Polygon",coordinates:[vn[0]]}}(xt,We);return{id:ct,isDefault:jt,connections:Rt,conflicts:zt,buildings:Ht,name:ws,zIndex:Ts,geometry:js}}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,jt){this.tileID=new c.bQ(We.tileID.overscaledZ,We.tileID.wrap,We.tileID.canonical.z,We.tileID.canonical.x,We.tileID.canonical.y),this.tileZoom=We.tileZoom,this.uid=We.uid,this.zoom=We.zoom,this.canonical=We.tileID.canonical,this.pixelRatio=We.pixelRatio,this.tileSize=We.tileSize,this.source=We.source,this.overscaling=this.tileID.overscaleFactor(),this.projection=We.projection,this.brightness=ct,this.worldview=jt}async parse(We,ct,jt){this.status="parsing";const Rt=new c.bQ(jt.tileID.overscaledZ,jt.tileID.wrap,jt.tileID.canonical.z,jt.tileID.canonical.x,jt.tileID.canonical.y),zt=[],Ht=ct.familiesBySource[jt.source],ws=new c.fG(Rt,jt.promoteId);ws.bucketLayerIDs=[],ws.is3DTile=!0;const Ts=await c.fH(We),js=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"),fn=new c.aj(this.zoom,{brightness:this.brightness,worldview:this.worldview});for(const gn in Ht)for(const vn of Ht[gn]){const Pn=vn[0];ws.bucketLayerIDs.push(vn.map(tr=>c.m(tr.id,tr.scope))),Pn.recalculate(fn,[]);const ir=c.fI(Ts,1/c.fJ(jt.tileID.canonical)),er=new c.fK(vn,ir,Rt,js,Ms,this.brightness,ws,this.worldview);zt.push(er),er.evaluate(Pn)}return this.status="done",{buckets:zt,featureIndex:ws,collisionBoxArray:null,glyphAtlasImage:null,lineAtlas:null,imageAtlas:null,brightness:null}}}class R{constructor({actor:We,layerIndex:ct,availableImages:jt,availableModels:Rt,brightness:zt,worldview:Ht}){this.actor=We,this.layerIndex=ct,this.availableImages=jt,this.availableModels=Rt,this.brightness=zt,this.loading={},this.loaded={},this.worldview=Ht}async loadTile(We){const ct=We.uid,jt=new AbortController,Rt=this.loading[ct]=new P(We,this.brightness,this.worldview);Rt.abort=()=>jt.abort();const zt=(ws,Ts)=>{const js=Rt.reloadCallback;js&&(delete Rt.reloadCallback,js(ws,Ts))};let Ht;try{Ht=(await c.d0(We.request,jt.signal)).data}catch(ws){if(delete this.loading[ct],Rt.status="done",this.loaded[ct]=Rt,jt.signal.aborted)return null;throw ws}if(delete this.loading[ct],!Ht||Ht.byteLength===0)return Rt.status="done",this.loaded[ct]=Rt,null;try{const ws=await Rt.parse(Ht,this.layerIndex,We);return this.loaded[ct]=Rt,zt(null,ws),ws}catch(ws){throw this.loaded[ct]=Rt,zt(ws),ws}}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((jt,Rt)=>{ct.reloadCallback=zt=>{zt?Rt(zt):jt()}}),this.loadTile(We)}abortTile(We){const ct=We.uid,jt=this.loading[ct];jt&&(jt.abort&&jt.abort(),delete this.loading[ct])}removeTile(We){const ct=this.loaded,jt=We.uid;ct&&ct[jt]&&delete ct[jt]}}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 jt of xt)ct+=`${D(jt)},`;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(jt){return typeof jt=="string"&&jt===We||(Array.isArray(jt)?jt.some(ct):!(!jt||typeof jt!="object")&&Object.values(jt).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,jt){this._options=jt;for(const zt of We)this._layerConfigs[zt.id]=zt,(this._layers[zt.id]=c.dM(zt,this.scope,null,this._options)).compileFilter(jt),this.keyCache[zt.id]&&delete this.keyCache[zt.id];for(const zt of ct)delete this.keyCache[zt],delete this._layerConfigs[zt],delete this._layers[zt];this.familiesBySource=Object.create(null);const Rt=function(zt,Ht){const ws=Object.create(null);for(let js=0;jsthis._layers[gn.id]),ws=Ht[0];if(ws.visibility==="none")continue;const Ts=ws.source||"";let js=this.familiesBySource[Ts];js||(js=this.familiesBySource[Ts]=Object.create(null));const Ms=ws.sourceLayer||"_geojsonTileLayer";let fn=js[Ms];fn||(fn=js[Ms]=[]),fn.push(Ht)}}}class V extends c.P{constructor(We,ct,jt,Rt,zt){super(We,ct),this.angle=Rt,this.z=jt,zt!==void 0&&(this.segment=zt)}clone(){return new V(this.x,this.y,this.z,this.angle,this.segment)}}function G(xt,We,ct,jt,Rt){if(We.segment===void 0)return!0;let zt=We,Ht=We.segment+1,ws=0;for(;ws>-ct/2;){if(Ht--,Ht<0)return!1;ws-=xt[Ht].dist(zt),zt=xt[Ht]}ws+=xt[Ht].dist(xt[Ht+1]),Ht++;const Ts=[];let js=0;for(;wsjt;)js-=Ts.shift().angleDelta;if(js>Rt)return!1;Ht++,ws+=Ms.dist(fn)}return!0}function Y(xt){let We=0;for(let ct=0;ctjs){const Pn=(js-Ts)/vn,ir=c.am(fn.x,gn.x,Pn),er=c.am(fn.y,gn.y,Pn),tr=new V(ir,er,0,gn.angleTo(fn),Ms);return!Ht||G(xt,tr,ws,Ht,We)?tr:void 0}Ts+=vn}}function ne(xt,We,ct,jt,Rt,zt,Ht,ws,Ts){const js=X(jt,zt,Ht),Ms=ae(jt,Rt),fn=Ms*Ht,gn=xt[0].x===0||xt[0].x===Ts||xt[0].y===0||xt[0].y===Ts;return We-fn=0&&qa=0&&et=0&&gn+js<=Ms){const Vt=new V(qa,et,0,vr,Pn);jt&&!G(xt,Vt,zt,jt,Rt)||vn.push(Vt)}}fn+=tr}return ws||vn.length||Ht||(vn=te(xt,fn/2,ct,jt,Rt,zt,Ht,!0,Ts)),vn}c.fL(V,"Anchor");class J{constructor(){this.scale=1,this.fontStack="",this.image=null}static forText(We,ct){const jt=new J;return jt.scale=We||1,jt.fontStack=ct,jt}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,jt,Rt=1){const zt=new ce;for(let Ht=0;Ht=0&&jt>=We&&ue[this.text.charCodeAt(jt)];jt--)ct--;this.text=this.text.substring(We,ct),this.sectionIndex=this.sectionIndex.slice(We,ct)}substring(We,ct){const jt=new ce;return jt.text=this.text.substring(We,ct),jt.sectionIndex=this.sectionIndex.slice(We,ct),jt.sections=this.sections,jt}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 jt=this.sections.length-1;for(let Rt=0;Rt=63743?null:++this.imageSectionID:(this.imageSectionID=57344,this.imageSectionID)}}function _e(xt,We){if(!xt.image)return!1;const ct=We.get(xt.image.toString());return!!ct&&ct.sdf}function he(xt,We,ct,jt,Rt,zt,Ht,ws,Ts,js,Ms,fn,gn,vn,Pn,ir=1,er=1){const tr=ce.fromFeature(xt,Rt,ir,er);fn===c.dt.vertical&&tr.verticalizePunctuation(gn);const vr=tr.toString();if(function(tn,sr){const nr=tn.sections.findIndex(Na=>_e(Na,sr));if(nr===-1)return;c.w(`SDF image ${tn.sections[nr].image.id.name} is not supported in text-field`);const Qr=tn.sections.map(Na=>_e(Na,sr));let na="";const $a=[];for(let Na=0;Na0&&ou>zo&&(zo=ou)}else{const dd=nr[Ad.fontStack];if(!dd)continue;dd[Zc]&&(Pf=dd[Zc]);const zl=sr[Ad.fontStack];if(!zl)continue;const Xi=zl.glyphs[Zc];if(!Xi)continue;if(oh=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;Pczt)&&(zt=Pn.x),(!vn||Pn.y>Ht)&&(Ht=Pn.y)}const Ts=Math.min(zt-jt,Ht-Rt);let js=Ts/2;const Ms=new c.fT([],Ae);if(Ts===0)return new c.P(jt,Rt);for(let vn=jt;vnfn.d||!fn.d)&&(fn=vn,ct&&console.log("found best %d after %d probes",Math.round(1e4*vn.d)/1e4,gn)),vn.max-fn.d<=We||(js=vn.h/2,Ms.push(new Ce(vn.p.x-js,vn.p.y-js,js,xt)),Ms.push(new Ce(vn.p.x+js,vn.p.y-js,js,xt)),Ms.push(new Ce(vn.p.x-js,vn.p.y+js,js,xt)),Ms.push(new Ce(vn.p.x+js,vn.p.y+js,js,xt)),gn+=4)}return ct&&(console.log(`num probes: ${gn}`),console.log(`best distance: ${fn.d}`)),fn.p}function Ae(xt,We){return We.max-xt.max}class Ce{constructor(We,ct,jt,Rt){this.p=new c.P(We,ct),this.h=jt,this.d=function(zt,Ht){let ws=!1,Ts=1/0;for(let js=0;jszt.y!=ir.y>zt.y&&zt.x<(ir.x-Pn.x)*(zt.y-Pn.y)/(ir.y-Pn.y)+Pn.x&&(ws=!ws),Ts=Math.min(Ts,c.fU(zt,Pn,ir))}}return(ws?1:-1)*Math.sqrt(Ts)}(this.p,Rt),this.max=this.d+this.h*Math.SQRT2}}const Ve=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 qe(xt){return!xt.imagePrimary.stretchX}function dt(xt){return!xt.imagePrimary.stretchY}function Xe(xt){return{width:xt.right-xt.left,height:xt.bottom-xt.top}}const at=Number.POSITIVE_INFINITY;function rt(xt,We,ct,jt,Rt,zt){const Ht=ze(xt)&&xt.collisionPadding?xt.collisionPadding:[0,0,0,0],ws={top:xt.top-Ht[1],bottom:xt.bottom+Ht[3],left:xt.left-Ht[0],right:xt.right+Ht[2],scaled:!1};return jt!==void 0&&function(Ts,js){Ts.top*=js,Ts.bottom*=js,Ts.left*=js,Ts.right*=js,Ts.scaled=!0}(ws,jt),zt&&(ws.left+=zt[0],ws.right+=zt[0],ws.top+=zt[1],ws.bottom+=zt[1]),ct&&function(Ts,js,Ms){if(!js)return;const fn=c.av(js),gn=new c.P(Ms?Ms[0]:0,Ms?Ms[1]:0),vn=new c.P(Ts.left,Ts.top),Pn=new c.P(Ts.right,Ts.top),ir=new c.P(Ts.left,Ts.bottom),er=new c.P(Ts.right,Ts.bottom);vn._rotateAround(fn,gn),Pn._rotateAround(fn,gn),ir._rotateAround(fn,gn),er._rotateAround(fn,gn),Ts.left=Math.min(vn.x,Pn.x,ir.x,er.x),Ts.right=Math.max(vn.x,Pn.x,ir.x,er.x),Ts.top=Math.min(vn.y,Pn.y,ir.y,er.y),Ts.bottom=Math.max(vn.y,Pn.y,ir.y,er.y)}(ws,ct,Rt),We?{top:Math.min(We.top,ws.top),bottom:Math.max(We.bottom,ws.bottom),left:Math.min(We.left,ws.left),right:Math.max(We.right,ws.right),scaled:We.scaled||ws.scaled}:ws}function Ke(xt,We,ct,jt,Rt,zt,Ht,ws=1,Ts,js,Ms,fn,gn,vn,Pn,ir,er){xt.createArrays(),xt.tilePixelRatio=c.a6/(512*xt.overscaling),xt.compareText={},xt.iconsNeedLinear=!1;const tr=xt.layers[0].layout,vr=xt.layers[0]._unevaluatedLayout._values,yr={};yr.scaleFactor=ws,yr.textSizeScaleRange=tr.get("text-size-scale-range"),yr.iconSizeScaleRange=tr.get("icon-size-scale-range");const[qa,et]=yr.textSizeScaleRange,[Vt,Es]=yr.iconSizeScaleRange;yr.textScaleFactor=c.b1(yr.scaleFactor,qa,et),yr.iconScaleFactor=c.b1(yr.scaleFactor,Vt,Es);const ln=vr["text-size"],tn=vr["icon-size"];if(xt.textSizeData.kind==="composite"){const{minZoom:La,maxZoom:to}=xt.textSizeData;yr.compositeTextSizes=[ln.possiblyEvaluate(new c.aj(La,{worldview:Ms}),zt),ln.possiblyEvaluate(new c.aj(to,{worldview:Ms}),zt)]}if(xt.iconSizeData.kind==="composite"){const{minZoom:La,maxZoom:to}=xt.iconSizeData;yr.compositeIconSizes=[tn.possiblyEvaluate(new c.aj(La,{worldview:Ms}),zt,fn),tn.possiblyEvaluate(new c.aj(to,{worldview:Ms}),zt,fn)]}yr.layoutTextSize=ln.possiblyEvaluate(new c.aj(Ht+1,{worldview:Ms}),zt),yr.layoutIconSize=tn.possiblyEvaluate(new c.aj(Ht+1,{worldview:Ms}),zt,fn),yr.textMaxSize=ln.possiblyEvaluate(new c.aj(18,{worldview:Ms}),zt);const sr=tr.get("symbol-placement"),nr=tr.get("text-rotation-alignment")==="map"&&sr!=="point",Qr=tr.get("text-size");let na=!1;const $a=[],Na=gn!=null&&gn!==0;for(const La of xt.features){if(Na&&La.properties&&ir&&ir(La.properties,gn))continue;let to=65535;if(xt.hdExt&&La.properties&&Object.hasOwn(La.properties,c.fV)){const pu=+La.properties[c.fV];if(!Number.isNaN(pu)){const Zc=xt.hdExt.resolveRoadElevation(La,pu);if(Zc==="defer")continue;to=Zc}}const xo=tr.get("text-font").evaluate(La,{},zt).join(","),oo=Qr.evaluate(La,{},zt)*yr.textScaleFactor,Lo=yr.layoutTextSize.evaluate(La,{},zt)*yr.textScaleFactor,Ul=yr.layoutIconSize.evaluate(La,{},zt,fn)*yr.iconScaleFactor,po={horizontal:{},vertical:void 0},nl=La.text;let Pl,Cd=[0,0];if(nl){const pu=nl.toString(),Zc=tr.get("text-letter-spacing").evaluate(La,{},zt)*c.dg,rd=tr.get("text-line-height").evaluate(La,{},zt)*c.dg,oh=c.fW(pu)?Zc:0,Pf=tr.get("text-anchor").evaluate(La,{},zt),Bd=tr.get("text-variable-anchor");if(!Bd){const dd=tr.get("text-radial-offset").evaluate(La,{},zt);if(dd)Cd=c.dv(Pf,[dd*c.dg,at]);else{const zl=tr.get("text-offset").evaluate(La,{},zt);Cd=[zl[0]*c.dg,zl[1]*c.dg]}}let ad=nr?"center":tr.get("text-justify").evaluate(La,{},zt);const Ph=sr==="point",Hu=Ph?tr.get("text-max-width").evaluate(La,{},zt)*c.dg:1/0,$d=dd=>{xt.allowVerticalPlacement&&c.fX(pu)&&(po.vertical=he(nl,We,ct,Rt,xo,Hu,rd,Pf,dd,oh,Cd,c.dt.vertical,!0,Lo,oo,Ts,yr.textScaleFactor))};if(!nr&&Bd){const dd=ad==="auto"?Bd.map(Xi=>c.dw(Xi)):[ad];let zl=!1;for(let Xi=0;Xi0?tr/Ts:1;vr&&(xt.iconBBox=rt(vr,xt.iconBBox,er,et!==1?et:void 0)),yr&&(xt.iconVerticalBBox=rt(yr,xt.iconVerticalBBox,er+90,et!==1?et:void 0))}function gt(xt,We,ct,jt,Rt,zt,Ht,ws){let Ts=null;const js=We.getAppearanceValueAndResolveTokens(ct,"icon-image",jt,Rt,ws);if(js){const Ms=xt.getResolvedImageFromTokens(js),fn=ct.hasLayoutProperty("icon-size")?ct.getUnevaluatedLayoutProperty("icon-size"):We._unevaluatedLayout._values["icon-size"],gn=c.g5(xt.zoom,fn,xt.worldview,ws),vn=c.fY(Ms,gn,fn,Rt,xt.zoom,jt,xt.pixelRatio,Ht,xt.worldview,ws);Ts=zt.get(vn.iconPrimary.toString())}return Ts}function ss(xt,We,ct,jt,Rt,zt,Ht,ws,Ts,js){const{appearanceTextOffset:Ms,appearanceTextRotate:fn,appearanceTextSize:gn}=c.g3(ct,We,jt,Rt,zt,Ht,ws),vn=gn/ws,Pn=[(Ms[0]-zt[0])*vn,(Ms[1]-zt[1])*vn],ir=Pn[0]!==0||Pn[1]!==0;Ts&&(xt.textBBox=rt(Ts,xt.textBBox,fn,vn,Ms,ir?Pn:void 0)),js&&(xt.textVerticalBBox=rt(js,xt.textVerticalBBox,fn+90,vn,Ms,ir?Pn:void 0))}function Yt(xt,We,ct,jt,Rt,zt,Ht,ws){if(!xt||!xt.usvg)return;const Ts=Xe(ct),js=Xe(jt),Ms=Rt!=="both"&&Rt!=="width"||!qe(ct)?1:js.width/Ts.width,fn=Rt!=="both"&&Rt!=="height"||!dt(ct)?1:js.height/Ts.height;We.scaleSelf(Ms,fn);const gn=We.toString();zt.set(gn,We),Ht.set(gn,xt);const{imagePosition:vn}=c.g0(gn,xt,c.g1);ws.set(gn,vn)}function ts(xt,We,ct){if(!We)return;const jt=ct.get(xt.toString()),Rt=ct.get(We.toString());jt&&Rt&&(jt.paddedRect.w===Rt.paddedRect.w&&jt.paddedRect.h===Rt.paddedRect.h||c.w(`Mismatch in icon variant sizes: ${xt.toString()} and ${We.toString()}`),jt.usvg!==Rt.usvg&&c.w(`Mismatch in icon variant image types: ${xt.id} and ${We.id}`))}function ys(xt,We,ct,jt,Rt,zt,Ht,ws,Ts,js){xt.iconAtlasPositions=js.iconPositions;const{featureData:Ms,sizes:fn,textAlongLine:gn,symbolPlacement:vn,coveragePolygons:Pn,coverageTileZoom:ir,symbolAnchorInFrcCoverage:er}=We,tr=We.hasAnySecondaryIcon||xt.hasAnySecondaryIcon;for(const vr of Ms){const{shapedIcon:yr,verticallyShapedIcon:qa,feature:et,shapedTextOrientations:Vt,shapedText:Es,layoutTextSize:ln,textOffset:tn,isSDFIcon:sr,iconPrimary:nr,iconSecondary:Qr,iconTextFit:na,iconOffset:$a,iconCollisionBounds:Na,iconVerticalCollisionBounds:La,textCollisionBounds:to,elevationFeatureIndex:xo}=vr;Bt(yr,js.iconPositions,nr,Qr),Bt(qa,js.iconPositions,nr,Qr),Ft(Vt,js.iconPositions),ts(nr,Qr,js.iconPositions),(Es||yr)&&Ks(xt,et,Vt,yr,qa,Ts,fn,ln,0,tn,sr,jt,Rt,Ht,ws,tr,na,$a,gn,vn,Na,La,to,0,0,Pn,ir,er,xo)}ct&&xt.generateCollisionDebugBuffers(zt,xt.collisionBoxArray,fn.textScaleFactor),xt.text.uboBinder&&xt.text.uboBinder.finalize(),xt.icon.uboBinder&&xt.icon.uboBinder.finalize()}function Bt(xt,We,ct,jt){if(!xt)return;const Rt=We.get(ct.toString());if(Rt&&(xt.imagePrimary=Rt),jt){const zt=We.get(jt.toString());xt.imageSecondary=zt}}function Ft(xt,We){for(const ct in xt.horizontal)as(xt.horizontal[ct],We);as(xt.vertical,We)}function as(xt,We){if(xt){for(const ct of xt.positionedLines)for(const jt of ct.positionedGlyphs)if(jt.image!==null){const Rt=jt.image.toString();jt.rect=We.get(Rt).paddedRect}}}function kt(xt,We,ct,jt,Rt,zt,Ht,ws,Ts){const js=gs(zt.horizontal)||zt.vertical,Ms=ct.get("icon-text-fit-padding").evaluate(jt,{},Rt);let fn,gn=We;return We&&Ts!=="none"&&(xt.allowVerticalPlacement&&zt.vertical&&(fn=c.f$(We,zt.vertical,Ts,Ms,ws,Ht)),js&&(gn=c.f$(We,js,Ts,Ms,ws,Ht))),{defaultShapedIcon:gn,verticallyShapedIcon:fn}}function Ks(xt,We,ct,jt,Rt,zt,Ht,ws,Ts,js,Ms,fn,gn,vn,Pn,ir,er,tr,vr,yr,qa,et,Vt,Es,ln,tn,sr,nr,Qr=65535){let na=Ht.textMaxSize.evaluate(We,{},gn);na===void 0?na=ws*Ht.textScaleFactor:na*=Ht.textScaleFactor;const $a=xt.layers[0].layout,Na=c.dg,La=c.f_(ws,Ht.textScaleFactor),to=gs(ct.horizontal)||ct.vertical,xo=xt.hasAnyAppearanceLayoutProperty(["text-size","text-offset","text-rotate"]),oo=xt.getAppearanceFeatureData(We.index);(er!=="none"||xo)&&oo&&(oo.textShaping=to,oo.iconTextFitPadding=$a.get("icon-text-fit-padding").evaluate(We,{},gn),oo.fontScale=La,oo.textScaleFactor=Ht.textScaleFactor);const Lo=vn.name==="globe",Ul=xt.tilePixelRatio*na/Na,po=(Cn=xt.overscaling,xt.zoom>18&&Cn>2&&(Cn>>=1),Math.max(c.a6/(512*Cn),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"&&yr!=="point",qt=po/2;var Cn;xt.hasAnyIconTextFit===!1&&er!=="none"&&(xt.hasAnyIconTextFit=!0);const rr=(ra,Yr,Aa)=>{if(Yr.x<0||Yr.x>=c.a6||Yr.y<0||Yr.y>=c.a6||tn&&tn.length>0&&We.properties&&nr&&nr(tn,We.properties,Yr,gn,sr))return;let gi=null;if(Lo){const{x:Ia,y:el,z:zo}=vn.projectTilePoint(Yr.x,Yr.y,Aa);gi={anchor:new V(Ia,el,zo,0,void 0),up:vn.upVector(Aa,Yr.x,Yr.y)}}(function(Ia,el,zo,Pc,Tu,iu,dm,Ad,pu,Zc,rd,oh,Pf,Bd,ad,Ph,Hu,$d,dd,zl,Xi,Ed,ou,Xc,vd,Ep,Fv,Lx,ya,Yy,Ci,Xg){const Om=Ia.addToLineVertexArray(el,Pc);let Rx,Gu,kc,Ro,kl,gu,fa,Ao=0,pl=0,Qc=0,ag=0,Wo=-1,$0=-1;const xh={};let df=c.dF("");const Ud=zo?zo.anchor:el,xu=Lx!=="none";let D_=0,Ov=0;if(pu._unevaluatedLayout.getValue("text-radial-offset")===void 0){const zm=pu.layout.get("text-offset").evaluate(Xi,{},vd);D_=zm[0]*c.dg,Ov=zm[1]*c.dg}else D_=pu.layout.get("text-radial-offset").evaluate(Xi,{},vd)*c.dg,Ov=at;if(Ia.allowVerticalPlacement&&Tu.vertical){const zm=Tu.vertical;if(ad)gu=Is(zm),Ad&&(fa=Is(Ad));else{const yu=pu.layout.get("text-rotate").evaluate(Xi,{},vd)+90;kc=ks(Zc,Ud,el,rd,oh,Pf,zm,Bd,yu,Ph,Xg),Ad&&(Ro=ks(Zc,Ud,el,rd,oh,Pf,Ad,$d,yu,null,Ci))}}if(iu){const zm=pu.layout.get("icon-rotate").evaluate(Xi,{},vd),yu=c.g6(iu,zm,ou,xu,Ed.iconScaleFactor),Ih=Ad?c.g6(Ad,zm,ou,xu,Ed.iconScaleFactor):void 0;Gu=ks(Zc,Ud,el,rd,oh,Pf,iu,$d,zm,null,Yy);const yh=function(Qg,ch,Ic,Jg,I1,L1,R1,Yw,Zw){const F_=Qg.layers[0],Pk=F_.appearances;let Ib=ch.length;if(Ic&&(Ib=Math.max(Ib,Ic.length)),Pk.length===0)return Ib;const[zv,k3]=Jg.get("icon-size-scale-range"),V2=c.b1(1,zv,k3);for(const rp of Pk)if(rp.hasLayoutProperty("icon-image")){const Ik=gt(Qg,F_,rp,I1,L1,R1,V2,Zw);Ik&&(Ib=Math.max(Ib,c.g8(Ik)))}return Ib}(Ia,yu,Ih,pu.layout,Xi,vd,Ia.iconAtlasPositions,0,Xc);Ao=4*yh;const Ui=pu.layout.get("icon-size").evaluate(Xi,{},vd,Xc),um=Ed.compositeIconSizes?Ed.compositeIconSizes[0].evaluate(Xi,{},vd,Xc):0,lh=Ed.compositeIconSizes?Ed.compositeIconSizes[1].evaluate(Xi,{},vd,Xc):0,np=c.g7(Ia.layerIds[0],Ia.iconSizeData,Ui,iu.imagePrimary.usvg?1:Ed.iconScaleFactor,um,lh);Ia.addSymbols(Ia.icon,yu,np,zl,dd,Xi,void 0,zo,el,Om.lineStartIndex,Om.lineLength,-1,Xc,vd,Ep,Fv,Ia.symbolInstances.length,yh),Wo=Ia.icon.placedSymbolArray.length-1,Ih&&(pl=4*yh,Ia.addSymbols(Ia.icon,Ih,np,zl,dd,Xi,c.dt.vertical,zo,el,Om.lineStartIndex,Om.lineLength,-1,Xc,vd,Ep,Fv,Ia.symbolInstances.length,yh),$0=Ia.icon.placedSymbolArray.length-1)}for(const zm in Tu.horizontal){const yu=zm,Ih=Tu.horizontal[yu];Rx||(df=c.dF(Ih.text),ad?kl=Is(Ih):Rx=ks(Zc,Ud,el,rd,oh,Pf,Ih,Bd,pu.layout.get("text-rotate").evaluate(Xi,{},vd),Ph,Xg));const yh=Ih.positionedLines.length===1;if(Qc+=wt(Ia,zo,el,Ih,dm,pu,ad,Xi,Ph,Om,Tu.vertical?c.dt.horizontal:c.dt.horizontalOnly,yh?Ve(Tu.horizontal):[yu],xh,Wo,Ed,Xc,vd,Ia.symbolInstances.length,Ep),yh)break}Tu.vertical&&(ag+=wt(Ia,zo,el,Tu.vertical,dm,pu,ad,Xi,Ph,Om,c.dt.vertical,["vertical"],xh,$0,Ed,Xc,vd,Ia.symbolInstances.length,Ep));let Dx=-1;const Pb=(zm,yu)=>zm?Math.max(zm,yu):yu;Dx=Pb(kl,Dx),Dx=Pb(gu,Dx),Dx=Pb(fa,Dx);const Kw=Dx>-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,Ud.x,Ud.y,Ud.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,$0,df,Rx!==void 0?Rx:Ia.collisionBoxArray.length,Rx!==void 0?Rx+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,ag,Ao,pl,Kw,0,D_,Ov,Dx,0,xu?1:0,ya)})(xt,Yr,gi,ra,ct,jt,zt,Rt,xt.layers[0],xt.collisionBoxArray,We.index,We.sourceLayerIndex,xt.index,nl,vr,js,0,Pl,au,tr,We,Ht,Ms,fn,gn,Pn,ir,er,Qr,qa,et,Vt)};if(yr==="line")for(const ra of c.dc(We.geometry,0,0,c.a6,c.a6)){const Yr=ne(ra,po,Cd,ct.vertical||to,jt,Na,Ul,xt.overscaling,c.a6);for(const Aa of Yr)to&&Xs(xt,to.text,qt,Aa)||rr(ra,Aa,gn)}else if(yr==="line-center"){for(const ra of We.geometry)if(ra.length>1){const Yr=le(ra,Cd,ct.vertical||to,jt,Na,Ul);Yr&&rr(ra,Yr,gn)}}else if(We.type==="Polygon")for(const ra of c.g4(We.geometry,0)){const Yr=Ne(ra,16);rr(ra[0],new V(Yr.x,Yr.y,0,0,void 0),gn)}else if(We.type==="LineString")for(const ra of We.geometry)rr(ra,new V(ra[0].x,ra[0].y,0,0,void 0),gn);else if(We.type==="Point")for(const ra of We.geometry)for(const Yr of ra)rr([Yr],new V(Yr.x,Yr.y,0,0,void 0),gn)}function wt(xt,We,ct,jt,Rt,zt,Ht,ws,Ts,js,Ms,fn,gn,vn,Pn,ir,er,tr,vr){const yr=c.g9(ct,jt,Ts,zt,Ht,ws,Rt,xt.allowVerticalPlacement,void 0,Pn.textScaleFactor),qa=zt.layout.get("text-size").evaluate(ws,{},er),et=Pn.compositeTextSizes?Pn.compositeTextSizes[0].evaluate(ws,{},er):0,Vt=Pn.compositeTextSizes?Pn.compositeTextSizes[1].evaluate(ws,{},er):0,Es=c.g7(xt.layerIds[0],xt.textSizeData,qa,Pn.textScaleFactor,et,Vt);xt.addSymbols(xt.text,yr,Es,Ts,Ht,ws,Ms,We,ct,js.lineStartIndex,js.lineLength,vn,ir,er,vr,!1,tr,yr.length);for(const ln of fn)gn[ln]=xt.text.placedSymbolArray.length-1;return 4*yr.length}function gs(xt){for(const We in xt)return xt[We];return null}function ks(xt,We,ct,jt,Rt,zt,Ht,ws,Ts,js,Ms){let fn,gn,vn,Pn;if(fn=Ms?Ms.top:Ht.top,gn=Ms?Ms.bottom:Ht.bottom,vn=Ms?Ms.left:Ht.left,Pn=Ms?Ms.right:Ht.right,ze(Ht)&&Ht.collisionPadding){const ir=Ht.collisionPadding;vn-=ir[0],fn-=ir[1],Pn+=ir[2],gn+=ir[3]}if(Ts){const ir=new c.P(vn,fn),er=new c.P(Pn,fn),tr=new c.P(vn,gn),vr=new c.P(Pn,gn),yr=c.av(Ts);let qa=new c.P(0,0);js&&(qa=new c.P(js[0],js[1])),ir._rotateAround(yr,qa),er._rotateAround(yr,qa),tr._rotateAround(yr,qa),vr._rotateAround(yr,qa),vn=Math.min(ir.x,er.x,tr.x,vr.x),Pn=Math.max(ir.x,er.x,tr.x,vr.x),fn=Math.min(ir.y,er.y,tr.y,vr.y),gn=Math.max(ir.y,er.y,tr.y,vr.y)}return xt.emplaceBack(We.x,We.y,We.z,ct.x,ct.y,vn,fn,Pn,gn,ws,jt,Rt,zt),xt.length-1}function Is(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 Xs(xt,We,ct,jt){const Rt=xt.compareText;if(We in Rt){const zt=Rt[We];for(let Ht=zt.length-1;Ht>=0;Ht--)if(jt.dist(zt[Ht])=We.maxzoom||We.visibility==="none")}parse(We,ct,jt,Rt,zt,Ht){this._parseAfterHD(We,ct,jt,Rt,zt,Ht)}_parseAfterHD(We,ct,jt,Rt,zt,Ht){let ws;if(this.status="parsing",this.data=We,this.renderSourceType===c.bS.HdRoadCoverage){const er=We.layers[c.bV];ws=er&&m?m(er):[]}this.collisionBoxArray=new c.bu;const Ts=new c.gc(Object.keys(We.layers).sort()),js=new c.fG(this.tileID,this.promoteId);js.bucketLayerIDs=[];const Ms={},fn=new c.gd(256,256),gn={featureIndex:js,iconDependencies:new Map,patternDependencies:new Map,glyphDependencies:{},lineAtlas:fn,availableImages:jt,brightness:this.brightness,scaleFactor:this.scaleFactor,showElevationIdDebug:this.showElevationIdDebug,elevationFeatures:void 0,elevationParams:this.elevation,crossSourceElevationEnabled:this.crossSourceElevationEnabled,terrainEnabled:this.terrainEnabled,activeFloors:void 0};this.indoor&&g&&(gn.activeFloors=g(We,this.indoor,zt,this.canonical));const vn=[],Pn=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 er in Pn)if(c.ge&&c.ge(this.frcCoverage.sourceLayers,this.source,er)){this.deferRoadStructure=!0;break}}for(const er in Pn){const tr=We.layers[er];if(!tr)continue;let vr=!1,yr=!1,qa=!1,et=!1;for(const nr of Pn[er])nr[0].type==="symbol"?vr=!0:nr[0].type==="fill-extrusion"?yr=!0:qa=!0,nr[0].is3D()&&nr[0].type!=="model"&&(et=!0);if(this.extraShadowCaster&&!et||this.renderSourceType===c.bS.Symbol&&!vr||this.renderSourceType===c.bS.FillExtrusion&&!yr||(this.renderSourceType===c.bS.Other||this.renderSourceType===c.bS.HdRoadCoverage)&&!qa)continue;const Vt=this.frcCoverage!=null&&!!c.ge&&c.ge(this.frcCoverage.sourceLayers,this.source,er);if(this.deferRoadStructure&&Vt)continue;tr.version===1&&c.w(`Vector tile source "${this.source}" layer "${er}" does not use vector tile spec v2 and therefore may have some rendering errors.`);const Es=Ts.encode(er),ln=[],tn=this.localizableLayerIds&&this.localizableLayerIds.has(er);let sr=!1;for(let nr=0,Qr=0;nrc.m(Na.id,Na.scope)));const $a=()=>{hr(nr,this.zoom,gn.brightness,jt,this.worldview,gn.activeFloors);const Na=Ms[Qr.id]=Qr.createBucket({index:na,layers:nr,zoom:this.zoom,lut:this.lut,canonical:this.canonical,pixelRatio:this.pixelRatio,overscaling:this.overscaling,collisionBoxArray:this.collisionBoxArray,sourceLayerIndex:Es,sourceLayerName:er,sourceID:this.source,projection:this.projection.spec,tessellationStep:this.tessellationStep,styleDefinedModelURLs:Rt,worldview:this.worldview,localizable:tn,availableImages:jt,maxUniformBufferBindings:this.maxUniformBufferBindings,maxUniformBlockSizeDwords:this.maxUniformBlockSizeDwords});E&&E(Na,this.frcCoverage?this.frcCoverage.sourceLayers:null),Na.populate(ln,gn,this.tileID.canonical,this.tileTransform)};Qr.mayUse("HD")||Qr.mayUse("Standard")?vn.push(Qr.prepare().then(()=>$a())):$a()}}const ir=()=>{fn.trim();const er=!(!gn.elevationFeatures||!gn.elevationFeatures.some(Qr=>Qr.heightRange.min<0));let tr,vr,yr,qa,et,Vt,Es,ln=gn.elevationFeatures;this.crossSourceElevationEnabled&&u&&(ln=ln||u(We,this.canonical)||[]);const tn={type:"maybePrepare",renderSourceType:this.renderSourceType,zoom:this.zoom},sr=()=>{if(tr)return this.status="done",Ht(tr);if(this.extraShadowCaster){this.status="done";const Qr=Object.values(Ms).filter(na=>!na.isEmpty());Ht(null,{buckets:Qr,containsHdExt:yn(Qr),containsStandardExt:Js(Qr),featureIndex:js,collisionBoxArray:null,hasTunnelGeometry:er,glyphAtlasImage:null,lineAtlas:null,imageAtlas:null,brightness:gn.brightness,hasDeferredElevationFeatures:!!I&&I(Ms),parsedElevationFeatures:ln,glyphMap:null,iconMap:null,glyphPositions:null})}else if(vr&&yr&&qa&&Es){const na=new Ss(vr),$a=new Map;for(const[La,to]of yr.entries()){const{imagePosition:xo}=c.g0(La,to,c.g1);$a.set(La,xo)}const Na={};for(const La in Ms){const to=Ms[La];if(to instanceof c.bv){hr(to.layers,this.zoom,gn.brightness,jt,this.worldview,gn.activeFloors);const xo=Ut(this.frcCoverage,this.source,to.layers[0].sourceLayer);Na[La]=Ke(to,vr,na.positions,yr,$a,this.tileID.canonical,this.tileZoom,this.scaleFactor,this.pixelRatio,et,this.worldview,jt,xo.frcMask,xo.polygons,xo.tileZoom,c.gf||null,f||null)}}et.size||Vt.size?this.rasterizeTask=zt.sendCancelable("rasterizeImages",{scope:this.scope,iconTasks:et,patternTasks:Vt},{},(La,to)=>{if(!La)for(const[xo,oo]of to.entries())yr.has(xo)&&yr.set(xo,Object.assign(yr.get(xo),{data:oo})),qa.has(xo)&&qa.set(xo,Object.assign(qa.get(xo),{data:oo}));nr(Na,na,void 0,Es)}):nr(Na,na,void 0,Es)}},nr=(Qr,na,$a,Na)=>{const La=yr.size>0||qa.size>0,to=Object.keys(Qr).length>0;if(!La&&!to){this.status="done";const oo=Object.values(Ms).filter(Lo=>!Lo.isEmpty());return void Ht(null,{buckets:oo,containsHdExt:yn(oo),containsStandardExt:Js(oo),featureIndex:js,collisionBoxArray:this.collisionBoxArray,hasTunnelGeometry:er,glyphAtlasImage:na.image,lineAtlas:fn,imageAtlas:null,brightness:gn.brightness,hasDeferredRoadStructure:this.deferRoadStructure,frcCoveragePolygons:ws,hasDeferredElevationFeatures:!!I&&I(Ms),parsedElevationFeatures:ln})}const xo=(oo,Lo)=>{for(const po in Ms){const nl=Ms[po];if(po in Qr)ys(nl,Qr[po],this.showCollisionBoxes,jt,this.tileID.canonical,this.tileZoom,this.projection,this.brightness,yr,Lo);else if(nl.hasPattern&&(nl instanceof c.bA||nl instanceof c.bB||nl instanceof c.aD)){hr(nl.layers,this.zoom,gn.brightness,jt,this.worldview,gn.activeFloors);const Pl=Object.fromEntries(Lo.patternPositions);nl.addFeatures(gn,this.tileID.canonical,Pl,jt,this.tileTransform,this.brightness)}}this.status="done";const Ul=Object.values(Ms).filter(po=>!po.isEmpty());Ht(null,{buckets:Ul,containsHdExt:yn(Ul),containsStandardExt:Js(Ul),featureIndex:js,collisionBoxArray:this.collisionBoxArray,hasTunnelGeometry:er,glyphAtlasImage:na.image,lineAtlas:fn,imageAtlas:oo,brightness:gn.brightness,hasDeferredRoadStructure:this.deferRoadStructure,frcCoveragePolygons:ws,hasDeferredElevationFeatures:!!I&&I(Ms),parsedElevationFeatures:ln})};if(La){const oo=new Map,Lo=c.gh(yr,oo),Ul=c.gh(qa,oo),po=new c.gi(Lo,Ul,Na,this.lut,this.scope,oo);zt.send("checkAtlasCache",{descriptor:po,scope:this.scope}).then(nl=>{let Pl,Cd;if(nl)Pl=new c.gj(nl.sourceHash),Cd=nl;else{const au=new c.gk(yr,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(yr,qa,this.lut,Na,this.scope);xo(Pl,Pl)})}else xo(null,{iconPositions:new Map,patternPositions:new Map})};if(!this.extraShadowCaster){const Qr=c.gg(gn.glyphDependencies,Na=>Object.keys(Na).map(Number));Object.keys(Qr).length?zt.send("getGlyphs",{uid:this.uid,stacks:Qr},{metadata:tn}).then(Na=>{tr||(vr=Na,sr())}).catch(Na=>{tr||(tr=Na,sr())}):vr={},Es=new Map;const na=Array.from(gn.iconDependencies.keys()).map(Na=>c.I.parse(Na)),$a=Array.from(gn.patternDependencies.keys()).map(Na=>c.I.parse(Na));na.length||$a.length?zt.send("getImages",{icons:na,patterns:$a,source:this.source,scope:this.scope,tileID:this.tileID},{metadata:tn}).then(Na=>{if(!tr){yr=new Map,qa=new Map,et=this.updateImageMapAndGetImageTaskQueue(yr,Na.images,gn.iconDependencies),Vt=this.updateImageMapAndGetImageTaskQueue(qa,Na.images,gn.patternDependencies);for(const[La,to]of Na.versions.entries())Es.set(La,to);sr()}}).catch(Na=>{tr||(tr=Na,sr())}):(yr=new Map,qa=new Map,et=new Map,Vt=new Map)}h&&h({buckets:Ms,data:We,sourceLayerCoder:Ts,canonical:this.tileID.canonical,options:gn}),sr()};vn.length>0?Promise.allSettled(vn).then(ir).catch(Ht):ir()}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,jt){const Rt=new Map;for(const zt of ct.keys()){const Ht=jt.get(zt)||[];for(const ws of Ht){const Ts=ws.toString(),js=ct.get(ws.id.toString());js.usvg?Rt.has(Ts)||(Rt.set(Ts,ws),We.set(Ts,{...js})):We.set(Ts,js)}}return Rt}cancelRasterize(){this.rasterizeTask&&this.rasterizeTask.abort()}}function hr(xt,We,ct,jt,Rt,zt){const Ht=new c.aj(We,{brightness:ct,worldview:Rt,activeFloors:zt});for(const ws of xt)ws.recalculate(Ht,jt)}class Rs extends c.E{constructor({actor:We,layerIndex:ct,availableImages:jt,availableModels:Rt,isSpriteLoaded:zt,tileProvider:Ht,brightness:ws,maxUniformBufferBindings:Ts,maxUniformBlockSizeDwords:js}){super(),this.actor=We,this.layerIndex=ct,this.availableImages=jt,this.availableModels=Rt,this.loadVectorData=c.cH,this.tileProvider=Ht,this.loading={},this.loaded={},this.deduped=new c.cC(We.scheduler),this.isSpriteLoaded=zt,this.scheduler=We.scheduler,this.brightness=ws,this.maxUniformBufferBindings=Ts,this.maxUniformBlockSizeDwords=js}loadTileData(We,ct){if(!this.tileProvider)return this.loadVectorData(We,ct);const jt=new AbortController;return this.loadTileWithProvider(this.tileProvider,We,jt,ct),()=>jt.abort()}async loadTileWithProvider(We,ct,jt,Rt){const{z:zt,x:Ht,y:ws}=ct.tileID.canonical;try{const Ts=await We.loadTile({z:zt,x:Ht,y:ws},{request:ct.request,signal:jt.signal});if(jt.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 js=new Headers;Ts.expires&&js.set("expires",Ts.expires),Ts.cacheControl&&js.set("cache-control",Ts.cacheControl),Rt(null,{rawData:Ts.data,headers:js})}catch(Ts){if(jt.signal.aborted)return;Rt(Ts instanceof Error?Ts:new Error(String(Ts)))}}_fetchTileData(We,ct){return new Promise((jt,Rt)=>{We.abort=this.loadTileData(ct,(zt,Ht)=>{zt?Rt(zt):jt(Ht)})})}async _parse(We,ct){const jt=!this.isSpriteLoaded;return jt&&await this.once("isSpriteLoaded"),new Promise((Rt,zt)=>{const Ht=()=>We.parse(We.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,(ws,Ts)=>{ws?zt(ws):Rt(Ts)});jt&&this.scheduler?this.scheduler.add(Ht,{type:"parseTile",renderSourceType:ct.renderSourceType,zoom:ct.tileZoom}):Ht()})}async loadTile(We){const ct=We.uid,jt=We&&We.request,Rt=jt&&jt.collectResourceTiming,zt=this.loading[ct]=new hn(We);zt.maxUniformBufferBindings=this.maxUniformBufferBindings,zt.maxUniformBlockSizeDwords=this.maxUniformBlockSizeDwords;const Ht=(Pn,ir)=>{const er=zt.reloadCallback;er&&(delete zt.reloadCallback,Pn||!ir?er(Pn,null):zt.parse(zt.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,er))};let ws,Ts;try{ws=await this._fetchTileData(zt,We)}catch(Pn){Ts=Pn}const js=!this.loading[ct];if(delete this.loading[ct],zt.cancelRasterize(),Ts||js||!ws){if(zt.status="done",js||(this.loaded[ct]=zt),Ts)throw Ts;return null}const Ms=ws.rawData;let fn;zt.vectorTile=ws.vectorTile||new c.gl(new c.c$(Ms)),this.loaded=this.loaded||{},this.loaded[ct]=zt;try{fn=await this._parse(zt,We)}catch(Pn){throw Ht(Pn),Pn}if(!fn)return Ht(null,null),null;const gn={};if(Rt){const Pn=d(jt);Pn.length>0&&(gn.resourceTiming=JSON.parse(JSON.stringify(Pn)))}const vn={rawTileData:Ms.slice(0),headers:ws.headers,...fn,...gn};return Ht(null,fn),vn}async reloadTile(We){const ct=this.loaded,jt=We.uid;if(ct&&ct[jt])return new Promise((Rt,zt)=>{const Ht=ct[jt];Ht.updateParameters(We);const ws=(Ts,js)=>{const Ms=Ht.reloadCallback;Ms&&(delete Ht.reloadCallback,Ht.parse(Ht.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,Ms)),Ts?zt(Ts):Rt(js)};Ht.status==="parsing"?Ht.reloadCallback=ws:Ht.status==="done"?Ht.vectorTile?Ht.parse(Ht.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,ws):ws():Rt(void 0)})}abortTile(We){const ct=We.uid,jt=this.loading[ct];jt&&(jt.abort&&jt.abort(),delete this.loading[ct])}removeTile(We){const ct=this.loaded,jt=We.uid;ct&&ct[jt]&&delete ct[jt]}}class jr{constructor(We){this.tileProvider=We.tileProvider,this.loading={}}async loadTile(We){const ct=We.uid,jt=new AbortController;if(this.loading[ct]={cancel:()=>jt.abort()},this.tileProvider)return this.loadTileWithProvider(this.tileProvider,ct,We,jt);try{const{data:Rt,headers:zt}=await c.d0(We.request,jt.signal);if(!Rt)return null;const Ht=await this.decodeTile(ct,Rt,We.encoding);return Ht.headers=zt,Ht}catch(Rt){if(jt.signal.aborted)return null;throw Rt}finally{delete this.loading[ct]}}async decodeTile(We,ct,jt){const Rt=ct instanceof ImageBitmap?ct:await createImageBitmap(new Blob([new Uint8Array(ct)],{type:"image/png"})),zt=1-(Rt.width-c.gm(Rt.width))/2,Ht=zt<1,ws=this.getImageData(Rt,zt);return Rt.close(),{dem:new c.gn(We,ws,jt,Ht),borderReady:Ht}}async loadTileWithProvider(We,ct,jt,Rt){const{z:zt,x:Ht,y:ws}=jt.tileID.canonical;try{const Ts=await We.loadTile({z:zt,x:Ht,y:ws},{request:jt.request,signal:Rt.signal});if(Rt.signal.aborted)return null;if(Ts==null){const fn=new Error("Tile not found");throw fn.status=404,fn}if(Ts.data==null)return null;const js=await this.decodeTile(ct,Ts.data,jt.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),js.headers=Ms,js}catch(Ts){if(Rt.signal.aborted)return null;throw Ts}finally{delete this.loading[ct]}}async reloadTile(We){}abortTile(We){const ct=We.uid,jt=this.loading[ct];jt&&(jt.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 jt=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),jt}}const kr=c.go.prototype.toGeoJSON;class $n{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 jt=0;jt(zt-bn)/Rt&&jt>(Ht-bn)/Rt}function Or(xt){const{id:We,geometry:ct,properties:jt}=xt;if(ct.type==="GeometryCollection")throw new Error("GeometryCollection not supported in dynamic mode.");const{type:Rt,coordinates:zt}=ct,Ht={id:We,type:1,geometry:[],tags:jt,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0},ws=Ht.geometry;if(Rt==="Point")la(zt,ws,Ht);else if(Rt==="MultiPoint")for(const Ts of zt)la(Ts,ws,Ht);else if(Rt==="LineString")Ht.type=2,Qn(zt,ws,Ht);else if(Rt==="MultiLineString")Ht.type=2,Cr(zt,ws,Ht);else if(Rt==="Polygon")Ht.type=3,Cr(zt,ws,Ht,!0);else{if(Rt!=="MultiPolygon")throw new Error("Input data is not a valid GeoJSON object.");Ht.type=3;for(const Ts of zt)Cr(Ts,ws,Ht,!0)}return Ht}function la([xt,We],ct,jt){const Rt=c.a7(xt);let zt=c.a8(We);zt=zt<0?0:zt>1?1:zt,ct.push(Rt,zt),jt.minX=Math.min(jt.minX,Rt),jt.minY=Math.min(jt.minY,zt),jt.maxX=Math.max(jt.maxX,Rt),jt.maxY=Math.max(jt.maxY,zt)}function Qn(xt,We,ct,jt=!1,Rt=!1){const zt=[];for(const Ht of xt)la(Ht,zt,ct);We.push(zt),jt&&function(Ht,ws){let Ts=0;for(let js=0,Ms=Ht.length,fn=Ms-2;js0===ws)for(let js=0,Ms=Ht.length;js=Ht&&fn>=Ht||(js>=Ht?(Ms+=Math.round(Pn*((Ht-js)/vn)),js=Ht):fn>=Ht&&(gn=Ms+Math.round(Pn*((Ht-js)/vn)),fn=Ht),Ms>=Ht&&gn>=Ht||(Ms>=Ht?(js+=Math.round(vn*((Ht-Ms)/Pn)),Ms=Ht):gn>=Ht&&(fn=js+Math.round(vn*((Ht-Ms)/Pn)),gn=Ht),ws&&js===ws.at(-2)&&Ms===ws.at(-1)||(ws=[js,Ms],Rt.push(ws)),ws.push(fn,gn)))))}}function ii(xt,We,ct,jt,Rt){const zt=(ct-bn)/We,Ht=(jt-bn)/We,ws=(ct+1+bn)/We,Ts=(jt+1+bn)/We;function js(gn,vn){let Pn=0;return gnws&&(Pn|=2),vnTs&&(Pn|=8),Pn}let Ms=[];for(let gn=1;gn<=8;gn*=2){let vn=xt.at(-2),Pn=xt.at(-1),ir=!(js(vn,Pn)&gn);for(let er=0;er>31}function Tc(xt,We){if(xt.type===4)return We.writeVarint(Ya(1,1)),We.writeVarint(ho(xt.x)),void We.writeVarint(ho(xt.y));let ct=0,jt=0;if(xt.type===1){const{geometry:Rt}=xt;We.writeVarint(Ya(1,Rt.length>>1));for(let zt=0;zt>1)-(Rt?1:0);for(let ws=0;wsxt},Ho=1073741824,ti=1/Ho,Xr=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:jt,maxZoom:Rt}=this.options;ct&&console.time("total time");const zt=Rt+1,Ht=`z${zt}: ${We.length} points`;ct&&console.time(Ht);const ws=this.stride;let Ts=We.length;for(const vr of We){const yr=vr.geometry;yr&&yr.type==="MultiPoint"&&(Ts+=yr.coordinates.length-1)}this.numPoints=Ts;const js=this.props=new Array(Ts),Ms=this.coords=new Float64Array(2*Ts);let fn=null;const gn=new Int32Array(Ts*ws);let vn=0,Pn=0;for(const vr of We){const yr=vr.geometry;if(!yr){Pn++;continue}const qa=yr.coordinates,et=yr.type==="MultiPoint";for(let Vt=0,Es=et?qa.length:1;Vt=jt;vr--){const yr=performance.now(),qa=tr||new Int32Array(er*ws);tr=null;const et=this._cluster(ir,er,vr,qa);et===er?(this.trees[vr]=this.trees[vr+1],tr=qa):(this.trees[vr]=this._createTree(qa,et),ir=qa,er=et),ct&&console.log(`z${vr}: ${this.trees[vr].numItems} clusters in ${(performance.now()-yr).toFixed(2)}ms`)}return ct&&console.timeEnd("total time"),this}getClusters(We,ct){let jt=((We[0]+180)%360+360)%360-180;const Rt=Math.max(-90,Math.min(90,We[1]));let zt=We[2]===180?180:((We[2]+180)%360+360)%360-180;const Ht=Math.max(-90,Math.min(90,We[3]));if(We[2]-We[0]>=360)jt=-180,zt=180;else if(jt>zt){const fn=this.getClusters([jt,Rt,180,Ht],ct),gn=this.getClusters([-180,Rt,zt,Ht],ct);return fn.concat(gn)}const ws=this.trees[this._limitZoom(ct)],Ts=ws.range(Xr(ao(jt)),Xr(ta(Ht)),Xr(ao(zt)),Xr(ta(Rt))),js=ws.data,Ms=[];for(const fn of Ts)Ms.push(this._featureJSON(js,this.stride*fn));return Ms}getChildren(We){const ct=this._getOriginId(We),jt=this._getOriginZoom(We),Rt="No cluster with the specified id.",zt=this.trees[jt];if(!zt)throw new Error(Rt);const Ht=zt.data;if(ct>=zt.numItems)throw new Error(Rt);const ws=this.options.radius/(this.options.extent*Math.pow(2,jt-1)),Ts=zt.within(Ht[ct*this.stride],Ht[ct*this.stride+1],ws*Ho),js=[];for(const Ms of Ts){const fn=Ms*this.stride;Ht[fn+4]===We&&js.push(this._featureJSON(Ht,fn))}if(js.length===0)throw new Error(Rt);return js}getLeaves(We,ct,jt){const Rt=[];return this._appendLeaves(Rt,We,ct=ct||10,jt=jt||0,0),Rt}getTile(We,ct,jt){return this._getTile(We,ct,jt,!1)}getTileRaw(We,ct,jt){return this._getTile(We,ct,jt,!0)}_getTile(We,ct,jt,Rt){const zt=this.trees[this._limitZoom(We)],Ht=Math.pow(2,We),{extent:ws,radius:Ts}=this.options,js=Ts/ws,Ms=Xr((jt-js)/Ht),fn=Xr((jt+1+js)/Ht),gn={features:[]};return this._addTileFeatures(zt.range(Xr((ct-js)/Ht),Ms,Xr((ct+1+js)/Ht),fn),zt.data,ct,jt,Ht,gn,Rt),ct===0&&this._addTileFeatures(zt.range(Xr(1-js/Ht),Ms,Xr(1),fn),zt.data,Ht,jt,Ht,gn,Rt),ct===Ht-1&&this._addTileFeatures(zt.range(Xr(0),Ms,Xr(js/Ht),fn),zt.data,-1,jt,Ht,gn,Rt),gn.features.length?gn:null}getClusterExpansionZoom(We){let ct=this._getOriginZoom(We)-1;for(;ct<=this.options.maxZoom;){const jt=this.getChildren(We);if(ct++,jt.length!==1)break;We=jt[0].properties.cluster_id}return ct}_appendLeaves(We,ct,jt,Rt,zt){const Ht=this.getChildren(ct);for(const ws of Ht){const Ts=ws.properties;if(Ts&&Ts.cluster?zt+Ts.point_count<=Rt?zt+=Ts.point_count:zt=this._appendLeaves(We,Ts.cluster_id,jt,Rt,zt):zt1;let fn,gn,vn;if(Ms)fn=ah(ct,js,this.clusterProps),gn=Eo(ct[js]),vn=Eo(ct[js+1]);else{const yr=ct[js+3];fn=this.props[yr],gn=this.coords[2*yr],vn=this.coords[2*yr+1]}const Pn=Math.round(this.options.extent*(gn*zt-jt)),ir=Math.round(this.options.extent*(vn*zt-Rt)),er=ws?{type:4,x:Pn,y:ir,tags:fn}:{type:1,geometry:[[Pn,ir]],tags:fn},tr=ct[js+3],vr=Ms||this.options.generateId?tr:this.ids?this.ids[tr]:void 0;vr!==void 0&&(er.id=vr),Ht.features.push(er)}}_limitZoom(We){return Math.max(this.options.minZoom,Math.min(Math.floor(+We),this.options.maxZoom+1))}_cluster(We,ct,jt,Rt){const{radius:zt,extent:Ht,reduce:ws,minPoints:Ts,maxZoom:js}=this.options,Ms=zt/(Ht*(1<jt&&(Vt+=We[ln+5])}if(Vt>et&&Vt>=Ts){let Es,ln=vr*et,tn=yr*et,sr=-1;const nr=(tr/vn<<5)+(jt+1)+this.numPoints;for(let Qr=0;Qr1)for(let Es=0;Es>5}_getOriginZoom(We){return(We-this.numPoints)%32}_featureJSON(We,ct){const jt=We[ct+3],Rt=We[ct+5]>1,zt=Rt?jt:this.ids?this.ids[jt]:void 0,Ht={type:"Feature",properties:Rt?ah(We,ct,this.clusterProps):this.props[jt],geometry:{type:"Point",coordinates:Rt?[xc(Eo(We[ct])),fl(Eo(We[ct+1]))]:[xc(this.coords[2*jt]),fl(this.coords[2*jt+1])]}};return zt!==void 0&&(Ht.id=zt),Ht}_map(We,ct,jt){if(We[ct+5]>1){const Ht=this.clusterProps[We[ct+6]];return jt?Object.assign({},Ht):Ht}const Rt=this.props[We[ct+3]],zt=this.options.map(Rt);return jt&&zt===Rt?Object.assign({},zt):zt}}function ah(xt,We,ct){const jt=xt[We+5],Rt=jt>=1e4?`${Math.round(jt/1e3)}k`:jt>=1e3?Math.round(jt/100)/10+"k":jt,zt=xt[We+6],Ht=zt===-1?{}:Object.assign({},ct[zt]);return Object.assign(Ht,{cluster:!0,cluster_id:xt[We+3],point_count:jt,point_count_abbreviated:Rt})}function ao(xt){return xt/360+.5}function ta(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 xc(xt){return 360*(xt-.5)}function fl(xt){const We=(180-360*xt)*Math.PI/180;return 360*Math.atan(Math.exp(We))/Math.PI-90}const Co=2147483647;function fu(xt,We,ct,jt){return{id:xt,type:4,x:We,y:ct,tags:jt}}function cc(xt,We,ct,jt){const Rt={id:xt,type:We,geometry:ct,tags:jt,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};if(We===1)nd(Rt,ct,0,ct.length);else{const zt=We===3;for(let Ht=0;Ht=0)&&nd(Rt,ct,ws,Ts),Ht=Ts}}return Rt}function nd(xt,We,ct,jt){for(let Rt=ct;Rtxt.maxX&&(xt.maxX=zt),Ht>xt.maxY&&(xt.maxY=Ht)}}function zr(xt,We,ct,jt){let Rt=jt;const zt=We+(ct-We>>1);let Ht,ws=ct-We;const Ts=xt[We],js=xt[We+1],Ms=xt[ct],fn=xt[ct+1];for(let gn=We+3;gnRt)Ht=gn,Rt=vn;else if(vn===Rt){const Pn=Math.abs(gn-zt);Pnjt){const gn=Ht;gn-We>3&&zr(xt,We,gn,jt),xt[gn+2]=Math.min(Math.sqrt(Rt),Co),ct-gn>3&&zr(xt,gn,ct,jt)}}function Hi(xt,We,ct,jt,Rt,zt){let Ht=Rt-ct,ws=zt-jt;if(Ht!==0||ws!==0){const Ts=((xt-ct)*Ht+(We-jt)*ws)/(Ht*Ht+ws*ws);Ts>1?(ct=Rt,jt=zt):Ts>0&&(ct+=Ht*Ts,jt+=ws*Ts)}return Ht=xt-ct,ws=We-jt,Ht*Ht+ws*ws}const zc="Input data is not a valid GeoJSON object.";function Bc(xt,We,ct,jt){var Pn;const Rt=We.geometry;if(!Rt)return;const zt=Rt.type==="GeometryCollection"?Rt.geometries:Rt.coordinates;if(!zt)throw new Error(zc);if(!zt.length)return;const Ht=ct.tolerance*ct.worldScale/((1<0&&(We+=2+3*ct.length);return We}let $l=0;function rg(xt,We,ct,jt,Rt,zt,Ht){const ws=cc(We,ct,jt,Rt);ct===2&&zt.lineMetrics&&(ws.start=0,ws.end=ws.size=Ht),xt.push(ws)}function Ix(xt,We,ct,jt,Rt,zt){const Ht=new zt.CoordArray(2+3*ct.length);Yo(Ht,0,ct,Rt,!1,!1,zt.worldScale,zt.originShift,zt.useInt32),rg(xt,We,2,Ht,jt,zt,$l)}function Yo(xt,We,ct,jt,Rt,zt,Ht,ws,Ts){if(ct.length===0)return We;const js=We,Ms=We+=2;let fn=0,gn=0,vn=0;for(let er=0;er0)if(Rt)vn+=(fn*vr-tr*gn)/2;else{const yr=tr-fn,qa=vr-gn;vn+=Math.sqrt(yr*yr+qa*qa)}fn=tr,gn=vr}const Pn=We;if(Rt&&(zt&&vn<0||!zt&&vn>=0)){const er=Pn-Ms;for(let tr=0;tr1?1:Rt)-ct)*We}function Yc(xt,We,ct,jt,Rt,zt,Ht){if(Rt>=We&&zt=ct)return null;const ws=Ht.lineMetrics,Ts=Ht.CoordArray;let js=null;for(let Ms=0;Ms=We&&er=We&&ir=ct?js===null&&(js=xt.slice(0,Ms)):(js===null&&(js=xt.slice(0,Ms)),gn!==1?Xa(vn,gn,We,ct,jt,fn,js,ws,Ts):_s(vn,We,ct,jt,fn,js,Ts))}return js===null?xt:js.length?js:null}function _s(xt,We,ct,jt,Rt,zt,Ht){let ws=0;for(let Ms=0;Ms=We&&xt[Ms+jt]=We&&xt[Ms+jt]=jt&&(js++,Ms++):vn>Rt?Pn<=Rt&&(js++,Ms++):js++,Pn=jt&&(js++,Ms++,ir=!0),Pn>Rt&&vn<=Rt&&(js++,Ms++,ir=!0),!Ht&&ir&&(js>0&&(Ts+=js,ws++),js=0)}const fn=xt[ct-3+zt];return fn>=jt&&fn<=Rt&&js++,Ht&&js>=2&&Ms>=1&&js++,js>0&&(Ts+=js,ws++),3*Ts+2*ws}function Ba(xt,We,ct,jt,Rt,zt,Ht,ws,Ts,js,Ms,fn,gn){const vn=fn!==null;let Pn=zt;Rt[zt]=0,Rt[zt+1]=jt;let ir=zt+=2,er=gn,tr=er,vr=0,yr=0;for(let sr=We;sr=Ht&&(yr=io(Rt,zt,nr,Qr,$a,Na,Ht,Ts,Ms),zt+=3,vn&&(tr=er+vr*yr)):La>ws?to<=ws&&(yr=io(Rt,zt,nr,Qr,$a,Na,ws,Ts,Ms),zt+=3,vn&&(tr=er+vr*yr)):(Rt[zt]=nr,Rt[zt+1]=Qr,Rt[zt+2]=na,zt+=3),to=Ht&&(yr=io(Rt,zt,nr,Qr,$a,Na,Ht,Ts,Ms),zt+=3,xo=!0),to>ws&&La<=ws&&(yr=io(Rt,zt,nr,Qr,$a,Na,ws,Ts,Ms),zt+=3,xo=!0),!js&&xo){const oo=(zt-ir)/3;oo>0&&(Rt[Pn]=oo,vn&&fn.push(tr,er+vr*yr),Pn=zt,Rt[zt]=0,Rt[zt+1]=jt,ir=zt+=2)}vn&&(er+=vr)}const qa=ct-3,et=xt[qa],Vt=xt[qa+1],Es=xt[qa+2],ln=Ts===0?et:Vt;ln>=Ht&&ln<=ws&&(Rt[zt]=et,Rt[zt+1]=Vt,Rt[zt+2]=Es,zt+=3),js&&zt-ir>=6&&(Rt[zt-3]!==Rt[ir]||Rt[zt-2]!==Rt[ir+1])&&(Rt[zt]=Rt[ir],Rt[zt+1]=Rt[ir+1],Rt[zt+2]=Rt[ir+2],zt+=3);const tn=(zt-ir)/3;return tn>0?(Rt[Pn]=tn,vn&&fn.push(tr,er)):zt=Pn,zt}function io(xt,We,ct,jt,Rt,zt,Ht,ws,Ts){let js;if(ws===0){js=(Ht-ct)/(Rt-ct);const Ms=jt+(zt-jt)*js;xt[We]=Ht,xt[We+1]=Ts?Math.floor(Ms+.5):Ms}else{js=(Ht-jt)/(zt-jt);const Ms=ct+(Rt-ct)*js;xt[We]=Ts?Math.floor(Ms+.5):Ms,xt[We+1]=Ht}return xt[We+2]=Co,js}function ko(xt,We){const ct=[];for(const jt of xt){if(jt.type===4){ct.push(fu(jt.id,jt.x+We,jt.y,jt.tags));continue}const Rt=qi(jt.geometry,jt.type,We),zt=cc(jt.id,jt.type,Rt,jt.tags);jt.start!==void 0&&(zt.start=jt.start,zt.end=jt.end,zt.size=jt.size),ct.push(zt)}return ct}function qi(xt,We,ct){const jt=xt.slice();if(We===1)for(let Rt=0;Rtxt.maxX&&(xt.maxX=er),tr>xt.maxY&&(xt.maxY=tr),xt.numPoints++,xt.numSimplified++;const vr={x:Zo(er,Rt,zt,ws,js,Ms),y:Zo(tr,Rt,Ht,ws,js,Ms),type:4,tags:We.tags||null};return We.id!==void 0&&(vr.id=We.id),void xt.features.push(vr)}const gn=We.geometry;let vn;if(We.minXxt.maxX&&(xt.maxX=We.maxX),We.maxY>xt.maxY&&(xt.maxY=We.maxY),fn===1){const er=gn.length/3;vn=new Ts(2*er);for(let tr=0,vr=0;tr0?Math.max(0,er/vr):0,Pn.mapbox_clip_end=tr>=vr?1:tr/vr}const ir={geometry:vn,type:fn,tags:Pn};We.id!==void 0&&(ir.id=We.id),xt.features.push(ir)}function Zg(xt,We,ct,jt,Rt,zt,Ht,ws,Ts,js,Ms,fn,gn,vn,Pn){const ir=(jt-ct)/3;if(Math.abs(Rt)Ht&&er++;zt.numPoints+=ir,zt.numSimplified+=er;const tr=new gn(2*er);let vr=0;for(let yr=ct;yrHt)&&(tr[vr++]=Zo(We[yr],Ts,js,fn,vn,Pn),tr[vr++]=Zo(We[yr+1],Ts,Ms,fn,vn,Pn));xt.push(tr)}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 jt=this.options=Object.assign(Object.create(Fl),ct),Rt=jt.debug;if(Rt&&console.time("preprocess data"),jt.maxZoom<0||jt.maxZoom>24)throw new Error("maxZoom should be in the 0-24 range");if(jt.promoteId&&jt.generateId)throw new Error("promoteId and generateId cannot be used together.");const zt=(jt.extent+2*jt.buffer)*(1<1&&console.time("creation"),Pn=this.tiles[vn]=cm(We,ct,jt,Rt,Ms),this.tileCoords.push({z:ct,x:jt,y:Rt}),this.stats[ct]=(this.stats[ct]||0)+1,this.total++,fn>1&&(console.log(`tile z${ct}-${jt}-${Rt} (features: ${Pn.numFeatures}, points: ${Pn.numPoints}, simplified: ${Pn.numSimplified})`),console.timeEnd("creation"))),Pn.source=We,zt==null){if(ct===Ms.indexMaxZoom||Pn.numPoints<=Ms.indexMaxPoints)continue}else{if(ct===Ms.maxZoom||ct===zt)continue;{const nr=zt-ct;if(jt!==Ht>>nr||Rt!==ws>>nr)continue}}if(Pn.source=null,We.length===0)continue;fn>1&&console.time("clipping");const ir=Ms.worldScale,er=Ms.originShift,tr=ir/gn,vr=.5*Ms.buffer*ir/(gn*Ms.extent),yr=(jt/gn-er)*ir,qa=(Rt/gn-er)*ir;let et=null,Vt=null,Es=null,ln=null;const tn=Yc(We,yr-vr,yr+tr/2+vr,0,Pn.minX,Pn.maxX,Ms),sr=Yc(We,yr+tr/2-vr,yr+tr+vr,0,Pn.minX,Pn.maxX,Ms);tn&&(et=Yc(tn,qa-vr,qa+tr/2+vr,1,Pn.minY,Pn.maxY,Ms),Vt=Yc(tn,qa+tr/2-vr,qa+tr+vr,1,Pn.minY,Pn.maxY,Ms)),sr&&(Es=Yc(sr,qa-vr,qa+tr/2+vr,1,Pn.minY,Pn.maxY,Ms),ln=Yc(sr,qa+tr/2-vr,qa+tr+vr,1,Pn.minY,Pn.maxY,Ms)),fn>1&&console.timeEnd("clipping"),Ts.push(et||[],Vt||[],Es||[],ln||[]),js.push(ct+1,2*jt,2*Rt,ct+1,2*jt,2*Rt+1,ct+1,2*jt+1,2*Rt,ct+1,2*jt+1,2*Rt+1)}}getTile(We,ct,jt){const Rt=this.findTile(We,ct,jt);return Rt?function(zt){const Ht=[];for(const ws of zt.features){let Ts;Ts=ws.type===4?{type:1,geometry:[[ws.x,ws.y]],tags:ws.tags??null}:ws.type===1?{type:1,geometry:xy(ws.geometry),tags:ws.tags??null}:{type:ws.type,geometry:ws.geometry.map(xy),tags:ws.tags??null},ws.id!=null&&(Ts.id=ws.id),Ht.push(Ts)}return{features:Ht}}(Rt):null}getTileRaw(We,ct,jt){const Rt=this.findTile(We,ct,jt);return Rt?{features:Rt.features}:null}findTile(We,ct,jt){const Rt=this.options.debug;if((We=+We)<0||We>24)return null;const zt=1<1&&console.log("drilling down to z%d-%d-%d",We,ct,jt);let ws,Ts=We,js=ct,Ms=jt;for(;!ws&&Ts>0;)Ts--,js>>=1,Ms>>=1,ws=this.tiles[Zd(Ts,js,Ms)];return ws&&ws.source?(Rt>1&&(console.log("found parent tile z%d-%d-%d",Ts,js,Ms),console.time("drilling down")),this.splitTile(ws.source,Ts,js,Ms,We,ct,jt),Rt>1&&console.timeEnd("drilling down"),this.tiles[Ht]??null):null}}function xy(xt){const We=[];for(let ct=0;ctjs.tags&&"3d_elevation_id"in js.tags&&"source"in js.tags&&js.tags.source==="elevation",zt=jt.features.filter(Rt);let Ht={_geojsonTileLayer:jt.features};zt.length>0&&(Ht={_geojsonTileLayer:jt.features.filter(js=>!Rt(js)),hd_road_elevation:zt});const ws=new Fn(Ht),Ts=function(js){const Ms=new c.gp;for(const fn of Object.keys(js))Ms.writeMessage(3,$i,{name:fn,features:js[fn]});return Ms.finish()}(Ht).buffer;We(null,{vectorTile:ws,rawData:Ts,headers:new Headers})}class cf extends Rs{constructor(We){super(We),this.loadVectorData=Vh,this._dynamicIndex=new xs}async loadData(We){const ct=We&&We.request,jt=ct&&ct.collectResourceTiming;this._geoJSONIndex=null;let Rt=await new Promise((Ht,ws)=>{this.loadGeoJSON(We,(Ts,js)=>{Ts?ws(Ts):Ht(js)})});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 Ht=c.c(We.filter,{type:"boolean","property-type":"data-driven",overridable:!1,transition:!1});if(Ht.result==="error")throw new Error(Ht.value.map(ws=>`${ws.key}: ${ws.message}`).join(", "));Rt.features=Rt.features.filter(ws=>Ht.value.evaluate({zoom:0},ws))}We.dynamic?(Rt.type==="Feature"&&(Rt={type:"FeatureCollection",features:[Rt]}),We.append||(this._dynamicIndex.clear(),this.loaded={}),this._dynamicIndex.load(Rt.features,this.loaded),We.cluster&&(Rt.features=this._dynamicIndex.getFeatures())):this.loaded={},this._geoJSONIndex=We.cluster?new Th(function({superclusterOptions:Ht,clusterProperties:ws}){if(!ws||!Ht)return Ht;const Ts={},js={},Ms={accumulated:null,zoom:0},fn={properties:null},gn=Object.keys(ws);for(const vn of gn){const[Pn,ir]=ws[vn],er=c.c(ir),tr=c.c(typeof Pn=="string"?[Pn,["accumulated"],["get",vn]]:Pn);Ts[vn]=er.value,js[vn]=tr.value}return Ht.map=vn=>{fn.properties=vn;const Pn={};for(const ir of gn)Pn[ir]=Ts[ir].evaluate(Ms,fn);return Pn},Ht.reduce=(vn,Pn)=>{fn.properties=Pn;for(const ir of gn)Ms.accumulated=vn[ir],vn[ir]=js[ir].evaluate(Ms,fn)},Ht}(We)).load(Rt.features):We.dynamic?this._dynamicIndex:new Ol(Rt,We.geojsonVtOptions);const zt={};if(jt){const Ht=d(ct);Ht&&(zt.resourceTiming={},zt.resourceTiming[We.source]=JSON.parse(JSON.stringify(Ht)))}return zt}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:jt})=>ct(null,jt)).catch(jt=>ct(jt));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 Ky{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 jt=[];for(const Rt in ct.layers){const zt=ct.getLayer(Rt),Ht=zt.getDataRange(zt.getBandList()),ws=ct.createDecodingTask(Ht),Ts=We.slice(Ht.firstByte,Ht.lastByte+1);jt.push(c.c_.performDecoding(Ts,ws).then(js=>ws.complete(null,js)).catch(js=>ws.complete(js,null)))}return await Promise.allSettled(jt),ct}}class ih{constructor({actor:We}){this.actor=We,this.loading={},this.loaded={}}async loadTile(We){const ct=We.uid,jt=new AbortController,Rt=this.loading[ct]=new Ky(We);Rt.abort=()=>jt.abort();try{const{data:zt,headers:Ht}=await c.d0(We.request,jt.signal);return zt?(this.loaded[ct]=Rt,{mrt:await Rt.parse(zt),headers:Ht}):(Rt.status="done",this.loaded[ct]=Rt,null)}catch(zt){if(jt.signal.aborted)return null;throw Rt.status="done",this.loaded[ct]=Rt,zt}finally{delete this.loading[ct]}}async reloadTile(We){}abortTile(We){const ct=We.uid,jt=this.loading[ct];jt&&(jt.abort&&jt.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:Rs,geojson:cf,"raster-dem":jr},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:jt}of this.rtlPluginParsingListeners)jt(!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:jt}=ct;if(this.isSpriteLoaded[We]||(this.isSpriteLoaded[We]={}),this.isSpriteLoaded[We][jt]=!0,this.workerSources[We]&&this.workerSources[We][jt])for(const Rt in this.workerSources[We][jt]){const zt=this.workerSources[We][jt][Rt];for(const Ht in zt){const ws=zt[Ht];ws instanceof Rs&&(ws.isSpriteLoaded=!0,ws.fire(new c.h("isSpriteLoaded")))}}}setImages(We,ct){this.availableImages[We]||(this.availableImages[We]={});const{scope:jt,images:Rt}=ct;if(this.availableImages[We][jt]=Rt,ct.isSpriteLoaded&&this.spriteLoaded(We,{scope:jt}),this.workerSources[We]&&this.workerSources[We][jt])for(const zt in this.workerSources[We][jt]){const Ht=this.workerSources[We][jt][zt];for(const ws in Ht)Ht[ws].availableImages=Rt}}setModels(We,{scope:ct,models:jt}){if(this.availableModels[We]||(this.availableModels[We]={}),this.availableModels[We][ct]=jt,this.workerSources[We]&&this.workerSources[We][ct])for(const Rt in this.workerSources[We][ct]){const zt=this.workerSources[We][ct][Rt];for(const Ht in zt)zt[Ht].availableModels=jt}}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:jt,maxUniformBlockSizeDwords:Rt}=ct.contextOptions;this.maxUniformBufferBindings=jt,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()}(),!ih)throw new Error('Could not load raster-array module for "raster-array" source.');this.workerSourceTypes["raster-array"]=ih}}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 jt=this.getExistingWorkerSource(We,ct);return jt?jt.abortTile(ct):void 0}removeTile(We,ct){const jt=this.getExistingWorkerSource(We,ct);return jt?jt.removeTile(ct):void 0}getExistingWorkerSource(We,ct){const{type:jt,source:Rt,scope:zt}=ct,Ht=this.workerSources[We];if(Ht&&Ht[zt]&&Ht[zt][jt])return Ht[zt][jt][Rt]}async removeSource(We,ct){const{type:jt,source:Rt,scope:zt}=ct,Ht=this.workerSources[We]&&this.workerSources[We][zt]&&this.workerSources[We][zt][jt],ws=Ht&&Ht[Rt];ws&&(delete Ht[Rt],ws.removeSource&&await ws.removeSource({source:Rt}))}async loadTileProvider(We,ct){const jt=new(await c.cN(ct.name,ct.url))(ct.options);return this.getWorkerSource(We,{type:ct.type,source:ct.source,scope:ct.scope},jt),jt.load&&ct.request?jt.load({request:ct.request}):null}async syncRTLPluginState(We,ct){if(c.fN.isParsed())return!0;if(c.fN.isParsing())return new Promise((Rt,zt)=>{this.rtlPluginParsingListeners.push({resolve:Rt,reject:zt})});c.fN.setState(ct);const jt=c.fN.getPluginURL();if(!c.fN.isLoaded()||c.fN.isParsed()||c.fN.isParsing())return!1;c.fN.setState({pluginStatus:c.gs.parsing,pluginURL:jt});try{return await self.__mapboxImport(jt),!!c.fN.isParsed()||new Promise((Rt,zt)=>{this.rtlPluginParsingListeners.push({resolve:Rt,reject:zt})})}catch(Rt){c.fN.setState({pluginStatus:c.gs.error,pluginURL:jt});for(const{reject:zt}of this.rtlPluginParsingListeners)zt(Rt);throw this.rtlPluginParsingListeners=[],Rt}}getAvailableImages(We,ct){this.availableImages[We]||(this.availableImages[We]={});let jt=this.availableImages[We][ct];return jt||(jt=[]),jt}getAvailableModels(We,ct){this.availableModels[We]||(this.availableModels[We]={});let jt=this.availableModels[We][ct];return jt||(jt={}),jt}getLayerIndex(We,ct){this.layerIndexes[We]||(this.layerIndexes[We]={});let jt=this.layerIndexes[We][ct];return jt||(jt=this.layerIndexes[We][ct]=new W,jt.scope=ct),jt}getWorkerSource(We,ct,jt){const{type:Rt,source:zt,scope:Ht}=ct,ws=this.workerSources;if(ws[We]||(ws[We]={}),ws[We][Ht]||(ws[We][Ht]={}),ws[We][Ht][Rt]||(ws[We][Ht][Rt]={}),this.isSpriteLoaded[We]||(this.isSpriteLoaded[We]={}),this.getExistingWorkerSource(We,ct))jt&&(ws[We][Ht][Rt][zt].tileProvider=jt);else{const Ts=this.actor.getWorkerSourceActor(We),js=this.workerSourceTypes[Rt];if(!js)throw new Error(`Unknown worker source type "${Rt}".`);ws[We][Ht][Rt][zt]=new js({actor:Ts,layerIndex:this.getLayerIndex(We,Ht),availableImages:this.getAvailableImages(We,Ht),availableModels:this.getAvailableModels(We,Ht),isSpriteLoaded:this.isSpriteLoaded[We][Ht],tileProvider:jt,brightness:this.brightness,worldview:this.worldview,maxUniformBufferBindings:this.maxUniformBufferBindings,maxUniformBlockSizeDwords:this.maxUniformBlockSizeDwords})}return ws[We][Ht][Rt][zt]}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 y=typeof document<"u"?document.documentElement&&document.documentElement.style:null,v=y&&y.userSelect!==void 0?"userSelect":"WebkitUserSelect";let b;function w(){y&&v&&(b=y[v],y[v]="none")}function S(){y&&v&&(y[v]=b)}function 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(Se(L,L.readVarint()+L.pos)):B===4?T.x1=L.readFloat():B===5?T.y1=L.readFloat():B===6?T.x2=L.readFloat():B===7&&(T.y2=L.readFloat());return T}function Se(L,k){const T={offset:0,opacity:255,rgb_color:V};let B;for(;B=L.nextField(k);)B===1?T.offset=L.readFloat():B===2?T.opacity=L.readVarint():B===3&&(T.rgb_color=ve(L.readVarint()));return T}function Le(L,k){const T={spread_method:1,stops:[],cx:.5,cy:.5,r:.5,fx:.5,fy:.5,fr:0};let B;for(;B=L.nextField(k);)B===1?T.transform=ce(L,L.readVarint()+L.pos):B===2?T.spread_method=L.readVarint():B===3?T.stops.push(Se(L,L.readVarint()+L.pos)):B===4?T.cx=L.readFloat():B===5?T.cy=L.readFloat():B===6?T.r=L.readFloat():B===7?T.fx=L.readFloat():B===8?T.fy=L.readFloat():B===9&&(T.fr=L.readFloat());return T}function Fe(L,k){const T={children:[]};let B;for(;B=L.nextField(k);)B===1?T.transform=ce(L,L.readVarint()+L.pos):B===2?T.clip_path_idx=L.readVarint():B===3&&T.children.push(te(L,L.readVarint()+L.pos));return T}function ke(L,k){const T={left:0,width:20,mask_type:1,children:[]};let B;for(;B=L.nextField(k);)B===1?T.left=T.top=L.readFloat():B===2?T.width=T.height=L.readFloat():B===3?T.top=L.readFloat():B===4?T.height=L.readFloat():B===5?T.mask_type=L.readVarint():B===6?T.mask_idx=L.readVarint():B===7&&T.children.push(te(L,L.readVarint()+L.pos));return T.height??(T.height=T.width),T.top??(T.top=T.left),T}class 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 Ne(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 Ve(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 qe(L,k,T,B,K){for(const Q of B.children)dt(L,k,T,Q,K)}function dt(L,k,T,B,K){B.group?(L.save(),function(Q,oe,me,we,Me){const Re=we.mask_idx!=null?me.masks[we.mask_idx]:null,Ze=we.clip_path_idx!=null?me.clip_paths[we.clip_path_idx]:null;if(we.transform&&(oe=Yt(we.transform).preMultiplySelf(oe)),!function(ut,bt,vt){return ut.opacity!==255||bt||vt}(we,Ze!=null,Re!=null))return void qe(Q,oe,me,we,Me);const Qe=Ve(Q.canvas.width,Q.canvas.height);qe(Qe,oe,me,we,Me),Ze&>(Qe,oe,me,Ze),Re&&ss(Qe,oe,me,Re,Me),Q.globalAlpha=we.opacity/255,Q.drawImage(Qe.canvas,0,0),ze()}(L,k,T,B.group,K),L.restore()):B.path&&(L.save(),function(Q,oe,me,we,Me){Q.setTransform(oe),we.paint_order===1?(Xe(Q,me,we,Me),rt(Q,me,we,Me)):(rt(Q,me,we,Me),Xe(Q,me,we,Me))}(L,k,T,B.path,K),L.restore())}function Xe(L,k,T,B){const K=T.fill;if(!K)return;const Q=K.opacity/255;switch(L.save(),L.beginPath(),ts(T,L),K.paint){case"rgb_color":L.fillStyle=Ne(K.rgb_color,K.opacity,B);break;case"linear_gradient_idx":{const oe=k.linear_gradients[K.linear_gradient_idx];oe.transform&&L.setTransform(Yt(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(Yt(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=ys(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=Ne(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 Qe=k.stops[0];return Ne(Qe.rgb_color,Qe.opacity*T,B)}const{x1:Q,y1:oe,x2:me,y2:we}=k;let Me=new DOMPoint(Q,oe),Re=new DOMPoint(me,we);if(K){const Qe=Yt(k.transform);Me=Qe.transformPoint(Me),Re=Qe.transformPoint(Re)}const Ze=L.createLinearGradient(Me.x,Me.y,Re.x,Re.y);for(const Qe of k.stops)Ze.addColorStop(Qe.offset,Ne(Qe.rgb_color,Qe.opacity*T,B));return Ze}function Je(L,k,T,B,K=!1){if(k.stops.length===1){const es=k.stops[0];return Ne(es.rgb_color,es.opacity*T,B)}const Q=Yt(k.transform),{fx:oe,fy:me,fr:we,cx:Me,cy:Re,r:Ze}=k;let Qe=new DOMPoint(oe,me),ut=new DOMPoint(Me,Re),bt=we,vt=Ze;if(K){Qe=Q.transformPoint(Qe),ut=Q.transformPoint(ut);const es=(Q.a+Q.d)/2;bt=we*es,vt=k.r*es}const Mt=L.createRadialGradient(Qe.x,Qe.y,bt,ut.x,ut.y,vt);for(const es of k.stops)Mt.addColorStop(es.offset,Ne(es.rgb_color,es.opacity*T,B));return Mt}function pt(L,k,T,B){const K=B.transform?Yt(B.transform).preMultiplySelf(k):k,Q=Ve(L.canvas.width,L.canvas.height);for(const me of B.children)if(me.group)pt(Q,K,T,me.group);else if(me.path){const we=me.path,Me=new Path2D;Me.addPath(ys(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=Ve(L.canvas.width,L.canvas.height);pt(K,k,T,B),L.globalCompositeOperation="destination-in",L.drawImage(K.canvas,0,0),ze()}function ss(L,k,T,B,K){if(B.children.length===0)return;const Q=B.mask_idx!=null?T.masks[B.mask_idx]:null;Q&&ss(L,k,T,Q,K);const oe=L.canvas.width,me=L.canvas.height,we=Ve(oe,me),Me=B.width,Re=B.height,Ze=B.left,Qe=B.top,ut=new Path2D,bt=new Path2D;bt.rect(Ze,Qe,Me,Re),ut.addPath(bt,k),we.clip(ut);for(const es of B.children)dt(we,k,T,es,K);const vt=we.getImageData(0,0,oe,me),Mt=vt.data;if(B.mask_type===1)for(let es=0;eso.I.from(T))}getImageVersions(k){return this.imageVersions.get(k)||new Map}hasImageProviderForSource(k,T){const B=this.imageProviders.get(T);if(!B)return!1;for(const K of B.values())if(K.sourceCache.getSource().id===k)return!0;return!1}getImages(k,T,B){const K=[],Q=[],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 me=!0;const we=!!this.loaded.get(T),Me=this.images.get(T);if(!we)for(const Re of K)Me.has(Re.toString())||(me=!1);we||me?this._notify(K,T,B):this.requestors.push({ids:K,scope:T,callback:B})}rasterizeImages(k,T){const B=new Map,{iconTasks:K,patternTasks:Q,scope:oe}=k;for(const me of[K,Q])for(const[we,Me]of me.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 me=K.get(oe.toString());if(!me){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:me.usvg?null:me.data.clone(),pixelRatio:me.pixelRatio,sdf:me.sdf,usvg:me.usvg,stretchX:me.stretchX,stretchY:me.stretchY,content:me.content,hasRenderCallback:!!(me.userImage&&me.userImage.render)};me.usvg&&Object.assign(we,{width:me.icon.usvg_tree.width,height:me.icon.usvg_tree.height}),Q.set(o.I.toString(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),me=this.getImage(k,T);if(!me)return null;if(oe){if(oe.position.version===me.version)return oe.position;oe.position.version=me.version}else{if(me.usvg&&!me.data){const we=this.getPatternInFlightId(K,T);if(this.patternsInFlight.has(we))return null;this.patternsInFlight.add(we);const Me=new o.i(k).scaleSelf(o.e.devicePixelRatio),Re=new Map([[Me.toString(),{image:me,imageVariant:Me}]]),Ze=this._rasterizeImages(T,Re);return this.storePatternImage(Me,T,me,B,Ze),null}this.storePattern(k,T,me)}return this._updatePatternAtlas(T,B),Q.get(K).position}getPatternInFlightId(k,T){return o.m(k,T)}hasPatternsInFlight(){return this.patternsInFlight.size!==0}storePatternImage(k,T,B,K,Q){const oe=k.toString(),me=Q?Q.get(oe):void 0;me&&(B.data=me,this.storePattern(k.id,T,B),this._updatePatternAtlas(T,K),this.patternsInFlight.delete(this.getPatternInFlightId(k.id.toString(),T)))}storePattern(k,T,B){const K={w:B.data.width+2*o.j,h:B.data.height+2*o.j,x:0,y:0},Q=new o.k(K,B,o.j);this.patterns.get(T).set(k.toString(),{bin:K,position:Q})}destroyAtlasTextures(){for(const k of this.atlasTexture.values())k&&k.destroy();this.atlasTexture.clear()}bind(k,T){const B=k.gl;let K=this.atlasTexture.get(T);K?this.dirty&&(K.update(this.atlasImage.get(T)),this.dirty=!1):(K=new o.T(k,this.atlasImage.get(T),B.RGBA8),this.atlasTexture.set(T,K)),K.bind(B.LINEAR,B.CLAMP_TO_EDGE)}_updatePatternAtlas(k,T){const B=this.patterns.get(k),K=Array.from(B.values()).map(({bin:Me})=>Me),{w:Q,h:oe}=o.p(K),me=this.atlasImage.get(k);me.resize({width:Q||1,height:oe||1});const we=this.images.get(k);for(const[Me,{bin:Re,position:Ze}]of B.entries()){let Qe=Ze.padding;const ut=Re.x+Qe,bt=Re.y+Qe,vt=we.get(Me).data,Mt=vt.width,es=vt.height;Qe=Qe>1?Qe-1:Qe,o.b.copy(vt,me,{x:0,y:0},{x:ut,y:bt},{width:Mt,height:es},T),o.b.copy(vt,me,{x:0,y:es-Qe},{x:ut,y:bt-Qe},{width:Mt,height:Qe},T),o.b.copy(vt,me,{x:0,y:0},{x:ut,y:bt+es},{width:Mt,height:Qe},T),o.b.copy(vt,me,{x:Mt-Qe,y:0},{x:ut-Qe,y:bt},{width:Qe,height:es},T),o.b.copy(vt,me,{x:0,y:0},{x:ut+Mt,y:bt},{width:Qe,height:es},T),o.b.copy(vt,me,{x:Mt-Qe,y:es-Qe},{x:ut-Qe,y:bt-Qe},{width:Qe,height:Qe},T),o.b.copy(vt,me,{x:0,y:es-Qe},{x:ut+Mt,y:bt-Qe},{width:Qe,height:Qe},T),o.b.copy(vt,me,{x:0,y:0},{x:ut+Mt,y:bt+es},{width:Qe,height:Qe},T),o.b.copy(vt,me,{x:Mt-Qe,y:0},{x:ut-Qe,y:bt+es},{width:Qe,height:Qe},T)}this.dirty=!0}beginFrame(){for(const k of this.images.keys())this.callbackDispatchedThisFrame.set(k,new Set);this.imageAtlasCache.beginFrame()}dispatchRenderCallbacks(k,T){const B=this.images.get(T);for(const K of k){if(this.callbackDispatchedThisFrame.get(T).has(K.toString()))continue;this.callbackDispatchedThisFrame.get(T).add(K.toString());const Q=B.get(K.toString());W(Q)&&this.updateImage(K,T,Q)}}}class as{constructor(k,T,B,K){this.message=(k?`${k}: `:"")+B,K&&(this.identifier=K),T!=null&&T.__line__&&(this.line=T.__line__)}}class kt extends as{}function Ks(L){const k=L.value,T=L.valueSpec,B=L.style,K=L.styleSpec,Q=L.key,oe=L.arrayElementValidator||dr;if(!Array.isArray(k))return[new as(Q,k,`array expected, ${o.n(k)} found`)];if(T.length&&k.length!==T.length)return[new as(Q,k,`array length ${T.length} expected, length ${k.length} found`)];if(T["min-length"]&&k.lengthK)return[new as(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 as(k,T,`object expected, ${o.n(T)} found`)];const B=L.valueSpec,K=o.u(T.type);let Q,oe,me,we={};const Me=K!=="categorical"&&T.property===void 0,Re=!Me,Ze=function(vt){const Mt=vt.stops;return Array.isArray(Mt)&&Array.isArray(Mt[0])&&o.l(Mt[0][0])}(T),Qe=Pa({key:L.key,value:L.value,valueSpec:L.styleSpec.function,style:L.style,styleSpec:L.styleSpec,objectElementValidators:{stops:function(vt){if(K==="identity")return[new as(vt.key,vt.value,'identity function may not have a "stops" property')];let Mt=[];const es=vt.value;return Mt=Mt.concat(Ks({key:vt.key,value:es,valueSpec:vt.valueSpec,style:vt.style,styleSpec:vt.styleSpec,arrayElementValidator:ut})),Array.isArray(es)&&es.length===0&&Mt.push(new as(vt.key,es,"array must have at least one stop")),Mt},default:function(vt){return dr({key:vt.key,value:vt.value,valueSpec:B,style:vt.style,styleSpec:vt.styleSpec})}}});return K==="identity"&&Me&&Qe.push(new as(L.key,L.value,'missing required property "property"')),K==="identity"||T.stops||Qe.push(new as(L.key,L.value,'missing required property "stops"')),K==="exponential"&&B.expression&&!o.r(B)&&Qe.push(new as(L.key,L.value,"exponential functions not supported")),L.styleSpec.$version>=8&&(Re&&!o.t(B)?Qe.push(new as(L.key,L.value,"property functions not supported")):Me&&!o.v(B)&&Qe.push(new as(L.key,L.value,"zoom functions not supported"))),K!=="categorical"&&!Ze||T.property!==void 0||Qe.push(new as(L.key,L.value,'"property" property is required')),Qe;function ut(vt){let Mt=[];const es=vt.value,Qt=vt.key;if(!Array.isArray(es))return[new as(Qt,es,`array expected, ${o.n(es)} found`)];if(es.length!==2)return[new as(Qt,es,`array length 2 expected, length ${es.length} found`)];if(Ze){if(!o.l(es[0]))return[new as(Qt,es,`object expected, ${o.n(es[0])} found`)];const Lt=es[0];if(Lt.zoom===void 0)return[new as(Qt,es,"object stop key must have zoom")];if(Lt.value===void 0)return[new as(Qt,es,"object stop key must have value")];const ps=o.u(Lt.zoom);if(typeof ps!="number")return[new as(Qt,Lt.zoom,"stop zoom values must be numbers")];if(me&&me>ps)return[new as(Qt,Lt.zoom,"stop zoom values must appear in ascending order")];ps!==me&&(me=ps,oe=void 0,we={}),Mt=Mt.concat(Pa({key:`${Qt}[0]`,value:es[0],valueSpec:{zoom:{}},style:vt.style,styleSpec:vt.styleSpec,objectElementValidators:{zoom:wt,value:bt}}))}else Mt=Mt.concat(bt({key:`${Qt}[0]`,value:es[0],style:vt.style,styleSpec:vt.styleSpec},es));return o.x(o.y(es[1]))?Mt.concat([new as(`${Qt}[1]`,es[1],"expressions are not allowed in function stops.")]):Mt.concat(dr({key:`${Qt}[1]`,value:es[1],valueSpec:B,style:vt.style,styleSpec:vt.styleSpec}))}function bt(vt,Mt){const es=o.n(vt.value),Qt=o.u(vt.value),Lt=vt.value!==null?vt.value:Mt;if(Q){if(es!==Q)return[new as(vt.key,Lt,`${es} stop domain type must match previous stop domain type ${Q}`)]}else Q=es;if(es!=="number"&&es!=="string"&&es!=="boolean"&&typeof Qt!="number"&&typeof Qt!="string"&&typeof Qt!="boolean")return[new as(vt.key,Lt,"stop domain value must be a number, string, or boolean")];if(es!=="number"&&K!=="categorical"){let ps=`number expected, ${es} found`;return o.t(B)&&K===void 0&&(ps+='\nIf you intended to use a categorical function, specify `"type": "categorical"`.'),[new as(vt.key,Lt,ps)]}return K!=="categorical"||es!=="number"||typeof Qt=="number"&&isFinite(Qt)&&Math.floor(Qt)===Qt?K!=="categorical"&&es==="number"&&typeof Qt=="number"&&typeof oe=="number"&&oe!==void 0&&Qtnew as(`${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 as(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 as(L.key,L.value,'"feature-state" data expressions are not supported with layout properties.')];if(L.expressionContext==="filter")return Is(T,L);if(L.expressionContext==="appearance")return Ss(T,L);if(L.expressionContext&&L.expressionContext.indexOf("cluster")===0){if(!o.B(T,["zoom","feature-state"]))return[new as(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 as(L.key,L.value,"Feature data expressions are not supported with initial expression part of cluster properties.")]}return[]}function Is(L,k){const T=new Set(["zoom","feature-state","pitch","distance-from-center"]);if(k.valueSpec&&k.valueSpec.expression)for(const K of k.valueSpec.expression.parameters)T.delete(K);if(T.size===0)return[];const B=[];return L instanceof o.F&&T.has(L.name)?[new as(k.key,k.value,`["${L.name}"] expression is not supported in a filter for a ${k.object.type} layer with id: ${k.object.id}`)]:(L.eachChild(K=>{B.push(...Is(K,k))}),B)}const Xs=new Set(["get","has","properties","geometry-type","id"]),ds=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 Ss(L,k){if(k.valueSpec&&k.valueSpec.expression)for(const B of k.valueSpec.expression.parameters)ds.delete(B);if(ds.size===0)return[];const T=[];if(L instanceof o.F){const B=Xs.has(L.name)?"feature":L.name;if(ds.has(B))return[new as(k.key,k.value,`["${L.name}"] is not an allowed parameter`)]}return L.eachChild(B=>{T.push(...Ss(B,k))}),T}function yn(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 as(k,T,`expected one of [${B.values.join(", ")}], ${JSON.stringify(T)} found`)):Object.keys(B.values).includes(o.u(T))||K.push(new as(k,T,`expected one of [${Object.keys(B.values).join(", ")}], ${JSON.stringify(T)} found`)),K}function Js(L){if(o.J(o.y(L.value))){const k=L.layerType||"fill";return ks({...L,expressionContext:"filter",valueSpec:L.styleSpec[`filter_${k}`]})}return Ut(L)}function Ut(L){const k=L.value,T=L.key;if(!Array.isArray(k))return[new as(T,k,`array expected, ${o.n(k)} found`)];if(k.length<1)return[new as(T,k,"filter array must have at least 1 element")];const B=L.styleSpec;let K=yn({key:`${T}[0]`,value:k[0],valueSpec:B.filter_operator});const Q=()=>{k.length>=2&&(o.H(k[1])||K.push(new as(`${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 as(T,k,`"$type" cannot be use with operator "${k[0]}"`)),k.length!==3&&K.push(new as(T,k,`filter array for operator "${k[0]}" must have 3 elements`)),Q();break;case"==":case"!=":k.length!==3&&K.push(new as(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 as(B,T[Me],`"${Me}" is prohibited for ref layers`))}),K.layers.forEach(Me=>{o.u(Me.id)===me&&(we=Me)}),we?we.ref?k.push(new as(B,T.ref,"ref cannot reference another ref layer")):oe=o.u(we.type):typeof me=="string"&&k.push(new as(B,T.ref,`ref layer "${me}" 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 as(B,T.source,`layer "${T.id}" requires a raster source`)):Me==="raster"&&oe!=="raster"?k.push(new as(B,T.source,`layer "${T.id}" requires a vector source`)):Me!=="vector"||T["source-layer"]?Me==="raster-dem"&&oe!=="hillshade"?k.push(new as(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 as(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 as(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 as(B,T.source,`layer "${T.id}" requires a 'raster-array' source.`)):k.push(new as(B,T.source,"raster-array source can only be used with layer type 'raster'.")):k.push(new as(B,T,`layer "${T.id}" must specify a "source-layer"`)):k.push(new as(B,T.source,`source "${T.source}" not found`))}else k.push(new as(`${B}.source`,T.source,'"source" must be a string'));else k.push(new as(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:()=>dr({key:`${B}.type`,value:T.type,valueSpec:Q.layer.type,style:L.style,styleSpec:L.styleSpec,object:T,objectKey:"type"}),filter:we=>Js({layerType:oe,...we}),layout:we=>Pa({layer:T,key:we.key,value:we.value,valueSpec:{},style:we.style,styleSpec:we.styleSpec,objectElementValidators:{"*":Me=>jr({layerType:oe,...Me})}}),paint:we=>Pa({layer:T,key:we.key,value:we.value,valueSpec:{},style:we.style,styleSpec:we.styleSpec,objectElementValidators:{"*":Me=>Rs({layerType:oe,layer:T,...Me})}}),appearances(we){const Me=Ks({key:we.key,value:we.value,valueSpec:we.valueSpec,style:we.style,styleSpec:we.styleSpec,arrayElementValidator:Qe=>function(ut){const{key:bt,layer:vt,layerType:Mt}=ut,es=o.u(ut.value),Qt=o.u(es.name),Lt=o.u(es.condition),ps=Pa({key:bt,value:es,valueSpec:ut.styleSpec.appearance,style:ut.style,styleSpec:ut.styleSpec,objectElementValidators:{condition:Hs=>function(Fs){const nn=[];return nn.push(...ks({key:Fs.key,value:Fs.object.condition,valueSpec:o.s.appearance.condition,expressionContext:"appearance"})),nn}({...Hs}),properties:Hs=>function(Fs){const nn=[],{styleSpec:$s,layer:rn,layerType:_n}=Fs,Mn=$s[`paint_${_n}`],Kn=$s[`layout_${_n}`],Bn=Fs.object[Fs.objectKey];for(const On in Bn){const Rr=On in Mn?"paint":On in Kn?"layout":void 0;if(!Rr){nn.push(new as(Fs.key,On,`unknown property "${On}" for layer type "${_n}"`));continue}const An={...Fs,key:`${Fs.key}.${On}`,objectKey:On,layer:rn,layerType:_n,value:Bn[On],valueSpec:Rr==="paint"?Mn[On]:Kn[On]};nn.push(...hr(An,Rr))}return nn}({layer:vt,layerType:Mt,...Hs})}});return Qt!=="hidden"&&Lt===void 0&&ps.push(new as(ut.key,"name",'Appearance with name different than "hidden" must have a condition')),ps}({layerType:oe,layer:T,...Qe})}),Re=Array.isArray(we.value)?we.value:[],Ze=new Set;return Re.forEach((Qe,ut)=>{const bt=o.u(Qe.name);if(bt)if(Ze.has(bt)){const vt=o.u(T.id);Me.push(new as(we.key,bt,`Duplicated appearance name "${bt}" for layer "${vt}"`))}else Ze.add(bt)}),Me}}})),k}function $n({key:L,value:k}){return o.H(k)?[]:[new as(L,k,`string expected, ${o.n(k)} found`)]}const kn={promoteId:function L({key:k,value:T}){if(o.H(T))return $n({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(me=>{K.push(new as(`${k}${me.key}`,null,`${me.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 as(`${k}`,null,"promoteId expression should be only feature dependent")),K)}if(!o.l(T))return[new as(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 as(T,k,`object expected, ${o.n(k)} found`)];if(!("type"in k))return[new as(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 kt(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:kn})),oe;case"geojson":if(oe=Pa({key:T,value:k,valueSpec:B.source_geojson,style:K,styleSpec:B,objectElementValidators:kn}),"cluster"in k&&"clusterProperties"in k){if(!o.l(k.clusterProperties))return[new as(`${T}.clusterProperties`,k,`object expected, ${o.n(k)} found`)];for(const me in k.clusterProperties){const we=k.clusterProperties[me];if(!Array.isArray(we))return[new as(`${T}.clusterProperties.${me}`,we,"array expected")];const[Me,Re]=we,Ze=typeof Me=="string"?[Me,["accumulated"],["get",me]]:Me;oe.push(...ks({key:`${T}.${me}.map`,value:Re,expressionContext:"cluster-map"})),oe.push(...ks({key:`${T}.${me}.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 as(T,null,"Please use runtime APIs to add canvas sources, rather than including them in stylesheets.","source.canvas")];default:return yn({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 Lr(L){const k=L.value;return k?o.H(k)?xs(k,!0)?[]:[new as(L.key,k,`invalid url "${k}"`)]:[new as(L.key,k,`string expected, "${o.n(k)}" found`)]:[]}function Or(L){const k=L.value,T=L.styleSpec,B=T.light,K=L.style;if(k===void 0)return[];if(!o.l(k))return[new as("light",k,`object expected, ${o.n(k)} found`)];let Q=[];for(const oe in k){const me=oe.match(o.K),we=oe.match(o.U);Q=Q.concat(we&&B[we[1]]?dr({key:oe,value:k[oe],valueSpec:{type:"string"},style:K,styleSpec:T}):me&&B[me[1]]&&B[me[1]].transition?dr({key:oe,value:k[oe],valueSpec:T.transition,style:K,styleSpec:T}):B[oe]?dr({key:oe,value:k[oe],valueSpec:B[oe],style:K,styleSpec:T}):[new as(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 as(T,k,`object expected, ${o.n(k)} found`)];let B=[];const K=L.styleSpec,Q=K["light-3d"],oe=L.style,me=L.style.lights;for(const Re of["type","id"])if(!(Re in k))return B=B.concat([new as(T,k,`missing property "${Re}"`)]),B;if(!o.H(k.type))return B=B.concat([new as(`${T}.type`,k.type,"string expected")]),B;if(me)for(let Re=0;Re[],array:Ks,boolean:function(L){const k=L.value,T=L.key;return o.G(k)?[]:[new as(T,k,`boolean expected, ${o.n(k)} found`)]},number:wt,color:function({key:L,value:k}){return o.H(k)?o.C.parse(o.u(k))===void 0?[new as(L,k,`color expected, "${k}" found`)]:[]:[new as(L,k,`color expected, ${o.n(k)} found`)]},enum:yn,filter:Js,function:gs,layer:kr,object:Pa,source:Fn,model:Lr,light:Or,"light-3d":la,terrain:Qn,fog:Cr,string:$n,formatted:function(L){return $n(L).length===0?[]:ks(L)},resolvedImage:function(L){return $n(L).length===0?[]:ks(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(dr({key:oe,value:k[oe],valueSpec:B[oe],style:K,styleSpec:T}));return Q}return o.H(k)?[]:[new as("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 as(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 as(`${L.key}.id`,Q,"import id can't be an empty string"));const me=o.u(Q.id);return me!=="__proto__"&&me!=="constructor"&&me!=="prototype"||oe.push(new as(`${L.key}.id`,Q,`import id can't be "${String(me)}"`)),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 as(T,k,"object expected")];if(!k.type)return[new as(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(me,we){return!(me!=="source"||!we.source)}(Q,k)){const me=K.sources&&Object.hasOwn(K.sources,k.source)?K.sources[k.source]:void 0,we=me&&o.u(me.type);me?we!=="raster-array"&&oe.push(new as(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 as(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)?dr({...K,valueSpec:{...K.valueSpec,type:"*",expression:void 0}}):B&&Array.isArray(Q)?dr({...K,valueSpec:{...K.valueSpec,type:B}}):dr(K)}}})}};function dr(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 ks(L)}if(B.type&&Un[B.type]){const Q=Un[B.type](L);return k===!0&&Q.length>0&&Array.isArray(L.value)?ks(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 as(k,T,`object expected, ${o.n(T)} found`)];let me=[];for(const we in T){if(!Object.hasOwn(T,we))continue;const Me=we.split(".")[0],Re=Object.hasOwn(B,Me),Ze=Object.hasOwn(B,"*"),Qe=Re?B[Me]:Ze?B["*"]:void 0;let ut;Object.hasOwn(K,Me)?ut=K[Me]:Re?ut=dr:Object.hasOwn(K,"*")?ut=K["*"]:Ze&&(ut=dr),ut?me=me.concat(ut({key:(k&&`${k}.`)+we,value:T[we],valueSpec:Qe,style:Q,styleSpec:oe,object:T,objectKey:we},T)):me.push(new kt(k,T[we],`unknown property "${we}"`))}for(const we in B){if(!Object.hasOwn(B,we)||Object.hasOwn(K,we))continue;const Me=B[we];!Me.required||Me.default!==void 0||Object.hasOwn(T,we)&&T[we]!==void 0||me.push(new as(k,T,`missing required property "${we}"`))}return me}function ii({key:L,value:k}){const T=$n({key:L,value:k});if(T.length)return T;const B=k;return B.includes("{fontstack}")||T.push(new as(L,k,'"glyphs" url must include a "{fontstack}" token')),B.includes("{range}")||T.push(new as(L,k,'"glyphs" url must include a "{range}" token')),T}function $i(L,k=o.s,T={}){return Pa({key:T.key||"",value:L,valueSpec:{...k.$root,"*":{type:"*"}},styleSpec:k,style:L,objectElementValidators:{glyphs:ii}})}function Rn(L){return L.slice().sort((k,T)=>k.line&&T.line?k.line-T.line:0)}const xa="setStyle",Ya="addLayer",ho="removeLayer",Tc="setPaintProperty",zd="setLayerProperty",Nl="setTerrain",Ho="removeImport",ti="addIconset",Xr="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 ah(L,k,T,B){Th(L,T,B),Eo(L,k,T)}function ao(L,k,T){let B;for(B in L[T])if(Object.hasOwn(L[T],B)&&B!=="data"&&!o.O(L[T][B],k[T][B]))return!1;for(B in k[T])if(Object.hasOwn(k[T],B)&&B!=="data"&&!o.O(L[T][B],k[T][B]))return!1;return!0}function ta(L,k,T,B,K,Q){let 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 xc(L){return L.id}function fl(L,k){return L[k.id]=k,L}const Co=new o.C(1,0,0,1),fu=new o.C(0,1,0,1),cc=new o.C(0,0,1,1),nd=new o.C(1,0,1,1),zr=new o.C(0,1,1,1);function Hi(L,k,T,B,K,Q,oe){const me=L.context,we=L.transform,Me=me.gl,Re=we.projection.name==="globe",Ze=Re?["PROJECTION_GLOBE_VIEW"]:[];let Qe=o.Q(T.projMatrix);if(Re&&o.S(we.zoom)>0){const Kn=o.V(T.canonical,we),Bn=o.W(Kn);Qe=o.X(new Float32Array(16),we.globeMatrix,Bn),o.X(Qe,we.projMatrix,Qe)}const ut=o.Y();ut[12]+=2*K/(o.e.devicePixelRatio*we.width),ut[13]+=2*Q/(o.e.devicePixelRatio*we.height),o.X(Qe,ut,Qe);const bt=L.getOrCreateProgram("debug",{defines:Ze}),vt=k.getTileByID(T.key);L.terrain&&L.terrain.setupElevationDraw(vt,bt);const Mt=o.Z.disabled,es=o._.disabled,Qt=L.colorModeForRenderPass(),Lt="$debug";me.activeTexture.set(Me.TEXTURE0),L.emptyTexture.bind(Me.LINEAR,Me.CLAMP_TO_EDGE),Re?vt._makeGlobeTileDebugBuffers(L.context,we):vt._makeDebugTileBoundsBuffers(L.context,we.projection);const ps=vt._tileDebugBuffer||L.debugBuffer,Hs=vt._tileDebugIndexBuffer||L.debugIndexBuffer,Fs=vt._tileDebugSegments||L.debugSegments;if(bt.draw(L,Me.LINE_STRIP,Mt,es,Qt,o.$.disabled,o.a0(Qe,B.toPremultipliedRenderColor(null)),Lt,ps,Hs,Fs,null,null,null,[vt._globeTileDebugBorderBuffer]),oe){const Kn=vt.latestRawTileData,Bn=Math.floor((Kn&&Kn.byteLength||0)/1024);let On=T.canonical.toString();T.overscaledZ!==T.canonical.z&&(On+=` => ${T.overscaledZ}`),On+=` ${vt.state}`,On+=` ${Bn}kb`,function(Rr,An){Rr.initDebugOverlayCanvas();const xr=Rr.debugOverlayCanvas,sa=Rr.context.gl,ka=Rr.debugOverlayCanvas.getContext("2d");ka.clearRect(0,0,xr.width,xr.height),ka.shadowColor="white",ka.shadowBlur=2,ka.lineWidth=1.5,ka.strokeStyle="white",ka.textBaseline="top",ka.font="bold 36px Open Sans, sans-serif",ka.fillText(An,5,5),ka.strokeText(An,5,5),Rr.debugOverlayTexture.update(xr),Rr.debugOverlayTexture.bind(sa.LINEAR,sa.CLAMP_TO_EDGE)}(L,On)}const nn=k.getTile(T).tileSize,$s=512/Math.min(nn,512)*(T.overscaledZ/we.zoom)*.5,rn=vt._tileDebugTextBuffer||L.debugBuffer,_n=vt._tileDebugTextIndexBuffer||L.quadTriangleIndexBuffer,Mn=vt._tileDebugTextSegments||L.debugSegments;bt.draw(L,Me.TRIANGLES,Mt,es,o.a1.alphaBlended,o.$.disabled,o.a0(Qe,o.C.transparent.toPremultipliedRenderColor(null),$s),Lt,rn,_n,Mn,null,null,null,[vt._globeTileDebugTextBuffer])}function zc(L,k,T,B){yc(L,0,k+T/2,L.transform.width,T,B)}function Bc(L,k,T,B){yc(L,k-T/2,0,T,L.transform.height,B)}function yc(L,k,T,B,K,Q){const oe=L.context,me=oe.gl;me.enable(me.SCISSOR_TEST),me.scissor(k*o.e.devicePixelRatio,T*o.e.devicePixelRatio,B*o.e.devicePixelRatio,K*o.e.devicePixelRatio),oe.clear({color:Q}),me.disable(me.SCISSOR_TEST)}function $l(L,k,T){const B=L.context,K=B.gl,Q=T.projMatrix,oe=L.getOrCreateProgram("debug"),me=k.getTileByID(T.key);L.terrain&&L.terrain.setupElevationDraw(me,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 Qe=me.queryGeometryDebugViz,ut=me.queryBoundsDebugViz;if(Qe&&Qe.vertices.length>0){Qe.lazyUpload(B);const bt=Qe.vertexBuffer,vt=Qe.indexBuffer,Mt=Qe.segments;bt!=null&&vt!=null&&Mt!=null&&oe.draw(L,K.LINE_STRIP,we,Me,Re,o.$.disabled,o.a0(Q,Qe.color.toPremultipliedRenderColor(null)),Ze,bt,vt,Mt)}if(ut&&ut.vertices.length>0){ut.lazyUpload(B);const bt=ut.vertexBuffer,vt=ut.indexBuffer,Mt=ut.segments;bt!=null&&vt!=null&&Mt!=null&&oe.draw(L,K.LINE_STRIP,we,Me,Re,o.$.disabled,o.a0(Q,ut.color.toPremultipliedRenderColor(null)),Ze,bt,vt,Mt)}}const rg=(L,k,T,B,K,Q,oe,me)=>{const we=o.a6/Q.tileSize;return{u_matrix:L,u_inv_rot_matrix:k,u_camera_to_center_distance:T.getCameraToCenterDistance(me),u_extrude_scale:[T.pixelsToGLUnits[0]/we,T.pixelsToGLUnits[1]/we],u_zoom_transition:B,u_tile_id:oe,u_merc_center:K}},Ix=(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 Rn($i(L,k))},validateSource:L=>Rn(Fn(L)),validateLight:L=>Rn(Or(L)),validateLights:L=>Rn(la(L)),validateTerrain:L=>Rn(Qn(L)),validateFog:L=>Rn(Cr(L)),validateSnow:L=>Rn(function(k){const T=k.value,B=k.style,K=k.styleSpec,Q=K.snow;if(T===void 0)return[];if(!o.l(T))return[new as("snow",T,`object expected, ${o.n(T)} found`)];let oe=[];for(const me in T){const we=me.match(o.K);oe=oe.concat(we&&Q[we[1]]&&Q[we[1]].transition?dr({key:me,value:T[me],valueSpec:K.transition,style:B,styleSpec:K}):Q[me]?dr({key:me,value:T[me],valueSpec:Q[me],style:B,styleSpec:K}):[new kt(me,T[me],`unknown property "${me}"`)])}return oe}(L)),validateRain:L=>Rn(function(k){const T=k.value,B=k.style,K=k.styleSpec,Q=K.rain;if(T===void 0)return[];if(!o.l(T))return[new as("rain",T,`object expected, ${o.n(T)} found`)];let oe=[];for(const me in T){const we=me.match(o.K);oe=oe.concat(we&&Q[we[1]]&&Q[we[1]].transition?dr({key:me,value:T[me],valueSpec:K.transition,style:B,styleSpec:K}):Q[me]?dr({key:me,value:T[me],valueSpec:Q[me],style:B,styleSpec:K}):[new kt(me,T[me],`unknown property "${me}"`)])}return oe}(L)),validateLayer:L=>Rn(kr(L)),validateFilter:L=>Rn(Js(L)),validatePaintProperty:L=>Rn(Rs(L)),validateLayoutProperty:L=>Rn(jr(L)),validateModel:L=>Rn(Lr(L)),diffStyles:function(L,k){if(!L)return[{command:xa,args:[k]}];let T=[];try{if(!o.O(L.version,k.version))return[{command:xa,args:[k]}];if(o.O(L.center,k.center)||T.push({command:"setCenter",args:[k.center]}),o.O(L.zoom,k.zoom)||T.push({command:"setZoom",args:[k.zoom]}),o.O(L.bearing,k.bearing)||T.push({command:"setBearing",args:[k.bearing]}),o.O(L.pitch,k.pitch)||T.push({command:"setPitch",args:[k.pitch]}),o.O(L.sprite,k.sprite)||T.push({command:"setSprite",args:[k.sprite]}),o.O(L.glyphs,k.glyphs)||T.push({command:"setGlyphs",args:[k.glyphs]}),o.O(L.imports,k.imports)||function(me=[],we=[],Me){we=we||[];const Re=(me=me||[]).map(xc),Ze=we.map(xc),Qe=me.reduce(fl,{}),ut=we.reduce(fl,{}),bt=Re.slice();let vt,Mt,es,Qt;for(vt=0,Mt=0;vt{me.source&&B[me.source]?T.push({command:ho,args:[me.id]}):Q.push(me)});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(me,we,Me){we=we||[];const Re=(me=me||[]).map(xc),Ze=we.map(xc),Qe=me.reduce(fl,{}),ut=we.reduce(fl,{}),bt=Re.slice(),vt=Object.create(null);let Mt,es,Qt,Lt,ps,Hs,Fs;for(Mt=0,es=0;Mt0){const qr=o.Y(),Za=Wr;o.aa(qr,Mn.placementInvProjMatrix,Me.glCoordMatrix),o.aa(qr,qr,Mn.placementViewportMatrix),Mt.push({circleArray:Gr,circleOffset:Qt,transform:Za,invTransform:qr,projection:Mn.getProjection()}),es+=Gr.length/4,Qt=es}if(!Tr)continue;L.terrain&&L.terrain.setupElevationDraw(_n,si);const Ga=Hr?[rn.canonical.x,rn.canonical.y,1<{const T=Mc[L];return T?T(...k):[]}}const _s=Yc("validateStyle"),Xa=Yc("validateSource"),No=Yc("validateLight"),Ba=Yc("validateLights"),io=Yc("validateTerrain"),ko=Yc("validateFog"),qi=Yc("validateSnow"),cm=Yc("validateRain"),Zo=Yc("validateLayer"),vo=Yc("validateFilter"),Zg=Yc("validatePaintProperty"),Fl=Yc("validateLayoutProperty"),Ol=Yc("validateModel"),xy=o.s.light;let Zd;class Vh extends o.E{constructor(k,T="flat"){super(),this._transitionable=new o.af(Zd||(Zd=new o.ag({anchor:new o.ah(xy.anchor),position:new o.ai(xy.position),color:new o.ah(xy.color),intensity:new o.ah(xy.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(_s,{value:T,style:{glyphs:!0,sprite:!0},styleSpec:o.s}))}}const cf=o.s.terrain;let Ky=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 ih(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),me=[K[0]+oe,K[1]+oe];return{range:T?[o.am(Q[0],me[0],B),o.am(Q[1],me[1],B)]:me,horizonBlend:this.properties.get("horizon-blend"),alpha:this.properties.get("color").a}}get(){return this._transitionable.serialize()}set(k,T,B={}){if(this._validate(ko,k,B))return;const K={...k};for(const Q of Object.keys(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(_s,{value:T,style:{glyphs:!0,sprite:!0},styleSpec:o.s}))}}let We,ct,jt=class extends o.E{constructor(L,k,T,B){super();const K=We||(We=new o.ag({density:new o.ah(o.s.snow.density),intensity:new o.ah(o.s.snow.intensity),color:new o.ah(o.s.snow.color),opacity:new o.ah(o.s.snow.opacity),vignette:new o.ah(o.s.snow.vignette),"vignette-color":new o.ah(o.s.snow["vignette-color"]),"center-thinning":new o.ah(o.s.snow["center-thinning"]),direction:new o.ah(o.s.snow.direction),"flake-size":new o.ah(o.s.snow["flake-size"])}));this._transitionable=new o.af(K,T,B),this.set(L,B),this._transitioning=this._transitionable.untransitioned(),this.properties=new o.al(K),this.scope=T}get state(){const L=this.properties.get("opacity"),k=this.properties.get("color"),T=this.properties.get("direction"),B=o.av(T[0]),K=-Math.max(o.av(T[1]),.01),Q=[Math.cos(B)*Math.cos(K),Math.sin(B)*Math.cos(K),Math.sin(K)],oe=this.properties.get("vignette"),me=this.properties.get("vignette-color"),we=new o.C(me.r,me.g,me.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(_s,{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"),me=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:me}}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(_s,{value:k,style:{glyphs:!0,sprite:!0},styleSpec:o.s}))}};const zt={workerUrl:"",workerClass:null,workerParams:void 0};function Ht(L){return zt.workerClass!=null?new zt.workerClass:new self.Worker(zt.workerUrl,{name:L,type:"module",...zt.workerParams})}const ws="mapboxgl_preloaded_worker_pool";class 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[ws]}numActive(){return Object.keys(this.active).length}}Ts.workerCount=2;class js{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)}}js.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 fn;const gn=()=>fn||(fn=new o.ag({color:new o.ah(o.s.properties_light_ambient.color),"color-use-theme":new o.ah({type:"string",default:"default","property-type":"data-constant"}),intensity:new o.ah(o.s.properties_light_ambient.intensity)}));let vn;const Pn=()=>vn||(vn=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"])})),ir=(L,k,T,B,K,Q,oe,me,we,Me=[0,0,1])=>({u_matrix:L,u_normal_matrix:k,u_opacity:T,u_faux_facade_ao_intensity:B,u_camera_pos:K,u_tile_to_meter:Q,u_facade_emissive_chance:oe,u_flood_light_color:me,u_flood_light_intensity:we,u_front_cutoff_params:Me}),er=L=>({u_matrix:L}),tr=L=>({u_matrix:L}),vr=o.az;async function yr(){return Promise.resolve()}function qa(L,k,T,B,K,Q,oe,me){T.resetLayerRenderingStats(L);const we=L.context,Me=we.gl,Re=L.transform,Ze=T.paint.get("fill-extrusion-pattern"),Qe=T.paint.get("fill-extrusion-pattern-cross-fade"),ut=Ze.constantOr(null),bt=Ze.constantOr(1),vt=T.paint.get("fill-extrusion-opacity"),Mt=L.style.enable3dLights(),es=T.paint.get(Mt&&!bt?"fill-extrusion-ambient-occlusion-wall-radius":"fill-extrusion-ambient-occlusion-radius"),Qt=[T.paint.get("fill-extrusion-ambient-occlusion-intensity"),es],Lt=T.layout.get("fill-extrusion-edge-radius"),ps=Lt>0&&!T.paint.get("fill-extrusion-rounded-roof"),Hs=ps?0:Lt,Fs=Re.projection.name==="globe"?o.aE():0,nn=Re.projection.name==="globe",$s=nn?o.S(Re.zoom):0,rn=[o.a7(Re.center.lng),o.a8(Re.center.lat)],_n=T.paint.get("fill-extrusion-flood-light-color-use-theme").constantOr("default")==="none",Mn=T.paint.get("fill-extrusion-flood-light-color").toNonPremultipliedRenderColor(_n?null:T.lut).toArray01().slice(0,3),Kn=T.paint.get("fill-extrusion-flood-light-intensity"),Bn=T.paint.get("fill-extrusion-vertical-scale"),On=T.paint.get("fill-extrusion-line-width").constantOr(1)!==0,Rr=T.paint.get("fill-extrusion-height-alignment"),An=T.paint.get("fill-extrusion-base-alignment"),xr=o.aF(L,T.paint.get("fill-extrusion-cutoff-fade-range")),sa=T.paint.get("fill-extrusion-front-cutoff"),ka=Vt(Re.pitch,sa,!!L.terrain),Hr=ka[2]<1;Hr&&(L.maxFrontCutoffRawStart=Math.max(L.maxFrontCutoffRawStart,sa[0]));const ea=[];let si;nn&&ea.push("PROJECTION_GLOBE_VIEW"),Qt[0]>0&&ea.push("FAUX_AO"),ps&&ea.push("ZERO_ROOF_RADIUS"),me&&ea.push("HAS_CENTROID"),Kn>0&&ea.push("FLOOD_LIGHT"),xr.shouldRenderCutoff&&ea.push("RENDER_CUTOFF"),Hr&&ea.push("RENDER_FRONT_CUTOFF"),On&&ea.push("RENDER_WALL_MODE");const Wr=L.renderPass==="shadow",Tr=L.shadowRenderer,Gr=Wr&&!!Tr,Ga=Wr?o.$.disabled:o.$.backCCW;L.shadowRenderer&&(L.shadowRenderer.useNormalOffset=!0);let qr=[0,0,0];if(Tr){const Do=L.style.directionalLight,so=L.style.ambientLight;Do&&so&&(qr=o.aG(L.style,Do,so)),Wr||(ea.push("RENDER_SHADOWS"),Tr.useNormalOffset&&ea.push("NORMAL_OFFSET")),si=ea.concat(["SHADOWS_SINGLE_CASCADE"])}const Za=Gr?"fillExtrusionDepth":bt?"fillExtrusionPattern":"fillExtrusion",Oi=T.getLayerRenderingStats();for(const Do of B){const so=k.getTile(Do),ql=so.getBucket(T);if(!ql||ql.projection.name!==Re.projection.name)continue;let vu=!1;Tr&&(vu=Tr.getMaxCascadeForTile(Do.toUnwrapped())===0);const Uc=L.isTileAffectedByFog(Do),Ko=ql.programConfigurations.get(T.id);let no=!1;if(ut&&so.imageAtlas){const dc=so.imageAtlas,Dh=o.aH.from(ut),Wh=Dh.getPrimary().scaleSelf(o.e.devicePixelRatio).toString(),Pd=Dh.getSecondary(),_c=dc.patternPositions.get(Wh),Kh=Pd?dc.patternPositions.get(Pd.scaleSelf(o.e.devicePixelRatio).toString()):null;no=!!_c&&!!Kh,_c&&Ko.setConstantPatternPositions(_c,Kh)}Qe>0&&(no||Ko.getPatternTransitionVertexBuffer("fill-extrusion-pattern"))&&ea.push("FILL_EXTRUSION_PATTERN_TRANSITION");const _d=L.getOrCreateProgram(Za,{config:Ko,defines:vu?si:ea,overrideFog:Uc});if(L.terrain&&L.terrain.setupElevationDraw(so,_d,{useMeterToDem:!0}),!ql.centroidVertexBuffer){const dc=_d.getAttributeLocation(Me,"a_centroid_pos");dc!==-1&&Me.vertexAttribI4ui(dc,0,0,0,0)}!Wr&&Tr&&Tr.setupShadows(so.tileID.toUnwrapped(),_d,"vector-tile"),bt&&(L.context.activeTexture.set(Me.TEXTURE0),so.imageAtlasTexture&&so.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(Wr&&Tr){if(nr(so.tileID,ql.maxHeight,L))continue;const dc=Tr.calculateShadowPassMatrixFromTile(so.tileID.toUnwrapped());Vl=o.aN(dc,Hs,_h,Bn,Rr,An)}else{const dc=L.translatePosMatrix(Do.expandedProjMatrix,so,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=bt?o.aI(dc,L,Gh,vt,Qt,Hs,_h,Do,so,Fs,Rr,An,$s,rn,Dh,Mn,Bn,Qe,Wh):o.aJ(dc,L,Gh,vt,Qt,Hs,_h,Do,Fs,Rr,An,$s,rn,Dh,Mn,Bn,Kn,qr,ka,Wh)}L.uploadCommonUniforms(we,_d,Do.toUnwrapped(),null,xr);let mm=ql.segments;if(Re.projection.name==="mercator"&&!Wr&&(mm=ql.getVisibleSegments(so.tileID,L.terrain,L.transform.getFrustum(0)),!mm.get().length))continue;if(Oi)if(Wr)for(const dc of mm.get())Oi.numRenderedVerticesInShadowPass+=dc.primitiveLength;else for(const dc of mm.get())Oi.numRenderedVerticesInTransparentPass+=dc.primitiveLength;const bc=[];(L.terrain||me)&&bc.push(ql.centroidVertexBuffer),nn&&bc.push(ql.layoutVertexExtBuffer),On&&bc.push(ql.wallVertexBuffer),_d.draw(L,we.gl.TRIANGLES,K,Q,oe,Ga,Vl,T.id,ql.layoutVertexBuffer,ql.indexBuffer,mm,T.paint,L.transform.zoom,Ko,bc)}L.shadowRenderer&&(L.shadowRenderer.useNormalOffset=!1)}class et{constructor(){this.translate=[0,0],this.translateAnchor="map",this.edgeRadius=0,this.cutoffFadeRange=0}}function Vt(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 me=Q?Q.findDEMTileFor(T):null;if(!(me&&me.dem||oe))return;Q&&me&&me.dem&&B.selfDEMTileTimestamp!==me.dem._timestamp&&(B.borderDoneWithNeighborZ=[-1,-1,-1,-1],B.selfDEMTileTimestamp=me.dem._timestamp);const we=(Lt,ps)=>{(Lt.flags|ps.flags)&o.aK?(Lt.flags|=o.aK,ps.flags|=o.aK):(Lt.flags&=~o.aK,ps.flags&=~o.aK)},Me=Lt=>new o.P(Math.ceil((Lt+o.aL)*o.aM),0),Re=(Lt,ps,Hs)=>{const Fs=Math.ceil((Lt+o.aL)*o.aM),nn=Math.floor(Math.max(0,Math.min(o.a6-1,Hs))/4);return new o.P(Fs,nn<<5|(3&ps)<<3|7)},Ze=(Lt,ps)=>{const Hs=Number.MAX_VALUE,Fs=ps[0][0]!==Hs,nn=ps[1][0]!==Hs,$s=ps[2][0]!==Hs,rn=ps[3][0]!==Hs;if(!((Fs?1:0)+(nn?1:0)+($s?1:0)+(rn?1:0)>2))return Lt<2?$s===rn?void 0:$s?0:o.a6-1:Fs===nn?void 0:Fs?0:o.a6-1},Qe=(Lt,ps,Hs,Fs)=>(ps?Ze(Lt,ps):void 0)??(Fs?Ze(Hs,Fs):void 0),ut=Lt=>{const ps=k.getSource().minzoom,Hs=nn=>{const $s=k.getTileByID(nn);if($s&&$s.hasData())return $s.getBucket(K)},Fs=[0,-1,1];for(const nn of Fs){if(Lt.overscaledZ+nn(bt[0]=Math.min(Lt.min.y,ps.min.y),bt[1]=Math.max(Lt.max.y,ps.max.y),bt[2]=o.a6-ps.min.x>Lt.max.x?ps.min.x-o.a6:Lt.max.x,bt),Mt=(Lt,ps)=>(bt[0]=Math.min(Lt.min.x,ps.min.x),bt[1]=Math.max(Lt.max.x,ps.max.x),bt[2]=o.a6-ps.min.y>Lt.max.y?ps.min.y-o.a6:Lt.max.y,bt),es=[(Lt,ps)=>vt(Lt,ps),(Lt,ps)=>vt(ps,Lt),(Lt,ps)=>Mt(Lt,ps),(Lt,ps)=>Mt(ps,Lt)],Qt=(Lt,ps,Hs,Fs,nn,$s,rn)=>{if(!Q)return 0;const _n=[[$s?Hs:Lt,$s?Lt:Hs,0],[$s?Hs:ps,$s?ps:Hs,0]],Mn=rn<0?o.a6+rn:rn,Kn=[$s?Mn:(Lt+ps)/2,$s?(Lt+ps)/2:Mn,0];return Hs===0&&rn<0||Hs!==0&&rn>0?Q.getForTilePoints(nn,[Kn],!0,Fs):_n.push(Kn),Q.getForTilePoints(T,_n,!0,me),Math.max(_n[0][2],_n[1][2],Kn[2])/Q.exaggeration()};for(let Lt=0;Lt<4;Lt++){const ps=B.borderFeatureIndices[Lt];if(ps.length===0)continue;const Hs=o.aC[Lt](T),Fs=ut(Hs);if(!(Fs&&Fs instanceof o.aD))continue;const nn=Q?Q.findDEMTileFor(Hs):null;if(!(nn&&nn.dem||oe)||(Q&&nn&&nn.dem&&B.borderDEMTileTimestamp[Lt]!==nn.dem._timestamp&&(B.borderDoneWithNeighborZ[Lt]=-1,B.borderDEMTileTimestamp[Lt]=nn.dem._timestamp),B.borderDoneWithNeighborZ[Lt]===Fs.canonical.z))continue;Fs.centroidVertexArray.length===0&&Fs.createCentroidsBuffer();const $s=(Lt<2?1:5)-Lt,rn=Fs.borderDoneWithNeighborZ[$s]!==B.canonical.z,_n=Fs.borderFeatureIndices[$s];let Mn=0;if(B.canonical.z!==Fs.canonical.z){for(const Rr of ps)B.showCentroid(B.featuresOnBorder[Rr],"discard");if(rn)for(const Rr of _n)Fs.showCentroid(Fs.featuresOnBorder[Rr],"discard");B.borderDoneWithNeighborZ[Lt]=Fs.canonical.z,Fs.borderDoneWithNeighborZ[$s]=B.canonical.z;continue}const Kn=new Map,Bn=new Set,On=new Set;for(let Rr=0;Rr<_n.length;Rr++){const An=Fs.featuresOnBorder[_n[Rr]];An.buildingId!==void 0&&Kn.set(An.buildingId,Rr)}for(const Rr of ps){const An=B.featuresOnBorder[Rr],xr=B.centroidData.get(An.centroidDataIndex);if(An.buildingId===void 0)continue;const sa=Kn.get(An.buildingId);if(sa===void 0)continue;const ka=Fs.featuresOnBorder[_n[sa]],Hr=Fs.centroidData.get(ka.centroidDataIndex);Bn.add(Rr),On.add(sa),oe&&we(xr,Hr);const ea=xr.groupCentroidPos.x!==0||xr.groupCentroidPos.y!==0?xr.groupCentroidPos:An.centroid(),si=Hr.groupCentroidPos.x!==0||Hr.groupCentroidPos.y!==0?Hr.groupCentroidPos:ka.centroid(),Wr=Q?void 0:Qe(Lt,An.borders,$s,ka.borders),Tr=Wr!==void 0?Wr:Lt<2?Math.round((ea.y+si.y)/2):Math.round((ea.x+si.x)/2),Gr=An.intersectsCount()>1||ka.intersectsCount()>1;{let Ga=0;if(nn&&nn.dem&&!Gr){const qr=es[Lt](xr,Hr),Za=Lt%2?o.a6-1:0;Ga=Qt(qr[0],Math.min(o.a6-1,qr[1]),Za,nn,Hs,Lt<2,qr[2])}xr.centroidXY=Re(Ga,Lt,Tr),Hr.centroidXY=Re(Ga,$s,Tr)}if(B.writeCentroidToBuffer(xr),Fs.writeCentroidToBuffer(Hr),An.buildingId!==void 0){for(const Ga of B.centroidData)Ga.buildingId===An.buildingId&&Ga!==xr&&(Ga.centroidXY=xr.centroidXY,B.writeCentroidToBuffer(Ga));for(const Ga of Fs.centroidData)Ga.buildingId===An.buildingId&&Ga!==Hr&&(Ga.centroidXY=Hr.centroidXY,Fs.writeCentroidToBuffer(Ga))}}for(const Rr of ps){if(Bn.has(Rr))continue;const An=B.featuresOnBorder[Rr],xr=B.centroidData.get(An.centroidDataIndex),sa=An.borders[Lt];let ka;for(;Mn<_n.length;){if(On.has(Mn)){Mn++;continue}ka=Fs.featuresOnBorder[_n[Mn]];const Hr=ka.borders[$s];if(Hr[1]>sa[0]+3||Hr[0]>sa[0]-3)break;Fs.showCentroid(ka,"keep"),Mn++}if(ka&&Mn<_n.length){let Hr=Mn,ea=0;for(;;)if(On.has(Mn)){if(++Mn===_n.length)break;ka=Fs.featuresOnBorder[_n[Mn]]}else{if(ka.borders[$s][0]>sa[1]-3||(ea++,++Mn===_n.length))break;ka=Fs.featuresOnBorder[_n[Mn]]}for(;Hr<_n.length&&On.has(Hr);)Hr++;if(Hr>=_n.length){B.showCentroid(An,"keep");continue}ka=Fs.featuresOnBorder[_n[Hr]];let si=!1;if(ea>=1){const Gr=ka.borders[$s];Math.abs(sa[0]-Gr[0])<3&&Math.abs(sa[1]-Gr[1])<3&&(ea=1,si=!0,Mn=Hr+1)}else if(ea===0){B.showCentroid(An,"keep");continue}const Wr=Fs.centroidData.get(ka.centroidDataIndex);oe&&si&&we(xr,Wr);const Tr=An.intersectsCount()>1||ka.intersectsCount()>1;if(ea>1)Mn=Hr,xr.centroidXY=Wr.centroidXY=new o.P(0,0);else if(nn&&nn.dem&&!Tr){const Gr=es[Lt](xr,Wr),Ga=Lt%2?o.a6-1:0,qr=Qt(Gr[0],Math.min(o.a6-1,Gr[1]),Ga,nn,Hs,Lt<2,Gr[2]);xr.centroidXY=Wr.centroidXY=Me(qr)}else if(Tr){const Gr=Q?void 0:Qe(Lt,An.borders,$s,ka.borders);Gr!==void 0?(xr.centroidXY=Re(0,Lt,Gr),Wr.centroidXY=Re(0,$s,Gr)):xr.centroidXY=Wr.centroidXY=new o.P(0,0)}else xr.centroidXY=B.encodeBorderCentroid(An),Wr.centroidXY=Fs.encodeBorderCentroid(ka);B.writeCentroidToBuffer(xr),Fs.writeCentroidToBuffer(Wr)}else B.showCentroid(An,"keep")}B.borderDoneWithNeighborZ[Lt]=Fs.canonical.z,Fs.borderDoneWithNeighborZ[$s]=B.canonical.z}(B.needsCentroidUpdate||!B.centroidVertexBuffer&&B.centroidVertexArray.length!==0)&&B.uploadCentroid(L)}const ln=[1,0,0],tn=[0,1,0],sr=[0,0,1];function nr(L,k,T){const B=T.transform,K=T.shadowRenderer;if(!K)return!0;const Q=T.frameCounter,oe=T.currentShadowCascade;let me=T._shadowCullCache;if(!me||me.frame!==Q||me.cascade!==oe){const es=B.tileSize*K._cascades[oe].scale,Qt=B.scaleZoom(es),Lt=K.shadowDirection,ps=[Lt[0],Lt[1],-Lt[2]],Hs=[ln,tn,sr,ps,[ps[0],0,ps[2]],[0,ps[1],ps[2]]];me={frame:Q,cascade:oe,cameraFrustum:o.aA.fromInvProjectionMatrix(B.invProjMatrix,B.worldSize,Qt,B.projection.name!=="globe"),edges:Hs,shadowDir:ps,ws:es,zoom:Qt},T._shadowCullCache=me}const{cameraFrustum:we,edges:Me,shadowDir:Re,ws:Ze,zoom:Qe}=me;let ut=k;if(B.elevation){const es=B.elevation.getMinMaxForTile(L);es&&(ut+=es.max)}ut/=o.aB(B.center.lat,Qe);const bt=K.computeSimplifiedTileShadowVolume(L.toUnwrapped(),ut,Ze,Re);if(!bt)return!1;const{vertices:vt,planes:Mt}=bt;return we.intersectsPrecise(vt,Mt,Me)===0||K.getCurrentCascadeFrustum().intersectsPrecise(vt,Mt,Me)===0}const Qr=new Float32Array(16),na=new Float32Array(16);function $a(L){const{painter:k,source:T,layer:B,coords:K}=L;let Q=L.defines;const oe=k.context,me=k.renderPass==="shadow",we=k.renderPass==="light-beam",Me=k.shadowRenderer,Re=o.aB(k.transform.center.lat,k.transform.zoom),Ze=o.aF(k,B.paint.get("building-cutoff-fade-range"));Ze.shouldRenderCutoff&&(Q=Q.concat("RENDER_CUTOFF"));const Qe=B.paint.get("building-front-cutoff"),ut=Qe[2]<1&&!k.terrain,bt=Vt(k.transform.pitch,Qe,!!k.terrain);ut&&(Q=Q.concat("RENDER_FRONT_CUTOFF"),k.maxFrontCutoffRawStart=Math.max(k.maxFrontCutoffRawStart,Qe[0])),L.floodLightIntensity>0&&(Q=Q.concat("FLOOD_LIGHT"));for(const vt of K){const Mt=T.getTile(vt),es=Mt.getBucket(B);if(!es)continue;Me&&Me.getMaxCascadeForTile(vt.toUnwrapped())===0&&(Q=Q.concat("SHADOWS_SINGLE_CASCADE"));const Qt=es.programConfigurations.get(B.id);let Lt,ps;const Hs=k.translatePosMatrix(vt.expandedProjMatrix,Mt,[0,0],"map");o.aO(Qr,Hs,[1,1,L.verticalScale]);const Fs=Qr;let nn;if(me&&Me){if(nr(Mt.tileID,es.maxHeight*Re,k))continue;const rn=Me.calculateShadowPassMatrixFromTile(Mt.tileID.toUnwrapped());o.aO(rn,rn,[1,1,L.verticalScale]),nn=tr(rn),Lt=ps=k.getOrCreateProgram("buildingDepth",{config:Qt,defines:Q,overrideFog:!1})}else if(we)Lt=ps=k.getOrCreateProgram("buildingBloom",{config:Qt,defines:Q,overrideFog:!1}),nn=er(Fs);else{const rn=k.transform.calculatePosMatrix(vt.toUnwrapped(),k.transform.worldSize);o.aO(rn,rn,[1,1,L.verticalScale]),o.aO(na,rn,[1,-1,1/Re]),o.aP(na,na),o.aQ(na,na);const _n=na,Mn=k.transform.getFreeCameraOptions().position,Kn=1<{if(we){const Mn=rn.entranceBloom;_n.draw(k,oe.gl.TRIANGLES,L.depthMode,o._.disabled,L.blendMode,o.$.disabled,nn,B.id,Mn.layoutVertexBuffer,Mn.indexBuffer,Mn.segmentsBucket,B.paint,k.transform.zoom,Qt,[Mn.layoutAttenuationBuffer,Mn.layoutColorBuffer])}else{const Mn=rn.segmentsBucket;let Kn=[rn.layoutNormalBuffer,rn.layoutCentroidBuffer,rn.layoutColorBuffer,rn.layoutFloodLightDataBuffer];rn.layoutFacadePaintBuffer&&(Kn=Kn.concat([rn.layoutFacadeDataBuffer,rn.layoutFacadeVerticalRangeBuffer,rn.layoutFacadePaintBuffer])),_n.draw(k,oe.gl.TRIANGLES,L.depthMode,o._.disabled,L.blendMode,me?o.$.disabled:o.$.backCW,nn,B.id,rn.layoutVertexBuffer,rn.indexBuffer,Mn,B.paint,k.transform.zoom,Qt,Kn)}};k.uploadCommonUniforms(oe,ps,vt.toUnwrapped(),null,Ze),es.buildingWithoutFacade&&$s(es.buildingWithoutFacade,ps),es.buildingWithFacade&&(Lt!==ps&&k.uploadCommonUniforms(oe,Lt,vt.toUnwrapped(),null,Ze),$s(es.buildingWithFacade,Lt))}}function Na(L,k,T,B,K,Q,oe,me,we,Me,Re,Ze,Qe,ut){const bt=L.context.gl,vt=L.depthModeForSublayer(1,o.Z.ReadOnly,bt.LEQUAL,!0),Mt=o.am(.1,3,Re),es=L._showOverdrawInspector,Qt=Ze,Lt=new et;if(!es){const ps=new o._({func:bt.ALWAYS,mask:255},255,255,bt.KEEP,bt.KEEP,bt.REPLACE),Hs=new o.a1([bt.ONE,bt.ONE,bt.ONE,bt.ONE],o.C.transparent,[!1,!1,!1,!0],bt.MIN);o.aR(Lt,L,k,T,B,vt,ps,Hs,o.$.disabled,K,"sdf",Q,oe,me,we,Me,Mt,Qt,!1,void 0)}{const ps=es?o._.disabled:new o._({func:bt.EQUAL,mask:255},255,255,bt.KEEP,bt.DECR,bt.DECR),Hs=es?L.colorModeForRenderPass():new o.a1([bt.ONE_MINUS_DST_ALPHA,bt.DST_ALPHA,bt.ONE,bt.ONE],o.C.transparent,[!0,!0,!0,!0]);o.aR(Lt,L,k,T,B,vt,ps,Hs,o.$.disabled,K,"color",Q,oe,me,we,Me,Mt,Qt,!1,void 0)}}class La{constructor(){this._previousClosestBuildingId=null,this._hysteresisRatio=.8,this._indoorMinimumZoom=16}findClosestBuilding(k,T,B,K,Q){if(Bwe*this._hysteresisRatio&&(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 me=this._convertRingToPoints(oe.coordinates[0]);if(o.aU(me,B))return!0}else if(oe.type==="MultiPolygon"){const me=this._convertMultiPolygonToPoints(oe.coordinates);if(o.aV(B,me))return!0}}return!1}_convertRingToPoints(k){return k.map(T=>new o.P(T[0],T[1]))}_convertMultiPolygonToPoints(k){return k.map(T=>T.length===0?[]:T[0].map(B=>new o.P(B[0],B[1])))}}const to=.05,xo=(L,k,T,B,K,Q,oe,me,we,Me,Re,Ze)=>({u_matrix:L,u_normalize_matrix:k,u_globe_matrix:T,u_merc_matrix:B,u_grid_matrix:K,u_tl_parent:Q,u_scale_parent:Me,u_fade_t:Re.mix,u_opacity:Re.opacity,u_image0:0,u_image1:1,u_raster_elevation:Ze,u_zoom_transition:oe,u_merc_center:me,u_cutoff_params:we}),oo=(L,k,T,B,K,Q,oe,me,we,Me)=>({u_particle_texture:L,u_particle_texture_side_len:k,u_tile_offset:T,u_velocity:B,u_color_ramp:Q,u_velocity_res:K,u_max_speed:oe,u_uv_offset:me,u_data_scale:[255*we[0],255*we[1]],u_data_offset:Me,u_particle_pos_scale:1.1,u_particle_pos_offset:[to,to]}),Lo=(L,k,T,B,K,Q,oe,me,we,Me)=>({u_particle_texture:L,u_particle_texture_side_len:k,u_velocity:T,u_velocity_res:B,u_max_speed:K,u_speed_factor:Q,u_reset_rate:oe,u_rand_seed:Math.random(),u_uv_offset:me,u_data_scale:[255*we[0],255*we[1]],u_data_offset:Me,u_particle_pos_scale:1.1,u_particle_pos_offset:[to,to]});function Ul(L,[k,T,B,K],[Q,oe]){if(Q===oe)return[0,0,0,0];const me=255*(L-1)/(L*(oe-Q));return[k*me,T*me,B*me,K*me]}function po(L,k,[T,B]){return T===B?0:.5/L+(k-T)*(L-1)/(L*(B-T))}var nl=o.a$([{name:"a_index",type:"Int16",components:1}]);class 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,me=k?(Q-k.timeAdded)/K:-1,we=T.getSource(),Me=B.coveringZoomLevel({tileSize:we.tileSize,roundZoom:we.roundZoom}),Re=!k||Math.abs(k.tileID.overscaledZ-Me)>Math.abs(L.tileID.overscaledZ-Me),Ze=Re&&L.refreshedUponExpiration?1:o.b1(Re?oe:1-me,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:me,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=po(o.ba,oe,[0,T.paint.get("raster-particle-max-speed")])),{texture:K,textureOffset:[we/(me+2*we),me/(me+2*we)],tileSize:me,scalarData:Re,scale:Q,offset:oe,defines:["RASTER_ARRAY",{uint8:"DATA_FORMAT_UINT8",uint16:"DATA_FORMAT_UINT16",uint32:"DATA_FORMAT_UINT32"}[Me]]}}function qt(L){const k=L._nearZ,T=L.projection.farthestPixelDistance(L),B=T-k,K=.2*L.height,Q=k+K;return[k,T,(Q-K-k)/B,(Q-k)/B]}var Cn=`#ifdef RASTER_ARRAY uniform sampler2D u_velocity;uniform mediump vec2 u_velocity_res;uniform mediump float u_max_speed;const vec4 NO_DATA=vec4(1);const vec2 INVALID_VELOCITY=vec2(-1);uniform highp vec2 u_uv_offset;uniform highp float u_data_offset;uniform highp vec2 u_data_scale;ivec4 rasterArrayLinearCoord(highp vec2 texCoord,highp vec2 texResolution,out highp vec2 fxy) {texCoord=texCoord*texResolution-0.5;fxy=fract(texCoord);texCoord-=fxy;return ivec4(texCoord.xxyy+vec2(1.5,0.5).xyxy);}highp vec2 lookup_velocity(highp vec2 uv) {uv=u_uv_offset.x+u_uv_offset.y*uv;highp vec2 fxy;ivec4 c=rasterArrayLinearCoord(uv,u_velocity_res,fxy);highp vec4 tl=texelFetch(u_velocity,c.yz,0);highp vec4 tr=texelFetch(u_velocity,c.xz,0);highp vec4 bl=texelFetch(u_velocity,c.yw,0);highp vec4 br=texelFetch(u_velocity,c.xw,0);if (tl==NO_DATA) {return INVALID_VELOCITY;}if (tr==NO_DATA) {return INVALID_VELOCITY;}if (bl==NO_DATA) {return INVALID_VELOCITY;}if (br==NO_DATA) {return INVALID_VELOCITY;}highp vec4 t=mix(mix(bl,br,fxy.x),mix(tl,tr,fxy.x),fxy.y);highp vec2 velocity=u_data_offset+vec2(dot(t.rg,u_data_scale),dot(t.ba,u_data_scale));velocity.y=-velocity.y;velocity/=max(u_max_speed,length(velocity));return velocity;} #endif uniform highp float u_particle_pos_scale;uniform highp vec2 u_particle_pos_offset;highp vec4 pack_pos_to_rgba(highp vec2 p) {highp vec2 v=(p+u_particle_pos_offset)/u_particle_pos_scale;highp vec4 r=vec4(v.x,fract(v.x*255.0),v.y,fract(v.y*255.0));return vec4(r.x-r.y/255.0,r.y,r.z-r.w/255.0,r.w);}highp vec2 unpack_pos_from_rgba(highp vec4 v) {v=floor(v*255.0+0.5)/255.0;highp vec2 p=vec2(v.x+(v.y/255.0),v.z+(v.w/255.0));return u_particle_pos_scale*p-u_particle_pos_offset;}`;o.bb["_prelude_raster_particle.glsl"]||(o.bb["_prelude_raster_particle.glsl"]=Cn);var rr={building:o.bc(`#include "_prelude_fog.fragment.glsl" #include "_prelude_shadow.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_indicator_cutout.fragment.glsl" #include "_prelude_feature_cutout.fragment.glsl" const float window_depth=0.5;const float ao_radius=0.2;in vec4 v_color;in highp vec3 v_normal;in highp vec3 v_pos; #if defined(RENDER_FRONT_CUTOFF) || defined(ROUTE_CORRIDOR) in float v_dither_opacity; #endif #ifdef BUILDING_FAUX_FACADE in lowp float v_faux_facade;in highp float v_faux_facade_ed;in highp vec2 v_faux_facade_window;in highp vec2 v_faux_facade_floor;in highp vec2 v_faux_facade_range;in highp float v_aspect;in highp vec3 v_tbn_0;in highp vec3 v_tbn_1;in highp vec3 v_tbn_2;in highp vec4 v_faux_color_emissive;uniform float u_faux_facade_ao_intensity; #endif #ifdef RENDER_SHADOWS in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1; #endif #ifdef FLOOD_LIGHT in highp float v_flood_radius;in float v_has_flood_light; #endif uniform lowp float u_opacity;uniform vec3 u_camera_pos;uniform highp float u_tile_to_meter;uniform float u_facade_emissive_chance;uniform vec3 u_flood_light_color;uniform float u_flood_light_intensity;vec3 linearTosRGB(in vec3 color) {return pow(color,vec3(1./2.2));} #ifdef BUILDING_FAUX_FACADE highp float hash12(in highp vec2 p) {highp vec3 p3 =fract(vec3(p.xyx)*0.1031);p3+=dot(p3,p3.yzx+33.33);return fract((p3.x+p3.y)*p3.z);}float min3(in vec3 v) {return min(min(v.x,v.y),v.z);}highp vec2 get_uv_mask_id(in highp vec2 q,out highp float mask,out highp vec2 id) {highp vec2 p=q;mask=step(v_faux_facade_range.x,p.y)*step(p.y,v_faux_facade_range.y);p.y=p.y-v_faux_facade_range.x;highp vec2 uv=modf(p/v_faux_facade_floor,id);highp vec4 d=(v_faux_facade_floor.xyxy+vec4(-v_faux_facade_window,v_faux_facade_window))*0.5;highp vec4 edge=d/v_faux_facade_floor.xyxy;highp vec2 m=step(edge.xy,uv)*step(uv,edge.zw);mask*=m.x*m.y;uv-=vec2(0.5);uv*=vec2(0.5)/(vec2(0.5)-edge.xy);uv+=vec2(0.5);return uv;}highp float ray_unit_box(in highp vec3 ray_o,in highp vec3 ray_d,in highp vec3 bmin,in highp vec3 bmax) {highp vec3 planes=mix(bmin,bmax,step(0.0,ray_d));highp vec3 t=(planes-ray_o)/ray_d;return min3(t);}float get_emissive(in vec2 id) {if (u_facade_emissive_chance > 0.0) {return (step(hash12(id),u_facade_emissive_chance)+0.05)*v_faux_color_emissive.a;}return 0.0;}vec3 get_shade_info(in highp vec3 v,in highp vec3 v_normalized,in vec3 color,in vec2 id,in mat3 tbn,inout vec3 out_normal,inout float out_emissive) {vec3 out_color=color;highp vec3 abs_v=abs(v_normalized);bool x_major=abs_v.x >=abs_v.y && abs_v.x >=abs_v.z;bool y_major=abs_v.y >=abs_v.x && abs_v.y >=abs_v.z;bool z_major=abs_v.z >=abs_v.x && abs_v.z >=abs_v.y;if (x_major) {out_normal=-sign(v.x)*tbn[0];} else if (y_major) {out_normal=vec3(0.0,0.0,-sign(v.y));} else if (z_major) {out_color=v_faux_color_emissive.rgb;out_emissive=v.z <=0.0 ? get_emissive(id) : out_emissive;}float ao=1.0;if (u_faux_facade_ao_intensity > 0.0) {vec4 ao_range=v_faux_facade_window.xxyy*0.5-vec4(0,ao_radius,0,ao_radius);vec2 ao_range_z=vec2(window_depth*0.5)-vec2(0.0,ao_radius);if (x_major || y_major) {ao*=smoothstep(-ao_range_z.x,-ao_range_z.y,v.z);} else if (z_major) {ao*=smoothstep(-ao_range.x,-ao_range.y,v.x)*(1.0-smoothstep(ao_range.y,ao_range.x,v.x));ao*=smoothstep(-ao_range.z,-ao_range.w,v.y)*(1.0-smoothstep(ao_range.w,ao_range.z,v.y));}ao=mix(1.0,min(1.0,ao+0.25),u_faux_facade_ao_intensity);}out_color*=ao;return out_color;} #endif vec3 apply_lighting_linear(in vec3 color,in vec3 normal,in float dir_factor) {float ambient_directional_factor=calculate_ambient_directional_factor(normal);vec3 ambient_contrib=ambient_directional_factor*u_lighting_ambient_color;vec3 directional_contrib=u_lighting_directional_color*dir_factor;return color*(ambient_contrib+directional_contrib);}void main() {vec3 normal=normalize(v_normal);vec3 base_color=v_color.rgb;float emissive=v_color.a; #ifdef BUILDING_FAUX_FACADE if (v_faux_facade > 0.0) {highp mat3 tbn=mat3(v_tbn_0,v_tbn_1,v_tbn_2);highp vec3 v=vec3(v_pos.xy,v_pos.z/u_tile_to_meter)-u_camera_pos;highp vec3 view_tangent=transpose(tbn)*v;highp vec2 q=vec2(v_faux_facade_ed,v_pos.z);float mask=0.0;vec2 id=vec2(0.0);highp vec2 uv=get_uv_mask_id(q,mask,id);uv*=v_faux_facade_window;highp vec3 bmin=vec3(0.0,0.0,-window_depth);highp vec3 bmax=bmin+vec3(v_faux_facade_window,window_depth);highp vec3 ray_o=vec3(uv,0.0);highp vec3 ray_d=normalize(view_tangent);highp float t_min=ray_unit_box(ray_o,ray_d,bmin,bmax);highp vec3 hit=ray_o+t_min*ray_d;highp vec3 r=vec3(v_faux_facade_window,-window_depth);hit-=r*0.5;highp vec3 normalized=hit/r;vec3 out_normal=normal;float out_emissive=emissive;vec3 room_color=get_shade_info(hit,normalized,base_color,id,tbn,out_normal,out_emissive);base_color=mix(base_color,room_color,mask);normal=mix(normal,out_normal,mask);emissive=mix(emissive,out_emissive,mask);} #endif vec4 color=vec4(base_color,1.0);vec3 xy_flipped_normal=vec3(-normal.xy,normal.z);float shadowed_lighting_factor=0.0; #ifdef RENDER_SHADOWS #ifdef RENDER_CUTOFF shadowed_lighting_factor=shadowed_light_factor_normal_opacity(xy_flipped_normal,v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w,v_cutoff_opacity);if (v_cutoff_opacity==0.0) {discard;} #else shadowed_lighting_factor=shadowed_light_factor_normal(xy_flipped_normal,v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w); #endif #else shadowed_lighting_factor=max(0.0,dot(xy_flipped_normal,u_lighting_directional_dir)); #endif color.rgb=apply_lighting_linear(color.rgb,xy_flipped_normal,shadowed_lighting_factor);color.rgb=linearTosRGB(color.rgb); #ifdef FLOOD_LIGHT float flood_radiance=(1.0-min(v_pos.z/v_flood_radius,1.0))*u_flood_light_intensity*v_has_flood_light;color.rgb=mix(color.rgb,u_flood_light_color,flood_radiance); #endif color.rgb=mix(color.rgb,linearTosRGB(base_color.rgb),emissive); #ifdef FOG color=fog_dither(fog_apply_premultiplied(color,v_fog_pos,v_pos.z)); #endif color*=u_opacity; #if defined(RENDER_FRONT_CUTOFF) || defined(ROUTE_CORRIDOR) if (v_dither_opacity < 1.0) {int index=viewport_dither_index(gl_FragCoord.xy);if (v_dither_opacity < DITHER_THRESHOLDS[index]) {discard;}} #endif glFragColor=color; #ifdef DEBUG_SHOW_NORMALS color.rgb=xy_flipped_normal*0.5+vec3(0.5,0.5,0.5);color.a=1.0;glFragColor=color; #endif #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_shadow.vertex.glsl" #include "_prelude_feature_cutout.vertex.glsl" in vec3 a_pos_3f;in ivec4 a_normal_3;in ivec4 a_centroid_3; #ifdef FLOOD_LIGHT in int a_flood_light_wall_radius_1i16; #endif #ifdef BUILDING_FAUX_FACADE in uvec4 a_faux_facade_data;in uvec2 a_faux_facade_vertical_range; #endif uniform mat4 u_matrix;uniform mat4 u_normal_matrix;uniform highp float u_tile_to_meter; #if defined(RENDER_FRONT_CUTOFF) || defined(ROUTE_CORRIDOR) #ifdef RENDER_FRONT_CUTOFF uniform vec3 u_front_cutoff_params; #endif out float v_dither_opacity; #endif out vec4 v_color;out vec3 v_normal;out highp vec3 v_pos; #ifdef BUILDING_FAUX_FACADE out lowp float v_faux_facade;out highp float v_faux_facade_ed;out highp vec2 v_faux_facade_window;out highp vec2 v_faux_facade_floor;out highp vec2 v_faux_facade_range;out highp float v_aspect;out highp vec3 v_tbn_0;out highp vec3 v_tbn_1;out highp vec3 v_tbn_2;out highp vec4 v_faux_color_emissive; #endif #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1; #endif #ifdef FLOOD_LIGHT out highp float v_flood_radius;out float v_has_flood_light; #endif const float MAX_UINT_16=65535.0;const float MAX_INT_16=32767.0;const float MAX_UINT_8=255.0;const float TWO_POW_8=256.0;const float FLOOD_LIGHT_MAX_RADIUS_METER=2048.0;vec3 sRGBToLinear(vec3 srgbIn) {return pow(srgbIn,vec3(2.2));} #ifdef BUILDING_FAUX_FACADE mat3 get_tbn(in vec3 normal) {const vec3 bitangent=vec3(0.0,0.0,1.0);vec3 tangent=normalize(vec3(normal.y,-normal.x,0.0));return mat3(tangent,bitangent,normal);} #endif #pragma mapbox: define-attribute-vertex-shader-only highp uvec2 part_color_emissive #pragma mapbox: define-attribute-vertex-shader-only highp uvec2 faux_facade_color_emissive void main() { #pragma mapbox: initialize-attribute-custom highp uvec2 part_color_emissive #pragma mapbox: initialize-attribute-custom highp uvec2 faux_facade_color_emissive #ifdef FLOOD_LIGHT v_flood_radius=(float(a_flood_light_wall_radius_1i16)/MAX_INT_16*FLOOD_LIGHT_MAX_RADIUS_METER);v_has_flood_light=step(0.0,v_flood_radius); #endif vec4 color_emissive=decode_color(vec2(part_color_emissive));v_color=vec4(sRGBToLinear(color_emissive.rgb),color_emissive.a);vec3 a_normal_3f=vec3(a_normal_3)/MAX_INT_16;v_normal=vec3(u_normal_matrix*vec4(a_normal_3f,0.0));float hidden=0.0;float depth_offset=0.0;float frontCutoffOpacity=1.0;float routeFade=0.0;vec2 centroid_xy=vec2(a_centroid_3.xy >> 2);vec2 spanBits=vec2(a_centroid_3.xy & 3); #ifdef BUILDING_FAUX_FACADE vec4 faux_facade_data=vec4(a_faux_facade_data);v_faux_facade=faux_facade_data.x;if (v_faux_facade > 0.0) {v_faux_facade_ed=faux_facade_data.x *u_tile_to_meter;float window_x_perc=floor(faux_facade_data.y/TWO_POW_8);float window_y_perc=faux_facade_data.y-TWO_POW_8*window_x_perc;vec2 window_perc=vec2(window_x_perc,window_y_perc)/MAX_UINT_8;v_faux_facade_floor=(faux_facade_data.zw/MAX_UINT_16*EXTENT)*u_tile_to_meter;v_faux_facade_window=window_perc*v_faux_facade_floor;v_faux_facade_range=(vec2(a_faux_facade_vertical_range)/MAX_UINT_16*EXTENT)*u_tile_to_meter;v_aspect=v_faux_facade_window.x/v_faux_facade_window.y;mat3 tbn=get_tbn(normalize(v_normal));v_tbn_0=tbn[0];v_tbn_1=tbn[1];v_tbn_2=tbn[2];v_faux_color_emissive=decode_color(vec2(faux_facade_color_emissive));v_faux_color_emissive.rgb=sRGBToLinear(v_faux_color_emissive.rgb);depth_offset=min(1000.0,float(a_centroid_3.z))*0.0000002;} #endif v_pos=a_pos_3f; #if defined(RENDER_CUTOFF) || defined(RENDER_FRONT_CUTOFF) float halfSpanX=spanBits.x*10.0/u_tile_to_meter;float halfSpanY=spanBits.y*10.0/u_tile_to_meter;vec2 screenUpInTile=vec2(u_matrix[0][1],u_matrix[1][1]);vec2 spanOffset=vec2(halfSpanX,halfSpanY)*sign(screenUpInTile);vec2 cutoff_highestCorner=centroid_xy+spanOffset;vec2 cutoff_lowestCorner=centroid_xy-spanOffset; #endif #if defined(RENDER_CUTOFF) || defined(RENDER_FRONT_CUTOFF) vec4 ground=u_matrix*vec4(centroid_xy,0.0,1.0); #endif #ifdef RENDER_CUTOFF v_cutoff_opacity=cutoff_opacity(u_cutoff_params,ground.z);hidden=float(v_cutoff_opacity==0.0);v_pos.z*=v_cutoff_opacity; #endif #ifdef RENDER_SHADOWS vec3 shadow_pos=v_pos; #ifdef NORMAL_OFFSET vec3 offset=shadow_normal_offset_model(v_normal);shadow_pos+=offset*shadow_normal_offset_multiplier0(); #endif v_pos_light_view_0=u_light_matrix_0*vec4(shadow_pos,1.0);v_pos_light_view_1=u_light_matrix_1*vec4(shadow_pos,1.0); #endif #ifdef FOG v_fog_pos=fog_position(v_pos); #endif #ifdef RENDER_FRONT_CUTOFF {hidden=max(hidden,float(ground.w <=0.0));float ndc_y=ground.y/max(ground.w,0.001);float threshold=u_front_cutoff_params.x*2.0-1.0;float range_ndc=u_front_cutoff_params.y*2.0;hidden=max(hidden,float(ndc_y < threshold-range_ndc));float t=clamp((ndc_y-(threshold-range_ndc))/max(range_ndc,0.001),0.0,1.0);frontCutoffOpacity=mix(u_front_cutoff_params.z,1.0,t);} #endif gl_Position=mix(u_matrix*vec4(v_pos,1),AWAY,hidden);gl_Position.z-=depth_offset*gl_Position.w; #if defined(RENDER_FRONT_CUTOFF) || defined(ROUTE_CORRIDOR) v_dither_opacity=1.0; #ifdef RENDER_FRONT_CUTOFF v_dither_opacity=min(v_dither_opacity,frontCutoffOpacity); #endif #endif }`),buildingBloom:o.bc(`in vec4 v_color_emissive; #pragma mapbox: define-attribute highp vec4 bloom_attenuation float saturate(float val) {return clamp(val,0.0,1.0);}void main() { #pragma mapbox: initialize-attribute highp vec4 bloom_attenuation float emission=v_color_emissive.a;float opacity=1.0; #ifdef HAS_ATTRIBUTE_a_bloom_attenuation float distance=length(vec2(1.3*max(0.0,abs(bloom_attenuation.x)-bloom_attenuation.z),bloom_attenuation.y));distance+= mix(0.5,0.0,clamp(emission-1.0,0.0,1.0));opacity*=saturate(1.0-distance*distance); #endif #ifdef RENDER_CUTOFF opacity*=v_cutoff_opacity; #endif glFragColor=vec4(v_color_emissive.rgb,1.0)*opacity;}`,`in vec3 a_pos_3f; #pragma mapbox: define-attribute-vertex-shader-only highp uvec2 part_color_emissive #pragma mapbox: define-attribute highp vec4 bloom_attenuation out vec4 v_color_emissive;uniform mat4 u_matrix;vec3 sRGBToLinear(vec3 srgbIn) {return pow(srgbIn,vec3(2.2));}void main() { #pragma mapbox: initialize-attribute-custom highp uvec2 part_color_emissive #pragma mapbox: initialize-attribute highp vec4 bloom_attenuation #ifdef HAS_ATTRIBUTE_a_part_color_emissive vec4 color_emissive=decode_color(vec2(part_color_emissive));float part_emissive=color_emissive.a*5.0;v_color_emissive=vec4(sRGBToLinear(color_emissive.rgb),part_emissive); #else v_color_emissive=vec4(1.0); #endif gl_Position=u_matrix*vec4(a_pos_3f,1.0); #ifdef RENDER_CUTOFF v_cutoff_opacity=cutoff_opacity(u_cutoff_params,gl_Position.z); #endif }`),buildingDepth:o.bc("void main() {}","in vec3 a_pos_3f;uniform mat4 u_matrix;void main() {gl_Position=u_matrix*vec4(a_pos_3f,1.0);}"),rasterParticle:o.bc(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" uniform float u_fade_t;uniform float u_opacity;uniform highp float u_raster_elevation;in vec2 v_pos0;in vec2 v_pos1;uniform sampler2D u_image0;uniform sampler2D u_image1;void main() {vec4 color0,color1,color;color0=texture(u_image0,v_pos0);color1=texture(u_image1,v_pos1);if (color0.a > 0.0) color0.rgb/=color0.a;if (color1.a > 0.0) color1.rgb/=color1.a;color=mix(color0,color1,u_fade_t);color.a*=u_opacity;vec3 out_color=color.rgb; #ifdef LIGHTING_3D_MODE out_color=apply_lighting_with_emission_ground(vec4(out_color,1.0),1.0).rgb; #endif #ifdef FOG highp float fog_limit_high_meters=1000000.0;highp float fog_limit_low_meters=600000.0;float fog_limit=1.0-smoothstep(fog_limit_low_meters,fog_limit_high_meters,u_raster_elevation);out_color=fog_dither(fog_apply(out_color,v_fog_pos,fog_limit)); #endif glFragColor=vec4(out_color*color.a,color.a); #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" uniform mat4 u_matrix;uniform mat4 u_normalize_matrix;uniform mat4 u_globe_matrix;uniform mat4 u_merc_matrix;uniform mat3 u_grid_matrix;uniform vec2 u_tl_parent;uniform float u_scale_parent;uniform float u_raster_elevation;uniform float u_zoom_transition;uniform vec2 u_merc_center; #define GLOBE_UPSCALE GLOBE_RADIUS/6371008.8 in ivec2 a_pos;in uvec2 a_texture_pos;out vec2 v_pos0;out vec2 v_pos1;void main() {float w=1.0;vec2 uv; #ifdef PROJECTION_GLOBE_VIEW vec3 decomposed_pos_and_skirt=decomposeToPosAndSkirt(a_pos);vec3 latLng=u_grid_matrix*vec3(decomposed_pos_and_skirt.xy,1.0);float mercatorY=mercatorYfromLat(latLng[0]);float mercatorX=mercatorXfromLng(latLng[1]);float tiles=u_grid_matrix[0][2];float idx=u_grid_matrix[1][2];float idy=u_grid_matrix[2][2];float uvX=mercatorX*tiles-idx;float uvY=mercatorY*tiles-idy;uv=vec2(uvX,uvY);vec3 globe_pos=latLngToECEF(latLng.xy);globe_pos+=normalize(globe_pos)*u_raster_elevation*GLOBE_UPSCALE;vec4 globe_world_pos=u_globe_matrix*vec4(globe_pos,1.0);vec4 merc_world_pos=vec4(0.0);if (u_zoom_transition > 0.0) {vec2 merc_pos=vec2(mercatorX,mercatorY);merc_world_pos=vec4(merc_pos,u_raster_elevation,1.0);merc_world_pos.xy-=u_merc_center;merc_world_pos.x=wrap(merc_world_pos.x,-0.5,0.5);merc_world_pos=u_merc_matrix*merc_world_pos;}vec4 interpolated_pos=vec4(mix(globe_world_pos.xyz,merc_world_pos.xyz,u_zoom_transition)*w,w);gl_Position=u_matrix*interpolated_pos; #ifdef FOG v_fog_pos=fog_position((u_normalize_matrix*vec4(globe_pos,1.0)).xyz); #endif #else uv=vec2(a_texture_pos)/8192.0;gl_Position=u_matrix*vec4(vec2(a_pos)*w,u_raster_elevation*w,w); #ifdef FOG v_fog_pos=fog_position(vec2(a_pos)); #endif #endif v_pos0=uv;v_pos1=(v_pos0*u_scale_parent)+u_tl_parent;}`),rasterParticleDraw:o.bc("uniform sampler2D u_color_ramp;in float v_particle_speed;void main() {glFragColor=texture(u_color_ramp,vec2(v_particle_speed,0.5));}",`#include "_prelude_raster_particle.glsl" in int a_index;uniform sampler2D u_particle_texture;uniform float u_particle_texture_side_len;uniform vec2 u_tile_offset;out float v_particle_speed;void main() {ivec2 pixel_coord=ivec2( mod(float(a_index),u_particle_texture_side_len),float(a_index)/u_particle_texture_side_len);vec4 pixel=texelFetch(u_particle_texture,pixel_coord,0);vec2 pos=unpack_pos_from_rgba(pixel)+u_tile_offset;vec2 tex_coord=fract(pos);vec2 velocity=lookup_velocity(tex_coord);if (velocity==INVALID_VELOCITY) {gl_Position=AWAY;v_particle_speed=0.0;} else {gl_Position=vec4(2.0*pos-1.0,0,1);v_particle_speed=length(velocity);}gl_PointSize=1.0;}`),rasterParticleTexture:o.bc("uniform sampler2D u_texture;uniform float u_opacity;in vec2 v_tex_pos;void main() {vec4 color=texture(u_texture,v_tex_pos);glFragColor=vec4(floor(255.0*color*u_opacity)/255.0);}","in ivec2 a_pos;out vec2 v_tex_pos;void main() {vec2 uv=0.5*vec2(a_pos)+vec2(0.5);v_tex_pos=uv;gl_Position=vec4(a_pos,0.0,1.0);}"),rasterParticleUpdate:o.bc(`#include "_prelude_raster_particle.glsl" uniform sampler2D u_particle_texture;uniform mediump float u_particle_texture_side_len;uniform mediump float u_speed_factor;uniform highp float u_reset_rate;uniform highp float u_rand_seed;in highp vec2 v_tex_coord;vec2 linearstep(vec2 edge0,vec2 edge1,vec2 x) {return clamp((x-edge0)/(edge1-edge0),vec2(0),vec2(1));}const highp vec3 rand_constants=vec3(12.9898,78.233,4375.85453);highp float rand(const highp vec2 co) {highp float t=dot(rand_constants.xy,co);return fract(sin(t)*(rand_constants.z+t));}void main() {ivec2 pixel_coord=ivec2(v_tex_coord*u_particle_texture_side_len);highp vec4 pixel=texelFetch(u_particle_texture,pixel_coord,0);highp vec2 pos=unpack_pos_from_rgba(pixel);highp vec2 velocity=lookup_velocity(clamp(pos,0.0,1.0));highp vec2 dp=velocity==INVALID_VELOCITY ? vec2(0) : velocity*u_speed_factor;pos=pos+dp;highp vec2 seed=(pos+v_tex_coord)*u_rand_seed;highp vec2 random_pos=vec2(rand(seed+1.3),rand(seed+2.1));highp vec2 persist_rate=pow( linearstep(vec2(-u_particle_pos_offset),vec2(0),pos)*linearstep(vec2(1.0+u_particle_pos_offset),vec2(1),pos),vec2(4) );highp vec2 per_frame_persist=pow(persist_rate,abs(dp)/u_particle_pos_offset);highp float drop_rate=1.0-per_frame_persist.x*per_frame_persist.y;drop_rate=any(greaterThanEqual(abs(pos-0.5),vec2(0.5+u_particle_pos_offset))) ? 1.0 : drop_rate;highp float drop=step(1.0-drop_rate-u_reset_rate,rand(seed));highp vec2 next_pos=mix(pos,random_pos,drop);glFragColor=pack_pos_to_rgba(next_pos);}`,"in ivec2 a_pos;out vec2 v_tex_coord;void main() {v_tex_coord=0.5*vec2(a_pos+ivec2(1));gl_Position=vec4(a_pos,0.0,1.0);}"),snowParticle:o.bc("in highp vec2 uv;in highp float alphaMultiplier;uniform vec4 u_particleColor;uniform vec2 u_simpleShapeParameters;void main() {float t=clamp((length(uv)-u_simpleShapeParameters.x)/(1.0-u_simpleShapeParameters.x),0.0,1.0);float alpha=1.0-pow(t,pow(10.0,u_simpleShapeParameters.y));alpha*=alphaMultiplier;alpha*=u_particleColor.a;vec3 color=u_particleColor.rgb*alpha;glFragColor=vec4(color,alpha) ;HANDLE_WIREFRAME_DEBUG;}",` in highp vec3 a_pos_3f;in highp vec2 a_uv;in highp vec4 a_snowParticleData;in highp vec4 a_snowParticleDataHorizontalOscillation;uniform mat4 u_modelview;uniform mat4 u_projection;uniform vec3 u_cam_pos;uniform vec2 u_screenSize;uniform float u_time;uniform float u_boxSize;uniform float u_velocityConeAperture; uniform float u_velocity;uniform vec3 u_direction;uniform float u_horizontalOscillationRadius; uniform float u_horizontalOscillationRate; uniform float u_billboardSize;uniform vec2 u_thinningCenterPos;uniform vec3 u_thinningShape;uniform float u_thinningAffectedRatio;uniform float u_thinningParticleOffset;out highp vec2 uv;out highp float alphaMultiplier;void main() {vec3 pos=a_pos_3f;float halfBoxSize=0.5*u_boxSize;pos.xyz*=halfBoxSize;pos+=u_cam_pos;float velocityConeApertureRad=radians(u_velocityConeAperture*0.5);float coneAnglePichRad=velocityConeApertureRad*a_snowParticleData.z;float coneAngleHeadingRad=a_snowParticleData.w*radians(360.0);vec3 localZ=normalize(u_direction);vec3 localX=normalize(cross(localZ,vec3(1,0,0)));vec3 localY=normalize(cross(localZ,localX));vec3 direction;direction.x=cos(coneAngleHeadingRad)*sin(coneAnglePichRad);direction.y=sin(coneAngleHeadingRad)*sin(coneAnglePichRad);direction.z=cos(coneAnglePichRad);direction=normalize(direction);vec3 simPosLocal=vec3(0,0,0);float velocityScale=(1.0+3.0*a_snowParticleData.y)*u_velocity;simPosLocal+=direction*velocityScale*u_time;float horizontalOscillationRadius=u_horizontalOscillationRadius*a_snowParticleDataHorizontalOscillation.x;float horizontalOscillationAngle=u_horizontalOscillationRate*u_time*(-1.0+2.0*a_snowParticleDataHorizontalOscillation.y);simPosLocal.xy+=horizontalOscillationRadius*vec2(cos(horizontalOscillationAngle),sin(horizontalOscillationAngle));vec3 simPos=localX*simPosLocal.x+ localY*simPosLocal.y+localZ*simPosLocal.z;pos+=simPos;pos=fract((pos+vec3(halfBoxSize))/vec3(u_boxSize))*u_boxSize-vec3(halfBoxSize);float clipZ=-u_cam_pos.z+pos.z;vec4 posView=u_modelview*vec4(pos,1.0);float size=u_billboardSize;alphaMultiplier=1.0;vec4 posScreen=u_projection*posView;posScreen/=posScreen.w;posScreen.xy=vec2(0.5)+posScreen.xy*0.5;posScreen.xy*=u_screenSize;vec2 thinningCenterPos=u_thinningCenterPos.xy;thinningCenterPos.y=u_screenSize.y-thinningCenterPos.y;float screenDist=length((thinningCenterPos-posScreen.xy)/(0.5*u_screenSize));screenDist+=a_snowParticleData.x*u_thinningParticleOffset;float scaleFactorMode=0.0;float thinningShapeDist=u_thinningShape.x+u_thinningShape.y;if (screenDist < thinningShapeDist) {float thinningFadeRatio=clamp((screenDist-u_thinningShape.x)/u_thinningShape.y,0.0,1.0);thinningFadeRatio=pow(thinningFadeRatio,u_thinningShape.z);if (a_snowParticleData.x < u_thinningAffectedRatio) {scaleFactorMode=1.0-thinningFadeRatio;alphaMultiplier=thinningFadeRatio;}}vec4 posScreen1=u_projection*vec4(posView.x-size,posView.yzw);posScreen1/=posScreen1.w;vec4 posScreen2=u_projection*vec4(posView.x+size,posView.yzw);posScreen2/=posScreen2.w;posScreen1.xy=vec2(0.5)+posScreen1.xy*0.5;posScreen1.xy*=u_screenSize;posScreen2.xy=vec2(0.5)+posScreen2.xy*0.5;posScreen2.xy*=u_screenSize;float screenLength=length(posScreen1.xy-posScreen2.xy);float screenEpsilon=3.0;float scaleFactor=1.0;if (screenLength < screenEpsilon) {scaleFactor=screenEpsilon/max(screenLength,0.01);scaleFactor=mix(scaleFactor,1.0,scaleFactorMode);}float screenEpsilon2=15.0;if (screenLength > screenEpsilon2) {scaleFactor=screenEpsilon2/max(screenLength,0.01);}size*=scaleFactor;vec2 right=size*vec2(1,0);vec2 up=size*vec2(0,1);posView.xy+=right*a_uv.x;posView.xy+=up*a_uv.y;uv=a_uv;gl_Position=u_projection*posView;}`),rainParticle:o.bc("in highp vec2 uv;in highp float particleRandomValue;uniform sampler2D u_texScreen;uniform float u_distortionStrength;uniform vec4 u_color;uniform vec2 u_thinningCenterPos;uniform vec3 u_thinningShape;uniform float u_thinningAffectedRatio;uniform float u_thinningParticleOffset;uniform float u_shapeDirectionalPower;uniform float u_mode;void main() {vec2 st=uv*0.5+vec2(0.5);vec2 uvm=uv;uvm.y=-1.0+2.0*pow(st.y,u_shapeDirectionalPower);float shape=clamp(1.0-length(uvm),0.0,1.0);float alpha=abs(shape)*u_color.a;vec2 screenSize=vec2(textureSize(u_texScreen,0));vec2 thinningCenterPos=u_thinningCenterPos.xy;thinningCenterPos.y=screenSize.y-thinningCenterPos.y;float screenDist=length((thinningCenterPos-gl_FragCoord.xy)/(0.5*screenSize));screenDist+=(0.5+0.5*particleRandomValue)*u_thinningParticleOffset;float thinningShapeDist=u_thinningShape.x+u_thinningShape.y;float thinningAlpha=1.0;if (screenDist < thinningShapeDist) {float thinningFadeRatio=clamp((screenDist-u_thinningShape.x)/u_thinningShape.y,0.0,1.0);thinningFadeRatio=pow(thinningFadeRatio,u_thinningShape.z);thinningAlpha*=thinningFadeRatio;}vec2 offsetXY=normalize(uvm)*abs(shape);vec2 stScreen=(gl_FragCoord.xy+offsetXY*u_distortionStrength*thinningAlpha)/screenSize;vec3 colorScreen=texture(u_texScreen,stScreen).rgb;alpha*=thinningAlpha;glFragColor=mix(vec4(colorScreen,1.0),vec4(u_color.rgb*alpha,alpha),u_mode);HANDLE_WIREFRAME_DEBUG;}",` in highp vec3 a_pos_3f;in highp vec2 a_uv;in highp vec4 a_rainParticleData;uniform mat4 u_modelview;uniform mat4 u_projection;uniform vec3 u_cam_pos;uniform float u_time;uniform float u_boxSize;uniform float u_velocityConeAperture; uniform float u_velocity; uniform vec2 u_rainDropletSize;uniform vec3 u_rainDirection;out highp vec2 uv;out highp float particleRandomValue;void main() {vec3 pos=a_pos_3f;float halfBoxSize=0.5*u_boxSize;pos*=halfBoxSize; pos+=u_cam_pos;float velocityConeApertureRad=radians(u_velocityConeAperture*0.5);float coneAnglePichRad=velocityConeApertureRad*a_rainParticleData.z;float coneAngleHeadingRad=a_rainParticleData.w*radians(360.0);vec3 localZ=normalize(u_rainDirection);vec3 localX=normalize(cross(localZ,vec3(1,0,0)));vec3 localY=normalize(cross(localZ,localX));vec3 directionLocal;directionLocal.x=cos(coneAngleHeadingRad)*sin(coneAnglePichRad);directionLocal.y=sin(coneAngleHeadingRad)*sin(coneAnglePichRad);directionLocal.z=cos(coneAnglePichRad);directionLocal=normalize(directionLocal);vec3 directionWorld=localX*directionLocal.x+localY*directionLocal.y+localZ*directionLocal.z;float velocityScale=(1.0+3.0*a_rainParticleData.y)*u_velocity;vec3 simPosLocal=vec3(0,0,0);simPosLocal+=directionLocal*velocityScale*u_time;vec3 simPos=localX*simPosLocal.x+ localY*simPosLocal.y+localZ*simPosLocal.z;pos+=simPos;pos=fract((pos+vec3(halfBoxSize))/vec3(u_boxSize))*u_boxSize-vec3(halfBoxSize);vec4 posView=u_modelview*vec4(pos,1.0);vec3 directionView=normalize((u_modelview*vec4(directionWorld,0.0)).xyz);vec3 side=cross(directionView,normalize(posView.xyz));posView.xyz+=side*a_uv.x*u_rainDropletSize.x;posView.xyz+=directionView*a_uv.y*u_rainDropletSize.y;uv=a_uv;particleRandomValue=a_rainParticleData.x;gl_Position=u_projection*posView;}`),vignette:o.bc("uniform vec3 u_vignetteShape;uniform vec4 u_vignetteColor;in vec2 st;void main() {float screenDist=length(st);float alpha=clamp((screenDist-u_vignetteShape.x)/u_vignetteShape.y,0.0,1.0);alpha=pow(alpha,u_vignetteShape.z)*u_vignetteColor.a;vec3 color=u_vignetteColor.rgb;glFragColor=vec4(color*alpha,alpha) ;}","in vec2 a_pos_2f;out vec2 st;void main() {st=a_pos_2f;gl_Position=vec4(a_pos_2f,0,1);}"),elevatedStructuresDepth:o.bc("void main() {}","in ivec2 a_pos;in float a_height;uniform mat4 u_matrix;uniform float u_depth_bias;void main() {gl_Position=u_matrix*vec4(a_pos,a_height,1);gl_Position.z=gl_Position.z+u_depth_bias;}"),elevatedStructures:o.bc(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" #include "_prelude_indicator_cutout.fragment.glsl" #include "_prelude_feature_cutout.fragment.glsl" in vec3 v_normal;in float v_height; #ifdef RENDER_SHADOWS in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1;in float v_depth; #endif vec3 linearTosRGB(vec3 color) {return pow(color,vec3(1./2.2));}vec3 sRGBToLinear(vec3 srgbIn) {return pow(srgbIn,vec3(2.2));}vec3 compute_view_dependent_emissive_color(float ndotl,float emissive_strength,vec3 color) {color=sRGBToLinear(color);color=color*(ndotl+(1.0-min(ndotl*57.29,1.0))*emissive_strength);color=linearTosRGB(color.rgb);return color;}uniform float u_emissive_strength;uniform float u_opacity_multiplier; #pragma mapbox: define highp vec4 structure_color void main() { #pragma mapbox: initialize highp vec4 structure_color vec3 color=structure_color.xyz;vec2 cutout_factors=vec2(0.0); #ifdef LIGHTING_3D_MODE vec3 normal=normalize(v_normal);vec3 transformed_normal=vec3(-normal.xy,normal.z);float ndotl=calculate_NdotL(transformed_normal);float emissive_strength=u_emissive_strength;emissive_strength=0.0;vec3 emissive_color=compute_view_dependent_emissive_color(ndotl,emissive_strength,color.xyz); #ifdef RENDER_SHADOWS float light=shadowed_light_factor_normal(transformed_normal,v_pos_light_view_0,v_pos_light_view_1,v_depth);light=mix(light,1.0,cutout_factors.y);color.rgb=apply_lighting(color.rgb,transformed_normal,light); #else color=apply_lighting(color,transformed_normal); #endif color=mix(color,emissive_color,emissive_strength);if (v_height < 0.0) {float penetration=max(v_height+7.5,0.0);float occlusion=1.0-1.0/PI*acos(1.0-penetration/4.0);color=color*(1.0-pow(occlusion,2.0)*0.3);} #endif #ifdef FOG color=fog_apply(color,v_fog_pos); #endif vec4 out_color=vec4(color,1.0);out_color*=u_opacity_multiplier;glFragColor=out_color;HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_shadow.vertex.glsl" in ivec2 a_pos;in float a_height;in ivec4 a_pos_normal_3;uniform mat4 u_matrix;out vec3 v_normal;out float v_height; #ifdef RENDER_SHADOWS uniform mat4 u_light_matrix_0;uniform mat4 u_light_matrix_1;out highp vec4 v_pos_light_view_0;out highp vec4 v_pos_light_view_1;out float v_depth; #endif #pragma mapbox: define highp vec4 structure_color void main() { #pragma mapbox: initialize highp vec4 structure_color v_normal=vec3(a_pos_normal_3)/16384.0;v_height=a_height;vec3 pos=vec3(vec2(a_pos),a_height);gl_Position=u_matrix*vec4(pos,1); #ifdef RENDER_SHADOWS vec3 shd_pos0=pos;vec3 shd_pos1=pos; #ifdef NORMAL_OFFSET vec3 offset=shadow_normal_offset(vec3(-v_normal.xy,v_normal.z));shd_pos0+=offset*shadow_normal_offset_multiplier0();shd_pos1+=offset*shadow_normal_offset_multiplier1(); #endif v_pos_light_view_0=u_light_matrix_0*vec4(shd_pos0,1);v_pos_light_view_1=u_light_matrix_1*vec4(shd_pos1,1);v_depth=gl_Position.w; #endif #ifdef FOG v_fog_pos=fog_position(vec2(a_pos)); #endif }`),elevatedStructuresDepthReconstruct:o.bc(`#include "_prelude_feature_cutout.fragment.glsl" #ifdef DEPTH_RECONSTRUCTION in float v_height; #endif void main() { #ifdef DEPTH_RECONSTRUCTION if (v_height >=0.0) discard; #else #endif glFragColor=vec4(1.0,0.0,0.0,1.0);}`,`in ivec2 a_pos;in float a_height;uniform mat4 u_matrix;uniform vec3 u_camera_pos;uniform highp float u_depth_bias;uniform lowp float u_height_scale;uniform lowp float u_reset_depth; #ifdef DEPTH_RECONSTRUCTION out float v_height; #endif void main() {vec3 vpos=vec3(a_pos,a_height*u_height_scale); #ifdef DEPTH_RECONSTRUCTION if (u_camera_pos.z > vpos.z) {vpos-=(u_camera_pos-vpos)*(vpos.z/(u_camera_pos.z-vpos.z));}v_height=a_height; #endif gl_Position=u_matrix*vec4(vpos,1);gl_Position.z=u_reset_depth==1.0 ? gl_Position.w : gl_Position.z+u_depth_bias;}`)};o.bc(Cn,"");const ra=o.a$([{type:"Float32",name:"a_pos_3f",components:3},{type:"Float32",name:"a_uv",components:2},{type:"Float32",name:"a_rainParticleData",components:4}]),Yr=o.a$([{type:"Float32",name:"a_pos_2f",components:2}]);class Aa{destroy(){this.vignetteVx&&this.vignetteVx.destroy(),this.vignetteIdx&&this.vignetteIdx.destroy()}draw(k,T){const B=k.getOrCreateProgram("vignette");if(!this.vignetteVx||!this.vignetteIdx){const oe=new o.bd,me=new o.ae;oe.emplaceBack(-1,-1),oe.emplaceBack(1,-1),oe.emplaceBack(1,1),oe.emplaceBack(-1,1),me.emplaceBack(0,1,2),me.emplaceBack(0,2,3),this.vignetteVx=k.context.createVertexBuffer(oe,Yr.members),this.vignetteIdx=k.context.createIndexBuffer(me)}const K=o.ad.simpleSegment(0,0,4,6);if(this.vignetteVx&&this.vignetteIdx){k.uploadCommonUniforms(k.context,B);const 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),me=o.av(Q.lat),we=k.pixelsPerMeter/T,Me=oe*o.bk,Re=o.bk*Math.log(Math.tan(Math.PI/4+me/2));if(this._offsetXPrev===void 0)this._offsetXPrev=0,this._offsetYPrev=0,this._elevationPrev=0,this._accumulatedOffsetX=0,this._accumulatedOffsetY=0,this._accumulatedElevation=0;else{const Ze=-this._offsetYPrev+Re,Qe=-this._elevationPrev+K;this._accumulatedOffsetX+=(-this._offsetXPrev+Me)*we,this._accumulatedOffsetY+=Ze*we,this._accumulatedElevation+=Qe*we,this._offsetXPrev=Me,this._offsetYPrev=Re,this._elevationPrev=K}}getPosition(){return[this._accumulatedOffsetX,this._accumulatedOffsetY,this._accumulatedElevation]}}function Ia(L,k){return[-(L[0]-Math.floor(L[0]/k)*k),-(L[1]-Math.floor(L[1]/k)*k),-(L[2]-Math.floor(L[2]/k)*k)]}function el(L){const k=o.bj(1323123451230),T=[];for(let B=0;B({u_matrix:L,u_depth_bias:k}),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}),pu={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 Qe=Math.floor(k.x/(1<me[Qt]!=vt>me[Qt]&&oe[Qt]B&&(Mt|=2),utK&&(Mt|=8),btB&&(es|=2),vtK&&(es|=8),!(Mt&es)&&(Mt===0||es===0||Bd(Qe,ut,bt,vt,k,T,B,K)))return!1}}for(let we=0;we<4;++we)if(!(1&Q[we]))return!1;return!0}function Bd(L,k,T,B,K,Q,oe,me){const we=(Me,Re,Ze,Qe,ut,bt,vt,Mt)=>{const es=(Ze-Me)*(bt-Re)-(Qe-Re)*(ut-Me),Qt=(Ze-Me)*(Mt-Re)-(Qe-Re)*(vt-Me);if(es>0&&Qt>0||es<0&&Qt<0)return!1;const Lt=(vt-ut)*(Re-bt)-(Mt-bt)*(Me-ut),ps=(vt-ut)*(Qe-bt)-(Mt-bt)*(Ze-ut);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,me)||we(L,k,T,B,K,me,oe,me)||we(L,k,T,B,K,Q,K,me))}class ad{constructor(){this._tileCoverages=[],this._snapshot=new oh}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 oh(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,$d=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,me=0;for(1&k?K=Q=oe=Hu:T=B=me=Hu;(k>>=1)>1;){const Me=T+K>>1,Re=B+Q>>1;1&k?(K=T,Q=B,T=oe,B=me):(T=K,B=Q,K=oe,Q=me),oe=Me,me=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 Ep,Fv=0;class Lx{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=++Fv),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 me=oe.queryRadius(Q)||0;this.queryPadding=Math.max(this.queryPadding,me)}k.imageAtlas&&(this.imageAtlas=T.style.imageManager.imageAtlasCache.getOrCache(k.imageAtlas)),k.glyphAtlasImage&&(this.glyphAtlasImage=k.glyphAtlasImage),k.lineAtlas&&(this.lineAtlas=k.lineAtlas),this._lastUpdatedBrightness=k.brightness}else this.collisionBoxArray=new o.bu}resetPlacementVisibility(){var k,T;for(const B in this.buckets)(T=(k=this.buckets[B]).resetPlacementVisibility)==null||T.call(k)}unloadVectorData(){if(this.hasData()){for(const k in this.buckets)this.buckets[k].destroy();this.buckets={},this.imageAtlas&&(this.imageAtlas=null),this.lineAtlas&&(this.lineAtlas=null),this.imageAtlasTexture&&(this.imageAtlasTexture=null),this.glyphAtlasTexture&&this.glyphAtlasTexture.destroy(),this.lineAtlasTexture&&this.lineAtlasTexture.destroy(),this._tileBoundsBuffer&&(this._tileBoundsBuffer.destroy(),this._tileBoundsIndexBuffer.destroy(),this._tileBoundsSegments.destroy(),this._tileBoundsBuffer=null),this._tileDebugBuffer&&(this._tileDebugBuffer.destroy(),this._tileDebugSegments.destroy(),this._tileDebugBuffer=null),this._tileDebugIndexBuffer&&(this._tileDebugIndexBuffer.destroy(),this._tileDebugIndexBuffer=null),this._globeTileDebugBorderBuffer&&(this._globeTileDebugBorderBuffer.destroy(),this._globeTileDebugBorderBuffer=null),this._tileDebugTextBuffer&&(this._tileDebugTextBuffer.destroy(),this._tileDebugTextSegments.destroy(),this._tileDebugTextIndexBuffer.destroy(),this._tileDebugTextBuffer=null),this._globeTileDebugTextBuffer&&(this._globeTileDebugTextBuffer.destroy(),this._globeTileDebugTextBuffer=null),this.latestFeatureIndex=null,this.state="unloaded"}}loadModelData(k,T,B){k&&(k.resourceTiming&&(this.resourceTiming=k.resourceTiming),this.buckets={...this.buckets,...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 me={},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",Qe=T.style.getLayerSourceCache(Re);Qe&&(me=Qe._state.getState(Ze,void 0))}Me={zoom:T.transform.zoom||0,pitch:T.transform.pitch||0,brightness:T.style.getBrightness()||0,worldview:T.worldview||""}}oe.upload(k,this.tileID.canonical,me,we,Me)}}const B=k.gl,K=this.imageAtlas;K&&T&&(this.imageAtlasTexture=T.style.imageManager.imageAtlasCache.getTextureForAtlas(K,k,B.RGBA8),K.uploaded=!0),this.glyphAtlasImage&&(this.glyphAtlasTexture=new o.T(k,this.glyphAtlasImage,B.R8),this.glyphAtlasImage=null),this.lineAtlas&&!this.lineAtlas.uploaded&&(this.lineAtlasTexture=new o.T(k,this.lineAtlas.image,B.R8),this.lineAtlas.uploaded=!0)}prepare(k,T,B){if(this.imageAtlas&&this.imageAtlasTexture&&T){const Qe=T.style.getLut(B);this.imageAtlas.patchUpdatedImages(k,this.imageAtlasTexture,B,Qe)}if(!T||!this.latestFeatureIndex||!this.latestFeatureIndex.rawTileData)return;const K=T.style.getBrightness(),Q=T.style.listImages(),oe=Q.length,me=T.style._changes.getUpdatedPaintProperties(),we=Object.keys(this.buckets).some(Qe=>this.buckets[Qe].layers.some(ut=>me.has(ut.fqid))),Me=Object.keys(this.buckets).some(Qe=>this.buckets[Qe].layers.some(ut=>ut.hasTransition&&ut.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,me,Q),this._lastUpdatedBrightness=K))}evaluateQueryRenderedFeaturePadding(){let k=0;for(const T in this.buckets){const B=this.buckets[T];B.evaluateQueryRenderedFeaturePadding&&(k=Math.max(k,B.evaluateQueryRenderedFeaturePadding()))}return k}queryRenderedFeatures(k,T,B,K,Q,oe,me){if(!this.latestFeatureIndex||!this.latestFeatureIndex.rawTileData&&!this.latestFeatureIndex.is3DTile)return{};const we=this.evaluateQueryRenderedFeaturePadding(),Me=function(Re,Ze){const Qe=o.bM([],[.5*Re.width,.5*-Re.height,1]);return o.bN(Qe,Qe,[1,-1,0]),o.X(Qe,Qe,Re.calculateProjMatrix(Ze.toUnwrapped())),Float32Array.from(Qe)}(Q,this.tileID);return this.latestFeatureIndex.query(k,{tilespaceGeometry:T,pixelPosMatrix:Me,transform:K,availableImages:B,tileTransform:this.tileTransform,worldview:this.worldview,queryRadius:we,scope:me})}querySourceFeatures(k,T){const B=this.latestFeatureIndex;if(!B||!B.rawTileData)return;const K=B.loadVTLayers(),Q=T?T.sourceLayer:"",oe=K._geojsonTileLayer||K[Q];if(!oe)return;const me=o.bw(T&&T.filter),{z:we,x:Me,y:Re}=this.tileID.canonical,Ze={z:we,x:Me,y:Re};for(let Qe=0;QeB)K=!1;else if(T)if(this.expirationTimeB.appearances&&B.appearances.length>0))return!0;return!1}updateBuckets(k,T,B,K,Q,oe){if(!this.latestFeatureIndex||!k.style)return;const me=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],Qe=Ze.layers[0],ut=Qe.sourceLayer||"_geojsonTileLayer",bt=k.style.getLayerSourceCache(Qe),vt=Ze.layers.some(Fs=>Me.has(Fs.fqid)),Mt=(K||vt)&&Ze instanceof o.bv?k.style.getOwnLayer(Re):void 0;let es=B&&B[ut]||{};bt&&!B&&(es=bt._state.getState(ut,void 0));const Qt=this.imageAtlas?Object.fromEntries(this.imageAtlas.patternPositions):{},Lt=Object.keys(es).length>0&&!T;Ze.hasAppearances=Ze.layers.some(Fs=>Fs.appearances&&Fs.appearances.length>0);const ps=Lt?Ze.stateDependentLayers:Ze.layers;if(Lt&&Ze.stateDependentLayers.length!==0||T||vt||K){const Fs=this.latestFeatureIndex.loadVTLayers()[ut];if(Ze.update(es,Fs,me,Qt,ps,T,we,this.tileID.canonical),(K||vt)&&(!T||T&&Ze instanceof o.bv&&(!Ze.text.uboBinder||Ze.text.uboBinder.isLightConstant||!Ze.icon.uboBinder||Ze.icon.uboBinder.isLightConstant))&&Ze instanceof o.bv&&Mt&&Mt.type==="symbol"){const nn=Ze;nn.text&&nn.text.uboBinder&&nn.text.uboBinder.updateDynamicExpressions(Mt,Fs,this.tileID.canonical,me,es,we),nn.icon&&nn.icon.uboBinder&&nn.icon.uboBinder.updateDynamicExpressions(Mt,Fs,this.tileID.canonical,me,es,we)}if(Ze instanceof o.bv){const nn=Ze,$s=k.context;nn.text&&nn.text.uboBinder&&nn.text.uboBinder.upload($s),nn.icon&&nn.icon.uboBinder&&nn.icon.uboBinder.upload($s)}}if(Lt&&Ze.stateDependentLayers.length!==0||T||Ze.hasAppearances){const Fs={zoom:k.transform.zoom,pitch:k.transform.pitch,brightness:k.style.getBrightness()||0,worldview:k.worldview},nn=Ze.updateAppearances(this.tileID.canonical,es,me,Fs,k.imageManager,Lt&&Ze.stateDependentLayers.length!==0);if(nn&&nn.hasUboChanges){const $s=k.context;Ze instanceof o.bv&&Ze.text&&Ze.text.uboBinder&&Ze.text.uboBinder.upload($s),Ze instanceof o.bv&&Ze.icon&&Ze.icon.uboBinder&&Ze.icon.uboBinder.upload($s)}}(Ze instanceof o.bA||Ze instanceof o.bB)&&k._terrain&&k._terrain.enabled&&bt&&Ze.uploadPending()&&k._terrain._clearRenderCacheForTile(bt.id,this.tileID);const Hs=k&&k.style&&k.style.getOwnLayer(Re);Hs&&(this.queryPadding=Math.max(this.queryPadding,Hs.queryRadius(Ze)||0))}}holdingForFade(){return this.symbolFadeHoldUntil!==void 0}symbolFadeFinished(){return!this.symbolFadeHoldUntil||this.symbolFadeHoldUntil=0;Mt--){const es=4*Mt,Qt=dd[es+0],Lt=dd[es+1],ps=dd[es+2],Hs=dd[es+3],Fs=Qt+ps>>1,nn=Lt+Hs>>1,$s=Fs+nn-Lt,rn=nn+Qt-Fs,_n=Lt*$d+Qt,Mn=Hs*$d+ps,Kn=nn*$d+Fs,Bn=Math.hypot((zl[2*_n+0]+zl[2*Mn+0])/2-zl[2*Kn+0],(zl[2*_n+1]+zl[2*Mn+1])/2-zl[2*Kn+1])>=16;Xi[Kn]=Xi[Kn]||(Bn?1:0),Mt<1022&&(Xi[Kn]=Xi[Kn]||Xi[(Lt+rn>>1)*$d+(Qt+$s>>1)]||Xi[(Hs+rn>>1)*$d+(ps+$s>>1)])}const Ze=new o.bt,Qe=new o.ae;let ut=0;function bt(Mt,es){const Qt=es*$d+Mt;return Ed[Qt]===0&&(Ze.emplaceBack(zl[2*Qt+0],zl[2*Qt+1],Mt*o.a6/Hu,es*o.a6/Hu),Ed[Qt]=++ut),Ed[Qt]-1}function vt(Mt,es,Qt,Lt,ps,Hs){const Fs=Mt+Qt>>1,nn=es+Lt>>1;if(Math.abs(Mt-ps)+Math.abs(es-Hs)>1&&Xi[nn*$d+Fs])vt(ps,Hs,Mt,es,Fs,nn),vt(Qt,Lt,ps,Hs,Fs,nn);else{const $s=bt(Mt,es),rn=bt(Qt,Lt),_n=bt(ps,Hs);Qe.emplaceBack($s,rn,_n)}}return vt(0,0,Hu,Hu,Hu,0),vt(Hu,Hu,0,0,0,Hu),{vertices:Ze,indices:Qe}}(this.tileID.canonical,T);K=oe.vertices,Q=oe.indices}else{K=new o.bt,Q=new o.ae;for(const{x:me,y:we}of B)K.emplaceBack(me,we,0,0);const oe=o.bG(K.int16.subarray(0,4*K.length),void 0,4);for(let me=0;me0&&(we=o.aP(new Float64Array(16),T.globeMatrix)),this._makeGlobeTileDebugBorderBuffer(k,K,T,oe,we,me),this._makeGlobeTileDebugTextBuffer(k,K,T,oe,we,me)}_globePoint(k,T,B,K,Q,oe,me){let we=o.bH(k,T,B);if(oe){const Me=1<.5?ut=-1:Qe<-.5&&(ut=1);let bt=(k/o.a6+B.x)/Me+ut,vt=(T/o.a6+B.y)/Me;bt=(bt-Re)*K._pixelsPerMercatorPixel+Re,vt=(vt-Ze)*K._pixelsPerMercatorPixel+Ze;const Mt=[bt*K.worldSize,vt*K.worldSize,0];o.bI(Mt,Mt,oe),we=o.bJ(we,Mt,me)}return o.bI(we,we,Q)}_makeGlobeTileDebugBorderBuffer(k,T,B,K,Q,oe){const me=new o.bD,we=new o.bE,Me=new o.bK,Re=(Qe,ut,bt,vt,Mt)=>{const es=(bt-Qe)/(Mt-1),Qt=(vt-ut)/(Mt-1),Lt=me.length;for(let ps=0;psZe*ut+bt;for(let ut=0;ut{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 Yy{constructor(){this.state=Object.create(null),this.stateChanges=Object.create(null),this.deletedStates=Object.create(null)}updateState(k,T,B){const K=String(T);if(this.stateChanges[k]=this.stateChanges[k]||Object.create(null),this.stateChanges[k][K]=this.stateChanges[k][K]||Object.create(null),Object.assign(this.stateChanges[k][K],B),this.deletedStates[k]===null){this.deletedStates[k]=Object.create(null);for(const Q in this.state[k])Q!==K&&(this.deletedStates[k][Q]=null)}else if(this.deletedStates[k]&&this.deletedStates[k][K]===null){this.deletedStates[k][K]=Object.create(null);for(const Q in this.state[k][K])B[Q]||(this.deletedStates[k][K][Q]=null)}else for(const Q in B)this.deletedStates[k]&&this.deletedStates[k][K]&&this.deletedStates[k][K][Q]===null&&delete this.deletedStates[k][K][Q]}removeFeatureState(k,T,B){if(this.deletedStates[k]===null)return;const K=String(T);if(this.deletedStates[k]=this.deletedStates[k]||Object.create(null),B&&T!==void 0)this.deletedStates[k][K]!==null&&(this.deletedStates[k][K]=this.deletedStates[k][K]||Object.create(null),this.deletedStates[k][K][B]=null);else if(T!==void 0)if(this.stateChanges[k]&&this.stateChanges[k][K])for(B in this.deletedStates[k][K]=Object.create(null),this.stateChanges[k][K])this.deletedStates[k][K][B]=null;else this.deletedStates[k][K]=null;else this.deletedStates[k]=null}getState(k,T){const B=this.state[k]||Object.create(null),K=this.stateChanges[k]||Object.create(null),Q=this.deletedStates[k];if(Q===null)return Object.create(null);if(T!==void 0){const me=String(T),we=Object.assign(Object.create(null),B[me],K[me]);if(Q){const Me=Q[T];if(Me===null)return Object.create(null);for(const Re in Me)delete we[Re]}return we}const oe=Object.assign(Object.create(null),B,K);if(Q)for(const me in Q)delete oe[me];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 me of Object.keys(this.deletedStates[K][oe]))delete this.state[K][oe][me];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 Yy,this._isRaster=this._source.type==="raster"||this._source.type==="raster-dem"||this._source.type==="raster-array"||this._source.type==="custom"&&"_dataType"in this._source&&this._source._dataType==="raster",this._supportsFading=this._source.type==="raster"||this._source.type==="raster-array"||this._source.type==="image"||this._source.type==="video"||this._source.type==="custom",this._isRasterElevatedOverTerrain=!1}onAdd(k){this.map=k,this._minTileCacheSize=this._minTileCacheSize===void 0&&k?k._minTileCacheSize:this._minTileCacheSize,this._maxTileCacheSize=this._maxTileCacheSize===void 0&&k?k._maxTileCacheSize:this._maxTileCacheSize}setSource(k){k.on("data",T=>{T.dataType==="source"&&T.sourceDataType==="metadata"&&(this._sourceLoaded=!0),this._sourceLoaded&&!this._paused&&T.dataType==="source"&&T.sourceDataType==="content"&&(this.reload(),this.transform&&this.update(this.transform))}),k.on("error",()=>{this._sourceErrored=!0}),this._source=k}loaded(){if(this._sourceErrored)return!0;if(!this._sourceLoaded||!this._source.loaded())return!1;for(const k in this._tiles)if(!this._tiles[k].loaded())return!1;return!0}getSource(){return this._source}pause(){this._paused=!0}resume(){if(!this._paused)return;const k=this._shouldReloadOnResume;this._paused=!1,this._shouldReloadOnResume=!1,k&&this.reload(),this.transform&&this.update(this.transform)}setMaxzoomOverride(k){this._maxzoomOverride=k}_loadTile(k,T){return k.renderSourceType=this._renderSourceType,k.isExtraShadowCaster=this._shadowCasterTiles[k.tileID.key],this._source.loadTile(k,T)}_unloadTile(k){if(this._source.unloadTile)return this._source.unloadTile(k)}_abortTile(k){if(this._source.abortTile)return this._source.abortTile(k)}serialize(){return this._source.serialize()}prepare(k){this._source.prepare&&this._source.prepare(),this._state.coalesceChanges(this._tiles,this.map?this.map.painter:null);for(const T in this._tiles){const B=this._tiles[T];B.upload(k,this.map?this.map.painter:void 0),B.prepare(this.map.style.imageManager,this.map?this.map.painter:null,this._source.scope)}}getIds(){return Object.values(this._tiles).map(k=>k.tileID).sort(Xg).map(k=>k.key)}getRenderableIds(k,T){const B=[];for(const K in this._tiles)this._isIdRenderable(+K,k,T)&&B.push(this._tiles[K]);return k?B.sort((K,Q)=>{const oe=K.tileID,me=Q.tileID,we=new o.P(oe.canonical.x,oe.canonical.y)._rotate(this.transform.angle),Me=new o.P(me.canonical.x,me.canonical.y)._rotate(this.transform.angle);return oe.overscaledZ-me.overscaledZ||Me.y-we.y||Me.x-we.x}).map(K=>K.tileID.key):B.map(K=>K.tileID).sort(Xg).map(K=>K.key)}hasRenderableParent(k){const T=this.findLoadedParent(k,0);return!!T&&this._isIdRenderable(T.tileID.key)}_isIdRenderable(k,T,B){return this._tiles[k]&&this._tiles[k].hasData()&&!this._coveredTiles[k]&&(T||!this._tiles[k].holdingForFade())&&(B||!this._shadowCasterTiles[k])}reload(){if(this._paused)this._shouldReloadOnResume=!0;else{this._cache.reset();for(const k in this._tiles)this._tiles[k].state!=="errored"&&this._reloadTile(+k,"reloading")}}_reloadTile(k,T){const B=this._tiles[k];B&&(B.state!=="loading"&&(B.state=T),this._loadTile(B,this._tileLoaded.bind(this,B,k,T)))}_tileLoaded(k,T,B,K,Q){if(K){if(k.state="errored",o.bP(K)){if(this._source.fire(new o.h("data",{dataType:"source",sourceDataType:"error",sourceId:this._source.id,tile:k})),!(k.tileID.key in this._loadedParentTiles))return;if(this._source.type==="raster-dem"&&this.usedForTerrain&&this.map.painter.terrain){const me=this.map.painter.terrain;this.update(this.transform,me.getScaledDemTileSize(),!0),me.resetTileLookupCache(this.id)}else this.update(this.transform)}else this._source.fire(new o.f(K,{tile:k}));return}k.timeAdded=o.e.now(),B==="expired"&&(k.refreshedUponExpiration=!0),this._setTileReloadTimer(T,k),this._source.type==="raster-dem"&&k.dem&&this._backfillDEM(k),this._state.initializeTileState(k,this.map?this.map.painter:null);let 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,me),K.neighboringTiles&&K.neighboringTiles[Me]&&(K.neighboringTiles[Me].backfilled=!0)))}}getTile(k){return this.getTileByID(k.key)}getTileByID(k){return this._tiles[k]}_retainLoadedChildren(k,T,B,K){const Q=this._source.type==="raster-array";for(const oe in this._tiles){let me=this._tiles[oe];if(K[oe]||!me.hasData()||me.tileID.overscaledZ<=T||me.tileID.overscaledZ>B||Q&&me.parentTile)continue;let we=me.tileID;for(;me&&me.tileID.overscaledZ>T+1;){const Re=me.tileID.scaledTo(me.tileID.overscaledZ-1);me=this._tiles[Re.key],me&&me.hasData()&&(we=Re)}let Me=we;for(;Me.overscaledZ>T;)if(Me=Me.scaledTo(Me.overscaledZ-1),k[Me.key]){K[we.key]=we;const Re=this._tiles[we.key];Re&&(Re.dashIdealZ=Me.overscaledZ);break}}}findLoadedParent(k,T){if(k.key in this._loadedParentTiles){const B=this._loadedParentTiles[k.key];return B&&B.tileID.overscaledZ>=T?B:null}for(let B=k.overscaledZ-1;B>=T;B--){const K=k.scaledTo(B),Q=this._getLoadedTile(K);if(Q)return Q}}_getLoadedTile(k){const T=this._tiles[k.key];return T&&T.hasData()?T:this._cache.getByKey(this._source.reparseOverscaled?k.wrapped().key:k.canonical.key)}updateCacheSize(k,T){T=T||this._source.tileSize;const B=Math.ceil(k.width/T)+1,K=Math.ceil(k.height/T)+1,Q=Math.floor(B*K*5),oe=typeof this._minTileCacheSize=="number"?Math.max(this._minTileCacheSize,Q):Q,me=typeof this._maxTileCacheSize=="number"?Math.min(this._maxTileCacheSize,oe):oe;this._cache.setMaxSize(me)}handleWrapJump(k){const T=Math.round((k-(this._prevLng===void 0?k:this._prevLng))/360);if(this._prevLng=k,T){const B={};for(const K in this._tiles){const Q=this._tiles[K];Q.tileID=Q.tileID.unwrapTo(Q.tileID.wrap+T),B[Q.tileID.key]=Q}this._tiles=B;for(const K in this._timers)clearTimeout(this._timers[K]),delete this._timers[K];for(const K in this._tiles)this._setTileReloadTimer(+K,this._tiles[K])}}update(k,T,B,K,Q){if(this.transform=k,!this._sourceLoaded||this._paused||this.transform.freezeTileCoverage||this.usedForTerrain&&!B)return;this.updateCacheSize(k,T),this.transform.projection.name!=="globe"&&this.handleWrapJump(this.transform.center.lng),this._shadowCasterTiles={},this._coveredTiles={};const oe=this._source.type==="batched-model";let me,we=this._source.maxzoom;this._maxzoomOverride!==null&&(we=Math.min(we,this._maxzoomOverride));const Me=this.map&&this.map.painter?this.map.painter._terrain:null;if(Me&&Me.sourceCache===this&&Me.attenuationRange()){const ut=Me.attenuationRange()[0],bt=Math.floor(ut)-Math.log2(Me.getDemUpscale());we>bt&&(we=bt)}const Re=this._maxzoomOverride===null&&this._source.reparseOverscaled;if(this.used||this.usedForTerrain){if(this._source.tileID)me=k.getVisibleUnwrappedCoordinates(this._source.tileID).map(ut=>new o.bQ(ut.canonical.z,ut.wrap,ut.canonical.z,ut.canonical.x,ut.canonical.y));else if(this.tileCoverLift!==0){const ut=k.clone();ut.tileCoverLift=this.tileCoverLift,me=ut.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"&&(me.push(new o.bQ(1,0,1,0,0)),me.push(new o.bQ(1,0,1,1,0)),me.push(new o.bQ(1,0,1,0,1)),me.push(new o.bQ(1,0,1,1,1)))}else if(me=k.coveringTiles({tileSize:T||this._source.tileSize,minzoom:this._source.minzoom,maxzoom:we,roundZoom:this._source.roundZoom&&!B,reparseOverscaled:Re,isTerrainDEM:this.usedForTerrain,calculateQuadrantVisibility:oe}),this._source.hasTile){const ut=this._source.hasTile.bind(this._source);me=me.filter(bt=>ut(bt))}}else me=[];if(me.length>0&&this.transform.projection.name!=="globe"&&!this.usedForTerrain&&!this._supportsFading){const ut=k.coveringZoomLevel({tileSize:T||this._source.tileSize,roundZoom:this._source.roundZoom&&!B}),bt=Math.min(ut,we);if(oe){const vt=k.extendTileCover(me,bt);for(const Mt of vt)me.push(Mt)}else if(Q){const vt=this.transform.getFrustum(bt),Mt=k.extendTileCoverToNearPlane(me,vt,bt);for(const es of Mt)me.push(es);if(bt>=18&&this._hasTunnelGeometry()){const es=k.extendTileCoverForTunnels(me,vt,bt,20);for(const Qt of es)me.push(Qt)}}else if(this.castsShadows&&K){const vt=k.extendTileCover(me,bt,K,16);for(const Mt of vt)this._shadowCasterTiles[Mt.key]=!0,me.push(Mt)}}for(const ut in this._tiles){const bt=this._tiles[ut];bt.dashIdealZ=bt.tileID.overscaledZ}const Ze=this._updateRetainedTiles(me);if(this._supportsFading&&me.length!==0){const ut={},bt={},vt=o.e.now(),Mt=Object.keys(Ze);for(const Qt of Mt){const Lt=Ze[Qt],ps=this._tiles[Qt];if(!ps||ps.fadeEndTime!==void 0&&ps.fadeEndTime<=vt)continue;const Hs=this.findLoadedParent(Lt,Math.max(Lt.overscaledZ-Ci.maxOverzooming,this._source.minzoom));Hs&&(this._addTile(Hs.tileID),ut[Hs.tileID.key]=Hs.tileID),bt[Qt]=Lt}const es=me.at(-1).overscaledZ;for(const Qt in this._tiles){const Lt=this._tiles[Qt];if(Ze[Qt]||!Lt.hasData())continue;let ps=Lt.tileID;for(;ps.overscaledZ>es;){ps=ps.scaledTo(ps.overscaledZ-1);const Hs=this._tiles[ps.key];if(Hs&&Hs.hasData()&&bt[ps.key]){Ze[Qt]=Lt.tileID;break}}}for(const Qt in ut)Ze[Qt]||(this._coveredTiles[Qt]=!0,Ze[Qt]=ut[Qt])}for(const ut in Ze)this._tiles[ut].clearFadeHold();const Qe=o.bR(this._tiles,Ze);for(const ut of Qe){const bt=this._tiles[ut];bt.hasSymbolBuckets&&!bt.holdingForFade()?bt.setHoldDuration(this.map._fadeDuration):bt.hasSymbolBuckets&&!bt.symbolFadeFinished()||this._removeTile(+ut)}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),me=Math.max(Q+Ci.maxUnderzooming,this._source.minzoom),we={};for(const Me of k){const Re=this._addTile(Me);T[Me.key]=Me,Re.hasData()||K=this._source.maxzoom){const Qe=Me.children(this._source.maxzoom)[0],ut=this.getTile(Qe);if(ut&&ut.hasData()){T[Qe.key]=Qe,ut.dashIdealZ=Me.overscaledZ;continue}}else{const Qe=Me.children(this._source.maxzoom);if(T[Qe[0].key]&&T[Qe[1].key]&&T[Qe[2].key]&&T[Qe[3].key])continue}let Ze=Re.wasRequested();for(let Qe=Me.overscaledZ-1;Qe>=oe;--Qe){const ut=Me.scaledTo(Qe);if(B[ut.key]||(B[ut.key]=!0,Re=this.getTile(ut),!Re&&Ze&&(Re=this._addTile(ut)),Re&&(T[ut.key]=ut,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,me,we,Me,Re){if(!Ep)throw new Error("Raster-array module is not loaded.");return Ep(oe,me,we,Me,Re)}(k,Q,this.transform.tileZoom,K,this._isRaster):new Lx(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",me=o.a7(Q.center.lng),we=Q.getFreeCameraOptions().position||new o.bT(0,0,0);for(const Me in this._tiles){const Re=this._tiles[Me];if(B&&Re.clearQueryDebugViz(),Re.holdingForFade())continue;let Ze;if(oe){const Qe=Re.tileID.canonical;if(Qe.z===0){const ut=[Math.abs(o.b1(me,...Om(Qe,-1))-me),Math.abs(o.b1(me,...Om(Qe,1))-me)];Ze=[0,2*ut.indexOf(Math.min(...ut))-1]}else{const ut=[Math.abs(o.b1(me,...Om(Qe,-1))-me),Math.abs(o.b1(me,...Om(Qe,0))-me),Math.abs(o.b1(me,...Om(Qe,1))-me)];Ze=[ut.indexOf(Math.min(...ut))-1]}}else Ze=[0];for(const Qe of Ze){const ut=k.containsTile(Re,Q,T,Qe,we);ut&&K.push(ut)}}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 me=1/(1<Q[oe.key]-Q[me.key]),T}hasTransition(){if(this._source.hasTransition())return!0;if(this._supportsFading){const k=o.e.now();for(const T in this._tiles){const B=this._tiles[T];if(B.fadeEndTime!==void 0&&B.fadeEndTime>=k)return!0}}return!1}setFeatureState(k,T,B){this._state.updateState(k=k||"_geojsonTileLayer",T,B)}removeFeatureState(k,T,B){this._state.removeFeatureState(k=k||"_geojsonTileLayer",T,B)}getFeatureState(k,T){return this._state.getState(k=k||"_geojsonTileLayer",T)}setDependencies(k,T,B){const K=this._tiles[k];K&&K.setDependencies(T,B)}reloadTilesForDependencies(k,T){for(const B in this._tiles)this._tiles[B].hasDependency(k,T)&&this._reloadTile(+B,"reloading");this._cache.filter(B=>!B.hasDependency(k,T))}_preloadTiles(k,T){if(!this._sourceLoaded){const we=()=>{this._sourceLoaded&&(this._source.off("data",we),this._preloadTiles(k,T))};return void this._source.on("data",we)}const B=new Map,K=Array.isArray(k)?k:[k],Q=this.map.painter.terrain,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 me=Array.from(B.values());o.bU(me,(we,Me)=>{const Re=new Lx(we,this._source.tileSize*we.overscaleFactor(),this.transform.tileZoom,this.map.painter,this._isRaster,this._source.worldview);this._loadTile(Re,Ze=>{this._source.type==="raster-dem"&&Re.dem&&this._backfillDEM(Re),Me(Ze,Re)})},T)}}function Xg(L,k){const T=Math.abs(2*L.wrap)-+(L.wrap<0),B=Math.abs(2*k.wrap)-+(k.wrap<0);return L.overscaledZ-k.overscaledZ||B-T||k.canonical.y-L.canonical.y||k.canonical.x-L.canonical.x}function 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!!me.hasDeferredElevationFeatures||oe&&(we=K,kl(B,Me=me.tileID.canonical)!==kl(we,Me));var we,Me})}const xu=L=>({u_matrix:L});function D_(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 Ov(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 Dx(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 Pb(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 me=Dx(L,oe);if(!me)continue;const we=me.buffers.frcLevelSegments[T];we&&Q.draw(L,K.TRIANGLES,o.Z.disabled,new o._({func:K.EQUAL,mask:255},L._tileClippingMaskIDs[oe.key]||0,255,K.KEEP,K.KEEP,K.INVERT),o.a1.disabled,o.$.disabled,xu(me.projMatrix),`$frc_coverage_${T}`,me.buffers.vertexBuffer,me.buffers.indexBuffer,we)}}function Kw(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 me=Dx(L,oe);if(!me)continue;const we=me.buffers.frcLevelSegments[T];we&&Q.draw(L,K.TRIANGLES,o.Z.disabled,new o._({func:K.EQUAL,mask:255},255&~(L._tileClippingMaskIDs[oe.key]||0),255,K.KEEP,K.KEEP,K.INVERT),o.a1.disabled,o.$.disabled,xu(me.projMatrix),`$frc_coverage_restore_${T}`,me.buffers.vertexBuffer,me.buffers.indexBuffer,we)}}function zm(L,k,T,B,K){if(k.length===0)return;let Q=0;for(const me of k)Q|=me.frcMask;const oe=k.map(me=>me.coord);for(let me=0;me<9;++me)if(Q&1<0&&K)for(const we of k)we.frcMask&1<0&&k.rings[0].length>0)return!0;return!1}function 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()),Qe=L.style.order.indexOf(T.fqid);if(function(ut,bt,vt,Mt,es,Qt){for(const Lt of Qt){const ps=bt.getTile(Lt).getBucket(vt);ps&&(es&&ps.updateReplacement(Lt,ut.replacementSource,Mt),ps.uploadUpdatedIndexBuffer(ut.context))}}(L,k,T,Qe,Ze,B),function(ut,bt,vt,Mt){for(const es of Mt){const Qt=bt.getTile(es).getBucket(vt);Qt&&Qt.needsEvaluation()&&Qt.uploadUpdatedColorBuffer(ut.context)}}(L,k,T,B),T.resetLayerRenderingStats(L),L.shadowRenderer&&(L.shadowRenderer.useNormalOffset=!0),L.renderPass==="shadow"&&L.shadowRenderer){const ut=[],bt=L.shadowRenderer.getShadowPassDepthMode();$a({painter:L,source:k,layer:T,coords:B,defines:ut,blendMode:o.a1.disabled,depthMode:bt,opacity:me,verticalScale:Re,facadeEmissiveChance:0,facadeAOIntensity:0,floodLightIntensity:0,floodLightColor:[0,0,0]})}else if(L.renderPass==="translucent"){let ut=["HAS_ATTRIBUTE_a_part_color_emissive","LIGHTING_3D_MODE"];Me&&(ut=ut.concat("RENDER_SHADOWS")),L.shadowRenderer&&L.shadowRenderer.useNormalOffset&&(ut=ut.concat("NORMAL_OFFSET"));const bt=T.paint.get("building-facade-emissive-chance"),vt=T.paint.get("building-ambient-occlusion-intensity"),Mt=T.paint.get("building-flood-light-intensity"),es=T.paint.get("building-flood-light-color-use-theme").constantOr("default")==="none",Qt=T.paint.get("building-flood-light-color").toNonPremultipliedRenderColor(es?null:T.lut).toArray01().slice(0,3),Lt=T.paint.get("building-flood-light-ground-attenuation"),ps=Mt>0,Hs=new o.Z(L.context.gl.LEQUAL,o.Z.ReadWrite,L.depthRangeFor3D);me<1&&$a({painter:L,source:k,layer:T,coords:B,defines:ut,blendMode:o.a1.disabled,depthMode:Hs,opacity:me,verticalScale:Re,facadeEmissiveChance:bt,facadeAOIntensity:vt,floodLightIntensity:Mt,floodLightColor:Qt,depthOnly:!0});const Fs=L.colorModeForRenderPass();$a({painter:L,source:k,layer:T,coords:B,defines:ut,blendMode:Fs,depthMode:Hs,opacity:me,verticalScale:Re,facadeEmissiveChance:bt,facadeAOIntensity:vt,floodLightIntensity:Mt,floodLightColor:Qt});const nn=T.paint.get("building-front-cutoff");Vt(L.transform.pitch,nn,!!L.terrain),we&&Na(L,k,T,B,!0,me,K,Q,Mt,Qt,oe,Ze),ps&&Na(L,k,T,B,!1,me,K,Q,Mt,Qt,Lt,Ze)}else if(L.renderPass==="light-beam"){const ut=["HAS_ATTRIBUTE_a_part_color_emissive","HAS_ATTRIBUTE_a_bloom_attenuation"],bt=new o.Z(L.context.gl.LEQUAL,o.Z.ReadOnly,L.depthRangeFor3D);$a({painter:L,source:k,layer:T,coords:B,defines:ut,blendMode:o.a1.alphaBlended,depthMode:bt,opacity:me,verticalScale:Re,facadeEmissiveChance:0,facadeAOIntensity:0,floodLightIntensity:0,floodLightColor:[0,0,0]})}L.shadowRenderer&&(L.shadowRenderer.useNormalOffset=!1),L.resetStencilClippingMasks()},BuildingTileBorderManager:class{constructor(){this.visibleTiles=[]}updateBorders(L,k){const T=[],B=[],K=L._getRenderableCoordinates(!1,!0);for(const me of K){const we=L.getTile(me);if(!we.hasData())continue;const Me=we.getBucket(k);Me&&(Me.isEmpty()||(T.push(me.key),B.push({bucket:Me,tileID:me.canonical})))}let Q=T.length!==this.visibleTiles.length;if(!Q){T.sort();for(let me=0;meme.tileID.z-we.tileID.z||me.tileID.x-we.tileID.x||me.tileID.y-we.tileID.y);for(const me of B){const we=new Array,Me=new Array,Re=me.bucket;for(const Ze of Re.featuresOnBorder)Re.footprints[Ze.footprintIndex].hiddenFlags&o.aS||(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,me,we,Me){if(!Me.length)return;const Re=oe.context,Ze=Re.gl,Qe=me.getSource();if(Qe.type!=="raster-array")return;const ut=Math.ceil(Math.sqrt(we.paint.get("raster-particle-count")));let bt=we.particlePositionRGBAImage;if(!bt||bt.width!==ut){const Lt=function(ps){const Hs=ps*ps,Fs=new Uint8Array(4*Hs),nn=.9090909090909091;for(let $s=0;$so.aC[Hr](Bn));xr.push(Bn);const sa=Bn.canonical.x,ka=Bn.canonical.y;for(const Hr of xr){const ea=ps.getTile(_n?Hr.wrapped():Hr);if(!ea)continue;const si=ea.rasterParticleState;if(!si)continue;const Wr=Hr.canonical.x+(1<k.getTileByID(me));for(const me of oe)me.updateNeeded(L.id,Q)&&(me._isHeaderLoaded||me.parentTile)&&B.prepareTile(me,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 me=0;meoe)return;const me=zo(0,1,B.revealStart,B.revealStart+B.revealRange,oe);if(!this.particlesVx||!this.particlesIdx)return;Q.strength*=me;const we=this.updateOnRender(L,T.timeFactor),Me=L.context,Re=Me.gl,Ze=L.transform;this.screenTexture&&this.screenTexture.size[0]===L.width&&this.screenTexture.size[1]===L.height||(this.screenTexture=new o.T(Me,{width:L.width,height:L.height,data:null},Re.RGBA8)),T.distortionStrength>0&&(Me.activeTexture.set(Re.TEXTURE0),this.screenTexture.bind(Re.LINEAR,Re.CLAMP_TO_EDGE),Re.copyTexSubImage2D(Re.TEXTURE_2D,0,0,0,0,0,L.width,L.height));const Qe=L.getOrCreateProgram("rainParticle");L.uploadCommonUniforms(Me,Qe),Me.activeTexture.set(Re.TEXTURE0),this.screenTexture.bind(Re.LINEAR,Re.CLAMP_TO_EDGE);const ut=[T.color.r,T.color.g,T.color.b,T.color.a],bt=(vt,Mt)=>{const es=Ia(this._movement.getPosition(),vt),Qt=T.dropletSizeX,Lt=T.dropletSizeX*T.dropletSizeYScale,ps=L.width/2,Hs=L.height/2,Fs=zo(0,T.screenThinning.start,0,1,T.screenThinning.intensity),nn=zo(.001,T.screenThinning.range,0,1,T.screenThinning.intensity),$s=zo(0,T.screenThinning.particleOffset,0,1,T.screenThinning.intensity),rn=(_n={modelview:we.modelviewMatrix,projection:we.projectionMatrix,time:this._accumulatedTimeFromStart,camPos:es,velocityConeAperture:T.velocityConeAperture,velocity:T.velocity,boxSize:vt,rainDropletSize:[Qt,Lt],distortionStrength:T.distortionStrength,rainDirection:K,color:ut,screenSize:[Ze.width,Ze.height],thinningCenterPos:[ps,Hs],thinningShape:[Fs,nn,Math.pow(10,T.screenThinning.fadePower)],thinningAffectedRatio:T.screenThinning.affectedRatio,thinningParticleOffset:$s,shapeDirectionalPower:T.shapeDirPower,shapeNormalPower:T.shapeNormalPower,mode:Mt?0:1},{u_modelview:Float32Array.from(_n.modelview),u_projection:Float32Array.from(_n.projection),u_time:_n.time,u_cam_pos:_n.camPos,u_texScreen:0,u_velocityConeAperture:_n.velocityConeAperture,u_velocity:_n.velocity,u_boxSize:_n.boxSize,u_rainDropletSize:_n.rainDropletSize,u_distortionStrength:_n.distortionStrength,u_rainDirection:_n.rainDirection,u_color:_n.color,u_screenSize:_n.screenSize,u_thinningCenterPos:_n.thinningCenterPos,u_thinningShape:_n.thinningShape,u_thinningAffectedRatio:_n.thinningAffectedRatio,u_thinningParticleOffset:_n.thinningParticleOffset,u_shapeDirectionalPower:_n.shapeDirectionalPower,u_shapeNormalPower:_n.shapeNormalPower,u_mode:_n.mode});var _n;const Mn=Math.round(T.intensity*this.particlesCount),Kn=o.ad.simpleSegment(0,0,4*Mn,2*Mn);Qe.draw(L,Re.TRIANGLES,o.Z.disabled,o._.disabled,o.a1.alphaBlended,o.$.disabled,rn,"rain_particles",this.particlesVx,this.particlesIdx,Kn)};T.distortionStrength>0&&bt(T.boxSize,!0),bt(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 me=0;meoe)return;const me=zo(0,1,B.revealStart,B.revealStart+B.revealRange,oe);Q.strength*=me;const we=this.updateOnRender(L,T.timeFactor);if(!this.particlesVx||!this.particlesIdx)return;const Me=L.context,Re=Me.gl,Ze=L.transform,Qe=L.getOrCreateProgram("snowParticle");L.uploadCommonUniforms(Me,Qe),((ut,bt,vt)=>{const Mt=Ia(this._movement.getPosition(),ut),es=Ze.width/2,Qt=Ze.height/2,Lt=zo(0,vt.screenThinning.start,0,1,vt.screenThinning.intensity),ps=zo(.001,vt.screenThinning.range,0,1,vt.screenThinning.intensity),Hs=zo(0,vt.screenThinning.particleOffset,0,1,vt.screenThinning.intensity),Fs=(nn={modelview:we.modelviewMatrix,projection:we.projectionMatrix,time:this._accumulatedTimeFromStart,camPos:Mt,velocityConeAperture:vt.velocityConeAperture,velocity:vt.velocity,horizontalOscillationRadius:vt.horizontalOscillationRadius,horizontalOscillationRate:vt.horizontalOscillationRate,boxSize:ut,billboardSize:1*vt.billboardSize,simpleShapeParameters:[vt.shapeFadeStart,vt.shapeFadePower],screenSize:[Ze.width,Ze.height],thinningCenterPos:[es,Qt],thinningShape:[Lt,ps,Math.pow(10,vt.screenThinning.fadePower)],thinningAffectedRatio:vt.screenThinning.affectedRatio,thinningParticleOffset:Hs,color:[vt.color.r,vt.color.g,vt.color.b,vt.color.a],direction:K},{u_modelview:Float32Array.from(nn.modelview),u_projection:Float32Array.from(nn.projection),u_time:nn.time,u_cam_pos:nn.camPos,u_velocityConeAperture:nn.velocityConeAperture,u_velocity:nn.velocity,u_horizontalOscillationRadius:nn.horizontalOscillationRadius,u_horizontalOscillationRate:nn.horizontalOscillationRate,u_boxSize:nn.boxSize,u_billboardSize:nn.billboardSize,u_simpleShapeParameters:nn.simpleShapeParameters,u_screenSize:nn.screenSize,u_thinningCenterPos:nn.thinningCenterPos,u_thinningShape:nn.thinningShape,u_thinningAffectedRatio:nn.thinningAffectedRatio,u_thinningParticleOffset:nn.thinningParticleOffset,u_particleColor:nn.color,u_direction:nn.direction});var nn;const $s=Math.round(vt.intensity*this.particlesCount),rn=o.ad.simpleSegment(0,0,4*$s,2*$s);this.particlesVx&&this.particlesIdx&&Qe.draw(L,Re.TRIANGLES,o.Z.disabled,o._.disabled,o.a1.alphaBlended,o.$.disabled,Fs,"snow_particles",this.particlesVx,this.particlesIdx,rn)})(T.boxSize,0,T),this._vignette.draw(L,Q)}},shaders:rr,programUniforms:pu,drawElevatedStructures:function(L){const{painter:k,sourceCache:T,layer:B,coords:K,colorMode:Q}=L,oe=k.context.gl,me=L.painter.shadowRenderer,we=!!me&&me.enabled,Me=new o.Z(k.context.gl.LEQUAL,o.Z.ReadOnly,k.depthRangeFor3D);let Re=[0,0,0];if(we){const Qe=k.style.directionalLight,ut=k.style.ambientLight;Qe&&ut&&(Re=o.aG(k.style,Qe,ut))}const Ze=Qe=>{for(const ut of K){const bt=T.getTile(ut),vt=bt.getBucket(B);if(!vt)continue;const Mt=vt.hdExt?vt.hdExt.elevatedStructures:void 0;if(!Mt)continue;let es,Qt;if(Qe?(es=Mt.renderableBridgeSegments,Qt=Mt.bridgeProgramConfigurations.get(B.id)):(es=Mt.renderableTunnelSegments,Qt=Mt.tunnelProgramConfigurations.get(B.id)),!es||es.segments[0].primitiveLength===0)continue;Qt.updatePaintBuffers(),k.prepareDrawTile();const Lt=k.isTileAffectedByFog(ut),ps=[];we&&ps.push("RENDER_SHADOWS","NORMAL_OFFSET");const Hs=k.getOrCreateProgram("elevatedStructures",{config:Qt,overrideFog:Lt,defines:ps}),Fs=k.translatePosMatrix(ut.projMatrix,bt,B.paint.get("fill-translate"),B.paint.get("fill-translate-anchor"));we&&me.setupShadows(bt.tileID.toUnwrapped(),Hs,"vector-tile");const nn=dm(Fs,Re);k.uploadCommonUniforms(k.context,Hs,ut.toUnwrapped()),Hs.draw(k,oe.TRIANGLES,Me,o._.disabled,Q,o.$.backCCW,nn,B.id,Mt.vertexBuffer,Mt.indexBuffer,es,B.paint,k.transform.zoom,Qt,[Mt.vertexBufferNormal])}};Ze(!0),Ze(!1)},drawElevatedFillShadows:function(L){const{painter:k,sourceCache:T,layer:B,coords:K}=L,Q=k.context.gl,oe=L.painter.shadowRenderer;for(const me of K){const we=T.getTile(me),Me=we.getBucket(B);if(!Me)continue;const Re=Me.hdExt?Me.hdExt.elevatedStructures:void 0;if(!Re||!Re.shadowCasterSegments||Re.shadowCasterSegments.segments[0].primitiveLength===0)continue;k.prepareDrawTile();const Ze=Me.bufferData.programConfigurations.get(B.id),Qe=k.isTileAffectedByFog(me),ut=k.getOrCreateProgram("elevatedStructuresDepth",{config:Ze,overrideFog:Qe}),bt=oe.calculateShadowPassMatrixFromTile(we.tileID.toUnwrapped());k.uploadCommonUniforms(k.context,ut,me.toUnwrapped());const vt=iu(bt,0);ut.draw(k,Q.TRIANGLES,oe.getShadowPassDepthMode(),o._.disabled,o.a1.disabled,o.$.disabled,vt,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),me=new o.Z(L.context.gl.GREATER,o.Z.ReadWrite,L.depthRangeFor3D),we=function(Qe){let ut=.01;return Qe.isOrthographic&&(ut=o.am(1e-4,ut,o.bp(Qe.pitch>=o.bo?1:Qe.pitch/o.bo))),2*ut}(L.transform),Me=L.transform.getFreeCameraOptions().position,Re="elevatedStructuresDepthReconstruct";let Ze;for(const Qe of B){const ut=k.getTile(Qe),bt=ut.getBucket(T);if(!bt||!bt.hdExt)continue;const vt=bt.hdExt.elevatedStructures,Mt=bt.hdExt.elevationBufferData;if(!vt||!vt.depthSegments||!Mt)continue;const es=Mt.heightRange,Qt=Zc(Qe.toUnwrapped(),Me),Lt=L.translatePosMatrix(Qe.projMatrix,ut,T.paint.get("fill-translate"),T.paint.get("fill-translate-anchor"));let ps,Hs,Fs;if(K==="initialize"){if(!es||es.min>=1||vt.depthSegments.segments[0].primitiveLength===0)continue;ps=Ad(Lt,Qt,we,1,0),Hs=oe,Fs=vt.depthSegments,Ze=Ze||L.getOrCreateProgram(Re,{defines:["DEPTH_RECONSTRUCTION"]})}else if(K==="reset"){if(!es||es.min>=0||vt.maskSegments.segments[0].primitiveLength===0)continue;ps=Ad(Lt,Qt,0,0,1),Hs=me,Fs=vt.maskSegments,Ze=Ze||L.getOrCreateProgram(Re,{defines:["DEPTH_RECONSTRUCTION"]})}else if(K==="geometry"){if(vt.depthSegments.segments[0].primitiveLength===0)continue;ps=Ad(Lt,Qt,we,1,0),Hs=oe,Fs=vt.depthSegments,Ze=Ze||L.getOrCreateProgram(Re)}Ze.draw(L,Q.TRIANGLES,Hs,o._.disabled,o.a1.disabled,o.$.disabled,ps,T.id,vt.vertexBuffer,vt.indexBuffer,Fs,T.paint,L.transform.zoom)}},drawGroundShadowMask:function(L,k,T,B){if(!k||!T.layout||T.layout.get("fill-elevation-reference")==="none"||T.paint.get("fill-opacity").constantOr(1)===0)return;const K=L.context.gl,Q=new o.Z(K.LEQUAL,o.Z.ReadOnly,L.depthRangeFor3D),oe=new o._({func:K.ALWAYS,mask:255},255,255,K.KEEP,K.KEEP,K.REPLACE),me=L.transform.getFreeCameraOptions().position;let we;for(const Me of B){const Re=k.getTile(Me),Ze=Re.getBucket(T);if(!Ze)continue;const Qe=Ze.hdExt?Ze.hdExt.elevatedStructures:void 0;if(!Qe||!Qe.depthSegments||Qe.depthSegments.segments[0].primitiveLength===0)continue;const ut=Zc(Me.toUnwrapped(),me),bt=L.translatePosMatrix(Me.projMatrix,Re,T.paint.get("fill-translate"),T.paint.get("fill-translate-anchor"));we=we||L.getOrCreateProgram("elevatedStructuresDepthReconstruct");const vt=Ad(bt,ut,0,1,0);we.draw(L,K.TRIANGLES,Q,oe,o.a1.disabled,o.$.disabled,vt,T.id,Qe.vertexBuffer,Qe.indexBuffer,Qe.depthSegments,T.paint,L.transform.zoom)}},IndoorManager:class extends o.E{constructor(L,k=!1){super(),this._style=L,this._buildings={},this._activeFloors=new Set,this._closestBuildingId=null,this._indoorState={selectedFloorId:null,activeFloorsVisible:!0,activeFloors:this._activeFloors},this._buildingDetectionStrategy=new La,this._initialLoadDone=!1,o.aW(["_updateUI"],this);const T=()=>{this._style.isIndoorEnabled()&&(this._style.map.on("load",()=>{this._initialLoadDone=!0,this._indoorState&&this._indoorState.needsUpdate&&(this._indoorState.needsUpdate=!1,this._style.updateIndoorDependentLayers()),this._updateUI()}),this._style.map.on("move",this._updateUI),this._style.map.on("idle",this._updateUI))};k?(this._initialLoadDone=!0,T()):this._style.on("style.load",T)}destroy(){this._buildings={},this._activeFloors=new Set,this._indoorState=null}selectFloor(L){L===this._selectedFloorId&&this._indoorState&&this._indoorState.activeFloorsVisible||(this._selectedFloorId=L,this._recalculateActiveFloors())}setActiveFloorsVisibility(L){this._updateActiveFloors(L),this._updateIndoorSelector()}setIndoorData(L){let k=!1;for(const[T,B]of Object.entries(L.buildings))if(this._buildings[T])for(const K of B.floorIds)this._buildings[T].floorIds.add(K),this._buildings[T].floors[K]?this._mergeFloors(this._buildings[T].floors[K],B.floors[K]):(this._buildings[T].floors[K]=B.floors[K],k=!0);else this._buildings[T]=B,k=!0;k&&this._recalculateActiveFloors()}getIndoorTileOptions(L,k){return this._indoorState?{sourceLayers:this._style.getIndoorSourceLayers(L,k),indoorState:this._indoorState}:null}getControlState(){const L=this._buildings,k=this._closestBuildingId,T=k&&L?L[k]:void 0;if(!T)return{selectedFloorId:null,activeFloorsVisible:!!this._indoorState&&this._indoorState.activeFloorsVisible,floors:[]};let B=null;for(const Q of T.floorIds)if(this._activeFloors&&this._activeFloors.has(Q)){B=Q;break}const K=Array.from(T.floorIds).map(Q=>({id:Q,name:T.floors[Q].name,zIndex:T.floors[Q].zIndex})).sort((Q,oe)=>oe.zIndex-Q.zIndex).filter((Q,oe,me)=>oe===0||Q.zIndex!==me[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 me=oe.frcCoveragePolygons;k.manager.addTileCoverage(oe.tileID.canonical,me&&me.length>0?me:[])}}const T=k.manager.updateSnapshotIfNeeded();if(L.map.painter&&(L.map.painter.frcCoverageSnapshot=T.empty()?null:T),!T.empty()){const B=[L._mergedOtherSourceCaches,L._mergedSymbolSourceCaches];for(const K of B)for(const Q in K){const oe=K[Q];for(const me in oe._tiles){const we=oe._tiles[me];we&&we.hasDeferredRoadStructure&&(we.hasDeferredRoadStructure=!1,oe._reloadTile(+me,"reloading"))}}}},updateHdCoverageSourceCache:function(L,k,T){if(T.type!=="fill"||T.sourceLayer!==o.bV||k.coverageSourceCaches[T.source])return;const B=L.getOwnSource(T.source);if(!B||B.type!=="vector")return;const K=`hd-road-coverage:${T.source}`,Q=o.m(K,L.scope),oe=L._sourceCaches[K]=new Ci(Q,B,o.bS.HdRoadCoverage);k.coverageSourceCaches[T.source]=oe,oe.setMaxzoomOverride(14),oe.onAdd(L.map);const me=L._otherSourceCaches[T.source];me&&me._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 me=o.m("sdCoverageFadeRange",Q.scope),we=Q.options?Q.options.get(me):void 0,Me=we?we.value||we.default:null;if(Me){const ut=Me.evaluate(K);Array.isArray(ut)&&ut.length===2&&(ut[0]>0||ut[1]>0)&&(T=[ut[0],ut[1]])}const Re=o.m("sdCoverageSourceLayers",Q.scope),Ze=Q.options?Q.options.get(Re):void 0,Qe=Ze?Ze.value||Ze.default:null;if(Qe){const ut=Qe.evaluate(K);Array.isArray(ut)&&ut.length>0&&(B=ut)}else{const ut=L.stylesheet&&L.stylesheet.imports||[];for(const bt of ut)if(bt.id===Q.scope){const vt=bt.config?bt.config.sdCoverageSourceLayers:void 0;Array.isArray(vt)&&vt.length>0&&(B=vt);break}}}),k.frcCoverageFadeRange=T,k.frcCoverageSourceLayers=T!=null?B||["road","structure"]:[]},HdElevationState:$0,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=ih(L,L.map&&L.map.transform);L._hdElevation||(L._hdElevation=new $0);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=ag(L),Ud(L,B)},updateElevationCoverage:Ud,updateCrossSourceElevationGate:function(L){L._crossSourceElevationActive=Qc(L)},buildElevationRequestParams:function(L,k,T){if(ih(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,me){const we=Q.getTilesIntersecting(oe);if(we.length===0)return{registry:[],hasCoveringTile:!1,allProvidersReady:me};const Me=[];for(const Re of we)for(const Ze of Re.features)Me.push({tileId:Re.tileId,feature:Ze});return Me.sort((Re,Ze)=>Re.feature.id-Ze.feature.id),{registry:Me,hasCoveringTile:!0,allProvidersReady:me}}(B,k.tileID.canonical,K):{registry:[],hasCoveringTile:!1,allProvidersReady:K}},FrcCoverageRenderer:class{constructor(){this.tileBuffers=new Map,this._context=null}update(L,k){this._context=L;const T=new Set;for(const B of k){if(B.frcMask===0)continue;let K=!1;for(const 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 me=T.length,we=B.length,Me=T.length,Re=[],Ze=[];let Qe=0;for(let bt=0;bt0&&Ze.push(Qe);for(const Mt of vt)T.emplaceBack(Mt.x,Mt.y),Re.push(Mt.x,Mt.y),Qe++}}const ut=o.bG(Re,Ze.length>0?Ze:void 0);for(let bt=0;bt0&&L.program.draw(k,L.drawMode,L.depthMode,L.stencilMode,L.colorMode,o.$.disabled,L.uniformValues,L.layer.id,L.bufferData.layoutVertexBuffer,L.indexBuffer,we.frcNonRoadSegments,L.layer.paint,Qe,L.programConfiguration,L.dynamicBuffers),"drawn"}return"fallthrough"},drawFillFrcCoverageSecondPass:function(L,k,T,B,K){if(T.length===0)return;const Q=Ih(L),oe=L.transform.zoom,me=(we,Me,Re)=>{Re!==1&&(we.uniformValues.u_opacity_multiplier=Re),we.program.draw(L,B,we.depthMode,Me,K,o.$.disabled,we.uniformValues,k.id,we.bufferData.layoutVertexBuffer,we.indexBuffer,we.segments,k.paint,oe,we.programConfiguration,we.dynamicBuffers),Re!==1&&(we.uniformValues.u_opacity_multiplier=1)};zm(L,T,Q,(we,Me,Re)=>me(we,Re,1),(we,Me,Re)=>me(we,Re,Q))},drawLineFrcCoverageDetect:function(L,k,T,B,K,Q,oe,me,we,Me){const Re=k.hdExt&&k.hdExt.frcData;if(!Re||Re.frcPerLevel.size===0||!L.frcCoverageSnapshot||B)return null;const Ze=L.frcCoverageSnapshot.getTileOrParent(T.canonical);if(!Ze||Ze.frcMask===0)return null;const Qe=yu(Ze.polygons),ut=L.frcCoverageFadeRange,bt=ut!=null&&L.transform.zoom>=ut[0];if(Qe&&bt){let vt=!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 me=k.hdExt&&k.hdExt.frcData;if(!me||!L.frcCoverageFadeRange)return;const[we,Me]=L.frcCoverageFadeRange;if(we>=Me)return;const Re=1-Math.max(0,Math.min(1,(L.transform.zoom-we)/(Me-we)));if(Re<=0)return;const Ze=K?Q:L.stencilModeForClipping(T),Qe=B.frcMask;for(const[ut,bt]of me.frcPerLevel)Qe&1<{const Ze=me.bucket.hdExt&&me.bucket.hdExt.frcData,Qe=Ze&&Ze.frcPerLevel.get(we);Qe&&Qe.segments.length!==0&&(Re!==1&&(me.uniformValues.u_opacity_multiplier=Re),me.program.draw(L,B.TRIANGLES,me.depthMode,Me,me.colorMode,o.$.disabled,me.uniformValues,k.id,me.bucket.layoutVertexBuffer,me.bucket.indexBuffer,Qe,k.paint,Q,me.programConfiguration,[me.bucket.layoutVertexBuffer2,me.bucket.patternVertexBuffer,me.bucket.zOffsetVertexBuffer,me.bucket.elevationIdColVertexBuffer,me.bucket.elevationGroundScaleVertexBuffer]),Re!==1&&(me.uniformValues.u_opacity_multiplier=1))};zm(L,T,K,(me,we,Me)=>oe(me,we,Me,1),(me,we,Me)=>oe(me,we,Me,K))}},Ui=yh;async function um(){return Promise.resolve()}function lh(L,k){const T=Math.pow(2,k.canonical.z),B=k.canonical.y;return[new o.bT(0,B/T).toLngLat().lat,new o.bT(0,(B+1)/T).toLngLat().lat]}function np(L,k,T,B,K,Q,oe){const me=L.context,we=me.gl,Me=T.hillshadeFBO;if(!Me)return;L.prepareDrawTile();const Re=L.isTileAffectedByFog(k),Ze=[];L.terrain&&L.terrain.renderingToTexture&&L.isEmissiveMrtActive()&&(Ze.push("USE_MRT1"),L.emissiveMode==="mrt-full-rgba"&&Ze.push("USE_MRT1_RGBA"));const Qe=L.getOrCreateProgram("hillshade",{overrideFog:Re,defines:Ze});me.activeTexture.set(we.TEXTURE0),we.bindTexture(we.TEXTURE_2D,Me.colorAttachment0.get());const ut=((es,Qt,Lt,ps)=>{const Hs=Lt.paint.get("hillshade-shadow-color"),Fs=Lt.paint.get("hillshade-shadow-color-use-theme").constantOr("default")==="none",nn=Lt.paint.get("hillshade-highlight-color"),$s=Lt.paint.get("hillshade-highlight-color-use-theme").constantOr("default")==="none",rn=Lt.paint.get("hillshade-accent-color"),_n=Lt.paint.get("hillshade-accent-color-use-theme").constantOr("default")==="none",Mn=Lt.paint.get("hillshade-emissive-strength");let Kn=o.av(Lt.paint.get("hillshade-illumination-direction"));if(Lt.paint.get("hillshade-illumination-anchor")==="viewport")Kn-=es.transform.angle;else if(es.style&&es.style.enable3dLights()&&es.style.directionalLight){const On=es.style.directionalLight.properties.get("direction"),Rr=o.b_(On.x,On.y,On.z);Kn=o.av(Rr[1])}const Bn=!es.options.moving;return{u_matrix:ps||es.transform.calculateProjMatrix(Qt.tileID.toUnwrapped(),Bn),u_image:0,u_latrange:lh(0,Qt.tileID),u_light:[Lt.paint.get("hillshade-exaggeration"),Kn],u_shadow:Hs.toPremultipliedRenderColor(Fs?null:Lt.lut),u_highlight:nn.toPremultipliedRenderColor($s?null:Lt.lut),u_emissive_strength:Mn,u_accent:rn.toPremultipliedRenderColor(_n?null:Lt.lut)}})(L,T,B,L.terrain?k.projMatrix:null);L.uploadCommonUniforms(me,Qe,k.toUnwrapped());const{tileBoundsBuffer:bt,tileBoundsIndexBuffer:vt,tileBoundsSegments:Mt}=L.getTileBoundsBuffers(T);Qe.draw(L,we.TRIANGLES,K,Q,oe,o.$.disabled,ut,B.id,bt,vt,Mt)}function Qg(L,k,T){if(!k.needsDEMTextureUpload)return;const B=L.context,K=B.gl;B.pixelStoreUnpackPremultiplyAlpha.set(!1),k.demTexture=k.demTexture||L.getTileTexture(T.stride);const Q=T.getPixels();k.demTexture?k.demTexture.update(Q,{premultiply:!1}):k.demTexture=new o.T(B,Q,K.R32F,{premultiply:!1}),k.needsDEMTextureUpload=!1}function ch(L,k,T){const B=L.context,K=B.gl;if(!k.dem)return;const Q=k.dem;if(B.activeTexture.set(K.TEXTURE1),Qg(L,k,Q),!k.demTexture)return;k.demTexture.bind(K.NEAREST,K.CLAMP_TO_EDGE);const oe=Q.dim;B.activeTexture.set(K.TEXTURE0);let me=k.hillshadeFBO;if(!me){const Qe=new o.T(B,{width:oe,height:oe,data:null},K.RGBA8);Qe.bind(K.LINEAR,K.CLAMP_TO_EDGE),me=k.hillshadeFBO=B.createFramebuffer(oe,oe,1,"renderbuffer"),me.colorAttachment0.set(Qe.texture)}B.bindFramebuffer.set(me.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,((Qe,ut)=>{const bt=ut.stride,vt=o.Y();return o.bZ(vt,0,o.a6,-o.a6,0,0,1),o.bN(vt,vt,[0,-o.a6,0]),{u_matrix:vt,u_image:1,u_dimension:[bt,bt],u_zoom:Qe.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 Jg 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 I1 extends Ic{getDefault(){return 1}set(k){(k!==this.current||this.dirty)&&(this.gl.clearDepth(k),this.current=k,this.dirty=!1)}}class L1 extends Ic{getDefault(){return 0}set(k){(k!==this.current||this.dirty)&&(this.gl.clearStencil(k),this.current=k,this.dirty=!1)}}class R1 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 Yw extends Ic{getDefault(){return!0}set(k){(k!==this.current||this.dirty)&&(this.gl.depthMask(k),this.current=k,this.dirty=!1)}}class Zw extends Ic{getDefault(){return 255}set(k){(k!==this.current||this.dirty)&&(this.gl.stencilMask(k),this.current=k,this.dirty=!1)}}class F_ 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 Pk 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 Ib 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 zv 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 k3 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 V2 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 rp 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 Ik 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 D1 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 ex 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 ap 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 Fx 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 qd 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 Bv=class extends Ic{getDefault(){return null}set(L){(L!==this.current||this.dirty)&&(this.gl.useProgram(L),this.current=L,this.dirty=!1)}};class IC 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 qT 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 VT 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 S3 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 Lb 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 Tp 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 U0 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 LC 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 C3 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 Rb 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 ip 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 Xw extends Ic{constructor(k,T){super(k),this.context=k,this.parent=T}getDefault(){return null}}class Dr extends Xw{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 Lk extends Xw{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 RC extends Xw{attachment(){return this.gl.DEPTH_ATTACHMENT}set(k){if(k===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const T=this.gl;T.framebufferTexture2D(T.FRAMEBUFFER,this.attachment(),T.TEXTURE_2D,k,0),this.current=k,this.dirty=!1}}class tx extends Lk{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}),F1=(L,k,T,B,K,Q,oe,me,we,Me,Re,Ze,Qe,ut,bt,vt,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:me,u_frustum_br:we,u_frustum_bl:Me,u_globe_pos:Re,u_globe_radius:Ze,u_viewport:Qe,u_grid_matrix:Mt?Float32Array.from(Mt):new Float32Array(9),u_skirt_height:ut,u_far_z_cutoff:bt,u_emissive_texture_available:vt});function q0(L,k){return L!=null&&k!=null&&!(!L.hasData()||!k.hasData())&&L.demTexture!=null&&k.demTexture!=null&&L.tileID.key!==k.tileID.key}const V0=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 Ox(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 Rk(L,k){const T=1<{if(Q[oe.key]="",!this._tiles[oe.key]){const me=new Lx(oe,this._source.tileSize*oe.overscaleFactor(),k.tileZoom,void 0,void 0,this._source.worldview);me.state="loaded",this._tiles[oe.key]=me}return Q},{});for(const Q in this._tiles)Q in K||(this.freeFBO(Q),this._tiles[Q].unloadVectorData(),delete this._tiles[Q])}freeFBO(k){const T=this.proxyCachedFBO[k];if(T!==void 0){const B=Object.values(T);this.renderCachePool.push(...B),delete this.proxyCachedFBO[k]}}deallocRenderCache(){this.renderCache.forEach(k=>k.fb.destroy()),this.renderCache=[],this.renderCachePool=[],this.proxyCachedFBO={}}}class Qw 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 z_(L,k){return k==="rgba8"?L.RGBA8:L.R8}class DC extends o.c2{constructor(k,T){super(),this.painter=k,this.terrainTileForTile={},this.prevTerrainTileForTile={};const[B,K,Q]=function(){const we=new o.bD,Me=new o.ae,Re=131;we.reserve(17161),Me.reserve(33800);const Ze=o.a6/128,Qe=o.a6+Ze/2,ut=Qe+Ze;for(let vt=-Ze;vtQe||vt<0||vt>Qe?24575:0,Qt=o.b1(Math.round(Mt),0,o.a6),Lt=o.b1(Math.round(vt),0,o.a6);we.emplaceBack(Qt+es,Lt)}const bt=(vt,Mt)=>{const es=Mt*Re+vt;Me.emplaceBack(es+1,es,es+Re),Me.emplaceBack(es+Re,es+Re+1,es+1)};for(let vt=1;vt<129;vt++)for(let Mt=1;Mt<129;Mt++)bt(Mt,vt);return[0,129].forEach(vt=>{for(let Mt=0;Mt<130;Mt++)bt(Mt,vt),bt(vt,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 O_(T.map),this.orthoMatrix=o.Y(),o.bZ(this.orthoMatrix,this.painter.transform.projection.name==="globe"?.015:0,o.a6,0,o.a6,0,1);const me=oe.gl;this._overlapStencilMode=new o._({func:me.GEQUAL,mask:255},0,255,me.KEEP,me.KEEP,me.REPLACE),this._previousZoom=k.transform.zoom,this.pool=[],this._findCoveringTileCache={},this._tilesDirty={},this.style=T,this._useVertexMorphing=!0,this._exaggeration=1,this._mockSourceCache=new Fk(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 me=k.terrain&&k.terrain.scope,we=K.get("source"),Me=Q?this._mockSourceCache:k.getSourceCache(we,me);if(!Me)return void o.w(`Couldn't find terrain source "${we}".`);if(this.sourceCache=Me,this._attenuationRange=k.terrain.getAttenuationRange(),this._exaggeration=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 me=Q-this._previousZoom;const we=this._previousUpdateTimestamp;let Me=Q;this._evaluationZoom!=null&&(Me=this._evaluationZoom,Math.abs(Q-Me)>.5&&(me=.5*(Q-Me+me)),me*K<0&&(Me+=me)),this._evaluationZoom=Me;const Re=oe.getExaggeration(Me),Ze=Re===oe.getExaggeration(Math.max(0,Me-.1));if(Ze&&Math.abs(Re-this._exaggeration)<.01)return Re;let Qe=Math.min(.1,.00375*(this._updateTimestamp-we));return(Ze||Re<.1||Math.abs(me)<1e-4)&&(Qe=Math.min(.2,4*Qe)),o.am(this._exaggeration,Re,Qe)}resetTileLookupCache(k){this._findCoveringTileCache[k]={}}attenuationRange(){return this._attenuationRange}getDemUpscale(){return this.proxySourceCache.getSource().tileSize/128}getScaledDemTileSize(){return this.sourceCache.getSource().tileSize/128*this.proxySourceCache.getSource().tileSize}_onStyleDataEvent(k){k.dataType==="source"&&k.coord?this._clearRenderCacheForTile(k.sourceCacheId,k.coord):k.dataType==="style"&&(this.invalidateRenderCache=!0,this._evaluationZoom=void 0,this._previousUpdateTimestamp=void 0,this._previousCameraAltitude=void 0)}_disable(){if(this.enabled&&(this.enabled=!1,this._emptyDEMTextureDirty=!0,this._sharedDepthStencil=void 0,this._evaluationZoom=void 0,this._previousUpdateTimestamp=void 0,this.proxySourceCache.deallocRenderCache(),this._style))for(const k in this._style._mergedSourceCaches)this._style._mergedSourceCaches[k].usedForTerrain=!1}destroy(){this._disable(),this._emptyDEMTexture&&this._emptyDEMTexture.destroy(),this.pool.forEach(k=>k.fb.destroy()),this.pool=[],this.framebufferCopyTexture&&this.framebufferCopyTexture.destroy()}_source(){return this.enabled?this.sourceCache:null}isUsingMockSource(){return this.sourceCache===this._mockSourceCache}exaggeration(){return this.enabled?this._exaggeration:0}get visibleDemTiles(){return this._visibleDemTiles}get drapeBufferSize(){const k=2*this.proxySourceCache.getSource().tileSize;return[k,k]}set useVertexMorphing(k){this._useVertexMorphing=k}updateTileBinding(k){if(!this.enabled)return;this.prevTerrainTileForTile=this.terrainTileForTile;const T=this.proxySourceCache,B=this.painter.transform;this._initializing&&(this._initializing=B._centerAltitude===0&&this.getAtPointOrZero(o.bT.fromLngLat(B.center),-1)===-1,this._emptyDEMTextureDirty=!this._initializing);const K=this.proxyCoords=T.getIds().map(we=>{const Me=T.getTileByID(we).tileID;return Me.projMatrix=B.calculateProjMatrix(Me.toUnwrapped()),Me});(function(we,Me){const Re=Me.transform.pointCoordinate(Me.transform.getCameraPoint()),Ze=new o.P(Re.x,Re.y);we.sort((Qe,ut)=>{if(ut.overscaledZ-Qe.overscaledZ)return ut.overscaledZ-Qe.overscaledZ;const bt=new o.P(Qe.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 Qw(we,we.key,this.orthoMatrix)),this._assignTerrainTiles(K),this._prepareDEMTextures(),this._setupDrapedRenderBatches(),this._initFBOPool(),this._setupRenderCache(Q),this.renderingToTexture=!1;const me={};this._visibleDemTiles=[];for(const we of this.proxyCoords){const Me=this.terrainTileForTile[we.key];if(!Me)continue;const Re=Me.tileID.key;Re in me||(this._visibleDemTiles.push(Me),me[Re]=Re)}}_assignTerrainTiles(k){this._initializing||k.forEach(T=>{if(this.terrainTileForTile[T.key])return;const B=this._findTileCoveringTileID(T,this.sourceCache);B&&(this.terrainTileForTile[T.key]=B)})}_prepareDEMTextures(){const k=this.painter.context,T=k.gl;for(const B in this.terrainTileForTile){const K=this.terrainTileForTile[B],Q=K.dem;!Q||K.demTexture&&!K.needsDEMTextureUpload||(k.activeTexture.set(T.TEXTURE1),Qg(this.painter,K,Q))}}_prepareDemTileUniforms(k,T,B,K){if(!T||T.demTexture==null)return!1;const Q=k.tileID.canonical,oe=Math.pow(2,T.tileID.canonical.z-Q.z),me=K||"";return B[`u_dem_tl${me}`]=[Q.x*oe%1,Q.y*oe%1],B[`u_dem_scale${me}`]=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 me=null,we=null,Me=1;if(B&&B.morphing&&this._useVertexMorphing){const ut=B.morphing.srcDemTile,bt=B.morphing.dstDemTile;Me=B.morphing.phase,ut&&bt&&(this._prepareDemTileUniforms(k,ut,oe,"_prev")&&(we=ut),this._prepareDemTileUniforms(k,bt,oe)&&(me=bt))}const Re=ut=>ut&&ut.demTexture&&this.painter.linearFloatFilteringSupported()?Q.LINEAR:Q.NEAREST;let Ze=null;var Qe;if(this.enabled?we&&me?(Ze=me.demTexture,K.activeTexture.set(Q.TEXTURE4),we.demTexture.bind(Re(we),Q.CLAMP_TO_EDGE),oe.u_dem_lerp=Me):(me=this.terrainTileForTile[k.tileID.key],Ze=this._prepareDemTileUniforms(k,me,oe)?me.demTexture:this.emptyDEMTexture):Ze=this.emptyDEMTexture,K.activeTexture.set(Q.TEXTURE2),Ze&&(oe.u_dem_size=(Qe=Ze).size[0]===1?1:Qe.size[0]-2,Ze.bind(Re(me),Q.CLAMP_TO_EDGE)),this.painter.setupDepthForOcclusion(B&&B.useDepthForOcclusion,T,oe),B&&B.useMeterToDem&&me){const ut=(1<{if(es===On)return;const Rr=[];On===1&&Rr.push("TERRAIN_VERTEX_MORPHING"),Rr.push("PROJECTION_GLOBE_VIEW"),Lt&&Rr.push("CUSTOM_ANTIALIASING");const An=Me.isTileAffectedByFog(Bn);Mt=Me.getOrCreateProgram("globeRaster",{defines:Rr,overrideFog:An}),es=On},Hs=Me.colorModeForRenderPass(),Fs=new o.Z(vt.LEQUAL,o.Z.ReadWrite,Me.depthRangeFor3D);V0.update(ut);const nn=o.b7(Qt),$s=[o.a7(Qt.center.lng),o.a8(Qt.center.lat)],rn=Me.globeSharedBuffers,_n=[Qt.width*o.e.devicePixelRatio,Qt.height*o.e.devicePixelRatio],Mn=Float32Array.from(Qt.globeMatrix),Kn={useDenormalizedUpVectorScale:!0};{const Bn=Me.transform,On=Ox(Bn.zoom,Re.exaggeration(),Re.sourceCache._source.tileSize);es=-1;const Rr=vt.TRIANGLES;for(const An of Qe){const xr=Ze.getTile(An),sa=o._.disabled,ka=Re.prevTerrainTileForTile[An.key],Hr=Re.terrainTileForTile[An.key];q0(ka,Hr)&&V0.newMorphing(An.key,ka,Hr,ut,250),H2(Me,xr.emissiveTexture),bt.activeTexture.set(vt.TEXTURE0),xr.texture&&xr.texture.bind(vt.LINEAR,vt.CLAMP_TO_EDGE);const ea=V0.getMorphValuesForProxy(An.key),si=ea?1:0;ea&&Object.assign(Kn,{morphing:{srcDemTile:ea.from,dstDemTile:ea.to,phase:o.b$(ea.phase)}});const Wr=o.b3(An.canonical),Tr=o.b4(Wr.getCenter().lat),Gr=o.b8(An.canonical,Wr,Tr,Bn.worldSize/Bn._pixelsPerMercatorPixel),Ga=o.b5(o.b6(An.canonical)),qr=Me.isEmissiveMrtActive()?1:0,Za=F1(Bn.expandedFarZProjMatrix,Mn,nn,Ga,o.S(Bn.zoom),$s,Bn.frustumCorners.TL,Bn.frustumCorners.TR,Bn.frustumCorners.BR,Bn.frustumCorners.BL,Bn.globeCenterInViewSpace,Bn.globeRadius,_n,On,Bn._farZ,qr,Gr);if(ps(An,si),Mt&&(Re.setupElevationDraw(xr,Mt,Kn),Me.uploadCommonUniforms(bt,Mt,An.toUnwrapped()),rn)){const[Oi,Do,so]=rn.getGridBuffers(Tr,On!==0);Mt.draw(Me,Rr,Fs,sa,Hs,o.$.backCCW,Za,"globe_raster",Oi,Do,so)}}}if(rn&&(Me.renderDefaultNorthPole||Me.renderDefaultSouthPole)){const Bn=["GLOBE_POLES","PROJECTION_GLOBE_VIEW"];Lt&&Bn.push("CUSTOM_ANTIALIASING"),Mt=Me.getOrCreateProgram("globeRaster",{defines:Bn});for(const On of Qe){const{x:Rr,y:An,z:xr}=On.canonical,sa=An===0,ka=An===(1<Oi.draw(Me,vt.TRIANGLES,Fs,o._.disabled,Hs,o.$.disabled,F1(Qt.expandedFarZProjMatrix,Gr,Gr,Ga,0,$s,Qt.frustumCorners.TL,Qt.frustumCorners.TR,Qt.frustumCorners.BR,Qt.frustumCorners.BL,Qt.globeCenterInViewSpace,Qt.globeRadius,_n,0,Qt._farZ,qr),"globe_pole_raster",Do,si,Wr);Re.setupElevationDraw(Tr,Mt,Kn),Me.uploadCommonUniforms(bt,Mt,On.toUnwrapped()),sa&&Me.renderDefaultNorthPole&&Za(Mt,Hr),ka&&Me.renderDefaultSouthPole&&(Gr=o.aO(o.Y(),Gr,[1,-1,1]),Za(Mt,ea))}}}})(K,Q,oe,me,we);else{const Me=K.context,Re=Me.gl;let Ze,Qe;const ut=K.shadowRenderer,bt=o.aF(K,K.longestCutoffRange),vt=Hs=>{if(Qe===Hs)return;const Fs=[];Hs===1&&Fs.push("TERRAIN_VERTEX_MORPHING"),bt.shouldRenderCutoff&&Fs.push("RENDER_CUTOFF"),ut&&(Fs.push("RENDER_SHADOWS"),ut.useNormalOffset&&Fs.push("NORMAL_OFFSET")),Ze=K.getOrCreateProgram("terrainRaster",{defines:Fs}),Qe=Hs},Mt=K.colorModeForRenderPass(),es=new o.Z(Re.LEQUAL,o.Z.ReadWrite,K.depthRangeFor3D);V0.update(we);const Qt=K.transform,Lt=Ox(Qt.zoom,Q.exaggeration(),Q.sourceCache._source.tileSize);let ps=[0,0,0];if(ut){const Hs=K.style.directionalLight,Fs=K.style.ambientLight;Hs&&Fs&&(ps=o.aG(K.style,Hs,Fs))}{Qe=-1;const Hs=Re.TRIANGLES,[Fs,nn]=[Q.gridIndexBuffer,Q.gridSegments];for(const $s of me){const rn=oe.getTile($s),_n=o._.disabled,Mn=Q.prevTerrainTileForTile[$s.key],Kn=Q.terrainTileForTile[$s.key];q0(Mn,Kn)&&V0.newMorphing($s.key,Mn,Kn,we,250),H2(K,rn.emissiveTexture),Me.activeTexture.set(Re.TEXTURE0),rn.texture&&rn.texture.bind(Re.LINEAR,Re.CLAMP_TO_EDGE);const Bn=V0.getMorphValuesForProxy($s.key),On=Bn?1:0;let Rr;Bn&&(Rr={morphing:{srcDemTile:Bn.from,dstDemTile:Bn.to,phase:o.b$(Bn.phase)}});const An=K.isEmissiveMrtActive()?1:0,xr=uf($s.projMatrix,Rk($s.canonical,Qt.renderWorldCopies)?Lt/10:Lt,ps,An);if(vt(On),!Ze)continue;Q.setupElevationDraw(rn,Ze,Rr);const sa=$s.toUnwrapped();ut&&ut.setupShadows(sa,Ze),K.uploadCommonUniforms(Me,Ze,sa,null,bt),Ze.draw(K,Hs,es,_n,Mt,o.$.backCCW,xr,"terrain_raster",Q.gridBuffer,Fs,nn)}}}}(T,this,this.proxySourceCache,k,this._updateTimestamp),this.renderingToTexture=!0,T.gpuTimingDeferredRenderEnd(),k.splice(0,k.length))}renderBatch(k){if(this._drapedRenderBatches.length===0)return k+1;this.renderingToTexture=!0;const T=this.painter,B=this.painter.context,K=this.proxySourceCache,Q=this.proxiedCoords[K.id],oe=this._drapedRenderBatches.shift(),me=T.style.order,we=[];this._updateFBOs(T.emissiveMode==="mrt-full-rgba"?"rgba8":T.emissiveMode==="mrt-fallback"?"r8":"none");let Me=0;for(const Re of Q){const Ze=K.getTileByID(Re.proxyTileKey),Qe=K.proxyCachedFBO[Re.key]?K.proxyCachedFBO[Re.key][k]:void 0,ut=Qe!==void 0?K.renderCache[Qe]:this.pool[Me++],bt=Qe!==void 0;if(Ze.texture=ut.tex,Ze.emissiveTexture=ut.emissiveTex,bt&&!ut.dirty){we.push(Ze.tileID);continue}B.bindFramebuffer.set(ut.fb.framebuffer);const vt=B.gl;let Mt;T.isEmissiveMrtActive()?vt.drawBuffers([vt.COLOR_ATTACHMENT0,vt.COLOR_ATTACHMENT1]):vt.drawBuffers([vt.COLOR_ATTACHMENT0]),this.renderedToTile=!1,ut.dirty&&(B.clear({color:o.C.transparent,stencil:0}),ut.dirty=!1);for(let es=oe.start;es<=oe.end;++es){const Qt=T.style._mergedLayers[me[es]];if(Qt.isHidden(T.transform.zoom))continue;const Lt=T.style.getLayerSourceCache(Qt),ps=Lt?this.proxyToSource[Re.key][Lt.id]:[Re];if(!ps)continue;const Hs=ps;B.viewport.set([0,0,ut.fb.width,ut.fb.height]),Mt!==(Lt?Lt.id:null)&&(this._setupStencil(ut,ps,Qt,Lt),Mt=Lt?Lt.id:null),T.renderLayer(T,Lt,Qt,Hs)}if(vt.drawBuffers([vt.COLOR_ATTACHMENT0]),this._drapedRenderBatches.length===0)for(const es of this._pendingGroundEffectLayers){const Qt=T.style._mergedLayers[me[es]];if(Qt.isHidden(T.transform.zoom))continue;const Lt=T.style.getLayerSourceCache(Qt),ps=Lt?this.proxyToSource[Re.key][Lt.id]:[Re];if(!ps)continue;const Hs=ps;B.viewport.set([0,0,ut.fb.width,ut.fb.height]),Mt!==(Lt?Lt.id:null)&&(this._setupStencil(ut,ps,Qt,Lt),Mt=Lt?Lt.id:null),T.renderLayer(T,Lt,Qt,Hs)}this.renderedToTile?(ut.dirty=!0,we.push(Ze.tileID)):bt||--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,me=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},z_(T,this._emissiveTexture)),oe.bind(T.LINEAR,T.CLAMP_TO_EDGE),Q.createColorAttachment(k,1),Q.colorAttachment1.set(oe.texture)),Q.depthAttachment=new tx(k,Q.framebuffer),this._sharedDepthStencil===void 0?(this._sharedDepthStencil=k.createRenderbuffer(k.gl.DEPTH_STENCIL,B[0],B[1]),this._stencilRef=0,Q.depthAttachment.set(this._sharedDepthStencil),k.clear({stencil:0})):Q.depthAttachment.set(this._sharedDepthStencil),k.extTextureFilterAnisotropic&&T.texParameterf(T.TEXTURE_2D,k.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,k.extTextureFilterAnisotropicMax),{fb:Q,tex:K,emissiveTex: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 me=new o.T(K,{width:oe[0],height:oe[1],data:null},z_(Q,T));me.bind(Q.LINEAR,Q.CLAMP_TO_EDGE),k.emissiveTex=me,B.createColorAttachment(K,1),B.colorAttachment1.set(me.texture)}else k.emissiveTex=void 0,B.removeColorAttachment(K,1);k.dirty=!0}_initFBOPool(){for(;this.pool.length{const T=this._style._mergedLayers[k],B=T.isHidden(this.painter.transform.zoom);return T.type==="hillshade"||T.type==="custom"?!B&&T.shouldRedrape():!B&&T.hasTransition()})}_clearLineLayersFromRenderCache(){let k=!1;for(const B of this._style.getSources())if(B.type==="vector"){k=!0;break}if(!k)return;const T={};for(let B=0;Bwe>me.end)||o.w("fill-extrusion with flood lighting and/or ground ambient occlusion should be moved to be on top of all draped layers.")}this._drapedRenderBatches=B}_setupRenderCache(k){const T=this.proxySourceCache;if(this._shouldDisableRenderCache()||this.invalidateRenderCache){if(this.invalidateRenderCache=!1,T.renderCache.length>T.renderCachePool.length){const oe=Object.values(T.proxyCachedFBO);T.proxyCachedFBO={};for(let me=0;me=0;oe--){const me=B[oe];if(T.getTileByID(me.key),T.proxyCachedFBO[me.key]!==void 0){const we=k[me.key],Me=this.proxyToSource[me.key];let Re=0;for(const Ze in Me){const Qe=Me[Ze],ut=we[Ze];if(!ut||ut.length!==Qe.length||Qe.some((bt,vt)=>bt!==ut[vt]||K[Ze]&&Object.hasOwn(K[Ze],bt.key))){Re=-1;break}++Re}for(const Ze in T.proxyCachedFBO[me.key])T.renderCache[T.proxyCachedFBO[me.key][Ze]].dirty=Re<0||Re!==Object.values(we).length}}const Q=[...this._drapedRenderBatches];Q.sort((oe,me)=>me.end-me.start-(oe.end-oe.start));for(const oe of Q)for(const me of B){if(T.proxyCachedFBO[me.key])continue;let we=T.renderCachePool.pop();we===void 0&&T.renderCache.length<50&&(we=T.renderCache.length,T.renderCache.push(this._createFBO())),we!==void 0&&(T.proxyCachedFBO[me.key]={},T.proxyCachedFBO[me.key][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 me;if(B.isTileClipped())me=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);me=1,this._overlapStencilMode.test={func:oe.GREATER,mask:255},this._overlapStencilType="Mask"}this._stencilRef+me>255&&(Q.clear({stencil:0}),this._stencilRef=0),this._stencilRef+=me,this._overlapStencilMode.ref=this._stencilRef,B.isTileClipped()&&this._renderTileClippingMasks(T,this._overlapStencilMode.ref)}clipOrMaskOverlapStencilType(){return this._overlapStencilType==="Clip"||this._overlapStencilType==="Mask"}stencilModeForRTTOverlap(k){return this.renderingToTexture&&this._overlapStencilType?(this._overlapStencilType==="Clip"&&(this._overlapStencilMode.ref=this.painter._tileClippingMaskIDs[k.key]),this._overlapStencilMode):o._.disabled}_renderTileClippingMasks(k,T){const B=this.painter,K=this.painter.context,Q=K.gl;B._tileClippingMaskIDs={},K.setColorMode(o.a1.disabled),K.setDepthMode(o.Z.disabled);const oe=B.getOrCreateProgram("clippingMask");for(const me of k){const we=B._tileClippingMaskIDs[me.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,xu(me.projMatrix),"$clipping",B.tileExtentBuffer,B.quadTriangleIndexBuffer,B.tileExtentSegments)}}pointCoordinate(k){const T=this.painter.transform;if(k.x<0||k.x>T.width||k.y<0||k.y>T.height)return null;const B=[k.x,k.y,1,1];o.c6(B,B,T.pixelMatrixInverse),o.c7(B,B,1/B[3]),B[0]/=T.worldSize,B[1]/=T.worldSize;const K=T._camera.position,Q=o.c4(1,T.center.lat),oe=[K[0],K[1],K[2]/Q,0],me=o.c8([],B.slice(0,3),oe);o.c9(me,me);const we=this.raycast(oe,me,this._exaggeration);return we!==null&&we?(o.ca(oe,oe,me,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(),me=oe.tileID;if(!me)return;const we=new o.P(me.x,me.y)._div(1<(Ze.min.x=Math.min(Ze.min.x,Qe.x-we.x),Ze.min.y=Math.min(Ze.min.y,Qe.y-we.y),Ze.max.x=Math.max(Ze.max.x,Qe.x-we.x),Ze.max.y=Math.max(Ze.max.y,Qe.y-we.y),Ze),{min:new o.P(Number.MAX_VALUE,Number.MAX_VALUE),max:new o.P(-Number.MAX_VALUE,-Number.MAX_VALUE)}),Re=(Ze,Qe)=>{const ut=Ze.wrap+Ze.canonical.x/(1<Mt+Me.max.x||bt+vtes+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,me,we;K=o.Y();const Me=T.tileID.wrap-k.wrap<0?(oe=o.a6>>Q,me=oe*((T.tileID.canonical.x<=Ze){const Qe=k.canonical.z-Ze;T.getSource().reparseOverscaled?(me=Math.max(k.canonical.z+2,T.transform.tileZoom),oe=new o.bQ(me,k.wrap,Ze,k.canonical.x>>Qe,k.canonical.y>>Qe)):Qe!==0&&(me=Ze,oe=new o.bQ(me,k.wrap,Ze,k.canonical.x>>Qe,k.canonical.y>>Qe))}oe.key!==k.key&&(Me.push(oe.key),B=T.getTile(oe))}const Re=Ze=>{Me.forEach(Qe=>{K[Qe]=Ze}),Me.length=0};for(me-=1;me>=we&&(!B||!B.hasData());me--){B&&Re(B.tileID.key);const Ze=oe.calculateScaledKey(me);if(B=T.getTileByID(Ze),B&&B.hasData())break;const Qe=K[Ze];if(Qe===null)break;Qe===void 0?Me.push(Ze):B=T.getTileByID(Qe)}return Re(B?B.tileID.key:null),B&&B.hasData()?B:null}findDEMTileFor(k){return this.enabled?this._findTileCoveringTileID(k,this.sourceCache):null}prepareDrawTile(){this.renderedToTile=!0}_clearRenderCacheForTile(k,T){let B=this._tilesDirty[k];B||(B=this._tilesDirty[k]={}),B[T.key]=!0}}let G2=null;const B_=[];function sx(L,k){return G2?G2.create(L,k):null}const FC=(L,k,T)=>({u_matrix:L,u_emissive_strength:k,u_ground_shadow_factor:T,u_opacity_multiplier:1}),O1=(L,k,T,B,K,Q=0)=>Object.assign(FC(L,k,K),o.cb(T,B,Q)),Jw=(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(O1(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}),ft=o.Y(),Tt=(L,k,T,B,K,Q,oe)=>{const me=L.transform,we=me.projection.name==="globe",Me=we?o.cc(me.zoom,k.canonical)*me._pixelsPerMercatorPixel:o.cd(T,1,Q),Re={u_matrix:k.projMatrix,u_extrude_scale:Me,u_intensity:oe,u_inv_rot_matrix:ft,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*Qe.paint.get("raster-opacity"),u_image0:0,u_image1:1,u_brightness_low:Qe.paint.get("raster-brightness-min"),u_brightness_high:Qe.paint.get("raster-brightness-max"),u_saturation_factor:o.cg(Qe.paint.get("raster-saturation")),u_contrast_factor:o.cf(Qe.paint.get("raster-contrast")),u_spin_weights:As(Qe.paint.get("raster-hue-rotate")),u_perspective_transform:ut,u_raster_elevation:bt,u_zoom_transition:me,u_merc_center:we,u_cutoff_params:Me,u_colorization_mix:Ul(o.ce,Mt,Qt),u_colorization_offset:po(o.ce,es,Qt),u_color_ramp:vt,u_color_ramp_size:o.ce,u_texture_offset:[ps/(Lt+2*ps),Lt/(Lt+2*ps)],u_texture_res:[Lt+2*ps,Lt+2*ps],u_emissive_strength:Hs,u_zbias_factor:ls(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 Ds=o.Y(),qs=(L,k,T,B,K,Q,oe,me,we,Me,Re,Ze,Qe,ut,bt,vt,Mt,es,Qt,Lt,ps,Hs,Fs,nn,$s)=>{const rn=K.transform,_n={u_is_size_zoom_constant:+(L==="constant"||L==="source"),u_is_size_feature_constant:+(L==="constant"||L==="camera"),u_size_t:k?k.uSizeT:0,u_size:k?k.uSize:0,u_camera_to_center_distance:rn.getCameraToCenterDistance(Lt),u_rotate_symbol:+T,u_aspect_ratio:rn.width/rn.height,u_fade_change:K.options.fadeDuration?K.symbolFadeChange:1,u_matrix:Q,u_label_plane_matrix:oe,u_coord_matrix:me,u_is_text:+Me,u_is_sdf:+Re,u_elevation_from_sea:we?1:0,u_pitch_with_map:+B,u_texsize:Ze,u_texsize_icon:Qe,u_texture:0,u_texture_icon:1,u_tile_id:[0,0,0],u_zoom_transition:0,u_inv_rot_matrix:Ds,u_merc_center:[0,0],u_camera_forward:[0,0,0],u_ecef_origin:[0,0,0],u_tile_matrix:Ds,u_up_vector:[0,-1,0],u_color_adj_mat:Fs,u_icon_transition:nn||0,u_gamma_scale:Re?B?K.transform.getCameraToCenterDistance(Lt)*Math.cos(K.terrain?0:K.transform._pitch):1:0,u_device_pixel_ratio:o.e.devicePixelRatio,u_is_halo:1,u_scale_factor:$s||1,u_ground_shadow_factor:ps,u_inv_matrix:o.aP(o.Y(),oe),u_normal_scale:Hs,u_lutTexture:o.ci.LUT,u_spp_fill_np_color:[0,0,0,1],u_spp_halo_np_color:[0,0,0,0],u_spp_opacity:1,u_spp_halo_width:0,u_spp_halo_blur:0,u_spp_emissive_strength:0,u_spp_occlusion_opacity:1,u_spp_z_offset:0,u_spp_translate_rotation:[1,0],u_spp_zoom_fraction:0,u_opacity_multiplier:1};return Lt.name==="globe"&&(_n.u_tile_id=[bt.canonical.x,bt.canonical.y,1<({u_matrix:L,u_emissive_strength:k,u_opacity:T,u_color:B}),Zn=(L,k,T,B,K,Q,oe,me,we)=>Object.assign(o.cj(K,Q,oe,B,me,we),{u_matrix:L,u_emissive_strength:k,u_opacity:T}),Ar={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){G2=L;for(const k of B_.splice(0))k()})({create:(L,k)=>new DC(L,k)}),Object.assign(Ar,{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 or={shaders:Qs};class br{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]),me=Q.add(oe)._div(2);B=[Q,oe],K=o.cq(Q,oe).every(we=>T.isPointAboveHorizon(we))&&T.isPointAboveHorizon(me)}return new br(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,me=B?this._bufferedCameraMercator(oe,T):this._bufferedScreenMercator(oe,T);let we=k.tileID.wrap+(me.unwrapped?K:0);const Me=me.polygon.map(Mt=>o.cs(k.tileTransform,Mt,we));if(!o.ct(Me,0,0,o.a6,o.a6))return;we=k.tileID.wrap+(this.screenGeometryMercator.unwrapped?K:0);const Re=this.screenGeometryMercator.polygon.map(Mt=>o.cu(k.tileTransform,Mt,we)),Ze=Re.map(Mt=>new o.P(Mt[0],Mt[1])),Qe=o.cu(k.tileTransform,Q,we),ut=Re.map(Mt=>{const es=o.cv(Mt,Mt,Qe);return o.c9(es,es),new o.cw(Qe,es)}),bt=o.cd(k,1,T.zoom)*T._pixelsPerMercatorPixel;return{queryGeometry:this,tilespaceGeometry:Ze,tilespaceRays:ut,bufferedTilespaceGeometry:Me,bufferedTilespaceBounds:(vt=o.cx(Me),vt.min.x=o.b1(vt.min.x,0,o.a6),vt.min.y=o.b1(vt.min.y,0,o.a6),vt.max.x=o.b1(vt.max.x,0,o.a6),vt.max.y=o.b1(vt.max.y,0,o.a6),vt),tile:k,tileID:k.tileID,pixelToTileUnitsFactor:bt};var vt}_bufferedScreenMercator(k,T){const B=pa(k);if(this._screenRaycastCache[B])return this._screenRaycastCache[B];{let K;return K=T.projection.name==="globe"?this._projectAndResample(this.bufferedScreenGeometry(k),T):{polygon:this.bufferedScreenGeometry(k).map(Q=>T.pointCoordinate3D(Q)),unwrapped:!0},this._screenRaycastCache[B]=K,K}}_bufferedCameraMercator(k,T){const B=pa(k);if(this._cameraRaycastCache[B])return this._cameraRaycastCache[B];{let K;return K=T.projection.name==="globe"?this._projectAndResample(this.bufferedCameraGeometryGlobe(k),T):{polygon:this.bufferedCameraGeometry(k).map(Q=>T.pointCoordinate3D(Q)),unwrapped:!0},this._cameraRaycastCache[B]=K,K}}_projectAndResample(k,T){const B=function(Q,oe){const me=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,me),o.c6(Me,Me,me),o.c6(Re,Re,me);const Ze=new o.P(we[0]/we[3],we[1]/we[3]),Qe=new o.P(Me[0]/Me[3],Me[1]/Me[3]),ut=o.cz(Q,Ze)&&we[3]1?aa(Q.slice(0,Mt),oe):[],Lt=Mtnew o.P(ur($s.x),$s.y)),Lt=Lt.map($s=>new o.P(ur($s.x),$s.y));const ps=[...Qt];ps.length===0&&ps.push(Lt.at(-1));const Hs=ps.at(-1),Fs=o.am(Hs.y,(Lt.length===0?Qt[0]:Lt[0]).y,es);let nn;return nn=ut?[new o.P(0,Fs),new o.P(0,0),new o.P(1,0),new o.P(1,Fs)]:[new o.P(1,Fs),new o.P(1,1),new o.P(0,1),new o.P(0,Fs)],ps.push(...nn),Lt.length===0?ps.push(Qt[0]):ps.push(...Lt),{polygon:ps.map($s=>new o.bT($s.x,$s.y)),unwrapped:!1}}(k,T);if(B)return B;const K=function(Q,oe){let me=!1,we=-1/0,Me=0;for(let Ze=0;Zewe&&(we=Q[Ze].x,Me=Ze);for(let Ze=0;Ze.5&&(ut.x{Ze.x-=1}),{polygon:Q,unwrapped:me}}(aa(k,T).map(Q=>new o.P(ur(Q.x),Q.y)),T);return{polygon:K.polygon.map(Q=>new o.bT(Q.x,Q.y)),unwrapped:K.unwrapped}}}function aa(L,k){return o.cA(L,T=>{const B=k.pointCoordinate3D(T);T.x=B.x,T.y=B.y},1/256)}function ur(L){return L<0?1+L%1:L%1}function pa(L){return 100*L|0}class cr 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(me=>me.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 me=new oe(Q);let we=null;if(me.load&&K&&(we=await me.load({request:K}),B.signal.aborted))return;this._tileProvider=me;const Me=o.cM(this._options,we,this.map._requestManager);Me instanceof Error?T(Me):T(null,Me)})().catch(K=>{B.signal.aborted||T(new Error(`Could not load tile provider ${k.name}`,{cause:K}))}),{cancel:()=>B.abort()}}loaded(){return this._loaded}onAdd(k){this.map=k,this.load()}reload(){this.cancelTileJSONRequest();const k=o.m(this.id,this.scope);this.load(()=>this.map.style.clearSource(k))}setTiles(k){return this._options.tiles=k,this.reload(),this}setUrl(k){return this.url=k,this._options.url=k,this.reload(),this}onRemove(k){this.cancelTileJSONRequest()}serialize(){return{...this._options}}hasTile(k){return!this.tileBounds||this.tileBounds.contains(k.canonical)}async loadTile(k,T){const B=o.e.devicePixelRatio>=2,K=this.map._requestManager.normalizeTileURL(k.tileID.canonical.url(this.tiles,this.scheme),B,this.tileSize),Q=new AbortController;if(k.request=Q,this._tileProvider)this.loadTileWithProvider(k,this._tileProvider,K,Q,T);else try{const oe=await this.map._requestManager.transformRequest(K,o.R.Tile,Q.signal);if(Q.signal.aborted)return delete k.request,T(null);const{data:me,headers:we}=await o.a(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(me,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:me,y:we}=k.tileID.canonical;try{const Me=await this.map._requestManager.transformRequest(B,o.R.Tile,K.signal);if(K.signal.aborted)return Q(null);const Re=await T.loadTile({z:oe,x:me,y:we},{request:Me,signal:K.signal});if(K.signal.aborted)return Q(null);if(Re==null){const Qe=new Error("Tile not found");return Qe.status=404,k.state="errored",Q(Qe)}if(Re.data==null)return k.state="loaded",Q(null);const Ze=Re.data instanceof ImageBitmap?Re.data:await createImageBitmap(new Blob([Re.data]));if(K.signal.aborted)return Q(null);k.setTexture(Ze,this.map.painter),k.state="loaded",this.map._refreshExpiredTiles&&k.setExpiryData({cacheControl:Re.cacheControl,expires:Re.expires}),Q(null)}catch(Me){if(K.signal.aborted)return Q(null);k.state="errored",Q(new Error(`Could not load tile from ${B}`,{cause:Me}))}finally{delete k.request}}abortTile(k,T){k.request&&(k.request.abort(),delete k.request),T&&T()}unloadTile(k,T){k.texture&&k.texture instanceof o.T?(k.destroy(!1),k.texture&&k.texture instanceof o.T&&this.map.painter.saveTileTexture(k.texture)):k.destroy(),T&&T()}hasTransition(){return!1}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null)}}function Ua(L,k,T,B,K,Q,oe,me){const we=[L,k,1,T,B,1,K,Q,1],Me=[oe,me,1],Re=o.cU([],we),[Ze,Qe,ut]=o.cT(Me,Me,Re);return o.cV(we,we,[Ze,0,0,0,Qe,0,0,0,ut])}function Ea(L,k,T,B,K,Q,oe,me){const we=function(Me,Re,Ze,Qe,ut,bt,vt,Mt){const es=Ua(0,0,1,0,1,1,0,1),Qt=Ua(Me,Re,Ze,Qe,ut,bt,vt,Mt),Lt=o.cU([],es);return o.cV(Qt,Qt,Lt)}(L,k,T,B,K,Q,oe,me);return[we[2]/we[8]/o.a6,we[5]/we[8]/o.a6]}function _o(L){return[L[0],Math.min(Math.max(L[1],-o.cP),o.cP)]}class Fi extends o.E{constructor(k,T,B,K){super(),this.id=k,this.dispatcher=B,this.coordinates=T.coordinates,this.type="image",this.minzoom=0,this.maxzoom=22,this.tileSize=512,this.tiles={},this._loaded=!1,this.onNorthPole=!1,this.onSouthPole=!1,this.setEventedParent(K),this.options=T,this._dirty=!1}async load(k,T){if(this._loaded=T||!1,this.fire(new o.h("dataloading",{dataType:"source"})),this.url=this.options.url,!this.url)return k&&(this.coordinates=k),this._loaded=!0,void this._finishLoading();const B=new AbortController;this._imageRequest=B;try{const K=await this.map._requestManager.transformRequest(this.url,o.R.Image,B.signal),{data:Q}=await o.a(K,B.signal);this._imageRequest=null,this._loaded=!0,this.image=Q,this._dirty=!0,this.width=this.image.width,this.height=this.image.height,k&&(this.coordinates=k),this._finishLoading()}catch(K){if(B.signal.aborted)return;this._imageRequest=null,this._loaded=!0,this.fire(new o.f(K))}}loaded(){return this._loaded}updateImage(k){return k.url?(this._imageRequest&&k.url!==this.options.url&&(this._imageRequest.abort(),this._imageRequest=null),this.options.url=k.url,this.load(k.coordinates,this._loaded),this):this}setTexture(k){if(!(k.handle instanceof WebGLTexture))throw new Error("The provided handle is not a WebGLTexture instance");return this.texture=new o.cO(this.map.painter.context,k.handle),this.width=k.dimensions[0],this.height=k.dimensions[1],this._dirty=!1,this._loaded=!0,this._finishLoading(),this}_finishLoading(){this.map&&(this.setCoordinates(this.coordinates),this.fire(new o.h("data",{dataType:"source",sourceDataType:"metadata"})))}onAdd(k){this.map=k,this.load()}onRemove(k){this._imageRequest&&(this._imageRequest.abort(),this._imageRequest=null),!this.texture||this.texture instanceof o.cO||this.texture.destroy(),this.boundsBuffer&&(this.boundsBuffer.destroy(),this.elevatedGlobeVertexBuffer&&this.elevatedGlobeVertexBuffer.destroy(),this.elevatedGlobeIndexBuffer&&this.elevatedGlobeIndexBuffer.destroy())}setCoordinates(k){if(this.coordinates=k,this._boundsArray=void 0,this._unsupportedCoords=!1,!k.length)return this;this.onNorthPole=!1,this.onSouthPole=!1;let T=k[0][1],B=k[0][1];for(const Q of k)Q[1]>B&&(B=Q[1]),Q[1]o.cP?this.onNorthPole=!0:K<-o.cP&&(this.onSouthPole=!0),!this.onNorthPole&&!this.onSouthPole){const Q=k.map(o.bT.fromLngLat);this.tileID=function(oe){let me=1/0,we=1/0,Me=-1/0,Re=-1/0;for(const vt of oe)me=Math.min(me,vt.x),we=Math.min(we,vt.y),Me=Math.max(Me,vt.x),Re=Math.max(Re,vt.y);const Ze=Math.max(Me-me,Re-we),Qe=Math.max(0,Math.floor(-Math.log2(Ze))),ut=Math.pow(2,Qe);let bt=Math.floor((me+Me)/2*ut);return bt>1&&(bt-=1),new o.bW(Qe,bt,Math.floor((we+Re)/2*ut))}(Q),this.minzoom=this.maxzoom=this.tileID.z}return this.fire(new o.h("data",{dataType:"source",sourceDataType:"content"})),this}_clear(){!this.texture||this.texture instanceof o.cO||(this.texture.destroy(),this._dirty=!0),this.texture=null,this._boundsArray=void 0,this._unsupportedCoords=!1}_prepareData(k){for(const Hs in this.tiles){const Fs=this.tiles[Hs];Fs.state!=="loaded"&&(Fs.state="loaded",Fs.texture=this.texture)}if(this._boundsArray||this.onNorthPole||this.onSouthPole||this._unsupportedCoords)return;const T=o.bq(new o.bW(0,0,0),this.map.transform.projection),B=[T.projection.project(this.coordinates[0][0],this.coordinates[0][1]),T.projection.project(this.coordinates[1][0],this.coordinates[1][1]),T.projection.project(this.coordinates[2][0],this.coordinates[2][1]),T.projection.project(this.coordinates[3][0],this.coordinates[3][1])];if(!function(Hs){const Fs=Hs[1].x-Hs[0].x,nn=Hs[1].y-Hs[0].y,$s=Hs[2].x-Hs[1].x,rn=Hs[2].y-Hs[1].y,_n=Hs[3].x-Hs[2].x,Mn=Hs[3].y-Hs[2].y,Kn=Hs[0].x-Hs[3].x,Bn=Hs[0].y-Hs[3].y,On=Fs*rn-$s*nn,Rr=$s*Mn-_n*rn,An=_n*Bn-Kn*Mn,xr=Kn*nn-Fs*Bn;return On>0&&Rr>0&&An>0&&xr>0||On<0&&Rr<0&&An<0&&xr<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,me,we]=this.coordinates.map(Hs=>{const Fs=K.projection.project(Hs[0],Hs[1]);return o.cs(K,Fs)._round()});this.perspectiveTransform=Ea(Q.x,Q.y,oe.x,oe.y,me.x,me.y,we.x,we.y);const Me=this._boundsArray=new o.bt;Me.emplaceBack(Q.x,Q.y,0,0),Me.emplaceBack(oe.x,oe.y,o.a6,0),Me.emplaceBack(we.x,we.y,0,o.a6),Me.emplaceBack(me.x,me.y,o.a6,o.a6),this.boundsBuffer&&(this.boundsBuffer.destroy(),this.elevatedGlobeVertexBuffer&&this.elevatedGlobeVertexBuffer.destroy(),this.elevatedGlobeIndexBuffer&&this.elevatedGlobeIndexBuffer.destroy()),this.boundsBuffer=k.createVertexBuffer(Me,Xc.members),this.boundsSegments=o.ad.simpleSegment(0,0,4,2);const Re=o.cS,Ze=Re+1,Qe=Re+1,ut=Ze*Qe,bt=Re*Re*2,vt=[],Mt=function(Hs){return[_o(Hs[0]),_o(Hs[1]),_o(Hs[2]),_o(Hs[3])]}(this.coordinates),[es,Qt,Lt,ps]=function(Hs){let Fs=Hs[0][0],nn=Fs,$s=Hs[0][1],rn=$s;for(let _n=1;_nnn&&(nn=Hs[_n][0]),Hs[_n][1]<$s?$s=Hs[_n][1]:Hs[_n][1]>rn&&(rn=Hs[_n][1]);return[Fs,$s,nn-Fs,rn-$s]}(Mt);{const Hs=new o.bt,[Fs,nn,$s,rn]=function(ea){let si=ea[0].x,Wr=si,Tr=ea[0].y,Gr=Tr;for(let Ga=1;GaWr&&(Wr=ea[Ga].x),ea[Ga].yGr&&(Gr=ea[Ga].y);return[si,Tr,Wr-si,Gr-Tr]}(B),_n=ea=>[(ea.x-Fs)/$s,(ea.y-nn)/rn],[Mn,Kn,Bn,On]=B.map(_n),Rr=function(ea,si,Wr,Tr,Gr,Ga,qr,Za){const Oi=Ua(0,0,1,0,1,1,0,1),Do=Ua(ea,si,Wr,Tr,Gr,Ga,qr,Za),so=o.cU([],Do);return o.cV(Oi,Oi,so)}(Mn[0],Mn[1],Kn[0],Kn[1],Bn[0],Bn[1],On[0],On[1]);this.elevatedGlobePerspectiveTransform=Ea(Mn[0],Mn[1],Kn[0],Kn[1],Bn[0],Bn[1],On[0],On[1]);const An=(ea,si)=>{vt.push(ea.lng);const Wr=Math.round((ea.lng-es)/Lt*o.a6),Tr=Math.round((ea.lat-Qt)/ps*o.a6),Gr=_n(si),Ga=o.cT([],[Gr[0],Gr[1],1],Rr),qr=Math.round(Ga[0]/Ga[2]*o.a6),Za=Math.round(Ga[1]/Ga[2]*o.a6);Hs.emplaceBack(Wr,Tr,qr,Za)},xr=B[3].x-B[0].x,sa=B[3].y-B[0].y,ka=B[2].x-B[1].x,Hr=B[2].y-B[1].y;for(let ea=0;ea{Fs.emplaceBack($s,rn,_n);const Mn=vt[$s],Kn=vt[rn],Bn=vt[_n],On=Math.min(Math.min(Mn,Kn),Bn),Rr=Math.max(Math.max(Mn,Kn),Bn)-On;Rr>this.maxLongitudeTriangleSize&&(this.maxLongitudeTriangleSize=Rr),Hs.push(On+Rr/2)};for(let $s=0;$sOn);_n.sort((Bn,On)=>$s[Bn]-$s[On]);const Mn=[],Kn=new o.ae;for(let Bn=0;Bn<_n.length;Bn++){const On=_n[Bn];Mn.push($s[On]);const Rr=3*On,An=Rr+1;Kn.emplaceBack(rn.uint16[Rr],rn.uint16[An],rn.uint16[An+1])}return[Mn,Kn]}(Hs,Fs),this.elevatedGlobeTrianglesCenterLongitudes=Hs,this.elevatedGlobeIndexBuffer=k.createIndexBuffer(Fs)}this.elevatedGlobeSegments=o.ad.simpleSegment(0,0,ut,bt),this.elevatedGlobeGridMatrix=new Float32Array([0,Lt/o.a6,0,ps/o.a6,0,0,Qt,es,0])}prepare(){const k=Object.keys(this.tiles).length!==0;if(this.tileID&&!k)return;const T=this.map.painter.context,B=T.gl;!this._dirty||this.texture instanceof o.cO||(this.texture?this.texture.update(this.image):(this.texture=new o.T(T,this.image,B.RGBA8),this.texture.bind(B.LINEAR,B.CLAMP_TO_EDGE)),this._dirty=!1),k&&this._prepareData(T)}loadTile(k,T){this.tileID&&this.tileID.equals(k.tileID.canonical)?(this.tiles[String(k.tileID.wrap)]=k,k.buckets={},T(null)):(k.state="errored",T(null))}serialize(){return{type:"image",url:this.options.url,coordinates:this.coordinates}}hasTransition(){return!1}getSegmentsForLongitude(k){const T=this.elevatedGlobeSegments;if(!this.elevatedGlobeTrianglesCenterLongitudes||!T)return null;const B=this.elevatedGlobeTrianglesCenterLongitudes;let K=(Q=k+180)+360*Math.round((B[0]-Q)/360);var Q;const oe=new o.ad,me=(Ze,Qe)=>{oe.segments.push({vertexOffset:0,primitiveOffset:Ze,vertexLength:T.segments[0].vertexLength,primitiveLength:Qe,sortKey:void 0,vaos:{}})},we=.51*this.maxLongitudeTriangleSize;if(Math.abs(B[0]-K)<=we){const Ze=o.cQ(B,0,B.length,K+we);return Ze===B.length||me(Ze,o.cR(B,Ze+1,B.length,K+360-we)-Ze),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,me=o.cM(this._options,oe,this.map._requestManager);me instanceof Error?k(me):k(null,me)})().catch(B=>{T.signal.aborted||k(B)}),{cancel:()=>T.abort()}}_setTileJSON(L){if(Object.assign(this,L),this.hasWorldviews=!!L.worldview_options,L.worldview_default&&(this.worldviewDefault=L.worldview_default),L.vector_layers){this.vectorLayers=L.vector_layers,this.vectorLayerIds=[],this.localizableLayerIds=new Set;for(const k of L.vector_layers)this.vectorLayerIds.push(k.id),L.worldview&&L.worldview[k.source]&&this.localizableLayerIds.add(k.id)}this.tileBounds=o.cF.fromTileJSON(L)}loaded(){return this._loaded}hasTile(L){return!this.tileBounds||this.tileBounds.contains(L.canonical)}onAdd(L){this.map=L,this.load()}reload(){this.cancelTileJSONRequest();const L=o.m(this.id,this.scope);this.load(()=>this.map.style.clearSource(L))}setTiles(L){return this._options.tiles=L,this.reload(),this}setUrl(L){return this.url=L,this._options.url=L,this.reload(),this}onRemove(L){this.cancelTileJSONRequest()}serialize(){return{...this._options}}async loadTile(L,k){const T=L.tileID.canonical.url(this.tiles,this.scheme),B=this.map._requestManager.normalizeTileURL(T),K=!L.actor||L.state==="expired";if(!K&&L.state==="loading")return void(L.reloadCallback=k);K&&(L.actor=this._tileWorkers[B]=this._tileWorkers[B]||this.dispatcher.getActor());const Q=new AbortController;L.request=Q;try{const 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 me=this.map.style?this.map.style.getLut(this.scope):null,we=me?{image:me.image.clone()}:null,Me=!(!this.map.style||!this.map.style._crossSourceElevationActive),Re=!(!this.map.style||!Me),Ze={request:B,data:void 0,uid:L.uid,tileID:L.tileID,tileZoom:L.tileZoom,zoom:L.tileID.overscaledZ,maxZoom:this.maxzoom,lut:we,tileSize:this.tileSize*L.tileID.overscaleFactor(),type:this.type,source:this.id,scope:this.scope,pixelRatio:o.e.devicePixelRatio,showCollisionBoxes:this.map.showCollisionBoxes,showElevationIdDebug:!!this.map.painter&&this.map.painter._debugParams.showElevationIdDebug,promoteId:this.promoteId,renderSourceType:L.renderSourceType,frcCoverage:(()=>{const ut=this.map.painter,bt=ut?ut.frcCoverageFadeRange:null;if(bt==null)return null;const vt=ut?ut.frcCoverageSnapshot:null,Mt=this.map.transform.zoom=Math.ceil(bt[1]),Lt=vt&&Qt?vt.getFullCoverageMask(L.tileID.canonical):null;return{frcMask:Qt?Lt??null:null,resolved:Mt||vt!=null,polygons:es&&es.frcMask!==0?es.polygons:null,tileZoom:es&&es.frcMask!==0?es.tileId.z:null,sourceLayers:ut?ut.frcCoverageSourceLayers:["road","structure"]}})(),terrainEnabled:ih(this.map.style,this.map.transform),crossSourceElevationEnabled:Re,elevation:Ui.buildElevationRequestParams?Ui.buildElevationRequestParams(this.map,L,Me):null,brightness:this.map.style&&this.map.style.getBrightness()||0,extraShadowCaster:L.isExtraShadowCaster,tessellationStep:this.map._tessellationStep,scaleFactor:this.map.getScaleFactor(),worldview:this.map.getWorldview()||this.worldviewDefault,indoor:this.map.getIndoorTileOptions(this.id,this.scope)};if(this.hasWorldviews&&o.cG(T)&&(Ze.localizableLayerIds=this.localizableLayerIds),Ze.request.collectResourceTiming=this._collectResourceTiming,Q)if(this.dispatcher.ready||this.provider)L.request=L.actor.sendCancelable("loadTile",Ze,{},Qe.bind(this));else{const ut=o.cH.call({deduped:this._deduped},Ze,(bt,vt)=>{L.aborted||(bt||!vt?Qe.call(this,bt):(Ze.data={rawData:vt.rawData.slice(0),headers:vt.headers},L.actor&&(L.request=L.actor.sendCancelable("loadTile",Ze,{},Qe.bind(this)))))},!0);K.signal.addEventListener("abort",ut,{once:!0})}else L.request=L.actor.sendCancelable("reloadTile",Ze,{},Qe.bind(this));function Qe(ut,bt){return delete L.request,L.aborted?oe(null):ut?oe(ut):(bt&&bt.resourceTiming&&(L.resourceTiming=bt.resourceTiming),this.map._refreshExpiredTiles&&bt&&L.setExpiryData(o.cI(bt.headers)),void(function(){if(L.aborted)return oe(null);L.loadVectorData(bt,this.map.painter),o.cJ(this.dispatcher),oe(null,bt),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:cr,"raster-dem":class extends cr{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,me=o.cM(this._options,oe,this.map._requestManager);me instanceof Error?k(me):k(null,me)})().catch(B=>{T.signal.aborted||k(B)}),{cancel:()=>T.abort()}}async loadTile(L,k){if(L.actor&&L.state!=="expired")return;const T=this.map._requestManager.normalizeTileURL(L.tileID.canonical.url(this.tiles,this.scheme),!1,this.tileSize);L.actor=this.dispatcher.getActor();const B=new AbortController;L.request=B;try{const K=await this.map._requestManager.transformRequest(T,o.R.Tile,B.signal);if(B.signal.aborted)return k(null);L.request=L.actor.sendCancelable("loadTile",{uid:L.uid,tileID:L.tileID,source:this.id,type:this.type,scope:this.scope,request:K,encoding:this.encoding},{},(function(Q,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,me={};return me[new o.bQ(L.overscaledZ,K,k.z,B,k.y).key]={backfilled:!1},me[new o.bQ(L.overscaledZ,oe,k.z,Q,k.y).key]={backfilled:!1},k.y>0&&(me[new o.bQ(L.overscaledZ,K,k.z,B,k.y-1).key]={backfilled:!1},me[new o.bQ(L.overscaledZ,L.wrap,k.z,k.x,k.y-1).key]={backfilled:!1},me[new o.bQ(L.overscaledZ,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,{},(me,we)=>Q&&!we?(L.state="loaded",k(null)):(delete L.request,L.destroy(!1),L.aborted?k(null):me?k(me):(L.loadVectorData(we,this.map.painter,T==="reloadTile"),void k(null))))}abortTile(L){L.request&&(L.request.abort(),delete L.request),L.aborted=!0}unloadTile(L,k){this.actor.notify("removeTile",{uid:L.uid,type:this.type,source:this.id,scope:this.scope}),L.destroy()}onRemove(L){this._pendingLoad&&this._pendingLoad.abort()}serialize(){return{...this._options,type:this.type,data:this._data}}hasTransition(){return!1}},video:class extends Fi{constructor(L,k,T,B){super(L,k,T,B),this.roundZoom=!0,this.type="video",this.options=k}async load(){this._loaded=!1;const L=this.options,k=new AbortController;this._imageRequest=k;try{const T=await Promise.all(L.urls.map(async K=>(await this.map._requestManager.transformRequest(K,o.R.Source,k.signal)).url));if(k.signal.aborted)return;this.urls=T;const B=await o.cW(T);if(k.signal.aborted)return;this._imageRequest=null,this.video=B,this.video.loop=!0,this.video.setAttribute("playsinline",""),this.video.addEventListener("playing",()=>{this.map.triggerRepaint()}),this.map&&this.video.play(),this._finishLoading()}catch(T){if(k.signal.aborted)return;this.fire(new o.f(T))}finally{this._loaded=!0}}pause(){this.video&&this.video.pause()}play(){this.video&&this.video.play()}seek(L){if(this.video){const k=this.video.seekable;Lk.end(0)?this.fire(new o.f(new as(`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 as(`sources.${L}`,null,'"coordinates" property must be an array of 4 longitude/latitude array pairs'))):this.fire(new o.f(new as(`sources.${L}`,null,'missing required property "coordinates"'))),k.animate&&typeof k.animate!="boolean"&&this.fire(new o.f(new as(`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 as(`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 as(`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(me){return me instanceof ImageData||me instanceof HTMLCanvasElement||me instanceof ImageBitmap||me 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"}))}}},lo=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:me,y:we,z:Me}=T;if(!isFinite(me)||!isFinite(we)||!isFinite(Me))throw new Error("Invalid MRT header");const Re=2**Me,Ze=Re*o.a7(L),Qe=Re*o.a8(k);return function([ut,bt],vt,{scaled:Mt=!0}={}){if(!vt)throw new Error("bandView is undefined");const{data:es,tileSize:Qt,buffer:Lt,offset:ps,scale:Hs,dimension:Fs}=vt;if(ut<-Lt||ut>Qt+Lt||bt<-Lt||bt>Qt+Lt)throw new Error(`Point (${ut}, ${bt}) out of bounds for tileSize=${Qt}, buffer=${Lt}`);const nn=(bt+Lt)*(Qt+2*Lt)+(ut+Lt);if(new Uint32Array(es.buffer)[nn]===4294967295)return null;let $s=[];$s=Mt?[]:new vt.data.constructor(Fs);for(let rn=0;rn=Qe||Ze<0||Ze>=Qe)throw new Xl(`Invalid overzoom, ${we}/${oe}/${me} is not a child of ${Q}/${B}/${K}.`);const ut=0|Math.log2(L),bt=Math.min(Me,ut),vt=Me-bt,Mt=L>>bt;return{offset:[(Re>>vt)*Mt,(Ze>>vt)*Mt],tileSize:Mt,deltaZ:Me}}o.c_.setPbf(o.c$);class hm extends Lx{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:me})=>{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,me)}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 me;const we=o.m(String(B),o.m(this.tileID.key,k));let Me=this._taskQueue.get(we);Me?Me.add(K):(Me=new Set,Me.add(K),this._taskQueue.set(we,Me));const Re=(bt,vt)=>{me.complete(bt,vt),bt?K(bt):(Me.forEach(Mt=>Mt(null,vt)),this._taskQueue.delete(we))},Ze=(bt,vt)=>{if(bt)return K(bt);let Mt,es=!1;if(T!==null){const Lt=this._workQueuePerLayer.get(T)||[];Lt.push(()=>{es=!0,Mt&&Mt.abort(),me.cancel()}),this._workQueuePerLayer.has(T)||this._workQueuePerLayer.set(T,Lt)}const Qt=()=>{es||(Mt=oe.sendCancelable("decodeRasterArray",{type:"raster-array",source:this.source,scope:this.scope,tileID:this.tileID,uid:this.uid,buffer:vt,task:me},{},Re))};this.workerReady!==void 0?this.workerReady.then(Qt).catch(Lt=>K(Lt)):Qt()};let Qe;try{Qe=Q.getLayer(k)}catch(bt){if(this.parentTile&&this.overzoomCoordsPerLayer)return void K(new Error(`Layer '${k}' not found in parent tile MRT`));if(this.state==="reloading")return;throw bt}if(!Qe)return void K(new Error(`Unknown sourceLayer "${k}"`));if(Qe.hasDataForBand(B))return Me.forEach(bt=>bt(null,null)),void this._taskQueue.delete(we);const ut=Qe.getDataRange([B]);if(me=Q.createDecodingTask(ut),!me||me.tasks.length)if(T!==null&&this.flushQueues(T),this.entireBuffer)Ze(null,this.entireBuffer.slice(ut.firstByte,ut.lastByte+1));else{const bt={...this.requestParams,headers:{Range:`bytes=${ut.firstByte}-${ut.lastByte}`}},vt=new AbortController;if(o.d0(bt,vt.signal).then(({data:Mt})=>Ze(null,Mt)).catch(Mt=>{vt.signal.aborted||Ze(Mt)}),T!==null){const Mt=this._fetchQueuePerLayer.get(T)||[];Mt.push(()=>{vt.abort(),me.cancel()}),this._fetchQueuePerLayer.has(T)||this._fetchQueuePerLayer.set(T,Mt)}}}updateNeeded(k,T){return(!this.textureDescriptorPerLayer.get(k)||this.textureDescriptorPerLayer.get(k).band!==T||this.refreshedUponExpiration)&&this.state!=="errored"}updateTextureDescriptor(k,T,B){if(!this._mrt)return;let K;try{K=this._mrt.getLayer(k)}catch{return}if(!K||!K.hasBand(B)||!K.hasDataForBand(B))return;let{bytes:Q,tileSize:oe,buffer:me,offset:we,scale:Me}=K.getBandView(B);if(this.parentTile&&this.overzoomCoordsPerLayer){const ut=this.overzoomCoordsPerLayer.get(k);ut&&(Q=this.cropBandData(Q,oe,me,ut),oe=ut.tileSize)}const Re=oe+2*me,Ze=new o.b({width:Re,height:Re},Q),Qe=this.texturePerLayer.get(T);Qe&&Qe instanceof o.T&&Qe.update(Ze,{premultiply:!1}),this.textureDescriptorPerLayer.set(T,{layer:k,band:B,img:Ze,buffer:me,offset:we,tileSize:oe,format:K.pixelFormat,mix:[Me,256*Me,65536*Me,16777216*Me]})}cropBandData(k,T,B,K){const{offset:Q,tileSize:oe}=K,me=T+2*B,we=oe+2*B;return function(Me,Re,Ze,Qe){const ut=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),bt=yo[ut];if(!bt)throw new Error(`Invalid data type "${ut}"`);const vt=Re[2]*Re[3],Mt=Re[1]*vt,es=Ze[2]*Ze[3],Qt=Ze[1]*es,Lt=new bt(Qt*Ze[0]);for(let ps=0;psnew hm(L,k,T,B,K);const To={RasterArrayTileSource:class extends cr{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 me=Q?null:new Error("Parent tile failed to load");for(const we of oe)we(me)};this.on("data",B)}triggerRepaint(L){const k=this.map.painter._terrain,T=this.map.style.getSourceCache(this.id);k&&k.enabled&&T&&k._clearRenderCacheForTile(T.id,L.tileID),this.map.triggerRepaint()}_setupOverzoomTile(L,k){const T=this._dataMaxzoom!==void 0?this._dataMaxzoom:this.maxzoom,B=this.map.style.getSourceCache(this.id);if(!B)return void k(new Error("Source cache not found"));L._isLoadInProgress=!0;const K=L.tileID.scaledTo(T);let Q=B.getTile(K);for(;Q&&Q.parentTile;)Q=Q.parentTile;Q||(Q=B._addTile(K));const oe=me=>{L._isLoadInProgress=!1,k(me)};this._waitForParent(Q,me=>{if(me||!L.setupOverzoom(Q))return L.state="errored",void oe(me||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,me,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&&me&&L.setExpiryData(o.cI(we)),this.partial&&L.state!=="expired")L.state="empty";else if(!this.partial){if(!me)return k(null);L.state="loaded",L._isHeaderLoaded=!0,L._mrt=me}k(null)};try{const oe=await this.map._requestManager.transformRequest(B,o.R.Tile,K.signal);if(K.signal.aborted)return k(null);L.requestParams=oe;const me={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",me,{},(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("/"),me=B.getLayer(Q);if(!me||!me.hasBand(oe)||!me.hasDataForBand(oe))continue;const{bytes:we,tileSize:Me,buffer:Re}=me.getBandView(oe),Ze=Me+2*Re,Qe={data:new o.b({width:Ze,height:Ze},we),pixelRatio:2,sdf:!1,usvg:!1,version:0};T.set(K,Qe)}return T}queryRasterArrayValueByBandId(L,k,T){const B=k._mrt;return new Promise(K=>{const Q={},oe=new Set;for(const[me,we]of Object.entries(B.layers)){if(T.layerName&&me!==T.layerName)continue;const Me={};Q[me]=Me;for(const{bands:Re}of we.dataIndex)for(const Ze of Re)T.bands&&!T.bands.includes(Ze)||(oe.add(o.m(me,Ze)),k.fetchBand(me,null,Ze,Qe=>{o.e.frame(()=>{Me[Ze]=Qe?null:hf([L.lng,L.lat],B,we.getBandView(Ze)),oe.delete(o.m(me,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 me=this.map.style.getSourceCache(this.id),we=new o.bQ(T,K,T,Q,oe);return me.findLoadedParent(we,this.minzoom)}}},Ql=To,$c={model:()=>yr().then(()=>vr.ModelSource),"batched-model":()=>yr().then(()=>vr.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 ig(L,k,T=""){return`${T}:${k.id||""}:${k.layer.id}:${function(B){if("layerId"in B)return`layer:${B.layerId}`;{const{featuresetId:K,importId:Q}=B;return`featureset:${K}${Q?`:import:${Q}`:""}`}}(L.target)}`}function Xd(L,k,T,B=""){if(L.uniqueFeatureID){const K=ig(L,k,B);if(T.has(K))return!0;T.add(K)}return!1}function og(L,k,T,B,K=!1,Q=void 0){const oe=k.sourceCache.transform,me=k.sourceCache.tilesIn(L,k.has3DLayers,K);me.sort(ud);const we=[];for(const Me of me){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 Qe of Me){const ut=Qe.queryResults,bt=Qe.wrappedTileID,vt=Ze[bt]=Ze[bt]||{};for(const Mt in ut){const es=ut[Mt],Qt=vt[Mt]=vt[Mt]||{},Lt=Re[Mt]=Re[Mt]||[];for(const ps of es)Qt[ps.featureIndex]||(Qt[ps.featureIndex]=!0,Lt.push(ps))}}return Re}(we)}function Lh(L,k,T,B,K,Q){const oe={},me=B.queryRenderedSymbols(L),we=[];for(const Me of Object.keys(me).map(Number))we.push(K[Me]);we.sort(ud);for(const Me of we){const Re=Me.featureIndex.lookupSymbolFeatures(me[Me.bucketInstanceId],Me.bucketIndex,Me.sourceLayerIndex,k,T,Q);for(const Ze in Re){const Qe=oe[Ze]=oe[Ze]||[],ut=Re[Ze];ut.sort((bt,vt)=>{const Mt=Me.featureSortOrder;if(Mt){const es=Mt.indexOf(bt.featureIndex);return Mt.indexOf(vt.featureIndex)-es}return vt.featureIndex-bt.featureIndex});for(const bt of ut)Qe.push(bt)}}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 me=1;Q.type==="fill-extrusion"?me=K.visible?Q.paint.get("fill-extrusion-vertical-scale"):0:Q.type==="building"&&(me=K.visible?Q.paint.get("building-vertical-scale"):0);let we=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:me})}k.hasAnyZOffset=!1;let B=!1;for(let K=0;K{oe in K&&(Q[oe]=K[oe])}),T}function op(L){L=L.slice();const k=Object.create(null);for(const T of L)k[T.id]=T;for(let T=0;T0?(K-oe)/me:0;return this.points[Q].mult(1-we).add(this.points[T].mult(we))}}const vh=100;class vc{constructor(k,T){this.gridRightBoundary=0,this.gridBottomBoundary=0,this.clippedSymbols=new Map,this.reset(k,T)}reset(k,T){const B=k.width+200,K=k.height+200;B!==this.gridRightBoundary||K!==this.gridBottomBoundary?(this.grid=new o.d2(B,K,25),this.ignoredGrid=new o.d2(B,K,25)):(this.grid.clear(),this.ignoredGrid.clear()),this.transform=k,this.fogState=T,this.pitchfactor=Math.cos(k._pitch)*k.cameraToCenterDistance,this.screenRightBoundary=k.width+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,me,we,Me,Re,Ze){let Qe=B.projectedAnchorX,ut=B.projectedAnchorY,bt=B.projectedAnchorZ;const vt=B.tileAnchorX,Mt=B.tileAnchorY,es=B.elevation,Qt=B.tileID,Lt=k.getProjection();if(es&&Qt){const[Bn,On,Rr]=Lt.upVector(Qt.canonical,B.tileAnchorX,B.tileAnchorY),An=Lt.upVectorScale(Qt.canonical,this.transform.center.lat,this.transform.worldSize).metersToTile;Qe+=Bn*es*An,ut+=On*es*An,bt+=Rr*es*An}const ps=k.projection.name==="globe",Hs=k.projection.name==="globe"?o.S(this.transform.zoom):0;if(Qt&&ps&&Hs<1&&!oe){const Bn=1<0,Lt),nn=Me*Fs.perspectiveRatio,$s=(B.x1*T+me.x-B.padding)*nn+Fs.point.x,rn=(B.y1*T+me.y-B.padding)*nn+Fs.point.y,_n=(B.x2*T+me.x+B.padding)*nn+Fs.point.x,Mn=(B.y2*T+me.y+B.padding)*nn+Fs.point.y,Kn=Fs.perspectiveRatio<=o.d9||Fs.occluded;return!this.isInsideGrid($s,rn,_n,Mn)||!we&&this.grid.hitTest($s,rn,_n,Mn,Ze)||Kn?{box:[],offscreen:!1,occluded:Fs.occluded}:{box:[$s,rn,_n,Mn],offscreen:this.isOffscreen($s,rn,_n,Mn),occluded:!1}}placeCollisionCircles(k,T,B,K,Q,oe,me,we,Me,Re,Ze,Qe,ut,bt,vt,Mt){const es=[],Qt=this.transform.elevation,Lt=k.getProjection(),ps=k.elevationType==="road",Hs=!!Qt||ps,Fs=o.c2.getAtTileOffsetFunc(Mt,this.transform.center.lat,this.transform.worldSize,Lt),nn=new o.P(B.tileAnchorX,B.tileAnchorY),$s=new o.P(B.tileAnchorX,B.tileAnchorY);let{x:rn,y:_n,z:Mn}=Lt.projectTilePoint($s.x,$s.y,Mt.canonical),Kn=null;if(Hs){Kn=ps&&k.hdExt?k.hdExt.makeRoadSymbolElevationParams(k,k.text,K,Mt,Fs,Qt,Lt,this.transform.center.lat,this.transform.worldSize):{getElevation:Fs,elevation:Qt,elevationFeature:null};const[Ga,qr,Za]=Kn.getElevation(nn,Qt,Kn.elevationFeature);rn+=Ga,_n+=qr,Mn+=Za}const Bn=Lt.name==="globe",On=this.projectAndGetPerspectiveRatio(we,rn,_n,Mn,Mt,Bn||!!Qt||this.transform.pitch>0,Lt),{perspectiveRatio:Rr}=On,An=(Qe?me/Rr:me*Rr)/o.dg,xr=o.da(rn,_n,Mn,Me),sa=B.lineOffsetX*An,ka=B.lineOffsetY*An,Hr=o.av(k.layers[0].layout.get("text-max-angle")),ea=Math.cos(Hr),si=On.signedDistanceFromCamera>0?o.db(An,oe,sa,ka,ps&&B.flipState===1,xr,$s,B,Q,Me,{},Hs&&!Qe?Kn:null,Qe&&Hs,Lt,Mt,Qe,ea):null;let Wr=!1,Tr=!1,Gr=!0;if(si&&!On.occluded){const Ga=.5*bt*Rr+vt,qr=new o.P(-100,-100),Za=new o.P(this.screenRightBoundary,this.screenBottomBoundary),Oi=new uh,{first:Do,last:so}=si,ql=Do.path.length;let vu=[];for(let no=ql-1;no>=1;no--)vu.push(Do.path[no]);for(let no=1;no(Hs&&!Bn&&(Gh=Kn.getElevation(_hno[3]<=0)&&(vu=[]));let Ko=[];if(vu.length>0){let no=1/0,_d=-1/0,Gh=1/0,_h=-1/0;for(const Vl of vu)no=Math.min(no,Vl[0]),Gh=Math.min(Gh,Vl[1]),_d=Math.max(_d,Vl[0]),_h=Math.max(_h,Vl[1]);_d>=qr.x&&no<=Za.x&&_h>=qr.y&&Gh<=Za.y&&(Ko=[vu.map(Vl=>new o.P(Vl[0],Vl[1]))],(noZa.x||GhZa.y)&&(Ko=o.dc(Ko,qr.x,qr.y,Za.x,Za.y)))}for(const no of Ko){Oi.reset(no,.25*Ga);let _d=0;_d=Oi.length<=.5*Ga?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,bc=Vl.y+vh;es.push(mm,bc,Ga,0);const dc=mm-Ga,Dh=bc-Ga,Wh=mm+Ga,Pd=bc+Ga;if(Gr=Gr&&this.isOffscreen(dc,Dh,Wh,Pd),Tr=Tr||this.isInsideGrid(dc,Dh,Wh,Pd),!T&&this.grid.hitTestCircle(mm,bc,Ga,ut)&&(Wr=!0,!Ze))return{circles:[],offscreen:!1,collisionDetected:Wr,occluded:!1}}}}return{circles:!Ze&&Wr||!Tr?[]:es,offscreen:Gr,collisionDetected:Wr,occluded:On.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 me=this.grid.query(B,K,Q,oe).concat(this.ignoredGrid.query(B,K,Q,oe)),we={},Me={};for(const Re of me){const Ze=Re.key;if(we[Ze.bucketInstanceId]===void 0&&(we[Ze.bucketInstanceId]={}),we[Ze.bucketInstanceId][Ze.featureIndex])continue;const Qe=this.clippedSymbols.get(Ze.bucketInstanceId);if(Qe&&Qe.has(Ze.featureIndex))continue;const ut=[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,ut)&&(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,me={bucketInstanceId:B,featureIndex:K,collisionGroupID:Q};for(let we=0;we0?(o.c6(we,we,k),this.fogState&&Q&&me.name!=="globe"&&(Me=o.dd(this.fogState,T,B,K,Q.toUnwrapped(),this.transform)>o.dh)):o.de(we,we,k);const Re=we[3];return{point:new o.P((we[0]/Re+1)/2*this.transform.width+vh,(-we[1]/Re+1)/2*this.transform.height+vh),perspectiveRatio:Math.min(.5+this.transform.getCameraToCenterDistance(me)/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 rx(L,k,T,B,K){const{horizontalAlign:Q,verticalAlign:oe}=o.du(L),me=-(Q-.5)*k,we=-(oe-.5)*T,Me=o.dv(L,B);return new o.P(me+Me[0]*K,we+Me[1]*K)}function Qd(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:me,crossTileID:we}=T,Me=o.dw(k),Re=B===o.dt.vertical?me: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),me>=0&&(L.text.placedSymbolArray.get(me).crossTileID=Re>=0&&me!==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:me,verticalPlacedTextSymbolIndex:we}=T,Me=L.text.placedSymbolArray;Q>=0&&(Me.get(Q).placedOrientation=B),oe>=0&&(Me.get(oe).placedOrientation=B),me>=0&&(Me.get(me).placedOrientation=B),we>=0&&(Me.get(we).placedOrientation=K)}class Jl{constructor(k,T,B,K,Q,oe,me){this.transform=k.clone(),this.projection=k.projection.name,me instanceof vc?(me.reset(this.transform,Q),this.collisionIndex=me):this.collisionIndex=new vc(this.transform,Q),this.buildingIndex=oe,this.frontCutoffStart=0,this.placements={},this.opacities={},this.variableOffsets={},this.stale=!1,this.commitTime=0,this.fadeDuration=T,this.retainedQueryData={},this.collisionGroups=new Pp(B),this.collisionCircleArrays={},this.prevPlacement=K,K&&(K.prevPlacement=void 0),this.placedOrientations={},this.lastReplacementSourceUpdateTime=0}getBucketParts(k,T,B,K,Q=1){const oe=B.getBucket(T),me=B.latestFeatureIndex;if(!oe||!me||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),Qe=B.tileSize/o.a6,ut=B.tileID.toUnwrapped();this.transform.setProjection(oe.projection);const bt=o.di(B.tileID,oe.getProjection(),this.transform,this.projection),vt=we.get("text-pitch-alignment")==="map",Mt=we.get("text-rotation-alignment")==="map";T.compileFilter(T.options);const es=T.dynamicFilter(),Qt=T.dynamicFilterNeedsFeature(),Lt=T.dynamicFilterNeedsGeometry(),ps=this.transform.calculatePixelsToTileUnitsMatrix(B),Hs=o.dj(bt,B.tileID.canonical,vt,Mt,this.transform,oe.getProjection(),ps);let Fs=null;const nn=oe.getProjection().createInversionMatrix(this.transform,B.tileID.canonical);if(vt){const An=o.dk(bt,B.tileID.canonical,vt,Mt,this.transform,oe.getProjection(),ps);Fs=o.X([],this.transform.labelPlaneMatrix,An)}let $s=null;es&&B.latestFeatureIndex&&($s={unwrappedTileID:ut,dynamicFilter:es,dynamicFilterNeedsFeature:Qt,needGeometry:Lt}),this.retainedQueryData[oe.bucketInstanceId]=new nx(oe.bucketInstanceId,me,oe.sourceLayerIndex,oe.index,B.tileID);const[rn,_n]=oe.layers[0].layout.get("text-size-scale-range"),Mn=o.b1(Q,rn,_n),[Kn,Bn]=we.get("icon-size-scale-range"),On=o.b1(Q,Kn,Bn),Rr={bucket:oe,layout:we,paint:Me,posMatrix:bt,invMatrix:nn,mercatorCenter:[o.a7(this.transform.center.lng),o.a8(this.transform.center.lat)],textLabelPlaneMatrix:Hs,labelToScreenMatrix:Fs,clippingData:$s,scale:Ze,textPixelRatio:Qe,holdingForFade:B.holdingForFade(),collisionBoxArray:Re,partiallyEvaluatedTextSize:o.dl(oe.textSizeData,this.transform.zoom,Mn),partiallyEvaluatedIconSize:o.dl(oe.iconSizeData,this.transform.zoom,On),collisionGroup:this.collisionGroups.get(oe.sourceID),latestFeatureIndex:B.latestFeatureIndex};if(K)for(const An of oe.sortKeyRanges){const{sortKey:xr,symbolInstanceStart:sa,symbolInstanceEnd:ka}=An;k.push({sortKey:xr,symbolInstanceStart:sa,symbolInstanceEnd:ka,parameters:Rr})}else k.push({symbolInstanceStart:0,symbolInstanceEnd:oe.symbolInstances.length,parameters:Rr})}placeLayerBucketPart(k,T,B,K=1){const{bucket:Q,layout:oe,paint:me,posMatrix:we,textLabelPlaneMatrix:Me,labelToScreenMatrix:Re,clippingData:Ze,textPixelRatio:Qe,mercatorCenter:ut,invMatrix:bt,holdingForFade:vt,collisionBoxArray:Mt,partiallyEvaluatedTextSize:es,partiallyEvaluatedIconSize:Qt,collisionGroup:Lt,latestFeatureIndex:ps}=k.parameters,Hs=oe.get("text-optional"),Fs=oe.get("icon-optional"),nn=oe.get("text-allow-overlap"),$s=oe.get("icon-allow-overlap"),rn=oe.get("text-rotation-alignment")==="map",_n=oe.get("icon-rotation-alignment")==="map",Mn=oe.get("text-pitch-alignment")==="map",Kn=me.get("symbol-z-offset"),Bn=oe.get("symbol-elevation-reference")==="sea",On=oe.get("symbol-placement"),Rr=oe.get("text-variable-anchor"),An=rn&&On!=="point",xr=_n&&On!=="point",sa=Rr&&Q.hasTextData(),ka=Q.hasIconTextFit()&&sa&&Q.hasIconData();this.transform.setProjection(Q.projection);const Hr=sa||An,ea=xr||ka;let si=nn&&($s||!Q.hasIconData()||Fs),Wr=$s&&(nn||!Q.hasTextData()||Hs);const Tr=!Kn.isConstant();!Q.collisionArrays&&Mt&&Q.deserializeCollisionBoxes(Mt);const Gr=(qr,Za,Oi)=>{const{crossTileID:Do,numVerticalGlyphVertices:so}=qr;let ql=null;if(Ze&&Ze.dynamicFilterNeedsFeature||Tr){const bu=this.retainedQueryData[Q.bucketInstanceId],id=ps.loadFeature({featureIndex:qr.featureIndex,bucketIndex:bu.bucketIndex,sourceLayerIndex:bu.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(qr.tileAnchorX,qr.tileAnchorY),this.transform.calculateDistanceTileData(Ze.unwrappedTileID)))return this.placements[Do]=new Rf(!1,!1,!1,!0),void T.add(Do);const vu=Kn.evaluate(ql,{});if((qr.zOffset||0)+(vu||0)>0&&this.frontCutoffStart>0){const bu=2*this.frontCutoffStart-1,id=[qr.tileAnchorX,qr.tileAnchorY,0,1],Rc=o.c6(o.dr(),id,we);if(Rc[1]/Rc[3]{bu.tileID=this.retainedQueryData[Q.bucketInstanceId].tileID;const id=this.transform.elevation;if(Q.elevationType==="road")bu.elevation=Bn?vu:vu+o.c2.getAtTileOffset(bu.tileID,new o.P(bu.tileAnchorX,bu.tileAnchorY),id,null);else{const Rc=Q.hdExt?Q.hdExt.elevationFeatures[qr.elevationFeatureIndex]:void 0;bu.elevation=Bn?vu:vu+o.c2.getAtTileOffset(bu.tileID,new o.P(bu.tileAnchorX,bu.tileAnchorY),id,Rc)}bu.elevation+=qr.zOffset},ug=Oi.textBox;if(ug){Kh(ug);const bu=Rc=>{let Yh=o.dt.horizontal;if(Q.allowVerticalPlacement&&!Rc&&this.prevPlacement){const ix=this.prevPlacement.placedOrientations[Do];ix&&(this.placedOrientations[Do]=ix,Yh=ix,Td(Q,Yh,qr))}return Yh},id=(Rc,Yh)=>{if(Q.allowVerticalPlacement&&so>0&&Oi.verticalTextBox){for(const ix of Q.writingModes)if(ix===o.dt.vertical?(Vl=Yh(),mm=Vl):Vl=Rc(),Vl&&Vl.box&&Vl.box.length)break}else Vl=Rc()};if(Rr){let Rc=Rr;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 hg=Q.getSymbolInstanceTextSize(es,qr,this.transform.zoom,Za),aj=(Ku.x2-Ku.x1)*hg+2*Ku.padding,ij=(Ku.y2-Ku.y1)*hg+2*Ku.padding,zb=qr.hasIconTextFit&&!$s?Li:null;zb&&Kh(zb);let Bb={box:[],offscreen:!1,occluded:!1};const X2=nn?2*Rc.length:Rc.length;for(let $b=0;$b=Rc.length,qr,Za,Q,wm,zb,es,Qt);if(_y&&(Bb=_y.placedGlyphBoxes,Bb&&Bb.box&&Bb.box.length)){Uc=!0,_h=_y.shift;break}}return Bb};id(()=>Yh(ug,Oi.iconBox,o.dt.horizontal),()=>{const Ku=Oi.verticalTextBox;return Ku&&Kh(Ku),Q.allowVerticalPlacement&&!(Vl&&Vl.box&&Vl.box.length)&&so>0&&Ku?Yh(Ku,Oi.verticalIconBox,o.dt.vertical):{box:null,offscreen:null,occluded:null}}),Vl&&(Uc=Vl.box,no=Vl.offscreen,_d=Vl.occluded);const ix=bu(!(!Vl||!Vl.box));if(!Uc&&this.prevPlacement){const Ku=this.prevPlacement.variableOffsets[Do];Ku&&(this.variableOffsets[Do]=Ku,ff(Q,Ku.anchor,qr,ix))}}else{const Rc=(Yh,ix)=>{const Ku=Q.getSymbolInstanceTextSize(es,qr,this.transform.zoom,Za),Li=this.collisionIndex.placeCollisionBox(Q,Ku,Yh,ut,bt,Hr,new o.P(0,0),nn,Qe,we,Lt.predicate);return Li&&Li.box&&Li.box.length&&(Td(Q,ix,qr),this.placedOrientations[Do]=ix),Li};id(()=>Rc(ug,o.dt.horizontal),()=>{const Yh=Oi.verticalTextBox;return Q.allowVerticalPlacement&&so>0&&Yh?(Kh(Yh),Rc(Yh,o.dt.vertical)):{box:null,offscreen:null,occluded:null}}),bu(!!(Vl&&Vl.box&&Vl.box.length))}}if(bc=Vl,Uc=bc&&bc.box&&bc.box.length>0,no=bc&&bc.offscreen,_d=bc&&bc.occluded,qr.useRuntimeCollisionCircles){const bu=qr.centerJustifiedTextSymbolIndex>=0?qr.centerJustifiedTextSymbolIndex:qr.verticalPlacedTextSymbolIndex,id=Q.text.placedSymbolArray.get(bu),Rc=o.ds(Q.textSizeData,es,id),Yh=oe.get("text-padding");dc=this.collisionIndex.placeCollisionCircles(Q,nn,id,bu,Q.lineVertexArray,Q.glyphOffsetArray,Rc,we,Me,Re,B,Mn,Lt.predicate,qr.collisionCircleDiameter*Rc/o.dg,Yh,this.retainedQueryData[Q.bucketInstanceId].tileID),Uc=nn||dc.circles.length>0&&!dc.collisionDetected,no=no&&dc.offscreen,_d=dc.occluded}if(Oi.iconFeatureIndex&&(_c=Oi.iconFeatureIndex),Oi.iconBox){const bu=id=>{Kh(id);const Rc=qr.hasIconTextFit&&_h?Qd(_h.x,_h.y,rn,Mn,this.transform.angle):new o.P(0,0),Yh=Q.getSymbolInstanceIconSize(Qt,this.transform.zoom,qr.placedIconSymbolIndex);return this.collisionIndex.placeCollisionBox(Q,Yh,id,ut,bt,ea,Rc,$s,Qe,we,Lt.predicate)};mm&&mm.box&&mm.box.length&&Oi.verticalIconBox?(Dh=bu(Oi.verticalIconBox),Ko=Dh.box.length>0):(Dh=bu(Oi.iconBox),Ko=Dh.box.length>0),no=no&&Dh.offscreen,Gh=Dh.occluded}const G_=Hs||qr.numHorizontalGlyphVertices===0&&so===0,e0=Fs||qr.numIconVertices===0;if(G_||e0?e0?G_||(Ko=Ko&&Uc):Uc=Ko&&Uc:Ko=Uc=Ko&&Uc,Uc&&bc&&bc.box&&this.collisionIndex.insertCollisionBox(bc.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,_c,Lt.ID),dc&&(Uc&&this.collisionIndex.insertCollisionCircles(dc.circles,oe.get("text-ignore-placement"),Q.bucketInstanceId,Wh,Lt.ID),B)){const bu=Q.bucketInstanceId;let id=this.collisionCircleArrays[bu];id===void 0&&(id=this.collisionCircleArrays[bu]=new Mp);for(let Rc=0;Rc=0;--Za){const Oi=qr[Za];Gr(Q.symbolInstances.get(Oi),Oi,Q.collisionArrays[Oi])}Q.hasAnyZOffset&&o.w(`${Q.layerIds[0]} layer symbol-z-elevate: symbols are not sorted by elevation if symbol-z-order is evaluated to viewport-y`)}else if(Q.hasAnyZOffset){const qr=Q.getSortedIndexesByZOffset();for(let Za=0;Za0){let Kn;return this.prevPlacement&&this.prevPlacement.variableOffsets[$s]&&this.prevPlacement.placements[$s]&&this.prevPlacement.placements[$s].text&&(Kn=this.prevPlacement.variableOffsets[$s].anchor),this.variableOffsets[$s]={textOffset:rn,width:oe,height:me,anchor:k,textScale:we,prevAnchor:Kn},ff(es,k,vt,Qt),es.allowVerticalPlacement&&(Td(es,Qt,vt),this.placedOrientations[$s]=Qt),{shift:_n,placedGlyphBoxes:Mn}}}commit(k){this.commitTime=k,this.zoomAtLastRecencyCheck=this.transform.zoom;const T=this.prevPlacement;let B=!1;this.prevZoomAdjustment=T?T.zoomAdjustment(this.transform.zoom):0;const K=T?T.symbolFadeChange(k):1,Q=T?T.opacities:{},oe=T?T.variableOffsets:{},me=T?T.placedOrientations:{};for(const we in this.placements){const Me=this.placements[we],Re=Q[we];Re?(this.opacities[we]=new 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 me)this.placedOrientations[we]||!this.opacities[we]||this.opacities[we].isHidden()||(this.placedOrientations[we]=me[we]);B?this.lastPlacementChangeTime=k:typeof this.lastPlacementChangeTime!="number"&&(this.lastPlacementChangeTime=T?T.lastPlacementChangeTime:k)}updateLayerOpacities(k,T,B,K,Q=!1,oe=1){K&&(this.lastReplacementSourceUpdateTime=K.updateTime);const me=new Set;for(const we of T){const Me=we.getBucket(k);if(Me&&we.latestFeatureIndex&&k.fqid===Me.layerIds[0]&&(this.updateBucketOpacities(Me,me,we,we.collisionBoxArray,B,K,we.tileID,k.scope),Me.elevationType==="offset"&&this.buildingIndex&&this.buildingIndex.updateZOffset(Me,we.tileID),Me.elevationType==="road"&&Me.hdExt&&Me.hdExt.updateRoadElevation(Me,we.tileID.canonical),Me.updateZOffset(),Q&&we.collisionBoxArray)){const Re=Me.layers[0].layout,[Ze,Qe]=Re.get("text-size-scale-range"),[ut,bt]=Re.get("icon-size-scale-range"),vt=o.b1(oe,Ze,Qe),Mt=o.b1(oe,ut,bt);Me.updateCollisionDebugBuffers(this.transform.zoom,we.collisionBoxArray,vt,Mt)}}}updateBucketOpacities(k,T,B,K,Q,oe,me,we){k.hasTextData()&&k.text.opacityVertexArray.clear(),k.hasIconData()&&k.icon.opacityVertexArray.clear(),k.hasIconCollisionBoxData()&&k.iconCollisionBox.collisionVertexArray.clear(),k.hasTextCollisionBoxData()&&k.textCollisionBox.collisionVertexArray.clear();const Me=k.layers[0].layout,Re=k.layers[0].paint,Ze=!!k.layers[0].dynamicFilter(),Qe=new Bm(null,0,!1,!1,!0),ut=Me.get("text-allow-overlap"),bt=Me.get("icon-allow-overlap"),vt=Me.get("text-variable-anchor"),Mt=Me.get("text-rotation-alignment")==="map",es=Me.get("text-pitch-alignment")==="map",Qt=Re.get("symbol-z-offset"),Lt=Me.get("symbol-elevation-reference")==="sea",ps=!Qt.isConstant(),Hs=new Bm(null,0,ut&&(bt||!k.hasIconData()||Me.get("icon-optional")),bt&&(ut||!k.hasTextData()||Me.get("text-optional")),!0);!k.collisionArrays&&K&&(k.hasIconCollisionBoxData()||k.hasTextCollisionBoxData())&&k.deserializeCollisionBoxes(K);const Fs=($s,rn,_n)=>{for(let Mn=0;Mn0||Mn>0,si=Bn>0,Wr=this.placedOrientations[Kn],Tr=Wr===o.dt.vertical,Gr=Wr===o.dt.horizontal||Wr===o.dt.horizontalOnly;!ea&&!si||Hr.isHidden()||nn++;let Ga=!1;if((ea||si)&&oe)for(const qr of k.activeReplacements){if(o.dm(qr,Q,o.dn.Symbol,we)||qr.min.x>On||On>qr.max.x||qr.min.y>Rr||Rr>qr.max.y)continue;const Za=o.dp(On,Rr,me.canonical,qr.footprintTileId.canonical);if(Ga=o.dq(Za,qr.footprint),Ga)break}if(Ga&&this.collisionIndex.markSymbolAsClipped(k.bucketInstanceId,rn.featureIndex),ea){const qr=Ga?lg:$1(Hr.text);Fs(k.text,_n,Tr?lg:qr),Fs(k.text,Mn,Gr?lg:qr);const Za=Hr.text.isHidden(),{leftJustifiedTextSymbolIndex:Oi,centerJustifiedTextSymbolIndex:Do,rightJustifiedTextSymbolIndex:so,verticalPlacedTextSymbolIndex:ql}=rn,vu=k.text.placedSymbolArray,Uc=Za||Tr?1:0;Oi>=0&&(vu.get(Oi).hidden=Uc),Do>=0&&(vu.get(Do).hidden=Uc),so>=0&&(vu.get(so).hidden=Uc),ql>=0&&(vu.get(ql).hidden=Za||Gr?1:0);const Ko=this.variableOffsets[Kn];Ko&&ff(k,Ko.anchor,rn,Wr);const no=this.placedOrientations[Kn];no&&(ff(k,"left",rn,no),Td(k,no,rn))}if(si){const qr=Ga?lg:$1(Hr.icon),{placedIconSymbolIndex:Za,verticalPlacedIconSymbolIndex:Oi}=rn,Do=k.icon.placedSymbolArray,so=Hr.icon.isHidden()?1:0;Za>=0&&(Fs(k.icon,Bn,Tr?lg:qr),Do.get(Za).hidden=so),Oi>=0&&(Fs(k.icon,rn.numVerticalIconVertices,Gr?lg:qr),Do.get(Oi).hidden=so)}if(k.hasIconCollisionBoxData()||k.hasTextCollisionBoxData()){const qr=k.collisionArrays[$s];if(qr){let Za=new o.P(0,0),Oi=!0;if(qr.textBox||qr.verticalTextBox){if(vt){const so=this.variableOffsets[Kn];so?(Za=rx(so.anchor,so.width,so.height,so.textOffset,so.textScale),Mt&&Za._rotate(es?this.transform.angle:-this.transform.angle)):Oi=!1}Ze&&(Oi=!Hr.clipped),qr.textBox&&Vd(k.textCollisionBox.collisionVertexArray,Hr.text.placed,!Oi||Tr,sa,Lt,Za.x,Za.y),qr.verticalTextBox&&Vd(k.textCollisionBox.collisionVertexArray,Hr.text.placed,!Oi||Gr,sa,Lt,Za.x,Za.y)}const Do=Oi&&!!(!Gr&&qr.verticalIconBox);qr.iconBox&&Vd(k.iconCollisionBox.collisionVertexArray,Hr.icon.placed,Do,sa,Lt,rn.hasIconTextFit?Za.x:0,rn.hasIconTextFit?Za.y:0),qr.verticalIconBox&&Vd(k.iconCollisionBox.collisionVertexArray,Hr.icon.placed,!Do,sa,Lt,rn.hasIconTextFit?Za.x:0,rn.hasIconTextFit?Za.y:0)}}}if(k.fullyClipped=nn===0,k.sortFeatures(this.transform.angle),this.retainedQueryData[k.bucketInstanceId]&&(this.retainedQueryData[k.bucketInstanceId].featureSortOrder=k.featureSortOrder),k.hasTextData()&&k.text.opacityVertexBuffer&&k.text.opacityVertexBuffer.updateData(k.text.opacityVertexArray),k.hasIconData()&&k.icon.opacityVertexBuffer&&k.icon.opacityVertexBuffer.updateData(k.icon.opacityVertexArray),k.hasIconCollisionBoxData()&&k.iconCollisionBox.collisionVertexBuffer&&k.iconCollisionBox.collisionVertexBuffer.updateData(k.iconCollisionBox.collisionVertexArray),k.hasTextCollisionBoxData()&&k.textCollisionBox.collisionVertexBuffer&&k.textCollisionBox.collisionVertexBuffer.updateData(k.textCollisionBox.collisionVertexArray),k.bucketInstanceId in this.collisionCircleArrays){const $s=this.collisionCircleArrays[k.bucketInstanceId];k.placementInvProjMatrix=$s.invProjMatrix,k.placementViewportMatrix=$s.viewportMatrix,k.collisionCircleArray=$s.circles,delete this.collisionCircleArrays[k.bucketInstanceId]}}symbolFadeChange(k){return this.fadeDuration===0?1:(k-this.commitTime)/this.fadeDuration+this.prevZoomAdjustment}zoomAdjustment(k){return Math.max(0,(this.transform.zoom-k)/1.5)}hasTransitions(k){return k-this.lastPlacementChangeTimek}isStale(){return this.stale}setStale(){this.stale=!0}}function Vd(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),zx=Math.pow(2,17),z1=Math.pow(2,16),bm=Math.pow(2,9),Ok=Math.pow(2,8),B1=Math.pow(2,1);function $1(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*zx+k*z1+T*bm+k*Ok+T*B1+k}const lg=0;class Db{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 me=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"),Qe=Re.layout.get("symbol-sort-key").constantOr(1)!==void 0,ut=Re.layout.get("symbol-z-order"),bt=ut==="viewport-y"||ut==="auto"&&!(ut!=="viewport-y"&&Qe),vt=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=bt&&vt,es=this._inProgressLayer=this._inProgressLayer||new Db(Re),Qt=o.m(we.source,we.scope);if(es.continuePlacement(Ze||Mt?K[Qt]:B[Qt],this.placement,this._showCollisionBoxes,we,me,Q))return;delete this._inProgressLayer}this._currentPlacementIndex--}this._forceFullPlacement=!1,this._done=!0}commit(k){return this._retiredCI=this.placement.prevPlacement?this.placement.prevPlacement.collisionIndex:null,this.placement.commit(k),this.placement}}const W2=512/o.a6/2;class zk{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-es);for(const Mt of vt){const es=this.crossTileIDs[Mt];if(this.keys[Mt]===Re&&!B.has(es)){B.add(es),Me.crossTileID=es;break}}}}}class yy{constructor(){this.maxCrossTileID=0}generate(){return++this.maxCrossTileID}}class vy{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 me=K[oe];me.tileID=me.tileID.unwrapTo(me.tileID.wrap+T),Q[me.tileID.key]=me}this.indexes[B]=Q}this.lng=k}addBucket(k,T,B){if(this.indexes[k.overscaledZ]&&this.indexes[k.overscaledZ][k.key]){if(this.indexes[k.overscaledZ][k.key].bucketInstanceId===T.bucketInstanceId)return!1;this.removeBucketCrossTileIDs(k.overscaledZ,this.indexes[k.overscaledZ][k.key])}for(let Q=0;Qk.overscaledZ)for(const me in oe){const we=oe[me];we.tileID.isChildOf(k)&&we.findMatches(T.symbolInstances,k,K)}else{const me=oe[k.scaledTo(Number(Q)).key];me&&me.findMatches(T.symbolInstances,k,K)}}for(let Q=0;Q{T[B]=!0});for(const B in this.layerIndexes)T[B]||delete this.layerIndexes[B]}}function Fb(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(!Bx(this._geometries[me],Q))return!1;const we=this._geometryData[me];return we===void 0||!B(we)};return(Q.kind==="box"?this._grid.hitTest(Q.left+K,Q.top+K,Q.right+K,Q.bottom+K,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(!Bx(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 lp(L){return 2*L.styleLayerId+L.symbolIdOrigin}function $_(L,k){const T=L.get(lp(k.symbolId));if(!T)return!1;const B=T.get(k.symbolId.symbolId);return B!==void 0&&B.has(k.variantIdx)}function Zy(L,k){const T=lp(k.symbolId);let B=L.get(T);B||(B=new Map,L.set(T,B));let K=B.get(k.symbolId.symbolId);K||(K=new Set,B.set(k.symbolId.symbolId,K)),K.add(k.variantIdx)}class Bk{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 U1(T,B,100,32),this._timestamp=k,this._symbols=[],this._ignoredSymbolVariantIds.clear(),this._onlyIfPlacedReferencedIds.clear(),this._placedVariantIds.clear(),this._placedSymbolIds.clear()}_hasPlacedSymbol(k){const T=this._placedSymbolIds.get(lp(k));return T!==void 0&&T.has(k.symbolId)}_addPlacedSymbol(k){const T=lp(k);let B=this._placedSymbolIds.get(T);B||(B=new Set,this._placedSymbolIds.set(T,B)),B.add(k.symbolId)}startSymbolSourceProcessing(k){if(!this._runStarted)throw new Error("Attempt to start symbol source processing outside of a placement run");if(this._processingSource)throw new Error("Attempt to start a placement symbol source processing before finishing the previous one");this._processingSource=k}startSymbolVariantProcessing(k,T,B){const K=this._processingSource;if(!K)throw new Error("Attempt to start a symbol variant processing outside of symbol source processing");if(this._variantProcessingStarted)throw new Error("Attempt to begin a symbol variant processing before finishing the previous one");this._symbols.push({priority:T,source:K,variantId:k,geometry:[],placementRules:B});const Q=B.collisionRules;Q&&(Q.symbolVariantToIgnoreCollisionWith&&Zy(this._ignoredSymbolVariantIds,Q.symbolVariantToIgnoreCollisionWith),Q.onlyIfPlaced&&Zy(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&&!$_(this._placedVariantIds,oe))Q=!1;else{const me=B.placementRules.collisionRules.symbolVariantToIgnoreCollisionWith;k.intersects(B.geometry,K?0:1,we=>{return me!==void 0&&(Me=we).variantIdx===(Re=me).variantIdx&&Me.symbolId.styleLayerId===Re.symbolId.styleLayerId&&Me.symbolId.symbolIdOrigin===Re.symbolId.symbolIdOrigin&&Me.symbolId.symbolId===Re.symbolId.symbolId;var Me,Re})!=="does-not-intersect"&&(Q=!1)}}if(Q&&B.placementRules.insertIntoCollisionGrid){const oe=$_(this._ignoredSymbolVariantIds,B.variantId)?B.variantId:void 0;k.insert(B.geometry,oe)||(Q=!1)}Q&&(this._addPlacedSymbol(B.variantId.symbolId),$_(this._onlyIfPlacedReferencedIds,B.variantId)&&Zy(this._placedVariantIds,B.variantId)),K!==Q&&(Q?B.source.showSymbolVariant(B.variantId,T):B.source.hideSymbolVariant(B.variantId,T))}}}class tj{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 Xy 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 yr(),vr.loadModel?await vr.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 me of K){const we=k[me];this.hasURLBeenRequested(we)&&!B.forceReload||(this.modelByURL[we]={modelId:me,scope:T},Q.push(this.loadModel(me,we)),oe.push(me)),this.models[T][me]||(this.models[T][me]={model:null,numReferences:1})}this.numModelsLoading[T]=(this.numModelsLoading[T]||0)+oe.length,Promise.allSettled(Q).then(me=>{for(let we=0;we{this.fire(new o.f(new Error(`Could not load models: ${me.message}`)))})}isLoaded(){for(const k in this.numModelsLoading)if(this.numModelsLoading[k]>0)return!1;return!0}hasModel(k,T,B={exactIdMatch:!1}){return!!(B.exactIdMatch?this.getModel(k,T):this.getModelByURL(this.modelUris[T][k]))}getModel(k,T){return this.models[T]||(this.models[T]=Object.create(null)),this.models[T][k]?this.models[T][k].model:void 0}getModelByURL(k){if(!k)return null;const T=this.modelByURL[k];return T?this.models[T.scope][T.modelId].model:null}hasModelBeenAdded(k,T){return this.models[T]&&this.models[T][k]!==void 0}getModelURIs(k){return this.modelUris[k]||Object.create(null)}addModel(k,T,B){this.models[B]||(this.models[B]=Object.create(null)),this.modelUris[B]||(this.modelUris[B]=Object.create(null));const K=this.requestManager.normalizeModelURL(T);if((this.hasModel(k,B,{exactIdMatch:!0})||this.hasModelBeenAdded(k,B))&&this.modelUris[B][k]===K)this.models[B][k].numReferences++;else if(this.hasURLBeenRequested(K)){const{scope:Q,modelId: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 cp=["RENDER_SHADOWS","NORMAL_OFFSET"],q1=new Set(["symbol","circle"]),$x=class sGe{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"),me=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"),Qe=(ut,bt=[],vt={})=>{this._queue.push({programId:ut,params:{...vt.params,defines:bt,overrideFog:!!vt.fog,overrideTerrain:!!vt.terrain,overrideGlobe:!!vt.globe,overrideRtt:!!vt.rtt,precompiled:!0}})};for(const ut of k){if(ut.visibility==="none")continue;const bt=ut.getProgramIds();if(bt)for(const vt of bt){if(q1.has(vt))continue;const Mt=ut.getDefaultProgramParams(vt,T.zoom,B._styleColorTheme.lut);if(!Mt)continue;const es=Me?Me.getShaderSource(vt):null,Qt=me&&(!es||es.usedDefines.has("RENDER_TO_TEXTURE"));let Lt=Mt.defines;if(Ze&&Qt&&(Lt=(Lt||[]).concat("USE_MRT1"),Me.emissiveMode==="mrt-full-rgba"&&(Lt=(Lt||[]).concat("USE_MRT1_RGBA"))),Re){Qe(vt,Mt.defines,{params:Mt}),Qt&&Qe(vt,Lt,{params:Mt,rtt:!0});continue}const ps=K&&(!es||es.usedDefines.has("FOG")),Hs=Q&&!ut.isDraped()&&(!es||es.usedDefines.has("TERRAIN")),Fs=oe&&(!es||es.usedDefines.has("GLOBE")),nn=we&&ut.hasElevation()&&(!es||es.usedDefines.has("RENDER_SHADOWS"));for(const $s of nn?[!1,!0]:[!1]){const rn=$s?(Mt.defines||[]).concat(cp):Mt.defines||[];for(const _n of Hs?[!1,!0]:[!1])for(const Mn of Fs?[!1,!0]:[!1])for(const Kn of ps?[!1,!0]:[!1])Qe(vt,rn,{params:Mt,fog:Kn,terrain:_n,globe:Mn})}Qt&&Qe(vt,Lt,{params:Mt,rtt:!0})}}if(Qe("clippingMask"),Q)for(const ut of[!1,!0])Qe("terrainRaster",ut?["TERRAIN_VERTEX_MORPHING"]:[],{terrain:!0,fog:K});if(!Re){if(k.some(ut=>ut.type==="hillshade")&&Qe("hillshadePrepare"),we)for(const ut of[!1,!0])for(const bt of[!1,!0]){const vt=[];ut&&vt.push("RENDER_CUTOFF"),vt.push("RENDER_SHADOWS"),bt&&vt.push("NORMAL_OFFSET"),Qe("groundShadow",vt),K&&Qe("groundShadow",vt,{fog:!0})}if(oe){for(const ut of[[],["TERRAIN_VERTEX_MORPHING"],["GLOBE_POLES"]])for(const bt of[!1,!0]){const vt=[...ut,"PROJECTION_GLOBE_VIEW"];bt&&vt.push("CUSTOM_ANTIALIASING"),Qe("globeRaster",vt,{terrain:Q,globe:!0,fog:K})}for(const ut of[!1,!0]){const bt=ut?["PROJECTION_GLOBE_VIEW","FOG"]:["FOG"];Qe("globeAtmosphere",bt,{fog:!0,terrain:Q,globe:ut}),Qe("globeAtmosphere",[...bt,"ALPHA_PASS"],{fog:!0,terrain:Q,globe:ut})}Qe("stars",[],{fog:K,terrain:Q,globe:!0})}}}_executeBatch(k,T,B){if(B.map&&B.map.isMoving())return void(this._idleHandle=o.e.requestIdleCallback(me=>this._executeBatch(me,T,B)));T.context.sweepPendingPrograms();const K=T.context.extParallelShaderCompile?sGe.DEADLINE_MARGIN_KHR_MS:sGe.DEADLINE_MARGIN_SYNC_MS;let Q=0;for(;this._queue.length>0;){const me=this._queue.shift();if(!me||me.programId in Ar&&(T.style=B,T._fogVisible=!!me.params.overrideFog,T.getOrCreateProgram(me.programId,me.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(me=>this._executeBatch(me,T,B)):null}processQueue(k,T){this._queue.length!==0&&(this._idleHandle!=null&&typeof cancelIdleCallback<"u"&&cancelIdleCallback(this._idleHandle),this._idleHandle=o.e.requestIdleCallback(B=>this._executeBatch(B,k,T)))}reset(){this._idleHandle!=null&&typeof cancelIdleCallback<"u"&&cancelIdleCallback(this._idleHandle),this._queue=[],this._idleHandle=null,this._needsBuild=!0}};$x.DEADLINE_MARGIN_KHR_MS=5,$x.DEADLINE_MARGIN_SYNC_MS=25;let dp=$x;const V1=o.s.colorTheme,A3=new o.ag({data:new o.ah(V1.data)});function $k(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,me=B*k;return[oe,me,oe+K*k,me+Q*k]}function HT(L){if(L)return L.map(([k,T])=>[k*o.e.devicePixelRatio,T*o.e.devicePixelRatio])}class $v{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,me]of Q)k.set(o.I.from({name:oe,iconsetId:this.id}),me),this.pendingRequests.delete(oe);for(const oe of this.pendingRequests)this.missingRequests.add(oe);return this.pendingRequests.clear(),k}}const Uv=(L,k)=>lm(L,k&&k.filter(T=>T.identifier!=="source.canvas")),H0=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"]),U_=new Set(["setCenter","setZoom","setBearing","setPitch"]),cg=new Set(["background","sky","slot","custom","placement-group"]),G0={version:8,layers:[],sources:{}},Qy={duration:300,delay:0};class up extends o.E{constructor(k,T={}){super(),this.map=k,this.scope=T.scope||"",this.globalId=null,this.fragments=[],this.importDepth=T.importDepth||0,this.importsCache=T.importsCache||new Map,this.resolvedImports=T.resolvedImports||new Set,this.transition={...Qy},this._buildingIndex=new lu(this),this.crossTileSymbolIndex=new ej,this.globalPlacement=null,this.symbolIdRangeAllocator=new tj,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 js(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 Xy(k._requestManager),this.modelManager.setEventedParent(this)),this._layers=Object.create(null),this._sourceCaches={},this._otherSourceCaches=Object.create(null),this._symbolSourceCaches=Object.create(null),this._fillExtrusionSourceCaches=Object.create(null),this._hdCoverage=null,this._hdElevation=null,this._crossSourceElevationActive=!1,this._loaded=!1,this._drapingLoaded=void 0,this._initialBroadcastDone=!1,this._programPrecompiler=this.map._precompilePrograms&&this.isRootStyle()?new dp:null,this._availableImages=[],this._availableModels={},this._order=[],this._markersNeedUpdate=!1,this.options=T.configOptions?T.configOptions:new Map,this._layerExpressionDependencies=T.layerExpressionDependencies?T.layerExpressionDependencies:new Map,this._config=T.config,this._styleColorTheme={lut:null,lutLoading:!1,lutLoadingCorrelationID:0,colorTheme:null,colorThemeOverride:T.colorThemeOverride},this._styleColorThemeForScope={},this._initialConfig=T.initialConfig;const K=this;this._rtlTextPluginCallback=up.registerForPluginStateChange(Q=>{K.dispatcher.send("syncRTLPluginState",{pluginStatus:Q.pluginStatus,pluginURL:Q.pluginURL}).then(oe=>{if(o.dD(null),oe.every(me=>me))for(const me in K._sourceCaches){const we=K._sourceCaches[me],Me=we.getSource().type;Me!=="vector"&&Me!=="geojson"||we.reload()}}).catch(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 me in this._layers){const we=this._layers[me];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(me){oe(me,!1)}};if(typeof k=="string"){const Q=this.map._requestManager.normalizeStyleURL(k),oe=new AbortController;this._request={cancel:()=>oe.abort()},(async()=>{const me=await this.map._requestManager.transformRequest(Q,o.R.Style,oe.signal),{data:we}=await o.g(me,oe.signal);this._request=null,K(we,T)})().catch(me=>{this._request=null,oe.signal.aborted||this.fire(new o.f(me))})}else typeof k=="object"&&K(k,T)}loadURL(k,T={}){this.fire(new o.h("dataloading",{dataType:"style"}));const B=typeof T.validate=="boolean"?T.validate:!o.cG(k);B&&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:me}=await o.g(oe,Q.signal);this._request=null,this.importsCache.set(k,me),this._load(me,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(G0,!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),me=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(me),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 up(this.map,{scope:T,styleChanges:this._changes,importDepth:this.importDepth+1,importsCache:this.importsCache,resolvedImports:new Set(this.resolvedImports),dispatcher:this.dispatcher,imageManager:this.imageManager,glyphManager:this.glyphManager,modelManager:this.modelManager,config:B,configOptions:this.options,colorThemeOverride:k["color-theme"],layerExpressionDependencies:this._layerExpressionDependencies});return Q.setEventedParent(this.map,{style:Q}),Q}_reloadImports(k=!1){this.mergeAll(),this._updateMapProjection(),k||this.updateConfigDependencies(),this._updateLayers(this._dependentLayerIds(T=>T.isIndoorDependent)),this.map._triggerCameraUpdate(this.camera),(!k||this.isRootStyle()||this.map.style._initialBroadcastDone)&&(k&&this.isRootStyle()?(this.forEachFragmentStyle(T=>{this.dispatcher.broadcast("setLayers",{layers:T._serializeLayers(T._order),scope:T.scope,options:T.options})}),this._initialBroadcastDone=!0):this.dispatcher.broadcast("setLayers",{layers:this._serializeLayers(this._order),scope:this.scope,options:this.options}))}_isInternalStyle(k){return this.isRootStyle()&&(k.fragment||!!k.schema&&k.fragment!==!1)}async _load(k,T){if(this._isInternalStyle(k)){const Q={id:"basemap",data:k,url:""},oe={...G0,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||Uv(this,_s(k))))return;this._loaded=!0;for(const Q in k.sources)this.addSource(Q,k.sources[Q],{validate:!1,isInitialLoad:!0});this.stylesheet=o.dG(k);const B=()=>{if(k.iconsets)for(const Me in k.iconsets)this.addIconset(Me,k.iconsets[Me]);k.sprite?this._loadIconset(k.sprite):(this.imageManager.setLoaded(!0,this.scope),this.dispatcher.broadcast("spriteLoaded",{scope:this.scope})),!this.glyphManager.url&&k.glyphs&&this.glyphManager.setURL(k.glyphs);const Q=op(this.stylesheet.layers);if(this._order=Q.map(Me=>Me.id),this.stylesheet.light&&o.w("The `light` root property is deprecated, prefer using `lights` with `flat` light type instead."),this.stylesheet.lights)if(this.stylesheet.lights.length===1&&this.stylesheet.lights[0].type==="flat"){const Me=this.stylesheet.lights[0];this.light=new 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),Qe=!!this.directionalLight&&this.directionalLight.shadowsEnabled();Ze&&Re.canCastShadows()&&Qe&&(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 Qe=Ze.layout.get("text-font");Qe&&Qe.value&&Qe.value.kind==="constant"&&Me.add(Qe.value.value.join(","))}}for(const Re of Me)this.glyphManager.prefetchRange(Re,0)}this.stylesheet.featuresets&&this.setFeaturesetSelectors(this.stylesheet.featuresets),this.stylesheet.models&&this.addModelURLs(this.stylesheet.models);const me=this.stylesheet.terrain;me&&(this.checkCanvasFingerprintNoise(),this.disableElevatedTerrain||this.terrainSetForDrapingOnly()||(this._startLiteLoad(),this._createTerrain(me,1))),this.stylesheet.fog&&this._createFog(this.stylesheet.fog),this.stylesheet.snow&&this._createSnow(this.stylesheet.snow),this.stylesheet.rain&&this._createRain(this.stylesheet.rain),this.stylesheet.transition&&this.setTransition(this.stylesheet.transition),this.fire(new o.h("data",{dataType:"style"}));const we=this.isRootStyle();k.imports?this._loadImports(k.imports,T).then(()=>{this._reloadImports(!0),this.fire(new o.h(we?"style.load":"style.import.load"))}).catch(Me=>{this.fire(new o.f(new Error("Failed to load imports",Me))),this.fire(new o.h(we?"style.load":"style.import.load"))}):(this._reloadImports(!0),this.fire(new o.h(we?"style.load":"style.import.load")))};this._styleColorTheme.colorTheme=this.stylesheet["color-theme"];const K=this._styleColorTheme.colorThemeOverride?this._styleColorTheme.colorThemeOverride:this._styleColorTheme.colorTheme;if(K){const Q=this._evaluateColorThemeData(K);this._loadColorTheme(Q).then(()=>{B()}).catch(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,me,we,Me,Re;const Ze={};this.terrain&&this.terrain.scope!==this.scope&&delete this.terrain,this.forEachFragmentStyle(Qe=>{if(Qe.stylesheet){if(Qe.disableElevatedTerrain&&(this.disableElevatedTerrain=!0),Qe.light!=null&&(k=Qe.light),Qe.stylesheet.lights)for(const ut of Qe.stylesheet.lights)ut.type==="ambient"&&Qe.ambientLight!=null&&(T=Qe.ambientLight),ut.type==="directional"&&Qe.directionalLight!=null&&(B=Qe.directionalLight);K=this._prioritizeTerrain(K,Qe.terrain,Qe.stylesheet.terrain),Qe.stylesheet.fog&&Qe.fog!=null&&(Q=Qe.fog),Qe.stylesheet.snow&&Qe.snow!=null&&(oe=Qe.snow),Qe.stylesheet.rain&&Qe.rain!=null&&(me=Qe.rain),Qe.stylesheet.camera!=null&&(Re=Qe.stylesheet.camera),Qe.stylesheet.projection!=null&&(we=Qe.stylesheet.projection),Qe.stylesheet.transition!=null&&(Me=Qe.stylesheet.transition),Ze[Qe.scope]=Qe._styleColorTheme}}),this.light=k,this.ambientLight=T,this.directionalLight=B,this.fog=Q,this.snow=oe,this.rain=me,this._styleColorThemeForScope=Ze,K===null?delete this.terrain:this.terrain=K,this.camera=Re||{"camera-projection":"perspective"},this.projection=we||{name:"mercator"},this.transition={...Qy,...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 me in oe._sourceCaches){const we=o.m(me,oe.scope);k[we]=oe._sourceCaches[me]}for(const me in oe._otherSourceCaches){const we=o.m(me,oe.scope);T[we]=oe._otherSourceCaches[me]}for(const me in oe._symbolSourceCaches){const we=o.m(me,oe.scope);B[we]=oe._symbolSourceCaches[me]}for(const me in oe._fillExtrusionSourceCaches){const we=o.m(me,oe.scope);K[we]=oe._fillExtrusionSourceCaches[me]}if(oe._hdCoverage){const me=oe._hdCoverage.coverageSourceCaches;for(const we in me)Q[o.m(we,oe.scope)]=me[we]}}),this._mergedSourceCaches=k,this._mergedOtherSourceCaches=T,this._mergedSymbolSourceCaches=B,this._mergedFillExtrusionSourceCaches=K,this._mergedHdRoadCoverageSourceCaches=Q,Object.keys(Q).length>0&&!this._hdCoverage&&Ui.HdCoverageState&&(this._hdCoverage=new Ui.HdCoverageState),Ui.updateCrossSourceElevationGate&&Ui.updateCrossSourceElevationGate(this)}mergeIndoor(){this._mergedIndoor={},this.forEachFragmentStyle(k=>{if(k.stylesheet&&k.stylesheet.indoor)for(const T of Object.values(k.stylesheet.indoor)){const B=T,K=o.m(B.sourceId,k.scope);this._mergedIndoor[K]=new Set(B.sourceLayers||[])}}),this._updateIndoorEnabled()}_updateIndoorEnabled(){const k=this._indoorEnabled;if(this._indoorEnabled=!1,Object.keys(this._mergedIndoor).length>0)for(const T of this._mergedOrder){const B=this._mergedLayers[T];if(B.visibility!=="none"&&this._mergedIndoor[o.m(B.source,B.scope)]){this._indoorEnabled=!0;break}}!this._indoorEnabled||k||this.indoorManager||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 me of oe._order){const we=oe._layers[me];if(we.type==="slot"){const Me=o.dH(me);if(k[Me])continue;k[Me]=[]}we.slot&&k[we.slot]?k[we.slot].push(we):T.push(we)}}),this._mergedOrder=[];let K=-1;const Q=(oe=[])=>{for(const me of oe)if(me.type==="slot"){const we=o.dH(me.id);k[we]&&Q(k[we]),this._mergedSlots.push(we)}else{const we=o.m(me.id,me.scope);this._mergedOrder.push(we),B[we]=me,me.is3D(!!this.terrain)&&(this._has3DLayers=!0,K=this._mergedOrder.length-1),me.type==="circle"&&(this._hasCircleLayers=!0),me.type==="symbol"&&(this._hasSymbolLayers=!0),me.type==="clip"&&(this._clipLayerPresent=!0)}};if(Q(T),this._has3DLayers){const oe={};for(let me=0;meoe[me]-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 me of Object.keys(V1))Q[me]===void 0&&(Q[me]=V1[me].default);const oe=new o.af(A3,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 me=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(me)&&this.removeImage(me),this.addImage(me,{data:new o.b({width:Me,height:Re},Ze),pixelRatio:1,sdf:!1,usvg:!1,version:0});const Qe=this.imageManager.getImage(me,this.scope);Qe?(this._styleColorTheme.lut={image:Qe.data,data:k},B()):K(new Error("Missing LUT image."))}})}getLut(k){const T=this._styleColorThemeForScope[k];return T?T.lut:null}setProjection(k){k?this.stylesheet.projection=k:delete this.stylesheet.projection,this.mergeProjection(),this._updateMapProjection()}applyProjectionUpdate(){this.map.transform.projection.requiresDraping&&this._startLiteLoad(),this._loaded&&(this.dispatcher.broadcast("setProjection",this.map.transform.projectionOptions),this.map.transform.projection.requiresDraping?(this.getTerrain()||this.stylesheet.terrain)&&!this.disableElevatedTerrain||this.setTerrainForDraping():this.terrainSetForDrapingOnly()&&this.setTerrain(null,0))}_updateMapProjection(){this.isRootStyle()&&(this.map._useExplicitProjection?this.applyProjectionUpdate():this.map._prioritizeAndUpdateProjection(null,this.projection))}_loadSprite(k){const T=new AbortController;this._spriteRequest=T,function(B,K,Q,oe){let me,we,Me;const Re=o.e.devicePixelRatio>1?"@2x":"";function Ze(Qe){Me||Qe&&Q.aborted||(Qe&&(Me=Qe),function(){if(Me)oe(Me);else if(me&&we){const ut=o.e.getImageData(we),bt={};for(const vt in me){const{width:Mt,height:es,x:Qt,y:Lt,sdf:ps,pixelRatio:Hs,stretchX:Fs,stretchY:nn,content:$s}=me[vt],rn=new o.b({width:Mt,height:es});o.b.copy(ut,rn,{x:Qt,y:Lt},{x:0,y:0},{width:Mt,height:es},null),bt[vt]={data:rn,pixelRatio:Hs!==void 0?Hs:1,sdf:ps!==void 0&&ps,stretchX:Fs,stretchY:nn,content:$s,usvg:!1,version:0}}oe(null,bt)}}())}(async function(){const Qe=await K.transformRequest(K.normalizeSpriteURL(B,Re,".json"),o.R.SpriteJSON,Q),{data:ut}=await o.g(Qe,Q);Me||(me=ut)})().then(()=>Ze(void 0),Qe=>Ze(Qe)),async function(){const Qe=await K.transformRequest(K.normalizeSpriteURL(B,Re,".png"),o.R.SpriteImage,Q),{data:ut}=await o.a(Qe,Q);Me||(we=ut)}().then(()=>Ze(void 0),Qe=>Ze(Qe))}(k,this.map._requestManager,T.signal,(B,K)=>{if(this._spriteRequest=null,B)this.dispatcher.broadcast("spriteLoaded",{scope:this.scope}),this.fire(new o.f(B));else if(K){const Q=new Map;for(const 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 $v(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,me){try{const we=await Q.transformRequest(Q.normalizeIconsetURL(K),o.R.Iconset,oe),{data:Me}=await o.d0(we,oe),Re={},Ze=function(Qe){const ut={icons:[]};let bt;for(;bt=Qe.nextField(void 0);)bt===1&&ut.icons.push(Y(Qe,Qe.readVarint()+Qe.pos));return ut}(new o.c$(Me));for(const Qe of Ze.icons){const ut={version:1,pixelRatio:o.e.devicePixelRatio,content:$k(Qe),stretchX:Qe.metadata?HT(Qe.metadata.stretch_x_areas):void 0,stretchY:Qe.metadata?HT(Qe.metadata.stretch_y_areas):void 0,sdf:!1,usvg:!0,icon:Qe};Re[Qe.name]=ut}me(null,Re)}catch(we){oe.aborted||me(we)}}(k,this.map._requestManager,B.signal,(K,Q)=>{if(this._spriteRequest=null,K)T?this._loadSprite(k):(this.dispatcher.broadcast("spriteLoaded",{scope:this.scope}),this.fire(new o.f(K)));else if(Q){const oe=new Map;for(const me in Q)oe.set(o.I.from(me),Q[me]);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:Qe}=Me[Re];(Ze||Qe)&&(this._updateWorkerLayers(Re,Ze,Qe),Q=!0)}this.updateSourceCaches(),this._updateTilesForChangedImages(),this.updateLayers(k),this.light&&this.light.updateTransitions(k),this.ambientLight&&this.ambientLight.updateTransitions(k),this.directionalLight&&this.directionalLight.updateTransitions(k),this.fog&&this.fog.updateTransitions(k),this.snow&&this.snow.updateTransitions(k),this.rain&&this.rain.updateTransitions(k),this._changes.reset()}const oe={};for(const Me in this._mergedSourceCaches){const Re=this._mergedSourceCaches[Me];oe[Me]=Re.used,Re.used=!1,Re.tileCoverLift=0}const me={};for(const Me of this._mergedOrder){const Re=this._mergedLayers[Me];if((Re.visibility!=="none"||Re.hasTransition())&&Re.recalculate(k,this._availableImages),!Re.isHidden(k.zoom)){Re.mayUse("HD")&&(Re.prepare(),um()),Re.mayUse("Standard")&&(Re.prepare(),yr()),Re.mayUse("Lite")&&(this.checkCanvasFingerprintNoise(),this.disableElevatedTerrain||this._startLiteLoad());const Ze=this.getLayerSourceCache(Re);Ze&&(Ze.used=!0,Ze.tileCoverLift=Math.max(Ze.tileCoverLift,Re.tileCoverLift()))}if(Re.source){const Ze=o.m(Re.source,Re.scope),Qe=this._mergedHdRoadCoverageSourceCaches[Ze];Qe&&!Qe.used&&(Qe.used=!0)}if(Re.type==="fill-extrusion"){const Ze=o.m(Re.source,Re.scope);if(Ze in this._mergedFillExtrusionSourceCaches){const Qe=Re.layout&&Re.layout.get("source-max-zoom");if(Qe!=null){const ut=me[Ze];me[Ze]=ut==null?Qe:Math.min(ut,Qe)}}}}if(this._programPrecompiler&&this._programPrecompiler.needsBuild()){const Me=this._mergedOrder.map(Re=>this._mergedLayers[Re]);this._programPrecompiler.buildQueue(Me,k,this)}for(const Me in this._mergedFillExtrusionSourceCaches)this._mergedFillExtrusionSourceCaches[Me].setMaxzoomOverride(me[Me]??null);this.terrain&&Q&&this.mergeLayers();const we=this.imageManager.getPendingImageProviders();for(const Me of we)Me.sourceCache.used=!0;for(const Me in 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(),Uv(this,_s(k)))return!1;if((k=o.dG(k)).layers=op(k.layers),!Mc.diffStyles)throw new Error("Debug module not loaded; cannot diff style.");const B=Mc.diffStyles(this.serialize(),k).filter(oe=>!U_.has(oe.command));if(B.length===0)return!1;const K=B.filter(oe=>!H0.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):lo(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 me=we=>{const Me=(we===o.bS.Symbol?"symbol:":we===o.bS.FillExtrusion?"fill-extrusion:":"other:")+Q.id,Re=o.m(Me,this.scope),Ze=this._sourceCaches[Me]=new Ci(Re,Q,we);we===o.bS.Symbol?this._symbolSourceCaches[Q.id]=Ze:we===o.bS.FillExtrusion?this._fillExtrusionSourceCaches[Q.id]=Ze:this._otherSourceCaches[Q.id]=Ze,Ze.onAdd(this.map)};me(o.bS.Other),T.type!=="vector"&&T.type!=="geojson"||(me(o.bS.Symbol),T.type==="vector"&&me(o.bS.FillExtrusion)),Q.onAdd&&Q.onAdd(this.map),K&&async function(we){if(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,Qe){bl[Ze]=Qe}(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=lo(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,gn(),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,Pn(),this.scope,this.options)}}const B=Object.assign(T,{worldview:this.map.getWorldview()}),K=new o.aj(this.z||0,B);this.ambientLight&&this.ambientLight.recalculate(K),this.directionalLight&&this.directionalLight.recalculate(K),this._brightness=this.calculateLightsBrightness(),this.dispatcher.broadcast("upsertRenderParams",{brightness:this._brightness})}calculateLightsBrightness(){const k=this.directionalLight,T=this.ambientLight;if(!k||!T)return;const B=Qe=>.2126*(Qe[0]<=.03928?Qe[0]/12.92:Math.pow((Qe[0]+.055)/1.055,2.4))+.7152*(Qe[1]<=.03928?Qe[1]/12.92:Math.pow((Qe[1]+.055)/1.055,2.4))+.0722*(Qe[2]<=.03928?Qe[2]/12.92:Math.pow((Qe[2]+.055)/1.055,2.4)),K=k.properties.get("color").toNonPremultipliedRenderColor(null).toArray01(),Q=k.properties.get("intensity"),oe=k.properties.get("direction"),me=1-o.b_(oe.x,oe.y,oe.z)[2]/90,we=B(K)*Q*me,Me=T.properties.get("color").toNonPremultipliedRenderColor(null).toArray01(),Re=T.properties.get("intensity"),Ze=B(Me)*Re;return Number(((we+Ze)/2).toFixed(6))}getBrightness(){return this._brightness}getLights(){if(!this.enable3dLights())return null;const k=[];return this.directionalLight&&k.push(this.directionalLight.get()),this.ambientLight&&k.push(this.ambientLight.get()),k}enable3dLights(){return!!this.ambientLight&&!!this.directionalLight}getFragmentStyle(k){if(k==null||k===""&&this.isRootStyle())return this;if(o.dI(k)){const T=o.dJ(k),B=this.fragments.find(({id:Q})=>Q===T);if(!B)return;const K=o.dH(k);return B.style.getFragmentStyle(K)}{const T=this.fragments.find(({id:B})=>B===k);return T?T.style:void 0}}setFeaturesetSelectors(k){if(!k)return;const T=(B,K="")=>`${B}::${K}`;this._featuresetSelectors={};for(const B in k){const K={},Q=this._featuresetSelectors[B]=[];for(const 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 me;if(oe.properties)for(const we in oe.properties){const Me=o.c(oe.properties[we]);Me.result==="success"&&(me=me||{},me[we]=Me.value)}Q.push({layerId:oe.layer,namespace:oe.featureNamespace,properties:me,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 me=B.getOwnLayer(oe.layer);me&&Q.push(me)}return Q}getConfigProperty(k,T){const B=this.getFragmentStyle(k);if(!B)return null;const K=o.m(T,B.scope),Q=B.options.get(K),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 Uv(this,oe.value);const me=oe.value.expression,we=o.m(T,K.scope),Me=K.options.get(we);if(!Me)return;let Re;const{minValue:Ze,maxValue:Qe,stepValue:ut,type:bt,values:vt}=Q[T],Mt=o.dK(Q[T].default,Q[T]);Mt.result==="success"&&(Re=Mt.value.expression),Re?(this.options.set(we,{...Me,value:me,default:Re,minValue:Ze,maxValue:Qe,stepValue:ut,type:bt,values:vt}),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),me=T.options.get(oe),we=me?me.value||me.default:null;K[Q]=we?we.serialize():null}return K}setConfig(k,T){const B=this.getFragmentStyle(k);B&&(B.updateConfig(T,B.stylesheet.schema),this.updateConfigDependencies())}getSchema(k){const T=this.getFragmentStyle(k);return T?T.stylesheet.schema:null}setSchema(k,T){const B=this.getFragmentStyle(k);B&&(B.stylesheet.schema=T,B.updateConfig(B._config,T),this.updateConfigDependencies())}updateConfig(k,T){if(this._config=k,k||T)if(T)for(const B in T){let K,Q;const oe=o.dK(T[B].default,T[B]);if(oe.result==="success"&&(K=oe.value.expression),k&&k[B]!==void 0){const Qe=o.dK(k[B],T[B]);Qe.result==="success"&&(Q=Qe.value.expression)}const{minValue:me,maxValue:we,stepValue:Me,type:Re,values:Ze}=T[B];if(K){const Qe=o.m(B,this.scope);this.options.set(Qe,{default:K,value:Q,minValue:me,maxValue:we,stepValue:Me,type:Re,values:Ze})}else this.fire(new o.f(new Error(`No schema defined for config option "${B}".`)))}else this.fire(new o.f(new Error("Attempting to set config for a style without schema.")))}_updateLayers(k){for(const T of k){const B=this.getLayer(T);B&&(B.possiblyEvaluateVisibility(),this._updateLayer(B),this._changes.setDirty())}}_dependentLayerIds(k){const T=[];for(const[B,K]of this._layerExpressionDependencies)k(K)&&T.push(B);return T}updateConfigDependencies(k){this._updateLayers(this._dependentLayerIds(T=>k?T.hasConfigDependency(k):T.isConfigDependent)),this.ambientLight&&this.ambientLight.updateConfig(this.options),this.directionalLight&&this.directionalLight.updateConfig(this.options),this.fog&&this.fog.updateConfig(this.options),this.snow&&this.snow.updateConfig(this.options),this.rain&&this.rain.updateConfig(this.options),this.forEachFragmentStyle(T=>{const B=T._styleColorTheme.colorThemeOverride?T._styleColorTheme.colorThemeOverride:T._styleColorTheme.colorTheme;if(B){const K=T._evaluateColorThemeData(B);(!T._styleColorTheme.lut&&K!==""||T._styleColorTheme.lut&&K!==T._styleColorTheme.lut.data)&&T.setColorTheme(B)}}),this._updateIndoorEnabled(),this._changes.setDirty()}addLayer(k,T,B={}){this._checkLoaded();const K=k.id;if(this._layers[K])return void this.fire(new o.f(new Error(`Layer with id "${K}" already exists on this map`)));let Q;if(k.type==="custom"){if(Uv(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 me=this.getOwnLayerSourceCache(Q),we=!!this.directionalLight&&this.directionalLight.shadowsEnabled();me&&Q.canCastShadows()&&we&&(me.castsShadows=!0);const Me=this._changes.getRemovedLayer(Q);if(Me&&Q.source&&me&&Q.type!=="custom"){this._changes.discardLayerRemoval(Q);const Re=o.m(Q.source,Q.scope);Me.type!==Q.type?this._changes.updateSourceCache(Re,"clear"):(this._changes.updateSourceCache(Re,"reload"),me.pause())}this._updateLayer(Q),Q.onAdd&&Q.onAdd(this.map),Q.scope=this.scope,this.mergeLayers()}moveLayer(k,T){this._checkLoaded();const B=this._checkLayer(k);if(!B||k===T)return;const K=this._order.indexOf(k);this._order.splice(K,1);let Q=this._order.length;if(T){const 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)&&Uv(Q,Fl.call(_s,{key:`layers.${k}.layout.${T}`,layerType:Q.type,objectKey:T,value:B,styleSpec:o.s,style:{glyphs:!0,sprite:!0}})))return;Q.setLayoutProperty(T,B),this._updateLayer(Q)}}getLayerProperty(k,T){const B=this._checkLayer(k);if(B){switch(T){case"minzoom":return B.minzoom;case"maxzoom":return B.maxzoom;case"filter":return this.getFilter(k);case"slot":return B.slot;case"appearances":return B.getAppearances().map(K=>K.serialize())}return B.isPaintProperty(T)?this.getPaintProperty(k,T):this.getLayoutProperty(k,T)}}setLayerProperty(k,T,B,K={}){this._checkLoaded();const Q=this._checkLayer(k);if(Q){switch(T){case"appearances":return Q.setAppearances(B),void this._updateLayer(Q);case"minzoom":return this.setLayerZoomRange(k,B);case"maxzoom":return this.setLayerZoomRange(k,null,B);case"filter":return this.setFilter(k,B,K);case"slot":return this.setSlot(k,B)}Q.isPaintProperty(T)?this.setPaintProperty(k,T,B,K):this.setLayoutProperty(k,T,B,K)}}getLayoutProperty(k,T){const B=this._checkLayer(k);if(B)return B.getLayoutProperty(T)}setPaintProperty(k,T,B,K={}){this._checkLoaded();const Q=this._checkLayer(k);Q&&(o.O(Q.getPaintProperty(T),B)||(B==null||K&&K.validate===!1||!Uv(Q,Zg.call(_s,{key:`layers.${k}.paint.${T}`,layerType:Q.type,objectKey:T,value:B,styleSpec:o.s})))&&(Q.setPaintProperty(T,B)&&this._updateLayer(Q),this._changes.updatePaintProperties(Q)))}getPaintProperty(k,T){const B=this._checkLayer(k);if(B)return B.getPaintProperty(T)}setFeatureState(k,T){if(this._checkLoaded(),"target"in k){if("featuresetId"in k.target){const{featuresetId:we,importId:Me}=k.target,Re=this.getFragmentStyle(Me),Ze=Re.getFeaturesetLayers(we);for(const{source:Qe,sourceLayer:ut}of Ze)Re.setFeatureState({id:k.id,source:Qe,sourceLayer:ut},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 me=this.getOwnSourceCaches(B);for(const we of me)we.setFeatureState(K,k.id,T)}removeFeatureState(k,T){if(this._checkLoaded(),"target"in k){if("featuresetId"in k.target){const{featuresetId:we,importId:Me}=k.target,Re=this.getFragmentStyle(Me),Ze=Re.getFeaturesetLayers(we);for(const{source:Qe,sourceLayer:ut}of Ze)Re.removeFeatureState({id:k.id,source:Qe,sourceLayer:ut},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 me=this.getOwnSourceCaches(B);for(const we of me)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:me}=k.target,we=this.getFragmentStyle(me),Me=we.getFeaturesetLayers(oe);for(const{source:Re,sourceLayer:Ze}of Me){const Qe=we.getFeatureState({id:k.id,source:Re,sourceLayer:Ze});if(Qe&&!Q)Q=Qe;else if(!o.O(Q,Qe))return void this.fire(new o.f(new Error("The same feature id exists in multiple sources in the featureset, but their feature states are not consistent through the sources.")))}}else if("layerId"in k.target){const 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:me}of Q)K.removeFeatureState({source:oe,sourceLayer:me})}else{const T=this._resolveLayerFragment(k.layerId);T==null||T.fragment.removeFeatureState({source:T.layer.source,sourceLayer:T.layer.sourceLayer})}}setTransition(k){return this.stylesheet.transition={...this.stylesheet.transition,...k},this.transition=this.stylesheet.transition,this}getTransition(){return{...this.stylesheet.transition}}setWorldview(k){k!==this._worldview&&(this._worldview=k,this.dispatcher.broadcast("upsertRenderParams",{worldview:this._worldview}),this.reloadSources())}serialize(){this._checkLoaded();const k=this.getTerrain(),T=k&&this.terrain&&this.terrain.scope===this.scope?k:this.stylesheet.terrain;return o.dN({version:this.stylesheet.version,name:this.stylesheet.name,metadata:this.stylesheet.metadata,fragment:this.stylesheet.fragment,iconsets:this.stylesheet.iconsets,featuresets:this.stylesheet.featuresets,imports:this._serializeImports(),schema:this.stylesheet.schema,camera:this.stylesheet.camera,light:this.stylesheet.light,lights:this.stylesheet.lights,terrain:T,fog:this.stylesheet.fog,snow:this.stylesheet.snow,rain:this.stylesheet.rain,indoor:this.stylesheet.indoor,center:this.stylesheet.center,"color-theme":this.stylesheet["color-theme"],zoom:this.stylesheet.zoom,bearing:this.stylesheet.bearing,pitch:this.stylesheet.pitch,sprite:this.stylesheet.sprite,glyphs:this.stylesheet.glyphs,transition:this.stylesheet.transition,projection:this.stylesheet.projection,sources:this._serializeSources(),layers:this._serializeLayers(this._order)},B=>B!==void 0)}_updateFilteredLayers(k){for(const T of Object.values(this._mergedLayers))k(T)&&this._updateLayer(T)}_updateLayer(k){this._changes.updateLayer(k);const T=this.getLayerSourceCache(k),B=o.m(k.source,k.scope),K=this._changes.getUpdatedSourceCaches();k.source&&!K[B]&&T&&T.getSource().type!=="raster"&&(this._changes.updateSourceCache(B,"reload"),T.pause()),k.invalidateCompiledFilter()}_flattenAndSortRenderedFeatures(k){const T=me=>this._mergedLayers[me].is3D(!!this.terrain),B=this.order,K={},Q=[];for(let me=B.length-1;me>=0;me--){const we=B[me];if(T(we)){K[we]=me;for(const Me of k){const Re=Me[we];if(Re)for(const Ze of Re)Q.push(Ze)}}}Q.sort((me,we)=>we.intersectionZ-me.intersectionZ);const oe=[];for(let me=B.length-1;me>=0;me--){const we=B[me];if(T(we))for(let Me=Q.length-1;Me>=0;Me--){const Re=Q[Me].feature;if(Re.layer&&K[Re.layer.id]{if(cg.has(Re.type))return;const Ze=this.getOwnLayerSourceCache(Re),Qe=Q[Ze.id]=Q[Ze.id]||{sourceCache:Ze,layers:{},has3DLayers:!1};Re.is3D(!!this.terrain)&&(Qe.has3DLayers=!0),Qe.layers[Re.fqid]=Qe.layers[Re.fqid]||{styleLayer:Re,targets:[]},Qe.layers[Re.fqid].targets.push({filter:K})};if(T&&T.layers){if(!Array.isArray(T.layers))return this.fire(new o.f(new Error("parameters.layers must be an Array."))),[];for(const Re of T.layers){const Ze=this._layers[Re];if(!Ze)return this.fire(new o.f(new Error(`The layer '${Re}' does not exist in the map's style and cannot be queried for features.`))),[];oe(Ze)}}else for(const Re in this._layers)oe(this._layers[Re]);const me=this._queryRenderedFeatures(k,Q,B),we=this._flattenAndSortRenderedFeatures(me),Me=[];for(const Re of we)o.dO(Re.layer.id)===this.scope&&Me.push(Re);return Me}queryRenderedFeatureset(k,T,B){let K;T&&!Array.isArray(T)&&T.filter&&(this._validate(vo,"queryRenderedFeatures.filter",T.filter,null,T),K=o.bw(T.filter));const Q="mock",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 Qe=Ze.getFeaturesetDescriptors();for(const ut of Qe)oe.push({targetId:Q,filter:K,target:ut})}}const me=this.queryRenderedTargets(k,oe,B),we=[],Me=new Set;for(const Re of me)for(const Ze of Re.variants[Q])Xd(Ze,Re,Me)||we.push(new o.dP(Re,Ze));return we}queryRenderedTargets(k,T,B){const K={},Q=(me,we,Me,Re)=>{const Ze=K[we.id]=K[we.id]||{sourceCache:we,layers:{},has3DLayers:!1};if(Ze.layers[me.fqid]=Ze.layers[me.fqid]||{styleLayer:me,targets:[]},me.is3D(!!this.terrain)&&(Ze.has3DLayers=!0),!Re)return Me.uniqueFeatureID=!1,void Ze.layers[me.fqid].targets.push(Me);Ze.layers[me.fqid].targets.push({...Me,namespace:Re.namespace,properties:Re.properties,uniqueFeatureID:Re.uniqueFeatureID})};for(const me of T)if("featuresetId"in me.target){const{featuresetId:we,importId:Me}=me.target,Re=this.getFragmentStyle(Me);if(!Re||!Re._featuresetSelectors)continue;const Ze=Re._featuresetSelectors[we];if(!Ze){this.fire(new o.f(new Error(`The featureset '${we}' does not exist in the map's style and cannot be queried for features.`)));continue}for(const Qe of Ze){const ut=Re.getOwnLayer(Qe.layerId);ut&&!cg.has(ut.type)&&Q(ut,Re.getOwnLayerSourceCache(ut),me,Qe)}}else if("layerId"in me.target){const{layerId:we}=me.target,Me=this.getLayer(we);if(!Me||cg.has(Me.type))continue;Q(Me,this.getLayerSourceCache(Me),me)}const oe=this._queryRenderedFeatures(k,K,B);return this._flattenAndSortRenderedFeatures(oe)}_queryRenderedFeatures(k,T,B){const K=[],Q=!!this.map._showQueryGeometry,oe=br.createFromScreenPoints(k,B);for(const me in T){const we=og(oe,T[me],this._availableImages,B,Q,this.getActualScope());Object.keys(we).length&&K.push(we)}if(this.placement)for(const me in T){if(T[me].sourceCache._renderSourceType!==o.bS.Symbol)continue;const we=Lh(oe.screenGeometry,T[me],this._availableImages,this.placement.collisionIndex,this.placement.retainedQueryData,this.map.getWorldview());Object.keys(we).length&&K.push(we)}return K}querySourceFeatures(k,T){const B=T&&T.filter;B&&this._validate(vo,"querySourceFeatures.filter",B,null,T);let K=[];const Q=this.getOwnSourceCaches(k);for(const 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 me in k)if(!o.O(k[me],K[me])){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 me="terrain-dem-src";this.addSource(me,B.source),B=o.dG(B),B=Object.assign(B,{source:me})}const Q={...B},oe={};if(this.terrain&&K){Q.source=this.terrain.get().source;const me=this.terrain?this.getFragmentStyle(this.terrain.scope):null;me&&(oe.style=me.serialize())}if(this._validate(io,"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 me of Object.keys(o.s.terrain))!Object.hasOwn(B,me)&&o.s.terrain[me].default&&(B[me]=o.s.terrain[me].default);for(const me in k)if(!o.O(k[me],oe[me])){Q.set(k,this.options),this.stylesheet.terrain=k;const we=this._getTransitionParameters({duration:0});Q.updateTransitions(we),this.fire(new o.h("data",{dataType:"style"}));break}}this.mergeTerrain(),this.updateDrapeFirstLayers(),this._markersNeedUpdate=!0}_createFog(k){const T=this.fog=new 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 jt(k,this.map.transform,this.scope,this.options);this.stylesheet.snow=T.get();const B=this._getTransitionParameters({duration:0});T.updateTransitions(B)}_createRain(k){const T=this.rain=new Rt(k,this.map.transform,this.scope,this.options);this.stylesheet.rain=T.get();const B=this._getTransitionParameters({duration:0});T.updateTransitions(B)}_updateMarkersOpacity(){this.map._markers.length!==0&&this.map._requestDomTask(()=>{for(const k of this.map._markers)k._evaluateOpacity()})}getFog(){return this.fog?this.fog.get():null}setFog(k){if(this._checkLoaded(),k)if(this.fog){const T=this.fog;if(!o.O(T.get(),k)){T.set(k,this.options),this.stylesheet.fog=T.get();const B=this._getTransitionParameters({duration:0});T.updateTransitions(B)}}else this._createFog(k);else delete this.fog,delete this.stylesheet.fog;this._markersNeedUpdate=!0,this._programPrecompiler&&this._programPrecompiler.reset()}getSnow(){return this.snow?this.snow.get():null}setSnow(k){if(this._checkLoaded(),!k)return delete this.snow,void delete this.stylesheet.snow;if(this.snow){const T=this.snow;if(!o.O(T.get(),k)){T.set(k,this.options),this.stylesheet.snow=T.get();const B=this._getTransitionParameters({duration:0});T.updateTransitions(B)}}else this._createSnow(k);this._markersNeedUpdate=!0}getRain(){return this.rain?this.rain.get():null}setRain(k){if(this._checkLoaded(),!k)return delete this.rain,void delete this.stylesheet.rain;if(this.rain){const T=this.rain;if(!o.O(T.get(),k)){T.set(k,this.options),this.stylesheet.rain=T.get();const B=this._getTransitionParameters({duration:0});T.updateTransitions(B)}}else this._createRain(k);this._markersNeedUpdate=!0}_reloadColorTheme(){const k=()=>{for(const K in this._layers)this._layers[K].lut=this._styleColorTheme.lut;for(const K in this._sourceCaches)this._sourceCaches[K].clearTiles()},T=this._styleColorTheme.colorThemeOverride?this._styleColorTheme.colorThemeOverride:this._styleColorTheme.colorTheme;if(!T)return this._styleColorTheme.lut=null,void k();const B=this._evaluateColorThemeData(T);this._loadColorTheme(B).then(()=>{this.fire(new o.h("colorthemeset")),k()}).catch(K=>{o.w(`Couldn't set color theme: ${K}`)})}setColorTheme(k){this._checkLoaded(),this._styleColorTheme.colorThemeOverride&&o.w("Note: setColorTheme is called on a style with a color-theme override, the passed color-theme won't be visible."),this._styleColorTheme.colorTheme=k,this._reloadColorTheme()}setImportColorTheme(k,T){const B=this.getFragmentStyle(k);B&&(B._styleColorTheme.colorThemeOverride=T,B._reloadColorTheme())}_getTransitionParameters(k){return{now:o.e.now(),transition:Object.assign(this.transition,k)}}updateDrapeFirstLayers(){if(!this.terrain)return;const k=[],T=[];for(const B of this._mergedOrder)this.isLayerDraped(this._mergedLayers[B])?k.push(B):T.push(B);this._drapedFirstOrder=[],this._drapedFirstOrder.push(...k),this._drapedFirstOrder.push(...T)}_createTerrain(k,T){const B=this.terrain=new Ky(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 Uv(this,k.call(_s,{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 me=this._mergedLayers[oe];me.type==="building"?B.add(me.source):me.type==="raster"&&me.paint&&me.paint.get("raster-elevation-reference")==="ground"&&Q.add(me.source),me.hasElevation()&&!K.has(me.source)&&K.add(me.source)}this.updateFrcCoverageFadeRange();for(const oe in this._mergedSourceCaches){const me=this._mergedSourceCaches[oe],we=K.has(me._source.id);me._isRasterElevatedOverTerrain=Q.has(me._source.id),B.has(me._source.id)&&(me._source.reparseOverscaled=!1),me.update(k,void 0,void 0,T,we)}this.updateFrcCoverage(),this.updateElevationCoverage()}_reloadSources(){for(const k in this._sourceCaches){const T=this._sourceCaches[k];T.resume(),T.reload()}}updateFrcCoverageFadeRange(){this.map.painter&&Ui.updateFrcCoverageFadeRange&&Ui.updateFrcCoverageFadeRange(this,this.map.painter)}updateFrcCoverage(){this._hdCoverage&&Ui.updateFrcCoverage&&Ui.updateFrcCoverage(this,this._hdCoverage)}updateElevationCoverage(){this.isRootStyle()&&Ui.setupAndUpdateElevationCoverage&&Ui.setupAndUpdateElevationCoverage(this)}_handleLayerOrderChange(){this._requestFullLabelPlacement(),this.fire(new o.h("neworder"))}_requestFullLabelPlacement(){this.pauseablePlacement||(this.pauseablePlacement=new ax),this.pauseablePlacement.requestFullPlacement()}_setLabelPlacementStale(){this.placement&&this.placement.setStale()}_updatePlacement(k,T,B,K,Q,oe){this.pauseablePlacement||(this.pauseablePlacement=new ax);let me=!1,we=!1;const Me={},Re={},Ze=oe==="global",Qe=Ze?[]:this._mergedOrder;Ze&&this._driveGlobalPlacement(k,Q);for(const Qt of Qe){const Lt=this._mergedLayers[Qt];if(Lt.type!=="symbol")continue;const ps=o.m(Lt.source,Lt.scope);let Hs=Me[ps];if(!Hs){const nn=this.getLayerSourceCache(Lt);if(!nn)continue;const $s=nn.getRenderableIds(!0).map(rn=>nn.getTileByID(rn));Re[ps]=$s.slice(),Hs=Me[ps]=$s.sort((rn,_n)=>_n.tileID.overscaledZ-rn.tileID.overscaledZ||(rn.tileID.isLessThan(_n.tileID)?-1:1))}const Fs=this.crossTileSymbolIndex.addLayer(Lt,Hs,k.center.lng,k.projection);me=me||Fs}this.crossTileSymbolIndex.pruneUnusedLayers(Qe);const ut=!!(this.placement&&!k.equals(this.placement.transform)),bt=!!(this.placement&&(this.placement.lastReplacementSourceUpdateTime!==0&&!Q||this.placement.lastReplacementSourceUpdateTime!==Q.updateTime)),vt=ut||bt||me,Mt=(vt||this.pauseablePlacement.isStale())&&B===0,es=this.pauseablePlacement.isDone()&&!this.placement.stillRecent(o.e.now(),k.zoom)&&B!==0;if((this.pauseablePlacement.isFullPlacementRequested()||!this.pauseablePlacement.placement||Mt||es)&&(this.pauseablePlacement=this.pauseablePlacement.startNewPlacement(k,Qe,T,B,K,this.placement,this.fog&&k.projection.supportsFog?this.fog.state:null,this._buildingIndex),this.map.painter)){const Qt=this.map.painter.maxFrontCutoffRawStart;if(Qt>0){const Lt=180*k.pitch/Math.PI;if(Lt>=15){const ps=Math.min(1,Math.max(0,(Lt-15)/5)),Hs=ps*ps*(3-2*ps);this.pauseablePlacement.placement.frontCutoffStart=-.5*(1-Hs)+Qt*Hs}}}if(this.pauseablePlacement.isDone()?vt&&B!==0&&this.pauseablePlacement.setStale():(this.pauseablePlacement.continuePlacement(Qe,this._mergedLayers,Me,Re,this.map.painter.scaleFactor),this.pauseablePlacement.isDone()&&(this.placement=this.pauseablePlacement.commit(o.e.now()),we=!0),me&&this.pauseablePlacement.setStale()),we||me){this._buildingIndex.onNewFrame(k.zoom);for(let Qt=0;Qtwe.getTileByID(Ze)),Re=this.isLayerClipped(me);me.placeSymbols(Q,Me,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],me=this.fragments[K];return B=B.filter(({id:we})=>we!==k),this.fragments=this.fragments.filter(({id:we})=>we!==k),this.stylesheet.imports=B.slice(0,Q).concat(oe).concat(B.slice(Q)),this.fragments=this.fragments.slice(0,Q).concat(me).concat(this.fragments.slice(Q)),this.mergeLayers(),this}setImportUrl(k,T){this._checkLoaded();const B=this.stylesheet.imports||[],K=this.getImportIndex(k);if(K===-1)return this;B[K].url=T;const Q=this.fragments[K];return Q.style=this._createFragmentStyle(B[K]),Q.style.on("style.import.load",()=>this.mergeAll()),Q.style.loadURL(T),this}setImportData(k,T){this._checkLoaded();const B=this.getImportIndex(k),K=this.stylesheet.imports||[];return B===-1?this:T?(this.fragments[B].style.setState(T),this._reloadImports(),this):(delete K[B].data,this.setImportUrl(k,K[B].url))}setImportConfig(k,T,B){this._checkLoaded();const K=this.getImportIndex(k),Q=this.stylesheet.imports||[];if(K===-1)return this;T?Q[K].config=T:delete Q[K].config;const oe=this.fragments[K];B&&oe.style.stylesheet&&(oe.style.stylesheet.schema=B);const me=oe.style.stylesheet&&oe.style.stylesheet.schema;return oe.config=T,oe.style.updateConfig(T,me),this.updateConfigDependencies(),this}removeImport(k){this._checkLoaded();const T=this.stylesheet.imports||[],B=this.getImportIndex(k);B!==-1&&(T.splice(B,1),this.fragments[B].style._remove(),this.fragments.splice(B,1),this._reloadImports())}getImportIndex(k){const T=(this.stylesheet.imports||[]).findIndex(B=>B.id===k);return T===-1&&this.fire(new o.f(new Error(`Import '${k}' does not exist in the map's style and cannot be updated.`))),T}getLayer(k){return this._mergedLayers[k]}getSources(){const k=[];for(const T in this._mergedOtherSourceCaches){const B=this._mergedOtherSourceCaches[T];B&&k.push(B.getSource())}return k}getSource(k,T){const B=this.getSourceCache(k,T);return B&&B.getSource()}getLayerSource(k){const T=this.getLayerSourceCache(k);return T&&T.getSource()}getSourceCache(k,T){const B=o.m(k,T);return this._mergedOtherSourceCaches[B]}getLayerSourceCache(k){const T=o.m(k.source,k.scope);return k.type==="symbol"?this._mergedSymbolSourceCaches[T]:k.type==="fill-extrusion"?this._mergedFillExtrusionSourceCaches[T]||this._mergedOtherSourceCaches[T]:k.type==="fill"&&k.sourceLayer===o.bV&&this._mergedHdRoadCoverageSourceCaches[T]?this._mergedHdRoadCoverageSourceCaches[T]:this._mergedOtherSourceCaches[T]}getSourceCaches(k){return k==null?Object.values(this._mergedSourceCaches):[this._mergedOtherSourceCaches[k],this._mergedSymbolSourceCaches[k],this._mergedFillExtrusionSourceCaches[k],this._mergedHdRoadCoverageSourceCaches[k]].filter(Boolean)}updateSourceCaches(){const k=this._changes.getUpdatedSourceCaches();for(const T in k){const B=k[T];B==="reload"?this.reloadSource(T):B==="clear"&&this.clearSource(T)}}updateLayers(k){const T=this._changes.getUpdatedPaintProperties();for(const B of T){const K=this.getLayer(B);K&&K.updateTransitions(k)}}getGlyphsUrl(){return this.stylesheet.glyphs}setGlyphsUrl(k){this.stylesheet.glyphs=k,this.glyphManager.setURL(k)}getOwnSourceCache(k){return this._otherSourceCaches[k]}getOwnLayerSourceCache(k){return k.type==="symbol"?this._symbolSourceCaches[k.source]:k.type==="fill-extrusion"&&this._fillExtrusionSourceCaches[k.source]||this._otherSourceCaches[k.source]}getOwnSourceCaches(k){return[this._otherSourceCaches[k],this._symbolSourceCaches[k],this._fillExtrusionSourceCaches[k],this._hdCoverage&&this._hdCoverage.coverageSourceCaches[k]].filter(Boolean)}_updateHdCoverageSourceCache(k){return Ui.HdCoverageState&&Ui.updateHdCoverageSourceCache?(this._hdCoverage||(this._hdCoverage=new Ui.HdCoverageState),Ui.updateHdCoverageSourceCache(this,this._hdCoverage,k),!1):k.type==="fill"&&k.sourceLayer===o.bV}_isSourceCacheLoaded(k){const T=this.getOwnSourceCaches(k);return T.length===0?(this.fire(new o.f(new Error(`There is no source with ID '${k}'`))),!1):T.every(B=>B.loaded())}has3DLayers(){return this._has3DLayers}hasSymbolLayers(){return this._hasSymbolLayers}hasCircleLayers(){return this._hasCircleLayers}isLayerClipped(k,T){if(!this._clipLayerPresent&&k.type!=="fill-extrusion"&&k.type!=="building")return!1;const B=k.type==="fill-extrusion"&&(k.sourceLayer==="building"||k.sourceLayer==="procedural_buildings"),K=k.type==="building";if(k.is3D(!!this.terrain)){if(B||K||T&&T.type==="batched-model"||k.type==="model")return!0}else if(k.type==="symbol")return!0;return!1}_clearWorkerCaches(){this.dispatcher.broadcast("clearCaches")}getBOMObject(){}destroy(){this._clearWorkerCaches(),this.imageManager.imageAtlasCache.clear(),this.fragments.forEach(k=>{k.style._remove()}),this.terrainSetForDrapingOnly()&&(delete this.terrain,delete this.stylesheet.terrain)}async getImages(k,T){const B=new Promise((we,Me)=>{this.imageManager.getImages(T.icons.concat(T.patterns),T.scope,(Re,Ze)=>{Re?Me(Re):we(Ze)})});this._updateTilesForChangedImages();const K=T.icons.map(we=>o.I.toString(we)),Q=T.patterns.map(we=>o.I.toString(we)),oe=we=>{we&&(we.setDependencies(T.tileID.key,"icons",K),we.setDependencies(T.tileID.key,"patterns",Q))},me=o.m(T.source,T.scope);return oe(this._mergedOtherSourceCaches[me]),oe(this._mergedSymbolSourceCaches[me]),(T.icons.some(we=>we.iconsetId)||T.patterns.some(we=>we.iconsetId))&&this.fire(new o.h("data",{dataType:"style"})),B}async rasterizeImages(k,T){return new Promise((B,K)=>{this.imageManager.rasterizeImages(T,(Q,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)})})}}up.registerForPluginStateChange=o.dz;class qv{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,me,we){this.context=k;let Me=this.boundPaintVertexBuffers.length!==K.length;for(let Ze=0;!Me&&Ze`#define ${Mt}`)).join(` `)}`,Re=[Me,o.dZ];for(const Mt of B.fragmentIncludes)Re.push(o.bb[Mt]);Re.push(B.fragmentSource);const Ze=Re.join(` `),Qe=[Me,o.d_];for(const Mt of B.vertexIncludes)Qe.push(o.bb[Mt]);this.forceManualRenderingForInstanceIDShaders=k.forceManualRenderingForInstanceIDShaders&&B.vertexSource.includes("gl_InstanceID"),this.forceManualRenderingForInstanceIDShaders&&Qe.push("uniform int u_instanceID;"),Qe.push(B.vertexSource);let ut=Qe.join(` `);this.forceManualRenderingForInstanceIDShaders&&(ut=ut.replaceAll("gl_InstanceID","u_instanceID"));const bt=we.createShader(we.FRAGMENT_SHADER);if(we.isContextLost())return this.failedToCreate=!0,void(this._pending=!1);we.shaderSource(bt,Ze),we.compileShader(bt),we.attachShader(this.program,bt);const vt=we.createShader(we.VERTEX_SHADER);if(we.isContextLost())return this.failedToCreate=!0,void(this._pending=!1);we.shaderSource(vt,ut),we.compileShader(vt),we.attachShader(this.program,vt),we.linkProgram(this.program),this._fragmentShader=bt,this._vertexShader=vt,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 me=this.fixedDefines,we=this.name;(me.includes("TERRAIN")||me.includes("ELEVATED")||we.includes("symbol")||we.includes("circle"))&&(this.terrainUniforms=(Me=>({u_dem:new o.aY(Me),u_dem_prev:new o.aY(Me),u_dem_tl:new o.a2(Me),u_dem_scale:new o.a3(Me),u_dem_tl_prev:new o.a2(Me),u_dem_scale_prev:new o.a3(Me),u_dem_size:new o.a3(Me),u_dem_lerp:new o.a3(Me),u_exaggeration:new o.a3(Me),u_depth:new o.aY(Me),u_depth_size_inv:new o.a2(Me),u_depth_range_unpack:new o.a2(Me),u_occluder_half_size:new o.a3(Me),u_occlusion_depth_offset:new o.a3(Me),u_meter_to_dem:new o.a3(Me),u_label_plane_matrix_inv:new o.a4(Me)}))(k)),me.includes("GLOBE")&&(this.globeUniforms=(Me=>({u_tile_tl_up:new o.a5(Me),u_tile_tr_up:new o.a5(Me),u_tile_br_up:new o.a5(Me),u_tile_bl_up:new o.a5(Me),u_tile_up_scale:new o.a3(Me)}))(k)),me.includes("FOG")&&(this.fogUniforms=(Me=>({u_fog_matrix:new o.a4(Me),u_fog_range:new o.a2(Me),u_fog_color:new o.aZ(Me),u_fog_horizon_blend:new o.a3(Me),u_fog_vertical_limit:new o.a2(Me),u_fog_temporal_offset:new o.a3(Me),u_frustum_tl:new o.a5(Me),u_frustum_tr:new o.a5(Me),u_frustum_br:new o.a5(Me),u_frustum_bl:new o.a5(Me),u_globe_pos:new o.a5(Me),u_globe_radius:new o.a3(Me),u_globe_transition:new o.a3(Me),u_is_globe:new o.aY(Me),u_viewport:new o.a2(Me)}))(k)),me.includes("RENDER_CUTOFF")&&(this.cutoffUniforms=o.d$(k)),me.includes("LIGHTING_3D_MODE")&&(this.lightsUniforms=(Me=>({u_lighting_ambient_color:new o.a5(Me),u_lighting_directional_dir:new o.a5(Me),u_lighting_directional_color:new o.a5(Me),u_ground_radiance:new o.a5(Me)}))(k)),me.includes("RENDER_SHADOWS")&&(this.shadowUniforms=o.e0(k))}maybeFinalize(){if(!this._pending)return;const k=this._context.extParallelShaderCompile;k&&!this._context.gl.getProgramParameter(this.program,k.COMPLETION_STATUS_KHR)||this._finalize()}_ensureReady(){this._pending&&(this._finalize(),this._context.sweepPendingPrograms())}getAttributeLocation(k,T){this._ensureReady();let B=this.attributes[T];return B===void 0&&(B=this.attributes[T]=k.getAttribLocation(this.program,T)),B}_setUniformGroup(k,T,B){this._ensureReady();const K=this[T];if(!this.failedToCreate&&K){k.program.set(this.program);for(const Q in B){const 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,me,we,Me,Re){const Ze=k.options.wireframe;if(Ze.terrain===!1&&Ze.layers2D===!1&&Ze.layers3D===!1)return;const Qe=k.context;if(!(!(!Ze.terrain||this.name!=="terrainRaster"&&this.name!=="globeRaster")||!(!Ze.layers2D||k._terrain&&k._terrain.renderingToTexture||!oa.includes(this.name))||!(!Ze.layers3D||!E3.includes(this.name))))return;const ut=Qe.gl,bt=k.wireframeDebugCache.getLinesFromTrianglesBuffer(k.frameCounter,Q,Qe);if(!bt)return;const vt=[...this.fixedDefines,"DEBUG_WIREFRAME"],Mt=k.getOrCreateProgram(this.name,{config:this.configuration,defines:vt});Mt._ensureReady(),Qe.program.set(Mt.program);const es=(ps,Hs,Fs)=>{if(Hs[ps]&&Fs[ps])for(const nn in Hs[ps])Fs[ps][nn]&&Fs[ps][nn].set(Fs.program,nn,Hs[ps][nn].current)};Me&&Me.setUniforms(Mt.program,Qe,Mt.binderUniforms,me,{zoom:we}),es("fixedUniforms",this,Mt),es("terrainUniforms",this,Mt),es("globeUniforms",this,Mt),es("fogUniforms",this,Mt),es("lightsUniforms",this,Mt),es("shadowUniforms",this,Mt),bt.bind(),Qe.setColorMode(new o.a1([ut.ONE,ut.ONE_MINUS_SRC_ALPHA,ut.ZERO,ut.ONE],o.C.transparent,[!0,!0,!0,!1])),Qe.setDepthMode(new o.Z(T.func===ut.LESS?ut.LEQUAL:T.func,o.Z.ReadOnly,T.range)),Qe.setStencilMode(o._.disabled);const Qt=3*oe.primitiveLength*2,Lt=3*oe.primitiveOffset*2*2;if(this.forceManualRenderingForInstanceIDShaders){const ps=Re||1;for(let Hs=0;Hs1?ut.drawElementsInstanced(ut.LINES,Qt,ut.UNSIGNED_SHORT,Lt,Re):ut.drawElements(ut.LINES,Qt,ut.UNSIGNED_SHORT,Lt);Q.bind(),Qe.program.set(this.program),Qe.setDepthMode(T),Qe.setStencilMode(B),Qe.setColorMode(K)}checkUniforms(k,T,B){if(this.fixedDefines.includes(T)){for(const K of Object.keys(B))if(!B[K].initialized)throw new Error(`Program '${this.name}', from draw '${k}': uniform ${K} not set but required by ${T} being defined`)}}draw(k,T,B,K,Q,oe,me,we,Me,Re,Ze,Qe,ut,bt,vt,Mt){const es=k.context,Qt=es.gl;if(this._ensureReady(),this.failedToCreate)return;es.program.set(this.program),es.setDepthMode(B),es.setStencilMode(K),es.setColorMode(Q),es.setCullFace(oe);for(const[$s,rn]of this.fixedUniformsEntries)rn.set(this.program,$s,me[$s]);bt&&bt.setUniforms(this.program,es,this.binderUniforms,Qe,{zoom:ut});const Lt={[Qt.POINTS]:1,[Qt.LINES]:2,[Qt.TRIANGLES]:3,[Qt.LINE_STRIP]:1}[T];this.checkUniforms(we,"RENDER_SHADOWS",this.shadowUniforms);const ps=vt||[],Hs=bt?bt.getPaintVertexBuffers():[],Fs=T===Qt.TRIANGLES&&Re,nn=Mt&&Mt>0?1:void 0;for(const $s of Ze.get()){const rn=$s.vaos||($s.vaos={});if((rn[we]||(rn[we]=new qv)).bind(es,this,Me,Hs,Re,$s.vertexOffset,ps,nn),this.forceManualRenderingForInstanceIDShaders){const _n=Mt||1;for(let Mn=0;Mn<_n;++Mn)this.instancingUniforms.u_instanceID.set(this.program,"u_instanceID",Mn),Re?Qt.drawElements(T,$s.primitiveLength*Lt,Qt.UNSIGNED_SHORT,$s.primitiveOffset*Lt*2):Qt.drawArrays(T,$s.vertexOffset,$s.vertexLength)}else Mt&&Mt>1?Qt.drawElementsInstanced(T,$s.primitiveLength*Lt,Qt.UNSIGNED_SHORT,$s.primitiveOffset*Lt*2,Mt):Re?Qt.drawElements(T,$s.primitiveLength*Lt,Qt.UNSIGNED_SHORT,$s.primitiveOffset*Lt*2):Qt.drawArrays(T,$s.vertexOffset,$s.vertexLength);Fs&&this._drawDebugWireframe(k,B,K,Q,Re,$s,Qe,ut,bt,Mt)}}}class dg{constructor(k,T,B,K){this.id=dg.uniqueIdxCounter,dg.uniqueIdxCounter++,this.context=k;const Q=k.gl;this.buffer=Q.createBuffer(),this.dynamicDraw=!!B,this.context.unbindVAO(),k.bindElementBuffer.set(this.buffer),Q.bufferData(Q.ELEMENT_ARRAY_BUFFER,T.arrayBuffer,this.dynamicDraw?Q.DYNAMIC_DRAW:Q.STATIC_DRAW),this.dynamicDraw||K||T.destroy()}bind(){this.context.bindElementBuffer.set(this.buffer)}updateData(k){this.id=dg.uniqueIdxCounter,dg.uniqueIdxCounter++;const T=this.context.gl;this.context.unbindVAO(),this.bind(),T.bufferSubData(T.ELEMENT_ARRAY_BUFFER,0,k.arrayBuffer)}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer)}}dg.uniqueIdxCounter=0;const Vv={Int8:"BYTE",Uint8:"UNSIGNED_BYTE",Int16:"SHORT",Uint16:"UNSIGNED_SHORT",Int32:"INT",Uint32:"UNSIGNED_INT",Float32:"FLOAT"};class Ux{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 me=k.gl;this.buffer=me.createBuffer(),k.bindVertexBuffer.set(this.buffer),me.bufferData(me.ARRAY_BUFFER,T.arrayBuffer,this.dynamicDraw?me.DYNAMIC_DRAW:me.STATIC_DRAW),this.dynamicDraw||Q||T.destroy()}bind(){this.context.bindVertexBuffer.set(this.buffer)}updateData(k){const T=this.context.gl;this.bind(),T.bufferSubData(T.ARRAY_BUFFER,0,k.arrayBuffer)}enableAttributes(k,T){for(const B of this.attributes){const K=T.getAttributeLocation(k,B.name);K!==-1&&k.enableVertexAttribArray(K)}}setVertexAttribPointers(k,T,B){for(const K of this.attributes){const Q=T.getAttributeLocation(k,K.name);if(Q!==-1){const oe=K.offset+this.itemSize*(B||0);K.type==="Float32"||K.normalized?k.vertexAttribPointer(Q,K.components,k[Vv[K.type]],!!K.normalized,this.itemSize,oe):k.vertexAttribIPointer(Q,K.components,k[Vv[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 Z2{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 Dr(k,oe,0)),K>1&&(this.colorAttachment1=new Dr(k,oe,1)),Q&&(this.depthAttachmentType=Q,this.depthAttachment=Q==="renderbuffer"?new Lk(k,oe):new RC(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 me=k.extRenderToTextureHalfFloat||k.extColorBufferFloat?k.gl.RGBA16F:k.gl.RGBA8,we=new o.T(k,{width:B,height:K,data:null},me);we.bind(oe.LINEAR,oe.CLAMP_TO_EDGE);const Me=k.createFramebuffer(B,K,1,null);if(Me.format=me,Me.colorAttachment0.set(we.texture),Q){const Re=k.createRenderbuffer(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 Dr(k,this.framebuffer,0):T===1&&(this.colorAttachment1=new Dr(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 Jg(this),this.clearDepth=new I1(this),this.clearStencil=new L1(this),this.colorMask=new R1(this),this.depthMask=new Yw(this),this.stencilMask=new Zw(this),this.stencilFunc=new F_(this),this.stencilOp=new Pk(this),this.stencilTest=new Ib(this),this.depthRange=new zv(this),this.depthTest=new k3(this),this.depthFunc=new V2(this),this.blend=new rp(this),this.blendFunc=new Ik(this),this.blendColor=new D1(this),this.blendEquation=new ex(this),this.cullFace=new ap(this),this.cullFaceSide=new Fx(this),this.frontFace=new qd(this),this.program=new Bv(this),this.activeTexture=new IC(this),this.viewport=new qT(this),this.bindFramebuffer=new VT(this),this.bindRenderbuffer=new S3(this),this.bindTexture=new Lb(this),this.bindVertexBuffer=new Tp(this),this.bindElementBuffer=new U0(this),this.bindVertexArrayOES=new LC(this),this.pixelStoreUnpack=new C3(this),this.pixelStoreUnpackPremultiplyAlpha=new Rb(this),this.pixelStoreUnpackFlipY=new ip(this),this.options=T?{...T}:{},this.options.extTextureFilterAnisotropicForceOff||(this.extTextureFilterAnisotropic=k.getExtension("EXT_texture_filter_anisotropic")||k.getExtension("MOZ_EXT_texture_filter_anisotropic")||k.getExtension("WEBKIT_EXT_texture_filter_anisotropic"),this.extTextureFilterAnisotropic&&(this.extTextureFilterAnisotropicMax=k.getParameter(this.extTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT))),this.extDebugRendererInfo=k.getExtension("WEBGL_debug_renderer_info"),this.extDebugRendererInfo&&(this.renderer=k.getParameter(this.extDebugRendererInfo.UNMASKED_RENDERER_WEBGL),this.vendor=k.getParameter(this.extDebugRendererInfo.UNMASKED_VENDOR_WEBGL)),this.forceManualRenderingForInstanceIDShaders=T&&!!T.forceManualRenderingForInstanceIDShaders||this.renderer&&this.renderer.includes("PowerVR"),this.options.extTextureFloatLinearForceOff||(this.extTextureFloatLinear=k.getExtension("OES_texture_float_linear")),this.extRenderToTextureHalfFloat=k.getExtension("EXT_color_buffer_half_float"),this.extColorBufferFloat=k.getExtension("EXT_color_buffer_float"),this.extTimerQuery=k.getExtension("EXT_disjoint_timer_query_webgl2"),this.maxTextureSize=k.getParameter(k.MAX_TEXTURE_SIZE),this.maxUniformBlockSize=Math.min(k.getParameter(k.MAX_UNIFORM_BLOCK_SIZE),32768),this.maxUniformBufferBindings=k.getParameter(k.MAX_UNIFORM_BUFFER_BINDINGS),this.extBlendFuncExtended=k.getExtension("WEBGL_blend_func_extended"),this.extParallelShaderCompile=k.getExtension("KHR_parallel_shader_compile")}sweepPendingPrograms(){if(this._pendingPrograms.size!==0)for(const k of this._pendingPrograms)k.maybeFinalize()}setDefault(){this.unbindVAO(),this.clearColor.setDefault(),this.clearDepth.setDefault(),this.clearStencil.setDefault(),this.colorMask.setDefault(),this.depthMask.setDefault(),this.stencilMask.setDefault(),this.stencilFunc.setDefault(),this.stencilOp.setDefault(),this.stencilTest.setDefault(),this.depthRange.setDefault(),this.depthTest.setDefault(),this.depthFunc.setDefault(),this.blend.setDefault(),this.blendFunc.setDefault(),this.blendColor.setDefault(),this.blendEquation.setDefault(),this.cullFace.setDefault(),this.cullFaceSide.setDefault(),this.frontFace.setDefault(),this.program.setDefault(),this.activeTexture.setDefault(),this.bindFramebuffer.setDefault(),this.pixelStoreUnpack.setDefault(),this.pixelStoreUnpackPremultiplyAlpha.setDefault(),this.pixelStoreUnpackFlipY.setDefault()}setDirty(){this.clearColor.dirty=!0,this.clearDepth.dirty=!0,this.clearStencil.dirty=!0,this.colorMask.dirty=!0,this.depthMask.dirty=!0,this.stencilMask.dirty=!0,this.stencilFunc.dirty=!0,this.stencilOp.dirty=!0,this.stencilTest.dirty=!0,this.depthRange.dirty=!0,this.depthTest.dirty=!0,this.depthFunc.dirty=!0,this.blend.dirty=!0,this.blendFunc.dirty=!0,this.blendColor.dirty=!0,this.blendEquation.dirty=!0,this.cullFace.dirty=!0,this.cullFaceSide.dirty=!0,this.frontFace.dirty=!0,this.program.dirty=!0,this.activeTexture.dirty=!0,this.viewport.dirty=!0,this.bindFramebuffer.dirty=!0,this.bindRenderbuffer.dirty=!0,this.bindTexture.dirty=!0,this.bindVertexBuffer.dirty=!0,this.bindElementBuffer.dirty=!0,this.bindVertexArrayOES.dirty=!0,this.pixelStoreUnpack.dirty=!0,this.pixelStoreUnpackPremultiplyAlpha.dirty=!0,this.pixelStoreUnpackFlipY.dirty=!0}createIndexBuffer(k,T,B){return new dg(this,k,T,B)}createVertexBuffer(k,T,B,K,Q){return new Ux(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 Z2(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 T3=o.Y();function GT(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 j9({width:L,height:k,anchor:T,textOffset:B,textScale:K},Q){const{horizontalAlign:oe,verticalAlign:me}=o.du(T),we=-(oe-.5)*L,Me=-(me-.5)*k,Re=o.dv(T,B);return new o.P((we/K+Re[0])*Q,(Me/K+Re[1])*Q)}function N9(L,k,T,B,K,Q,oe,me,we,Me){const Re=L.text.placedSymbolArray,Ze=L.text.dynamicLayoutVertexArray,Qe=L.icon.dynamicLayoutVertexArray,ut={},bt=L.getProjection(),vt=o.e1(oe,bt,K),Mt=K.elevation,es=bt.upVectorScale(oe.canonical,K.center.lat,K.worldSize).metersToTile;Ze.clear();for(let Qt=0;Qt=0&&(ut[Lt.associatedIconIndex]={x:Kn,y:Bn,z:On,angle:ka})}else o.e3(Fs,Ze)}if(Me){Qe.clear();const Qt=L.icon.placedSymbolArray;for(let Lt=0;Lt{let _c=[0,0,0];if(Pd){const Kh=L.style.directionalLight,ug=L.style.ambientLight;Kh&&ug&&(_c=o.aG(L.style,Kh,ug))}return _c},Ko=Pd=>{const _c=Math.floor(L.context.maxUniformBlockSize/4),Kh=Math.floor(_c/4);Pd.push(`MAX_UBO_SIZE_VEC4 ${Kh}u`)},no=Pd=>{rn.depthOcclusionForSymbolsAndCircles&&(T.hasOcclusionOpacityProperties||L.terrain)&&(Pd.push("DEPTH_D24"),Pd.push("DEPTH_OCCLUSION"))},_d=Pd=>{T.lut&&!Fs&&(T.lut.texture||(T.lut.texture=new o.e7(L.context,T.lut.image,[T.lut.image.height,T.lut.image.height,T.lut.image.height],nn.gl.RGBA8)),nn.activeTexture.set(nn.gl.TEXTURE0+o.ci.LUT),T.lut.texture&&T.lut.texture.bind(nn.gl.LINEAR,nn.gl.CLAMP_TO_EDGE),Pd.push("APPLY_LUT_ON_GPU"))},Gh=()=>{const Pd=_n&&T.layout.get("symbol-placement")!=="point",_c=[];no(_c),_d(_c);const Kh=Pd||so,ug=Gr.elevationType==="road",G_=L.shadowRenderer,e0=ug&&Kn&&!!G_&&G_.enabled,rj=Uc(e0),bu=ug&&Kn&&!L.terrain?xr:An,id=T.paint.get("icon-image-cross-fade");L.terrainRenderModeElevated()&&Kn&&_c.push("PITCH_WITH_MAP_TERRAIN"),Ga&&(_c.push("PROJECTION_GLOBE_VIEW"),Kh&&_c.push("PROJECTED_POS_ON_VIEWPORT")),id>0&&Gr.hasAnySecondaryIcon&&_c.push("ICON_TRANSITION"),!Gr.icon.zOffsetVertexBuffer||ug&&L.terrain||_c.push("Z_OFFSET"),es===0&&Qt===0&&Lt===0&&ps===1||_c.push("COLOR_ADJUSTMENT"),e0&&_c.push("RENDER_SHADOWS","NORMAL_OFFSET"),ug&&Kn&&!L.terrain&&Gr.icon.orientationVertexBuffer&&_c.push("ELEVATED_ROADS"),Ko(_c);const Rc=L.getOrCreateProgram("symbol",{defines:_c}),Yh=Tr.imageAtlasTexture?Tr.imageAtlasTexture.size:[0,0],ix=Gr.iconSizeData,Ku=o.dl(ix,rn.zoom),Li=Kn||!rn.isOrthographic,wm=o.e2(Za,Tr.tileID.canonical,Kn,_n,rn,Gr.getProjection(),Oi),hg=o.dk(Za,Tr.tileID.canonical,Kn,_n,rn,Gr.getProjection(),Oi),aj=Gr.icon.uboBinder&&Gr.icon.uboBinder.hasPerFeatureTranslate()?[0,0]:me,ij=L.translatePosMatrix(hg,Tr,aj,Me,!0),zb=L.translatePosMatrix(Za,Tr,aj,Me),Bb=Kh?T3:wm,X2=_n&&!Kn&&!Pd;let $b=si;!Hr&&!rn.mercatorFromTransition||_n||($b=GT(rn));const _y=Ga?$b:si,$m=T.getColorAdjustmentMatrix(es,Qt,Lt,ps),co=qs(ix.kind,Ku,X2,Kn,L,zb,Bb,ij,Hs,!1,Gr.sdfIcons,Yh,[0,0],0,Wr,qr,sa,ql,_y,Gr.getProjection(),rj,vu,$m,id,null),hp=Tr.imageAtlasTexture?Tr.imageAtlasTexture:null,Um=T.layout.get("icon-size").constantOr(0)!==1||Gr.iconsNeedLinear,wY=Gr.sdfIcons||L.options.rotating||L.options.zooming||Um||Li?$s.LINEAR:$s.NEAREST,W_=Gr.sdfIcons&&T.paint.get("icon-halo-width").constantOr(1)!==0,Y6=L.terrain&&Kn&&Pd?o.aP(o.Y(),wm):T3;if(Pd&&Gr.icon){const Of=o.c2.getAtTileOffsetFunc(Wr,rn.center.lat,rn.worldSize,Gr.getProjection()),Z6=o.dj(Za,Tr.tileID.canonical,Kn,_n,rn,Gr.getProjection(),Oi),R9=T.layout.get("icon-size-scale-range"),D9=o.b1(L.scaleFactor,R9[0],R9[1]);o.e6(Gr,Za,L,!1,Z6,hg,Kn,vt,Of,Wr,D9)}return{program:Rc,buffers:Gr.icon,uniformValues:co,atlasTexture:hp,atlasTextureIcon:null,atlasInterpolation:wY,atlasInterpolationIcon:null,isSDF:Gr.sdfIcons,hasHalo:W_,depthMode:bu,tile:Tr,renderWithShadows:e0,labelPlaneMatrixInv:Y6}},_h=()=>{const Pd=Mn&&T.layout.get("symbol-placement")!=="point",_c=[],Kh=Pd||ka||so,ug=Gr.elevationType==="road",G_=L.shadowRenderer,e0=ug&&Bn&&!!G_&&G_.enabled,rj=Uc(e0),bu=ug&&Bn&&!L.terrain?xr:An;L.terrainRenderModeElevated()&&Bn&&_c.push("PITCH_WITH_MAP_TERRAIN"),Ga&&(_c.push("PROJECTION_GLOBE_VIEW"),Kh&&_c.push("PROJECTED_POS_ON_VIEWPORT")),!Gr.text.zOffsetVertexBuffer||ug&&L.terrain||_c.push("Z_OFFSET"),Gr.iconsInText&&_c.push("RENDER_TEXT_AND_SYMBOL"),e0&&_c.push("RENDER_SHADOWS","NORMAL_OFFSET"),ug&&Bn&&!L.terrain&&Gr.text.orientationVertexBuffer&&_c.push("ELEVATED_ROADS"),no(_c),Ko(_c);const id=L.getOrCreateProgram("symbol",{defines:_c});let Rc,Yh=[0,0],ix=null;const Ku=Gr.textSizeData;Gr.iconsInText&&(Yh=Tr.imageAtlasTexture?Tr.imageAtlasTexture.size:[0,0],ix=Tr.imageAtlasTexture?Tr.imageAtlasTexture:null,Rc=Bn||!rn.isOrthographic||L.options.rotating||L.options.zooming||Ku.kind==="composite"||Ku.kind==="camera"?$s.LINEAR:$s.NEAREST);const Li=Tr.glyphAtlasTexture?Tr.glyphAtlasTexture.size:[0,0],wm=T.layout.get("text-size-scale-range"),hg=o.b1(L.scaleFactor,wm[0],wm[1]),aj=o.dl(Ku,rn.zoom,hg),ij=o.e2(Za,Tr.tileID.canonical,Bn,Mn,rn,Gr.getProjection(),Oi),zb=o.dk(Za,Tr.tileID.canonical,Bn,Mn,rn,Gr.getProjection(),Oi),Bb=Gr.text.uboBinder&&Gr.text.uboBinder.hasPerFeatureTranslate()?[0,0]:we,X2=L.translatePosMatrix(zb,Tr,Bb,Re,!0),$b=L.translatePosMatrix(Za,Tr,Bb,Re),_y=Kh?T3:ij,$m=Mn&&!Bn&&!Pd;let co=si;!Hr&&!rn.mercatorFromTransition||Mn||(co=GT(rn));const hp=qs(Ku.kind,aj,$m,Bn,L,$b,_y,X2,Hs,!0,!0,Li,Yh,0,Wr,qr,sa,ql,Ga?co:si,Gr.getProjection(),rj,vu,null,null,hg),Um=Tr.glyphAtlasTexture?Tr.glyphAtlasTexture:null,wY=$s.LINEAR,W_=T.paint.get("text-halo-width").constantOr(1)!==0,Y6=L.terrain&&Bn&&Pd?o.aP(o.Y(),ij):T3;if(Pd&&Gr.text){const Of=o.c2.getAtTileOffsetFunc(Wr,rn.center.lat,rn.worldSize,Gr.getProjection()),Z6=o.dj(Za,Tr.tileID.canonical,Bn,Mn,rn,Gr.getProjection(),Oi);o.e6(Gr,Za,L,!0,Z6,zb,Bn,Mt,Of,Wr,hg)}return{program:id,buffers:Gr.text,uniformValues:hp,atlasTexture:Um,atlasTextureIcon:ix,atlasInterpolation:wY,atlasInterpolationIcon:Rc,isSDF:!0,hasHalo:W_,depthMode:bu,tile:Tr,renderWithShadows:e0,labelPlaneMatrixInv:Y6}},Vl=Gr.icon.segments.get().length,mm=Gr.text.segments.get().length,bc=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(On&&Gr.canOverlap){Rr=!0;const Pd=Dh&&!oe.onlyText?Gr.icon.segments.get():[],_c=Wh&&!oe.onlyIcons?Gr.text.segments.get():[];for(const Kh of Pd)ea.push({segments:new o.ad([Kh]),sortKey:Kh.sortKey,state:bc});for(const Kh of _c)ea.push({segments:new o.ad([Kh]),sortKey:Kh.sortKey,state:dc})}else oe.onlyText||ea.push({segments:Dh?Gr.icon.segments:new o.ad([]),sortKey:0,state:bc}),oe.onlyIcons||ea.push({segments:Wh?Gr.text.segments:new o.ad([]),sortKey:0,state:dc})}Rr&&ea.sort((Wr,Tr)=>Wr.sortKey-Tr.sortKey);for(const Wr of ea){const Tr=Wr.state;if(Tr)if(L.terrain?L.terrain.setupElevationDraw(Tr.tile,Tr.program,{useDepthForOcclusion:rn.depthOcclusionForSymbolsAndCircles,labelPlaneMatrixInv:Tr.labelPlaneMatrixInv}):L.setupDepthForOcclusion(rn.depthOcclusionForSymbolsAndCircles,Tr.program),nn.activeTexture.set($s.TEXTURE0),Tr.atlasTexture&&Tr.atlasTexture.bind(Tr.atlasInterpolation,$s.CLAMP_TO_EDGE,!0),Tr.atlasTextureIcon&&(nn.activeTexture.set($s.TEXTURE1),Tr.atlasTextureIcon&&Tr.atlasTextureIcon.bind(Tr.atlasInterpolationIcon,$s.CLAMP_TO_EDGE,!0)),Tr.renderWithShadows&&L.shadowRenderer.setupShadows(Tr.tile.tileID.toUnwrapped(),Tr.program,"vector-tile"),L.uploadCommonLightUniforms(L.context,Tr.program),Tr.hasHalo){const Gr=Tr.uniformValues;Gr.u_is_halo=1,OC(Tr.buffers,Wr.segments,T,L,Tr.program,Tr.depthMode,K,Q,Gr,2),Gr.u_is_halo=0}else{if(Tr.isSDF){const Gr=Tr.uniformValues;Tr.hasHalo&&(Gr.u_is_halo=1,OC(Tr.buffers,Wr.segments,T,L,Tr.program,Tr.depthMode,K,Q,Gr,1)),Gr.u_is_halo=0}OC(Tr.buffers,Wr.segments,T,L,Tr.program,Tr.depthMode,K,Q,Tr.uniformValues,1)}}}function OC(L,k,T,B,K,Q,oe,me,we,Me){const Re=B.context,Ze=Re.gl,Qe=[L.dynamicLayoutVertexBuffer,L.opacityVertexBuffer,L.iconTransitioningVertexBuffer,L.globeExtVertexBuffer,L.zOffsetVertexBuffer,L.orientationVertexBuffer];L.featureIdBuffer&&Qe.push(L.featureIdBuffer);const ut=L.uboBinder?null:L.programConfigurations.get(T.id);if(L.uboBinder){L.uboBinder.layer=T;const Mt=B.transform.zoom,es=B.style.getBrightness?B.style.getBrightness():null,Qt=L.uboBinder.getConstantUniformValues(Mt,es);we.u_spp_fill_np_color=Qt.fill_np_color,we.u_spp_halo_np_color=Qt.halo_np_color,we.u_spp_opacity=Qt.opacity,we.u_spp_halo_width=Qt.halo_width,we.u_spp_halo_blur=Qt.halo_blur,we.u_spp_emissive_strength=Qt.emissive_strength,we.u_spp_occlusion_opacity=Qt.occlusion_opacity,we.u_spp_z_offset=Qt.z_offset,we.u_spp_zoom_fraction=Mt-L.uboBinder._floorZoom;const Lt=T.paint.get(L.uboBinder.isText?"text-translate-anchor":"icon-translate-anchor"),ps=L.uboBinder.hasPerFeatureTranslate()&&Lt==="map"?B.transform.angle:0;we.u_spp_translate_rotation=[Math.cos(ps),Math.sin(ps)]}const{batchIndices:bt,batchSegments:vt}=L.getBatchGrouping(k);for(const Mt of bt){const es=vt.get(Mt);L.uboBinder&&L.uboBinder.bind(Re,K.program,Mt),K.draw(B,Ze.TRIANGLES,Q,oe,me,o.$.disabled,we,T.id,L.layoutVertexBuffer,L.indexBuffer,es,T.paint,B.transform.zoom,ut,Qe,Me)}}function zC(L,k,T,B,K,Q){const oe=T.paint.get("line-width"),me=T.paint.get("line-emissive-strength").isConstant(),we=T.paint.get("line-emissive-strength").constantOr(0),Me=T.paint.get("line-occlusion-opacity"),Re=T.layout.get("line-elevation-reference"),Ze=T.layout.get("line-width-unit")==="meters",Qe=Re==="sea",ut=!(!L.terrain||!L.terrain.enabled),bt=L.context,vt=bt.gl;if(T.hasElevatedBuckets&&L.transform.projection.name==="globe")return;const Mt=T.layout.get("line-cross-slope"),es=Mt!==void 0,Qt=Mt<1,Lt=K||L.colorModeForDrapableLayerRenderPass(me?we:null),ps=L.terrain&&L.terrain.renderingToTexture||Q,Hs=ps?1:o.e.devicePixelRatio,Fs=T.paint.get("line-dasharray"),nn=Fs.constantOr(1),$s=T.layout.get("line-cap"),rn=Fs.constantOr(null),_n=$s.constantOr(null),Mn=T.paint.get("line-pattern"),Kn=Mn.constantOr(1),Bn=T.paint.get("line-pattern-cross-fade"),On=Mn.constantOr(null),Rr=T.paint.get("line-opacity").constantOr(1);let An=!Kn&&Rr!==1||L.depthOcclusion&&Me>0&&Me<1;const xr=T.paint.get("line-gradient"),sa=T.paint.get("line-border-width").constantOr(1)!==0?T.paint.get("line-border-gradient"):null,ka=Kn?"linePattern":"line",Hr=o.ea(T);let ea;if(ps&&L.terrain&&L.terrain.clipOrMaskOverlapStencilType()&&(An=!1),Me!==0&&L.depthOcclusion){const Za=T.paint._values["line-opacity"];Za&&Za.value&&Za.value.kind==="constant"?ea=Za.value:o.w(`Occlusion opacity for layer ${T.id} is supported only when line-opacity isn't data-driven.`)}oe.value.kind!=="constant"&&oe.value.isLineProgressConstant===!1&&Hr.push("VARIABLE_LINE_WIDTH");const si=T.paint.get("line-emissive-strength");Kn||si.value.kind==="constant"||si.value.isLineProgressConstant!==!1||Hr.push("VARIABLE_LINE_EMISSIVE_STRENGTH"),L._debugParams.showElevationIdDebug&&Hr.push("DEBUG_ELEVATION_ID"),ps&&(L.emissiveMode!=="dual-source-blending"||me?L.isEmissiveMrtActive()&&(Hr.push("USE_MRT1"),L.emissiveMode==="mrt-full-rgba"&&Hr.push("USE_MRT1_RGBA")):Hr.push("DUAL_SOURCE_BLENDING"));const Wr={},Tr=[],Gr=(Za,Oi,Do,so,ql,vu)=>{for(const Uc of Za){const Ko=k.getTile(Uc);if(Kn&&!Ko.patternsLoaded())continue;const no=Ko.getBucket(T);if(!no||no.elevationType!=="none"&&!ql||no.elevationType==="none"&&ql)continue;L.prepareDrawTile();const _d=[...Oi],Gh=no.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 bc=no.programConfigurations.get(T.id);let dc=!1;if(On&&Ko.imageAtlas){const Li=o.aH.from(On),wm=Li.getPrimary().scaleSelf(Hs).toString(),hg=Ko.imageAtlas.patternPositions.get(wm),aj=Li.getSecondary(),ij=aj?Ko.imageAtlas.patternPositions.get(aj.scaleSelf(Hs).toString()):null;dc=!!hg&&!!ij,hg&&bc.setConstantPatternPositions(hg,ij)}Bn>0&&(dc||bc.getPatternTransitionVertexBuffer("line-pattern"))&&_d.push("LINE_PATTERN_TRANSITION"),no.elevationGroundScaleVertexBuffer&&_d.push("ELEVATION_GROUND_SCALE");const Dh=L.isTileAffectedByFog(Uc),Wh=L.getOrCreateProgram(ka,{config:bc,defines:_d,overrideFog:Dh});if(!Kn&&rn&&_n&&Ko.lineAtlas){const Li=Ko.lineAtlas.getDash(rn,_n);Li&&bc.setConstantPatternPositions(Li)}Vl&&_h.setupShadows(Ko.tileID.toUnwrapped(),Wh,"vector-tile");let[Pd,_c]=T.paint.get("line-trim-offset");(_n==="round"||_n==="square")&&Pd!==_c&&(Pd===0&&(Pd-=1),_c===1&&(_c+=1));const Kh=ps?Uc.projMatrix:null,ug=Ze?1/no.tileToMeter/o.cd(Ko,1,L.transform.zoom):1,G_=Ze?1/no.tileToMeter/o.cd(Ko,1,Math.floor(L.transform.zoom)):1,e0=nn?T.paint._values["line-floorwidth"]:null;let rj;const bu=Ko.dashIdealZ;if(e0&&e0.value.kind==="constant"&&bu!==Ko.tileID.overscaledZ){const Li=no.zoom;Li in Wr||(Wr[Li]=Math.max(.01,T.widthExpression().evaluate({zoom:Li}))),rj=e0.value.value,e0.value.value=Wr[Li]*Math.pow(2,bu-Li)}const id=Kn?o.eb(L,Ko,T,Kh,Hs,ug,G_,[Pd,_c],mm,Bn):o.ec(L,Ko,T,Kh,no.lineClipsArray.length,Hs,ug,G_,[Pd,_c],mm),Rc=(Li,wm,hg,aj,ij,zb)=>{let Bb=Li.texture;if(wm!==Li.version){let X2=256;if(hg){const $b=k.getSource().maxzoom,_y=Uc.canonical.z===$b?Math.ceil(1<{wm&&wm.get().length!==0&&(ea!=null&&(ea.value=Rr*Me),hg!==void 0&&(id.u_opacity_multiplier=hg),Wh.draw(L,vt.TRIANGLES,Do,Li,Lt,o.$.disabled,id,T.id,no.layoutVertexBuffer,no.indexBuffer,wm,T.paint,L.transform.zoom,bc,[no.layoutVertexBuffer2,no.patternVertexBuffer,no.zOffsetVertexBuffer,no.elevationIdColVertexBuffer,no.elevationGroundScaleVertexBuffer]),hg!==void 0&&(id.u_opacity_multiplier=1),ea!=null&&(ea.value=Rr))},Ku=Li=>{Yh&&Yh.active&&Ui.drawLineFrcRenderLine?Ui.drawLineFrcRenderLine(no,Yh,Li,ix):ix(Li,no.segments)};if(An&&!ql){const Li=L.stencilModeForClipping(Uc).ref;Li===0&&ps&&bt.clear({stencil:0});const wm={func:vt.EQUAL,mask:255};id.u_alpha_discard_threshold=.8,Ku(new o._(wm,Li,255,vt.KEEP,vt.KEEP,vt.INVERT)),id.u_alpha_discard_threshold=0,Ku(new o._(wm,Li,255,vt.KEEP,vt.KEEP,vt.KEEP))}else id.u_alpha_discard_threshold=An&&ql&&vu?.8:0,Ku(ql?so:L.stencilModeForClipping(Uc));Yh&&Ui.drawLineFrcFadePass&&Ui.drawLineFrcFadePass(L,no,Uc,Yh,ql,so,ix),rj!==void 0&&(e0.value.value=rj)}};let Ga=L.depthModeForSublayer(0,o.Z.ReadOnly);const qr=new o.Z(L.depthOcclusion?vt.GREATER:vt.LEQUAL,o.Z.ReadOnly,L.depthRangeFor3D);if(T.hasNonElevatedBuckets){const Za=!ps&&L.terrain;Me!==0&&Za?o.w(`Occlusion opacity for layer ${T.id} is supported on terrain only if the layer has line-z-offset enabled.`):Za?o.w(`Cannot render non-elevated lines in immediate mode when terrain is enabled. Layer: ${T.id}.`):Gr(B,Hr,Ga,o._.disabled,!1,!0)}if(T.hasElevatedBuckets){Re==="hd-road-markup"?ut||(Ga=qr,Hr.push("ELEVATED_ROADS")):(Hr.push("ELEVATED"),Ga=qr,es&&Hr.push(Qt?"CROSS_SLOPE_HORIZONTAL":"CROSS_SLOPE_VERTICAL"),Qe&&Hr.push("ELEVATION_REFERENCE_SEA"));const Za=An?L.stencilModeFor3D():o._.disabled;Re!=="hd-road-markup"&&(L.forceTerrainMode=!0),Gr(B,Hr,Ga,Za,!0,!0),An&&Gr(B,Hr,Ga,Za,!0,!1),Re!=="hd-road-markup"&&(L.forceTerrainMode=!1)}Ui.drawLineFrcCoverageSecondPass&&Ui.drawLineFrcCoverageSecondPass(L,T,Tr),An&&(L.resetStencilClippingMasks(),ps&&bt.clear({stencil:0})),Me===0||L.depthOcclusion||ps||L.layersWithOcclusionOpacity.push(L.currentLayer)}class W0{destroy(){this.fbo&&(this.fbo.destroy(),this.fbo=null),this.drapeFbo&&(this.drapeFbo.destroy(),this.drapeFbo=null)}}class WT{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 M3={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 Ob(L){return!(!L.extRenderToTextureHalfFloat&&!L.extColorBufferFloat)}function qk(L,k){return L==="additive"&&Ob(k)?o.a1.additiveAlphaWeightedUnboundedAlpha:M3[L].colorMode}function sj(L,k,T){const B=L.context,K=B.gl;let Q=T.width,oe=T.height,me=T.colorAttachment0.get();k.lineBlendDensityReadback||(k.lineBlendDensityReadback=new WT(K));const we=k.lineBlendDensityReadback;let Me=0,Re=!0;for(;Q>1||oe>1;){const ut=Math.max(1,Math.floor(Q/2)),bt=Math.max(1,Math.floor(oe/2)),vt=Me===0?"fboA":"fboB";we[vt]=Z2.createWithTexture(B,we[vt],ut,bt,!1);const Mt=we[vt];B.bindFramebuffer.set(Mt.framebuffer),B.viewport.set([0,0,ut,bt]),B.activeTexture.set(K.TEXTURE0),K.bindTexture(K.TEXTURE_2D,me),L.getOrCreateProgram("lineBlendReduce").draw(L,K.TRIANGLES,o.Z.disabled,o._.disabled,o.a1.unblended,o.$.disabled,He(0,[1/Q,1/oe],Re),k.id,L.viewportBuffer,L.quadTriangleIndexBuffer,L.viewportSegments,k.paint,L.transform.zoom),Q=ut,oe=bt,me=Mt.colorAttachment0.get(),Me=1-Me,Re=!1}const Ze=Ob(B),Qe=Ze?16:4;we.sync&&(K.deleteSync(we.sync),we.sync=null),K.bindBuffer(K.PIXEL_PACK_BUFFER,we.pbo),K.bufferData(K.PIXEL_PACK_BUFFER,Qe,K.STREAM_READ),K.readPixels(0,0,1,1,K.RGBA,Ze?K.FLOAT:K.UNSIGNED_BYTE,0),K.bindBuffer(K.PIXEL_PACK_BUFFER,null),we.sync=K.fenceSync(K.SYNC_GPU_COMMANDS_COMPLETE,0),B.viewport.set([0,0,L.width,L.height])}function Vk(L,k,T){if(!Ob(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),Ob(oe)){const me=new Float32Array(4);Q.getBufferSubData(Q.PIXEL_PACK_BUFFER,0,me);const we=me[1];K.maxDensity=Math.max(2*(we>0?me[0]/we:0),1)}else K.maxDensity=1;Q.bindBuffer(Q.PIXEL_PACK_BUFFER,null)}}(B,L.context.gl,L.context),B.sync||(sj(L,k,T),L.style.map.triggerRepaint())):(sj(L,k,T),L.style.map.triggerRepaint())}function BC(L,k,T,B,K,Q){const oe=L.context,me=oe.gl,we=T==="additive"?1:k.paint.get("line-opacity").constantOr(1),Me=T==="additive"?function(Ze,Qe){const ut=Qe.paint.get("line-blend-additive-clamp");if(ut>0)return ut;const bt=Qe.lineBlendDensityReadback;return bt&&bt.maxDensity!==0?bt.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(me.TEXTURE0),me.bindTexture(me.TEXTURE_2D,B.colorAttachment0.get());const Re=qk(T,L.context);L.getOrCreateProgram("lineBlendComposite").draw(L,me.TRIANGLES,o.Z.disabled,o._.disabled,Re,o.$.disabled,((Ze,Qe,ut,bt)=>({u_image:0,u_opacity:Qe,u_blend_mode:ut,u_max_density:bt}))(0,we,M3[T].compositeUniformValue,Me),k.id,L.viewportBuffer,L.quadTriangleIndexBuffer,L.viewportSegments,k.paint,L.transform.zoom)}function $C(L,k,T,B){const{painter:K,sourceCache:Q,layer:oe,coords:me,colorMode:we,elevationType:Me,terrainEnabled:Re,pass:Ze}=L,Qe=K.context.gl,ut=oe.paint.get("fill-pattern"),bt=oe.paint.get("fill-pattern-cross-fade"),vt=ut.constantOr(null);let Mt=Me;Me!=="road"||k&&!Re||(Mt="none");const es=Mt==="road",Qt=L.painter.shadowRenderer,Lt=es&&!!Qt&&Qt.enabled,ps=new o.Z(K.context.gl.LEQUAL,o.Z.ReadOnly,K.depthRangeFor3D);let Hs=[0,0,0];if(Lt){const rn=K.style.directionalLight,_n=K.style.ambientLight;rn&&_n&&(Hs=o.aG(K.style,rn,_n))}const Fs=ut&&ut.constantOr(1),nn=K.terrain&&K.terrain.renderingToTexture,$s=(rn,_n)=>{let Mn,Kn,Bn,On,Rr;_n?(Mn=Fs&&!oe.getPaintProperty("fill-outline-color")?"fillOutlinePattern":"fillOutline",Bn=Qe.LINES):(Mn=Fs?"fillPattern":"fill",Bn=Qe.TRIANGLES);const An=[];for(const xr of me){const sa=Q.getTile(xr);if(Fs&&!sa.patternsLoaded())continue;const ka=sa.getBucket(oe);if(!ka)continue;const Hr=k?ka.hdExt&&ka.hdExt.elevationBufferData:ka.bufferData;if(!Hr||Hr.isEmpty())continue;K.prepareDrawTile();const ea=Hr.programConfigurations.get(oe.id),si=K.isTileAffectedByFog(xr),Wr=[],Tr=[];es&&(Wr.push("ELEVATED_ROADS"),Tr.push(Hr.elevatedLayoutVertexBuffer)),Lt&&Wr.push("RENDER_SHADOWS","NORMAL_OFFSET"),nn&&T&&(Wr.push("USE_MRT1"),K.emissiveMode==="mrt-full-rgba"&&Wr.push("USE_MRT1_RGBA")),Fs&&(K.context.activeTexture.set(Qe.TEXTURE0),sa.imageAtlasTexture&&sa.imageAtlasTexture.bind(Qe.LINEAR,Qe.CLAMP_TO_EDGE),ea.updatePaintBuffers());let Gr=!1;if(vt&&sa.imageAtlas){const ql=sa.imageAtlas,vu=o.aH.from(vt),Uc=vu.getPrimary().scaleSelf(o.e.devicePixelRatio).toString(),Ko=vu.getSecondary(),no=ql.patternPositions.get(Uc),_d=Ko?ql.patternPositions.get(Ko.scaleSelf(o.e.devicePixelRatio).toString()):null;Gr=!!no&&!!_d,no&&ea.setConstantPatternPositions(no,_d)}bt>0&&(Gr||ea.getPatternTransitionVertexBuffer("fill-pattern"))&&Wr.push("FILL_PATTERN_TRANSITION");const Ga=K.getOrCreateProgram(Mn,{config:ea,overrideFog:si,defines:Wr}),qr=K.translatePosMatrix(xr.projMatrix,sa,oe.paint.get("fill-translate"),oe.paint.get("fill-translate-anchor"));Lt&&Qt.setupShadows(sa.tileID.toUnwrapped(),Ga,"vector-tile");const Za=oe.paint.get("fill-emissive-strength");if(_n){On=Hr.lineIndexBuffer,Rr=Hr.lineSegments;const ql=K.terrain&&K.terrain.renderingToTexture?K.terrain.drapeBufferSize:[Qe.drawingBufferWidth,Qe.drawingBufferHeight];Kn=Mn==="fillOutlinePattern"&&Fs?Pe(qr,Za,K,sa,ql,Hs,bt):Jw(qr,Za,ql,Hs)}else On=Hr.indexBuffer,Rr=Hr.triangleSegments,Kn=Fs?O1(qr,Za,K,sa,Hs,bt):FC(qr,Za,Hs);K.uploadCommonUniforms(K.context,Ga,xr.toUnwrapped());let Oi=rn;if((Me==="road"&&!Re||Me==="offset")&&(Oi=ps),!Rr||Rr.get&&Rr.get().length===0)continue;const Do=B||K.stencilModeForClipping(xr);let so="fallthrough";!_n&&Ui.drawFillFrcCoverageFirstPass&&(so=Ui.drawFillFrcCoverageFirstPass({painter:K,layer:oe,bucket:ka,coord:xr,elevatedGeometry:k,program:Ga,programConfiguration:ea,uniformValues:Kn,drawMode:Bn,depthMode:Oi,stencilMode:Do,colorMode:we,bufferData:Hr,indexBuffer:On,segments:Rr,dynamicBuffers:Tr,polygonCoverageTiles:An})),so==="fallthrough"&&Ga.draw(K,Bn,Oi,Do,we,o.$.disabled,Kn,oe.id,Hr.layoutVertexBuffer,On,Rr,oe.paint,K.transform.zoom,ea,Tr)}!_n&&Ui.drawFillFrcCoverageSecondPass&&Ui.drawFillFrcCoverageSecondPass(K,oe,An,Bn,we)};K.renderPass===Ze&&$s(K.depthModeForSublayer(1,K.renderPass==="opaque"?o.Z.ReadWrite:o.Z.ReadOnly),!1),Mt==="none"&&K.renderPass==="translucent"&&oe.paint.get("fill-antialias")&&$s(K.depthModeForSublayer(oe.getPaintProperty("fill-outline-color")?2:0,o.Z.ReadOnly),!0)}function D6(L){return[L[0]*o.eg,L[1]*o.eg,L[2]*o.eg,0]}function P3(L,k,T,B,K,Q,oe,me,we,Me){const Re=K.getSource(),Ze=B.globeSharedBuffers;if(!Ze)return;let Qe,ut,bt;if(T&&(Qe=K.getTile(T)),Re instanceof Fi?(ut=Re.texture,bt=o.c1(0,0,B.transform)):Qe&&T&&(ut=Qe.texture,bt=o.c1(T.canonical.z,T.canonical.x,B.transform)),!ut||!bt)return;k||(bt=o.aO(o.Y(),bt,[1,-1,1]));const vt=B.context,Mt=vt.gl,es=Q.paint.get("raster-resampling")==="nearest"?Mt.NEAREST:Mt.LINEAR,Qt=B.colorModeForDrapableLayerRenderPass(oe),Lt=me.defines;Lt.push("GLOBE_POLES");const ps=new o.Z(Mt.LEQUAL,o.Z.ReadWrite,B.depthRangeFor3D),Hs=B.transform.expandedFarZProjMatrix,Fs=Float32Array.from(o.b5(o.b6(new o.bW(0,0,0))));B.terrain&&B.terrain.prepareDrawTile(),vt.activeTexture.set(Mt.TEXTURE0),ut.bind(es,Mt.CLAMP_TO_EDGE),vt.activeTexture.set(Mt.TEXTURE1),ut.bind(es,Mt.CLAMP_TO_EDGE),"useMipmap"in ut&&vt.extTextureFilterAnisotropic&&B.transform.pitch>20&&Mt.texParameterf(Mt.TEXTURE_2D,vt.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,vt.extTextureFilterAnisotropicMax);const[nn,$s,rn,_n]=T?Ze.getPoleBuffers(T.canonical.z,!1):Ze.getPoleBuffers(0,!0),Mn=L;let Kn;k?(Kn=nn,B.renderDefaultNorthPole=Mn!==0):(Kn=$s,B.renderDefaultSouthPole=Mn!==0);const Bn=D6(me.mix),On=((An,xr,sa,ka,Hr,ea,si,Wr,Tr,Gr,Ga,qr,Za,Oi)=>Ns(An,xr,sa,ka,new Float32Array(16),new Float32Array(9),[0,0],Hr,[0,0],[0,0,0,0],1,{opacity:1,mix:0},si,[0,0],Tr,2,Ga,qr,Za,1,0,Oi))(B,Hs,Fs,bt,o.S(B.transform.zoom),0,Q,0,Mn,0,Bn,me.offset,me.range,oe),Rr=B.getOrCreateProgram("raster",{defines:Lt});B.uploadCommonUniforms(vt,Rr,null),Rr.draw(B,Mt.TRIANGLES,ps,Me,Qt,we,On,Q.id,Kn,rn,_n)}function F6(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 KT(L,k,T,B){if(L)return k.type==="raster-array"?k.getTextureDescriptor(L,T,!0):{texture:L.texture,mix:D6(B.mix),offset:B.offset,buffer:0,tileSize:1}}const O6=o.df(new Float32Array(16)),UC={"dual-source-blending":"dual-source-blending","mrt-fallback":"mrt","mrt-full-rgba":"mrt-rgba"},k9=o.a$([{name:"a_pos_3f",components:3,type:"Float32"}]),{members:z6}=k9;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,z6),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,me=k.paint.get("sky-atmosphere-color"),we=k.paint.get("sky-atmosphere-halo-color"),Me=k.paint.get("sky-atmosphere-sun-intensity"),Re=((Ze,Qe,ut,bt,vt)=>({u_matrix_3f:Ze,u_sun_direction:Qe,u_sun_intensity:ut,u_color_tint_r:[bt.r,bt.g,bt.b,bt.a],u_color_tint_m:[vt.r,vt.g,vt.b,vt.a],u_luminance:5e-5}))(o.ek(o.el(),B),K,Me,me.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 Ws{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 Qe=o.bj(30),ut=[];for(let bt=0;bt{const $s=Q.projection.name==="globe"?["PROJECTION_GLOBE_VIEW","FOG"]:["FOG"];nn&&$s.push("ALPHA_PASS");const rn=k.getOrCreateProgram("globeAtmosphere",{defines:$s}),_n=((Kn,Bn,On,Rr,An,xr,sa,ka,Hr,ea,si,Wr)=>({u_frustum_tl:Kn,u_frustum_tr:Bn,u_frustum_br:On,u_frustum_bl:Rr,u_horizon:An,u_transition:xr,u_fadeout_range:sa,u_atmosphere_fog_color:ka.toArray01(),u_high_color:Hr.toArray01(),u_space_color:ea.toArray01(),u_temporal_offset:si,u_horizon_angle:Wr}))(Q.frustumCorners.TL,Q.frustumCorners.TR,Q.frustumCorners.BR,Q.frustumCorners.BL,Q.frustumCorners.horizon,me,Mt,Re,Qe,bt,Qt,Hs);k.uploadCommonUniforms(B,rn);const Mn=this.atmosphereBuffer;Mn&&rn.draw(k,K.TRIANGLES,oe,o._.disabled,nn?this.colorModeWriteAlpha:this.colorModeAlphaBlendedWriteRGB,o.$.backCW,_n,nn?"atmosphere_glow_alpha":"atmosphere_glow",Mn.vertexBuffer,Mn.indexBuffer,Mn.segments)};Fs(!1),Fs(!0)}drawStars(k,T){const B=o.b1(T.properties.get("star-intensity"),0,1);if(B===0)return;const K=k.context,Q=K.gl,oe=k.transform,me=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),Qe=o.eu([],Ze);let ut=this.params.sizeMultiplier;const bt=[0,1,0];o.cT(bt,bt,Qe),o.dV(bt,bt,ut);const vt=[1,0,0];o.cT(vt,vt,Qe),o.dV(vt,vt,ut);const Mt=(es=bt,Qt=vt,Lt=B,{u_matrix:Float32Array.from(Re),u_up:es,u_right:Qt,u_intensity_multiplier:Lt});var es,Qt,Lt;k.uploadCommonUniforms(K,me),this.starsVx&&this.starsIdx&&me.draw(k,Q.TRIANGLES,o.Z.disabled,o._.disabled,this.colorModeAlphaBlendedWriteRGB,o.$.disabled,Mt,"atmosphere_stars",this.starsVx,this.starsIdx,this.starsSegments)}}class mr{}class $r{constructor(){this._storage=new Map}getLinesFromTrianglesBuffer(k,T,B){{const Ze=this._storage.get(T.id);if(Ze)return Ze.lastUsedFrameIdx=k,Ze.buf}const K=B.gl,Q=K.getBufferParameter(K.ELEMENT_ARRAY_BUFFER,K.BUFFER_SIZE),oe=new ArrayBuffer(Q),me=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 di{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(),me=T.layout.get("text-variable-anchor"),we=T.layout.get("text-size-scale-range"),Me=o.b1(L.scaleFactor,we[0],we[1]);me&&function(Qe,ut,bt,vt,Mt,es,Qt,Lt){const ps=ut.transform,Hs=Mt==="map",Fs=es==="map";for(const nn of Qe){const $s=vt.getTile(nn),rn=$s.getBucket(bt);if(!rn||!rn.text||!rn.text.segments.get().length)continue;const _n=o.dl(rn.textSizeData,ps.zoom,Lt),Mn=o.e1(nn,rn.getProjection(),ps),Kn=ps.calculatePixelsToTileUnitsMatrix($s),Bn=o.e2(Mn,$s.tileID.canonical,Fs,Hs,ps,rn.getProjection(),Kn),On=rn.hasIconTextFit()&&rn.hasIconData();_n&&N9(rn,Hs,Fs,Qt,ps,Bn,nn,Math.pow(2,ps.zoom-$s.tileID.overscaledZ),_n,On)}}(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)?Uk(L,k,T,B,Q,oe):(Re&&Uk(L,k,T,B,Q,oe,{onlyIcons:!0}),Ze&&Uk(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"),me=T.layout.get("circle-sort-key").constantOr(1)!==void 0,we=T.paint.get("circle-emissive-strength");if(K.constantOr(1)===0&&(Q.constantOr(1)===0||oe.constantOr(1)===0))return;const Me=L.context,Re=Me.gl,Ze=L.transform,Qe=!(!L.terrain||!L.terrain.enabled),ut=T.layout.get("circle-elevation-reference"),bt=L.depthModeForSublayer(0,o.Z.ReadOnly),vt=new o.Z(L.context.gl.LEQUAL,o.Z.ReadOnly,L.depthRangeFor3D),Mt=ut==="none"||Qe?bt:vt,es=o._.disabled,Qt=L.colorModeForDrapableLayerRenderPass(we),Lt=Ze.projection.name==="globe",ps=[o.a7(Ze.center.lng),o.a8(Ze.center.lat)],Hs=[];for(let nn=0;nnnn.sortKey-$s.sortKey);const Fs={useDepthForOcclusion:Ze.depthOcclusionForSymbolsAndCircles};for(const nn of Hs){const{programConfiguration:$s,program:rn,layoutVertexBuffer:_n,dynamicBuffers:Mn,indexBuffer:Kn,uniformValues:Bn,tile:On}=nn.state,Rr=nn.segments;L.terrain&&L.terrain.setupElevationDraw(On,rn,Fs),L.uploadCommonUniforms(Me,rn,On.tileID.toUnwrapped()),rn.draw(L,Re.TRIANGLES,Mt,es,Qt,o.$.disabled,Bn,T.id,_n,Kn,Rr,T.paint,Ze.zoom,$s,Mn)}},heatmap:function(L,k,T,B){if(T.paint.get("heatmap-opacity")!==0)if(L.renderPass==="offscreen"){const K=L.context,Q=K.gl,oe=o._.disabled,me=new o.a1([Q.ONE,Q.ONE,Q.ONE,Q.ONE],o.C.transparent,[!0,!0,!0,!0]),we=L.transform.projection.name==="globe"?.5:.25;T.heatmapFbo=Z2.createWithTexture(K,T.heatmapFbo,L.width*we,L.height*we),K.clear({color:o.C.transparent});const Me=L.transform,Re=Me.projection.name==="globe",Ze=Re?["PROJECTION_GLOBE_VIEW"]:[],Qe=Re?o.$.frontCCW:o.$.disabled,ut=[o.a7(Me.center.lng),o.a8(Me.center.lat)];for(let bt=0;bt({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"),me=L.terrain&&L.terrain.renderingToTexture;if(oe==="default"||L.transform.projection.name==="globe")L.renderPass==="translucent"&&zC(L,k,T,B);else{if(me)return void function(we,Me,Re,Ze,Qe){if(we.renderPass!=="translucent")return;const ut=we.context,bt=ut.gl,vt=we.terrain;if(!vt)return;const Mt=ut.bindFramebuffer.current,es=we.isEmissiveMrtActive(),Qt=vt.drapeBufferSize[0],Lt=vt.drapeBufferSize[1];Re.lineBlendFbos||(Re.lineBlendFbos=new W0),Re.lineBlendFbos.drapeFbo=Z2.createWithTexture(ut,Re.lineBlendFbos.drapeFbo,Qt,Lt,!0),es&&bt.drawBuffers([bt.COLOR_ATTACHMENT0]),ut.clear({color:M3[Qe].clearColor,depth:1,stencil:0});const ps=we.currentStencilSource,Hs=we._tileClippingMaskIDs,Fs=we.nextStencilID;we.currentStencilSource=void 0,we._tileClippingMaskIDs={},we.nextStencilID=1;const nn=we._terrain;we._terrain=null,we._renderTileClippingMasks(Re,Me,Ze),zC(we,Me,Re,Ze,qk(Qe,we.context),!0),we._terrain=nn,we.currentStencilSource=ps,we._tileClippingMaskIDs=Hs,we.nextStencilID=Fs,es&&bt.drawBuffers([bt.COLOR_ATTACHMENT0,bt.COLOR_ATTACHMENT1]);const $s=vt.drapeBufferSize,rn=Re.lineBlendFbos&&Re.lineBlendFbos.drapeFbo;rn&&(Qe==="additive"&&Vk(we,Re,rn),BC(we,Re,Qe,rn,Mt,$s))}(L,k,T,B,oe);if(L.renderPass==="offscreen")return void function(we,Me,Re,Ze,Qe){const ut=we.context,bt=Math.ceil(we.width),vt=Math.ceil(we.height);Re.lineBlendFbos||(Re.lineBlendFbos=new W0),Re.lineBlendFbos.fbo=Z2.createWithTexture(ut,Re.lineBlendFbos.fbo,bt,vt,!0),ut.clear({color:M3[Qe].clearColor,depth:1,stencil:0});const Mt=we.currentStencilSource,es=we._tileClippingMaskIDs,Qt=we.nextStencilID;we.currentStencilSource=void 0,we._tileClippingMaskIDs={},we.nextStencilID=1,we._renderTileClippingMasks(Re,Me,Ze);const Lt=we.renderPass;we.renderPass="translucent",zC(we,Me,Re,Ze,qk(Qe,we.context)),we.renderPass=Lt,we.currentStencilSource=Mt,we._tileClippingMaskIDs=es,we.nextStencilID=Qt,ut.viewport.set([0,0,we.width,we.height]),Qe==="additive"&&Vk(we,Re,Re.lineBlendFbos.fbo)}(L,k,T,B,oe);if(L.renderPass==="translucent"){const we=T.lineBlendFbos&&T.lineBlendFbos.fbo;return void(we&&BC(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"),me=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),Qe={painter:L,sourceCache:k,layer:T,coords:B,colorMode:me,elevationType:Re,terrainEnabled:Ze,pass:Me};if(L.renderPass==="shadow")return void(L.shadowRenderer&&Re==="road"&&!Ze&&Ui.drawElevatedFillShadows&&Ui.drawElevatedFillShadows(Qe));const ut=L.isEmissiveMrtActive();if(Re!=="offset"){if($C(Qe,!1,ut),Re==="road"){const bt=!Ze&&L.renderPass==="translucent";bt&&Ui.drawDepthPrepass&&Ui.drawDepthPrepass(L,k,T,B,"geometry"),$C(Qe,!0,ut,o._.disabled),bt&&Ui.drawElevatedStructures&&Ui.drawElevatedStructures(Qe)}}else $C(Qe,!1,ut,L.stencilModeFor3D())},"fill-extrusion":function(L,k,T,B){const K=T.paint.get("fill-extrusion-opacity"),Q=L.context,oe=Q.gl,me=L.terrain,we=me&&me.renderingToTexture;if(K===0)return;const Me=L.isEmissiveMrtActive(),Re=L.conflationActive&&L.style.isLayerClipped(T,k.getSource()),Ze=L.style.order.indexOf(T.fqid);if(Re&&function(Qe,ut,bt,vt,Mt){for(const es of vt){const Qt=ut.getTile(es).getBucket(bt);Qt&&(Qt.updateReplacement(es,Qe.replacementSource,Mt),Qt.uploadCentroid(Qe.context))}}(L,k,T,B,Ze),me||Re)for(const Qe of B){const ut=k.getTile(Qe).getBucket(T);ut&&Es(L.context,k,Qe,ut,T,me,Re)}if(L.renderPass==="shadow"&&L.shadowRenderer){if(me&&K<.65&&T._transitionablePaint._values["fill-extrusion-opacity"].value.expression instanceof o.ak)return;const Qe=L.shadowRenderer.getShadowPassDepthMode();qa(L,k,T,B,Qe,o._.disabled,o.a1.disabled,Re)}else if(L.renderPass==="translucent"){const Qe=!T.paint.get("fill-extrusion-pattern").constantOr(1),ut=T.paint.get("fill-extrusion-color").constantOr(o.C.white);if(!we&&ut.a!==0){const vt=new o.Z(L.context.gl.LEQUAL,o.Z.ReadWrite,L.depthRangeFor3D);K===1&&Qe?qa(L,k,T,B,vt,o._.disabled,o.a1.unblended,Re):(qa(L,k,T,B,vt,o._.disabled,o.a1.disabled,Re),qa(L,k,T,B,vt,L.stencilModeFor3D(),L.colorModeForRenderPass(),Re),L.resetStencilClippingMasks())}const bt=L.style.enable3dLights()&&Qe&&(!me&&L.transform.projection.name!=="globe"||we);if(bt&&!vr.drawGroundEffect&&yr(),bt&&vr.drawGroundEffect){const vt=T.paint.get("fill-extrusion-opacity"),Mt=T.paint.get("fill-extrusion-ambient-occlusion-intensity"),es=T.paint.get("fill-extrusion-ambient-occlusion-ground-radius"),Qt=T.paint.get("fill-extrusion-flood-light-intensity"),Lt=T.paint.get("fill-extrusion-flood-light-color-use-theme").constantOr("default")==="none",ps=T.paint.get("fill-extrusion-flood-light-color").toNonPremultipliedRenderColor(Lt?null:T.lut).toArray01().slice(0,3),Hs=Mt>0&&es>0,Fs=Qt>0,nn=new et;nn.translate=T.paint.get("fill-extrusion-translate"),nn.translateAnchor=T.paint.get("fill-extrusion-translate-anchor"),nn.edgeRadius=T.layout.get("fill-extrusion-edge-radius"),nn.cutoffFadeRange=T.paint.get("fill-extrusion-cutoff-fade-range");const $s=rn=>{const _n=L.depthModeForSublayer(1,o.Z.ReadOnly,oe.LEQUAL,!0),Mn=T.paint.get(rn?"fill-extrusion-ambient-occlusion-ground-attenuation":"fill-extrusion-flood-light-ground-attenuation"),Kn=o.am(.1,3,Mn),Bn=L._showOverdrawInspector;if(!Bn){const On=new o._({func:oe.ALWAYS,mask:255},255,255,oe.KEEP,oe.KEEP,oe.REPLACE),Rr=new o.a1([oe.ONE,oe.ONE,oe.ONE,oe.ONE],o.C.transparent,[!1,!1,!1,!0],oe.MIN);vr.drawGroundEffect(nn,L,k,T,B,_n,On,Rr,o.$.disabled,rn,"sdf",vt,Mt,es,Qt,ps,Kn,Re,!1)}{const On=Bn?o._.disabled:new o._({func:oe.EQUAL,mask:255},255,255,oe.KEEP,oe.DECR,oe.DECR),Rr=Bn?L.colorModeForRenderPass():new o.a1([oe.ONE_MINUS_DST_ALPHA,oe.DST_ALPHA,oe.ONE,oe.ONE],o.C.transparent,[!0,!0,!0,!0]);vr.drawGroundEffect(nn,L,k,T,B,_n,On,Rr,o.$.disabled,rn,"color",vt,Mt,es,Qt,ps,Kn,Re,!1)}};if(we){const rn=()=>{const Mn=me.drapeBufferSize[0],Kn=me.drapeBufferSize[1];let Bn=me.framebufferCopyTexture;return Bn&&(!Bn||Bn.size[0]===Mn&&Bn.size[1]===Kn)||(Bn&&Bn.destroy(),Bn=me.framebufferCopyTexture=new o.T(Q,new o.b({width:Mn,height:Kn}),oe.RGBA8)),Bn.bind(oe.LINEAR,oe.CLAMP_TO_EDGE),oe.copyTexSubImage2D(oe.TEXTURE_2D,0,0,0,0,0,Mn,Kn),Bn},_n=(Mn,Kn,Bn)=>{const On=L.depthModeForSublayer(1,o.Z.ReadOnly,oe.LEQUAL,!1),Rr=T.paint.get(Mn?"fill-extrusion-ambient-occlusion-ground-attenuation":"fill-extrusion-flood-light-ground-attenuation"),An=o.am(.1,3,Rr);{const xr=new o.a1([oe.ONE,oe.ONE,oe.ONE,oe.ONE],o.C.transparent,[!1,!1,!1,!0]);vr.drawGroundEffect(nn,L,k,T,B,On,o._.disabled,xr,o.$.disabled,Mn,"clear",vt,Mt,es,Qt,ps,An,Re,Kn)}{const xr=new o._({func:oe.ALWAYS,mask:255},255,255,oe.KEEP,oe.KEEP,oe.REPLACE),sa=new o.a1([oe.ONE,oe.ONE,oe.ONE,oe.ONE],o.C.transparent,[!1,!1,!1,!0],oe.MIN);vr.drawGroundEffect(nn,L,k,T,B,On,xr,sa,o.$.disabled,Mn,"sdf",vt,Mt,es,Qt,ps,An,Re,Kn)}Me&&!Mn&&(Bn=rn());{const xr=Mn?oe.ZERO:oe.ONE_MINUS_DST_ALPHA,sa=new o._({func:oe.EQUAL,mask:255},255,255,oe.KEEP,oe.DECR,oe.DECR),ka=new o.a1([xr,oe.DST_ALPHA,oe.ONE_MINUS_DST_ALPHA,oe.ZERO],o.C.transparent,[!0,!0,!0,!0]);vr.drawGroundEffect(nn,L,k,T,B,On,sa,ka,o.$.disabled,Mn,"color",vt,Mt,es,Qt,ps,An,Re,Kn)}if(!Me||Mn){const xr=new o.a1([oe.ONE,oe.ONE,oe.ONE,Mn?oe.ZERO:oe.ONE],o.C.transparent,[!1,!1,!1,!0],Mn?oe.FUNC_ADD:oe.MAX);vr.drawGroundEffect(nn,L,k,T,B,On,o._.disabled,xr,o.$.disabled,Mn,"clear",vt,Mt,es,Qt,ps,An,Re,Kn,Bn)}else{oe.drawBuffers([oe.NONE,oe.COLOR_ATTACHMENT1]);const xr=new o._({func:oe.EQUAL,mask:255},254,255,oe.KEEP,oe.DECR,oe.DECR),sa=new o.a1([oe.ONE,oe.ONE,oe.ONE,oe.ONE],o.C.transparent,[!0,!1,!1,!1],oe.MAX);vr.drawGroundEffect(nn,L,k,T,B,On,xr,sa,o.$.disabled,Mn,"emissive",vt,Mt,es,Qt,ps,An,Re,Kn,Bn),oe.drawBuffers([oe.COLOR_ATTACHMENT0])}};if(Hs||Fs){let Mn;L.prepareDrawTile(),Me&&!Hs||(Mn=rn()),Hs&&_n(!0,!1,Mn),Fs&&_n(!1,!0,Mn)}}else Hs&&$s(!0),Fs&&$s(!1),(Hs||Fs)&&L.resetStencilClippingMasks()}}},hillshade:function(L,k,T,B){if(L.renderPass!=="offscreen"&&L.renderPass!=="translucent"||L.style.disableElevatedTerrain)return;const K=L.context,Q=L.terrain&&L.terrain.renderingToTexture,[oe,me]=L.renderPass!=="translucent"||Q?[{},B]:L.stencilConfigForOverlap(B);for(const we of me){const Me=k.getTile(we);if(Me.needsHillshadePrepare&&L.renderPass==="offscreen")ch(L,Me,T);else if(L.renderPass==="translucent"){const Re=L.depthModeForSublayer(0,o.Z.ReadOnly),Ze=T.paint.get("hillshade-emissive-strength"),Qe=L.colorModeForDrapableLayerRenderPass(Ze),ut=Q&&L.terrain?L.terrain.stencilModeForRTTOverlap(we):oe[we.overscaledZ];np(L,we,Me,T,Re,ut,Qe)}}K.viewport.set([0,0,L.width,L.height]),L.resetStencilClippingMasks()},raster:function(L,k,T,B,K,Q){if(L.renderPass!=="translucent")return;const oe=T.paint.get("raster-opacity");if(oe===0)return;const me=L.transform.projection.name==="globe",we=T.paint.get("raster-elevation"),Me=T.paint.get("raster-elevation-reference")==="ground",Re=we>0,Ze=L.terrain&&L.terrain.exaggeration()>0&&Re&&Me,Qe=Re&&me,ut=!me&&Ze;if(L.renderElevatedRasterBackface&&!Qe)return;const bt=L.context,vt=bt.gl,Mt=k.getSource(),es=function(Mn,Kn,Bn,On,Rr){const An=Bn.paint.get("raster-color"),xr=Kn.type==="raster-array",sa=[],ka=Bn.paint.get("raster-resampling"),Hr=Bn.paint.get("raster-color-mix");let ea=Bn.paint.get("raster-color-range");const si=[Hr[0],Hr[1],Hr[2],0],Wr=Hr[3];let Tr=ka==="nearest"?Rr.NEAREST:Rr.LINEAR;if(xr&&(sa.push("RASTER_ARRAY"),An||sa.push("RASTER_COLOR"),ka==="linear"&&sa.push("RASTER_ARRAY_LINEAR"),Tr=Rr.NEAREST,An&&Bn.paint.get("raster-color-scale")==="log"&&sa.push("RASTER_COLOR_SCALE_LOG"),!ea&&Kn.rasterLayers)){const Gr=Kn.rasterLayers.find(({id:Ga})=>Ga===Bn.sourceLayer);Gr&&Gr.fields&&Gr.fields.range&&(ea=Gr.fields.range)}if(ea=ea||[0,1],An){sa.push("RASTER_COLOR"),On.activeTexture.set(Rr.TEXTURE2),Bn.updateColorRamp(ea);let Gr=Bn.colorRampTexture;Gr||(Gr=Bn.colorRampTexture=new o.T(On,Bn.colorRamp,Rr.RGBA8)),Gr.bind(Tr,Rr.CLAMP_TO_EDGE)}return Mn.terrain&&Mn.terrain.renderingToTexture&&Mn.isEmissiveMrtActive()&&(sa.push("USE_MRT1"),Mn.emissiveMode==="mrt-full-rgba"&&sa.push("USE_MRT1_RGBA")),{mix:si,range:ea,offset:Wr,defines:sa,resampling:Tr}}(L,Mt,T,bt,vt);if(Mt instanceof Fi&&!B.length&&!me)return;const Qt=T.paint.get("raster-emissive-strength"),Lt=L.colorModeForDrapableLayerRenderPass(Qt),ps=L.terrain&&L.terrain.renderingToTexture,Hs=!L.options.moving,Fs=T.paint.get("raster-resampling")==="nearest"?vt.NEAREST:vt.LINEAR;if(Mt instanceof Fi&&!B.length&&(Mt.onNorthPole||Mt.onSouthPole)){const Mn=Re?L.stencilModeFor3D():o._.disabled;return void P3(we,!!Mt.onNorthPole,null,L,k,T,Qt,es,o.$.disabled,Mn)}if(!B.length)return;const[nn,$s]=Mt instanceof Fi||ps?[{},B]:L.stencilConfigForOverlap(B),rn=$s.at(-1).overscaledZ;Qe&&es.defines.push("PROJECTION_GLOBE_VIEW"),Re&&es.defines.push("RENDER_CUTOFF","ELEVATED"),Ze&&es.defines.push("ELEVATION_REFERENCE_GROUND");const _n=(Mn,Kn,Bn)=>{for(const On of Mn){const Rr=On.toUnwrapped(),An=k.getTile(On);if(ps&&(!An||!An.hasData()))continue;bt.activeTexture.set(vt.TEXTURE0);const xr=KT(An,Mt,T,es);if(!xr||!xr.texture)continue;const{texture:sa,mix:ka,offset:Hr,tileSize:ea,buffer:si}=xr;let Wr,Tr;ps?(Wr=o.Z.disabled,Tr=On.projMatrix):Re?(Wr=new o.Z(vt.LEQUAL,o.Z.ReadWrite,L.depthRangeFor3D),Tr=me?L.transform.expandedFarZProjMatrix:L.transform.calculateProjMatrix(Rr,Hs)):(Wr=L.depthModeForSublayer(On.overscaledZ-rn,oe===1?o.Z.ReadWrite:o.Z.ReadOnly,vt.LESS),Tr=L.transform.calculateProjMatrix(Rr,Hs));const Gr=L.terrain&&ps?L.terrain.stencilModeForRTTOverlap(On):nn[On.overscaledZ],Ga=Q?0:T.paint.get("raster-fade-duration");An.registerFadeDuration(Ga);const qr=k.findLoadedParent(On,0),Za=Cd(An,qr,k,L.transform,Ga);let Oi,Do;!Za.isFading&&An.refreshedUponExpiration&&(An.refreshedUponExpiration=!1),L.terrain&&L.terrain.prepareDrawTile(),bt.activeTexture.set(vt.TEXTURE0),sa.bind(Fs,vt.CLAMP_TO_EDGE),bt.activeTexture.set(vt.TEXTURE1),qr?(qr.texture&&qr.texture.bind(Fs,vt.CLAMP_TO_EDGE),Oi=Math.pow(2,qr.tileID.overscaledZ-An.tileID.overscaledZ),Do=[An.tileID.canonical.x*Oi%1,An.tileID.canonical.y*Oi%1]):sa.bind(Fs,vt.CLAMP_TO_EDGE),"useMipmap"in sa&&bt.extTextureFilterAnisotropic&&L.transform.pitch>20&&vt.texParameterf(vt.TEXTURE_2D,bt.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,bt.extTextureFilterAnisotropicMax);const so=L.transform;let ql;const vu=Re?F6(so):[0,0,0,0];let Uc,Ko,no,_d,Gh,_h=0;if(Qe&&Mt instanceof Fi&&Mt.coordinates.length>3)Uc=Float32Array.from(o.b5(o.b6(new o.bW(0,0,0)))),Ko=Float32Array.from(so.globeMatrix),no=Float32Array.from(o.b7(so)),_d=[o.a7(so.center.lng),o.a8(so.center.lat)],ql=Mt.elevatedGlobePerspectiveTransform,Gh=Mt.elevatedGlobeGridMatrix||new Float32Array(9);else if(Qe){const dc=o.b3(On.canonical);_h=o.b4(dc.getCenter().lat),Uc=Float32Array.from(o.b5(o.b6(On.canonical))),Ko=Float32Array.from(so.globeMatrix),no=Float32Array.from(o.b7(so)),_d=[o.a7(so.center.lng),o.a8(so.center.lat)],ql=[0,0],Gh=Float32Array.from(o.b8(On.canonical,dc,_h,so.worldSize/so._pixelsPerMercatorPixel))}else ql=Mt instanceof Fi?Mt.perspectiveTransform:[0,0],Uc=new Float32Array(16),Ko=new Float32Array(9),no=new Float32Array(16),_d=[0,0],Gh=new Float32Array(9);const Vl=Ns(L,Tr,Uc,Ko,no,Gh,Do||[0,0],o.S(L.transform.zoom),_d,vu,Oi||1,Za,T,ql,we,2,ka,Hr,es.range,ea,si,Qt),mm=L.isTileAffectedByFog(On),bc=L.getOrCreateProgram("raster",{defines:es.defines,overrideFog:mm});if(L.uploadCommonUniforms(bt,bc,Rr),Mt instanceof Fi){const dc=Mt.elevatedGlobeVertexBuffer,Dh=Mt.elevatedGlobeIndexBuffer;if(ps||!me)Mt.boundsBuffer&&Mt.boundsSegments&&bc.draw(L,vt.TRIANGLES,Wr,o._.disabled,Lt,o.$.disabled,Vl,T.id,Mt.boundsBuffer,L.quadTriangleIndexBuffer,Mt.boundsSegments);else if(dc&&Dh){const Wh=so.zoom<=o.ef?Mt.elevatedGlobeSegments:Mt.getSegmentsForLongitude(so.center.lng);Wh&&bc.draw(L,vt.TRIANGLES,Wr,o._.disabled,Lt,Kn,Vl,T.id,dc,Dh,Wh)}}else if(Qe){Wr=new o.Z(vt.LEQUAL,o.Z.ReadOnly,L.depthRangeFor3D);const dc=L.globeSharedBuffers;if(dc){Ze&&(L.terrain.setupElevationDraw(An,bc),L.uploadCommonUniforms(bt,bc,An.tileID.toUnwrapped()));const[Dh,Wh,Pd]=dc.getGridBuffers(_h,!1),_c=bc.getAttributeLocation(vt,"a_texture_pos");_c!==-1&&vt.vertexAttribI4ui(_c,0,0,0,0),bc.draw(L,vt.TRIANGLES,Wr,Bn||Gr,L.colorModeForRenderPass(),Kn,Vl,T.id,Dh,Wh,Pd)}}else if(ut)Wr=new o.Z(vt.LEQUAL,o.Z.ReadOnly,L.depthRangeFor3D),L.terrain.setupElevationDraw(An,bc),L.uploadCommonUniforms(bt,bc,An.tileID.toUnwrapped()),so.pitch>20&&bc.draw(L,vt.TRIANGLES,Wr,o._.disabled,o.a1.disabled,o.$.frontCCW,Vl,T.id,L.terrain.gridBuffer,L.terrain.gridIndexBuffer,L.terrain.gridSegments),bc.draw(L,vt.TRIANGLES,Wr,Gr,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(An);bc.draw(L,vt.TRIANGLES,Wr,Gr,Lt,o.$.disabled,Vl,T.id,dc,Dh,Wh)}}if(!(Mt instanceof Fi)&&Qe)for(const On of Mn){const Rr=On.canonical.y===(1<nn.tileID)),ut&&(Me.activeTexture.set(Re.TEXTURE0),L.imageManager.bind(L.context,T.scope));const Fs=[];if(L.terrain&&L.terrain.renderingToTexture&&L.isEmissiveMrtActive()&&(Fs.push("USE_MRT1"),L.emissiveMode==="mrt-full-rgba"&&Fs.push("USE_MRT1_RGBA")),we){const nn=L.getOrCreateProgram(Lt,{overrideFog:!1,overrideRtt:!0,defines:Fs}),$s=O6,rn=new o.bQ(0,0,0,0,0),_n=ut?Zn($s,me,oe,L,ut,T.scope,bt,we,{tileID:rn,tileSize:Qe}):on($s,me,oe,K.toPremultipliedRenderColor(Q?null:T.lut));return void nn.draw(L,Re.TRIANGLES,es,Mt,Qt,o.$.disabled,_n,T.id,L.viewportBuffer,L.quadTriangleIndexBuffer,L.viewportSegments)}for(const nn of Hs){const $s=L.isTileAffectedByFog(nn),rn=L.getOrCreateProgram(Lt,{overrideFog:$s,defines:Fs}),_n=nn.toUnwrapped(),Mn=B?nn.projMatrix:L.transform.calculateProjMatrix(_n);L.prepareDrawTile();const Kn=k?k.getTile(nn):ps?ps[nn.key]:new Lx(nn,Qe,Ze.zoom,L),Bn=ut?Zn(Mn,me,oe,L,ut,T.scope,bt,we,{tileID:nn,tileSize:Qe}):on(Mn,me,oe,K.toPremultipliedRenderColor(Q?null:T.lut));L.uploadCommonUniforms(Me,rn,_n);const{tileBoundsBuffer:On,tileBoundsIndexBuffer:Rr,tileBoundsSegments:An}=L.getTileBoundsBuffers(Kn);rn.draw(L,Re.TRIANGLES,es,Mt,Qt,o.$.disabled,Bn,T.id,On,Rr,An)}},sky:function(L,k,T){const B=L._atmosphere?o.S(L.transform.zoom):1,K=T.paint.get("sky-opacity")*B;if(K===0)return;const Q=L.context,oe=T.paint.get("sky-type"),me=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,Qe=Ze.gl;let ut=Re.skyboxFbo;if(!ut){ut=Re.skyboxFbo=Ze.createFramebuffer(32,32,1,null),Re.skyboxGeometry=new de(Ze),Re.skyboxTexture=Ze.gl.createTexture(),Qe.bindTexture(Qe.TEXTURE_CUBE_MAP,Re.skyboxTexture),Qe.texParameteri(Qe.TEXTURE_CUBE_MAP,Qe.TEXTURE_WRAP_S,Qe.CLAMP_TO_EDGE),Qe.texParameteri(Qe.TEXTURE_CUBE_MAP,Qe.TEXTURE_WRAP_T,Qe.CLAMP_TO_EDGE),Qe.texParameteri(Qe.TEXTURE_CUBE_MAP,Qe.TEXTURE_MIN_FILTER,Qe.LINEAR),Qe.texParameteri(Qe.TEXTURE_CUBE_MAP,Qe.TEXTURE_MAG_FILTER,Qe.LINEAR);for(let es=0;es<6;++es)Qe.texImage2D(Qe.TEXTURE_CUBE_MAP_POSITIVE_X+es,0,Qe.RGBA,32,32,0,Qe.RGBA,Qe.UNSIGNED_BYTE,null)}Ze.bindFramebuffer.set(ut.framebuffer),Ze.viewport.set([0,0,32,32]);const bt=Re.getCenter(Me,!0),vt=Me.getOrCreateProgram("skyboxCapture"),Mt=new Float64Array(16);o.ei(Mt,.5*-Math.PI),Oe(Me,Re,vt,Mt,bt,0),o.ei(Mt,.5*Math.PI),Oe(Me,Re,vt,Mt,bt,1),o.ej(Mt,.5*-Math.PI),Oe(Me,Re,vt,Mt,bt,2),o.ej(Mt,.5*Math.PI),Oe(Me,Re,vt,Mt,bt,3),o.df(Mt),Oe(Me,Re,vt,Mt,bt,4),o.ei(Mt,Math.PI),Oe(Me,Re,vt,Mt,bt,5),Ze.viewport.set([0,0,Me.width,Me.height])}(L,T),T.markSkyboxValid(L)):L.renderPass==="sky"&&function(Me,Re,Ze,Qe,ut){const bt=Me.context,vt=bt.gl,Mt=Me.transform,es=Me.getOrCreateProgram("skybox");bt.activeTexture.set(vt.TEXTURE0),vt.bindTexture(vt.TEXTURE_CUBE_MAP,Re.skyboxTexture);const Qt=((Lt,ps,Hs,Fs,nn)=>({u_matrix:Lt,u_sun_direction:ps,u_cubemap:0,u_opacity:Fs,u_temporal_offset:nn}))(Mt.skyboxMatrix,Re.getCenter(Me,!1),0,Qe,ut);Me.uploadCommonUniforms(bt,es),es.draw(Me,vt.TRIANGLES,Ze,o._.disabled,Me.colorModeForRenderPass(),o.$.backCW,Qt,"skybox",Re.skyboxGeometry.vertexBuffer,Re.skyboxGeometry.indexBuffer,Re.skyboxGeometry.segment)}(L,T,me,K,we):oe==="gradient"&&L.renderPass==="sky"&&function(Me,Re,Ze,Qe,ut){const bt=Me.context,vt=bt.gl,Mt=Me.transform,es=Me.getOrCreateProgram("skyboxGradient");Re.skyboxGeometry||(Re.skyboxGeometry=new de(bt)),bt.activeTexture.set(vt.TEXTURE0);let Qt=Re.colorRampTexture;Qt||(Qt=Re.colorRampTexture=new o.T(bt,Re.colorRamp,vt.RGBA8)),Qt.bind(vt.LINEAR,vt.CLAMP_TO_EDGE);const Lt=((ps,Hs,Fs,nn,$s)=>({u_matrix:ps,u_color_ramp:0,u_center_direction:Hs,u_radius:o.av(Fs),u_opacity:nn,u_temporal_offset:$s}))(Mt.skyboxMatrix,Re.getCenter(Me,!1),Re.paint.get("sky-gradient-radius"),Qe,ut);Me.uploadCommonUniforms(bt,es),es.draw(Me,vt.TRIANGLES,Ze,o._.disabled,Me.colorModeForRenderPass(),o.$.backCW,Lt,"skyboxGradient",Re.skyboxGeometry.vertexBuffer,Re.skyboxGeometry.indexBuffer,Re.skyboxGeometry.segment)}(L,T,me,K,we)},custom:function(L,k,T,B){const K=L.context,Q=T.implementation;if(!L.transform.projection.unsupportedLayers||!L.transform.projection.unsupportedLayers.includes("custom")||L.terrain&&(L.terrain.renderingToTexture||L.renderPass==="offscreen")&&T.isDraped(k)){if(L.renderPass==="offscreen"){const oe=Q.prerender;if(oe){if(L.setCustomLayerDefaults(),K.setColorMode(L.colorModeForRenderPass()),L.transform.projection.name==="globe"){const me=L.transform.pointMerc;oe.call(Q,K.gl,L.transform.customLayerMatrix(),L.transform.getProjection(),L.transform.globeToMercatorMatrix(),o.S(L.transform.zoom),[me.x,me.y],L.transform.pixelsPerMeterRatio)}else oe.call(Q,K.gl,L.transform.customLayerMatrix());K.setDirty(),L.setBaseState()}}else if(L.renderPass==="translucent"){if(L.terrain&&L.terrain.renderingToTexture){const me=Q.renderToTile;if(me){const we=B[0].canonical,Me={x:we.x+B[0].wrap*(Q.wrapTileId?0:1<k.getTileByID(me));for(const me of oe)me.updateNeeded(L.id,Q)&&B.prepareTile(me,K,L.id,Q)}};async function Zi(L){if(await yr(),Object.assign(Mi,{model:vr.drawModels}),Object.assign(gl,{model:vr.prepare}),L&&!L._destroyed&&!L._shadowRenderer){const k=vr.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 di,this.setup(),this.numSublayers=Ci.maxUnderzooming+Ci.maxOverzooming+1,this.depthEpsilon=1/Math.pow(2,16),this.deferredRenderGpuTimeQueries=[],this.gpuTimers={},this.frameCounter=0,this.frameTimeDelta=0,this.lastPaintStartTimeStamp=0,this._shadowCullCache=null,this._backgroundTiles={},this.conflationActive=!1,this.replacementSource=new o.ew,this.longestCutoffRange=0,this.minCutoffZoom=0,this._fogVisible=!1,this._cachedTileFogOpacities={},this._wireframeDebugCache=new $r,this.renderDefaultNorthPole=!0,this.renderDefaultSouthPole=!0,this.layersWithOcclusionOpacity=[];const me=new o.b({width:1,height:1},Uint8Array.of(0,0,0,0));this.emptyDepthTexture=new o.T(this.context,me,k.RGBA8),this._clippingActiveLastFrame=!1,this.scaleFactor=K,this.maxFrontCutoffRawStart=0,this.worldview=Q,this._forceEmissiveMode=!1,this.emissiveMode="constant"}updateTerrain(k,T){const B=!!k&&!!k.terrain&&this.transform.projection.supportsTerrain;var K;(B||this._terrain&&this._terrain.enabled)&&(this._terrain||(this._terrain=sx(this,k),this._terrain)?(this.transform.elevation=B?this._terrain:null,this._terrain.update(k,this.transform,T),this.transform.elevation&&!this._terrain.enabled&&(this.transform.elevation=null)):this._terrainRendererRetryPending||(this._terrainRendererRetryPending=!0,K=()=>{this._terrainRendererRetryPending=!1,this.style&&this.style.map&&this.style.map._update(!1)},G2?K():B_.push(K)))}_updateFog(k){const T=k.fog;if(!T||this.transform.projection.name==="globe"||T.getOpacity(this.transform.pitch)<1||T.properties.get("horizon-blend")<.03)return void(this.transform.fogCullDistSq=null);const[B,K]=T.getRangeForProjection();if(B>K)return void(this.transform.fogCullDistSq=null);const Q=B+.78*(K-B);this.transform.fogCullDistSq=Q*Q}get terrain(){return this.transform._terrainEnabled()&&this._terrain&&this._terrain.enabled||this._forceTerrainMode?this._terrain:null}get forceTerrainMode(){return this._forceTerrainMode}set forceTerrainMode(k){k&&!this._terrain&&(this._terrain=sx(this,this.style),this._terrain||console.warn("forceTerrainMode: Lite module not loaded yet, terrain renderer unavailable")),this._forceTerrainMode=k}get shadowRenderer(){return this._shadowRenderer&&this._shadowRenderer.enabled?this._shadowRenderer:null}get wireframeDebugCache(){return this._wireframeDebugCache}resize(k,T){if(this.width=k*o.e.devicePixelRatio,this.height=T*o.e.devicePixelRatio,this.context.viewport.set([0,0,this.width,this.height]),this.style)for(const B of this.style.order)this.style._mergedLayers[B].resize()}setup(){const k=this.context,T=new o.bD;T.emplaceBack(0,0),T.emplaceBack(o.a6,0),T.emplaceBack(0,o.a6),T.emplaceBack(o.a6,o.a6),this.tileExtentBuffer=k.createVertexBuffer(T,o.bF.members),this.tileExtentSegments=o.ad.simpleSegment(0,0,4,2);const B=new o.bD;B.emplaceBack(0,0),B.emplaceBack(o.a6,0),B.emplaceBack(0,o.a6),B.emplaceBack(o.a6,o.a6),this.debugBuffer=k.createVertexBuffer(B,o.bF.members),this.debugSegments=o.ad.simpleSegment(0,0,4,5);const K=new o.bD;K.emplaceBack(-1,-1),K.emplaceBack(1,-1),K.emplaceBack(-1,1),K.emplaceBack(1,1),this.viewportBuffer=k.createVertexBuffer(K,o.bF.members),this.viewportSegments=o.ad.simpleSegment(0,0,4,2);const Q=new o.bt;Q.emplaceBack(0,0,0,0),Q.emplaceBack(o.a6,0,o.a6,0),Q.emplaceBack(0,o.a6,0,o.a6),Q.emplaceBack(o.a6,o.a6,o.a6,o.a6),this.mercatorBoundsBuffer=k.createVertexBuffer(Q,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 me=new o.bE;for(const Me of[0,1,3,2,0])me.emplaceBack(Me);this.debugIndexBuffer=k.createIndexBuffer(me),this.emptyTexture=new o.T(k,new o.b({width:1,height:1},Uint8Array.of(0,0,0,0)),k.gl.RGBA8),this.identityMat=o.Y();const we=this.context.gl;this.stencilClearMode=new o._({func:we.ALWAYS,mask:0},0,255,we.ZERO,we.ZERO,we.ZERO),this.loadTimeStamps.push(performance.now())}getMercatorTileBoundsBuffers(){return{tileBoundsBuffer:this.mercatorBoundsBuffer,tileBoundsIndexBuffer:this.quadTriangleIndexBuffer,tileBoundsSegments:this.mercatorBoundsSegments}}getTileBoundsBuffers(k){return k._makeTileBoundsBuffers(this.context,this.transform.projection),k._tileBoundsBuffer?{tileBoundsBuffer:k._tileBoundsBuffer,tileBoundsIndexBuffer:k._tileBoundsIndexBuffer,tileBoundsSegments:k._tileBoundsSegments}:this.getMercatorTileBoundsBuffers()}clearStencil(){const k=this.context.gl;this.nextStencilID=1,this.currentStencilSource=void 0,this._tileClippingMaskIDs={},this.getOrCreateProgram("clippingMask").draw(this,k.TRIANGLES,o.Z.disabled,this.stencilClearMode,o.a1.disabled,o.$.disabled,xu(this.identityMat),"$clipping",this.viewportBuffer,this.quadTriangleIndexBuffer,this.viewportSegments)}resetStencilClippingMasks(){this.terrain||(this.currentStencilSource=void 0,this._tileClippingMaskIDs={})}_renderTileClippingMasks(k,T,B){if(!T||this.currentStencilSource===T.id||!k.isTileClipped()||!B||B.length===0)return;if(this._tileClippingMaskIDs&&!this.terrain){let me=!1;for(const we of B)if(this._tileClippingMaskIDs[we.key]===void 0){me=!0;break}if(!me)return}this.currentStencilSource=T.id;const K=this.context,Q=K.gl;this.nextStencilID+B.length>256&&this.clearStencil(),K.setColorMode(o.a1.disabled),K.setDepthMode(o.Z.disabled);const oe=this.getOrCreateProgram("clippingMask");this._tileClippingMaskIDs={};for(const me of B){const we=T.getTile(me),Me=this._tileClippingMaskIDs[me.key]=this.nextStencilID++,{tileBoundsBuffer:Re,tileBoundsIndexBuffer:Ze,tileBoundsSegments:Qe}=this.getTileBoundsBuffers(we);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,xu(me.projMatrix),"$clipping",Re,Ze,Qe)}}stencilModeFor3D(){this.currentStencilSource=void 0,this.nextStencilID+1>256&&this.clearStencil();const k=this.nextStencilID++,T=this.context.gl;return new o._({func:T.NOTEQUAL,mask:255},k,255,T.KEEP,T.KEEP,T.REPLACE)}stencilModeForClipping(k){if(this.terrain)return this.terrain.stencilModeForRTTOverlap(k);const T=this.context.gl;return new o._({func:T.EQUAL,mask:255},this._tileClippingMaskIDs[k.key],0,T.KEEP,T.KEEP,T.REPLACE)}stencilConfigForOverlap(k){const T=this.context.gl,B=k.sort((oe,me)=>me.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 me=0;methis.style._getOrder(K);let oe=Q(),me=!1,we=!1,Me=null,Re=0,Ze=!1;for(const An of oe){const xr=B[An];xr.visibility!=="none"&&(xr.type==="circle"?me=!0:xr.type==="building"?(Me=xr,++Re):xr.type==="symbol"&&(xr.hasOcclusionOpacityProperties?we=!0:me=!0))}this.updateEmissiveMode();let Qe=oe.map(An=>B[An]);const ut=this.style._mergedSourceCaches;this.imageManager=k.imageManager,this.modelManager=k.modelManager,this.symbolFadeChange=k.placement.symbolFadeChange(o.e.now()),this.imageManager.beginFrame();for(const An in ut){const xr=ut[An];xr.used&&(xr.prepare(this.context),xr.getSource().usedInConflation&&++Re)}let bt=!1;for(const An of Qe)An.isHidden(this.transform.zoom)||(An.type==="clip"&&(bt=!0),this.prepareLayer(An));const vt={},Mt={},es={},Qt={},Lt={};for(const An in ut){const xr=ut[An];vt[An]=xr.getVisibleCoordinates(),Mt[An]=vt[An].slice().reverse(),es[An]=xr.getVisibleCoordinates(!0).reverse(),Qt[An]=xr.getShadowCasterCoordinates(),Lt[An]=xr.sortCoordinatesByDistance(vt[An])}const ps=An=>{const xr=this.style.getLayerSourceCache(An);return xr&&xr.used?xr.getSource():null};if(Re||bt||this._clippingActiveLastFrame){const An=[],xr=[];let sa=0;for(const ka of Qe)this.isSourceForClippingOrConflation(ka,ps(ka))&&(An.push(ka),xr.push(sa)),sa++;if(An&&(bt||An.length>1)||this._clippingActiveLastFrame){bt=!1;const ka=[];for(let Hr=0;Hr0){const ka=ps(xr);ka&&(this.minCutoffZoom=Math.max(ka.minzoom,this.minCutoffZoom)),xr.minzoom&&(this.minCutoffZoom=Math.max(xr.minzoom,this.minCutoffZoom))}xr.is3D(K)&&(this.opaquePassCutoff===1/0&&(this.opaquePassCutoff=An),this._lastOcclusionLayer=An)}const Hs=this.style&&this.style.fog;Hs?(this._fogVisible=Hs.getOpacity(this.transform.pitch)!==0,this._fogVisible&&this.transform.projection.name!=="globe"&&(this._fogVisible=Hs.isVisibleOnFrustum(this.transform.cameraFrustum))):this._fogVisible=!1,this._cachedTileFogOpacities={},this.terrain&&(this.terrain.updateTileBinding(es),this.opaquePassCutoff=0,oe=Q(),Qe=oe.map(An=>B[An])),this.style.enable3dLights()&&!this._shadowRenderer&&Zi(this);const Fs=this._shadowRenderer;if(Fs){Fs.updateShadowParameters(this.transform,this.style.directionalLight,Qt);for(const An in ut)for(const xr of vt[An]){let sa={min:0,max:0};this.terrain&&(sa=this.terrain.getMinMaxForTile(xr)||sa),Fs.addShadowReceiver(xr.toUnwrapped(),sa.min,sa.max)}}this.transform.projection.name!=="globe"||this.globeSharedBuffers||(this.globeSharedBuffers=new o.ey(this.context)),this.style.fog&&this.transform.projection.supportsFog?(this._atmosphere||(this._atmosphere=new Ws),this._atmosphere.update(this)):this._atmosphere&&(this._atmosphere.destroy(),this._atmosphere=void 0);let nn=!(!this.style||!this.style.snow),$s=!(!this.style||!this.style.rain);if(nn&&!this._snow&&Ui.Snow&&(this._snow=new Ui.Snow),!nn&&this._snow&&(this._snow.destroy(),delete this._snow),$s&&!this._rain&&Ui.Rain&&(this._rain=new Ui.Rain),!$s&&this._rain&&(this._rain.destroy(),delete this._rain),this._snow&&this._snow.update(this),this._rain&&this._rain.update(this),Me&&(!this.buildingTileBorderManager&&Ui.BuildingTileBorderManager&&(this.buildingTileBorderManager=new Ui.BuildingTileBorderManager),this.buildingTileBorderManager)){const An=this.style.getLayerSourceCache(Me);this.buildingTileBorderManager.updateBorders(An,Me)}if(!o.ez(this.context.gl))return;this.renderPass="offscreen";for(const An of Qe){const xr=k.getLayerSourceCache(An);if(!An.hasOffscreenPass()||An.isHidden(this.transform.zoom))continue;const sa=xr?Mt[xr.id]:void 0;(An.type==="custom"||An.type==="raster"||An.type==="raster-particle"||An.isSky()||sa&&sa.length)&&this.renderLayer(this,xr,An,sa)}this.depthRangeFor3D=[0,1-(Qe.length+2)*this.numSublayers*this.depthEpsilon],this._shadowRenderer&&(this.renderPass="shadow",this._shadowRenderer.drawShadowPass(this.style,Qt)),this.context.bindFramebuffer.set(null),this.context.viewport.set([0,0,this.width,this.height]);const rn=this.transform.projection.name==="globe"||this.transform.isHorizonVisible(),_n=(()=>{if(T.showOverdrawInspector)return o.C.black;const An=this.style.fog;if(An&&this.transform.projection.supportsFog){const xr=this.style.getLut(An.scope);if(!rn){const sa=An.properties.get("color-use-theme")==="none",ka=An.properties.get("color").toNonPremultipliedRenderColor(sa?null:xr).toArray01();return new o.C(...ka)}if(rn){const sa=An.properties.get("space-color-use-theme")==="none",ka=An.properties.get("space-color").toNonPremultipliedRenderColor(sa?null:xr).toArray01();return new o.C(...ka)}}return o.C.transparent})();if(this.context.clear({color:_n,depth:1}),this.clearStencil(),this._showOverdrawInspector=T.showOverdrawInspector,this.renderPass="opaque",this.style.fog&&this.transform.projection.supportsFog&&this._atmosphere&&!this._showOverdrawInspector&&rn&&this._atmosphere.drawStars(this,this.style.fog),!this.terrain)for(this.currentLayer=oe.length-1;this.currentLayer>=0;this.currentLayer--){const An=Qe[this.currentLayer],xr=k.getLayerSourceCache(An);if(An.isSky())continue;const sa=xr?(An.is3D(K)?Lt:Mt)[xr.id]:void 0;this._renderTileClippingMasks(An,xr,sa),this.renderLayer(this,xr,An,sa)}if(this.style.fog&&this.transform.projection.supportsFog&&this._atmosphere&&!this._showOverdrawInspector&&rn&&this._atmosphere.drawAtmosphereGlow(this,this.style.fog),this.renderPass="sky",(!this._atmosphere||o.S(this.transform.zoom)>0)&&(this.transform.projection.name==="globe"||this.transform.isHorizonVisible()))for(this.currentLayer=0;this.currentLayer{for(this.currentLayer=0;this.currentLayer=this._lastOcclusionLayer&&this.layersWithOcclusionOpacity.length>0){const sa=this.currentLayer;this.depthOcclusion=!0;for(const ka of this.layersWithOcclusionOpacity){this.currentLayer=ka;const Hr=Qe[this.currentLayer],ea=k.getLayerSourceCache(Hr),si=ea?Mt[ea.id]:void 0;this.terrain||this._renderTileClippingMasks(Hr,ea,ea?vt[ea.id]:void 0),this.renderLayer(this,ea,Hr,si)}this.depthOcclusion=!1,this.currentLayer=sa,this.renderPass="translucent",this.layersWithOcclusionOpacity=[]}++this.currentLayer}}if(this.terrain&&this.terrain.postRender(),this._snow&&this._snow.draw(this),this._rain&&this._rain.draw(this),this.options.showTileBoundaries||this.options.showQueryGeometry||this.options.showTileAABBs){let An=null;Qe.forEach(xr=>{const sa=k.getLayerSourceCache(xr);sa&&!xr.isHidden(this.transform.zoom)&&sa.getVisibleCoordinates().length&&(!An||An.getSource().maxzoom0?T.pop():null}terrainRenderModeElevated(){return this.style&&this.style.hasTerrain()&&!!this.terrain&&!this.terrain.renderingToTexture||this.forceTerrainMode}linearFloatFilteringSupported(){return this.context.extTextureFloatLinear!=null}currentGlobalDefines(k,T,B,K,Q){const oe=B===void 0?!!this._terrain&&this._terrain.renderingToTexture:B,me=K===void 0?this.terrainRenderModeElevated():K,we=Q===void 0?this.transform.projection.name==="globe":Q,Me=[];return this.style&&this.style.enable3dLights()&&(k==="globeRaster"||k==="terrainRaster"?(Me.push("LIGHTING_3D_MODE"),Me.push("LIGHTING_3D_ALPHA_EMISSIVENESS"),this.emissiveMode==="mrt-full-rgba"&&Me.push("USE_MRT1_RGBA")):oe||Me.push("LIGHTING_3D_MODE")),me&&(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:me,overrideGlobe:we,precompiled:Me}=T||{},Re=this.currentGlobalDefines(k,Q,oe,me,we).concat(B||[]),Ze=this.getShaderSource(k),Qe=Ui.programUniforms,ut=vr.programUniforms,bt=Ar[k]||Qe&&Qe[k]||ut&&ut[k],vt=Y2.cacheKey(Ze,k,Re,K);return this.cache[vt]||(this.cache[vt]=new Y2(this.context,k,Ze,K,bt,Re,Me)),this.cache[vt]}getShaderSource(k){const T=Ui.shaders,B=vr.shaders,K=or.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=((me,we,Me,Re)=>{const Ze=me.properties.get("direction"),Qe=me.properties.get("color-use-theme")==="none",ut=me.properties.get("color").toNonPremultipliedRenderColor(Qe?null:Me.getLut(me.scope)).toArray01();let bt=me.properties.get("intensity");const vt=we.properties.get("color-use-theme")==="none",Mt=we.properties.get("color").toNonPremultipliedRenderColor(vt?null:Me.getLut(we.scope)).toArray01();let es=we.properties.get("intensity");const Qt=[Ze.x,Ze.y,Ze.z];Re&&(Re.ambientIntensity!==void 0&&(es=Re.ambientIntensity),Re.directionalIntensity!==void 0&&(bt=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&&(ut[0]=Re.directionalColor[0],ut[1]=Re.directionalColor[1],ut[2]=Re.directionalColor[2]));const Lt=o.dU(Mt,es),ps=o.dU(ut,bt);return{u_lighting_ambient_color:Lt,u_lighting_directional_dir:Qt,u_lighting_directional_color:ps,u_ground_radiance:K2(Qt,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 me=this.style.fog;if(me){const we=me.getOpacity(this.transform.pitch),Me=((Re,Ze,Qe,ut,bt,vt,Mt,es,Qt,Lt,ps,Hs)=>{const Fs=Re.transform,nn=Ze.properties.get("color-use-theme")==="none",$s=Ze.properties.get("color").toNonPremultipliedRenderColor(nn?null:Re.style.getLut(Ze.scope)).toArray01();$s[3]=ut;const rn=Re.frameCounter/1e3%1,[_n,Mn]=Ze.properties.get("vertical-range");return{u_fog_matrix:Qe?Fs.calculateFogTileMatrix(Qe):Hs||Re.identityMat,u_fog_range:Ze.getRangeForProjection(),u_fog_color:$s,u_fog_horizon_blend:Ze.properties.get("horizon-blend"),u_fog_vertical_limit:[Math.min(_n,Mn),Mn],u_fog_temporal_offset:rn,u_frustum_tl:bt,u_frustum_tr:vt,u_frustum_br:Mt,u_frustum_bl:es,u_globe_pos:Qt,u_globe_radius:Lt,u_viewport:ps,u_globe_transition:o.S(Fs.zoom),u_is_globe:+(Fs.projection.name==="globe")}})(this,me,B,we,this.transform.frustumCorners.TL,this.transform.frustumCorners.TR,this.transform.frustumCorners.BR,this.transform.frustumCorners.BL,this.transform.globeCenterInViewSpace,this.transform.globeRadius,[this.transform.width*o.e.devicePixelRatio,this.transform.height*o.e.devicePixelRatio],K);T.setFogUniformValues(k,Me)}Q&&T.setCutoffUniformValues(k,Q.uniformValues)}setTileLoadedFlag(k){this.tileLoaded=k}saveCanvasCopy(){const k=this.canvasCopy();k&&(this.frameCopies.push(k),this.tileLoaded=!1)}canvasCopy(){const k=this.context.gl,T=k.createTexture();return k.bindTexture(k.TEXTURE_2D,T),k.copyTexImage2D(k.TEXTURE_2D,0,k.RGBA,0,0,k.drawingBufferWidth,k.drawingBufferHeight,0),T}getCanvasCopiesAndTimestamps(){return{canvasCopies:this.frameCopies,timeStamps:this.loadTimeStamps}}averageElevationNeedsEasing(){if(!this.transform._elevation)return!1;const k=this.style&&this.style.fog;return!!k&&k.getOpacity(this.transform.pitch)!==0}getBackgroundTiles(){const k=this._backgroundTiles,T=this._backgroundTiles={},B=this.transform.coveringTiles({tileSize:512});for(const K of B)T[K.key]=k[K.key]||new Lx(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 me;B||(B={u_dem:2,u_dem_prev:4,u_dem_tl:[0,0],u_dem_tl_prev:[0,0],u_dem_scale:0,u_dem_scale_prev:0,u_dem_size:0,u_dem_lerp:1,u_depth:3,u_depth_size_inv:[0,0],u_depth_range_unpack:[0,1],u_occluder_half_size:16,u_occlusion_depth_offset:-1e-4,u_exaggeration:0}),K.activeTexture.set(Q.TEXTURE3),k&&this.depthFBO&&this.depthTexture?(this.depthTexture.bind(Q.NEAREST,Q.CLAMP_TO_EDGE),B.u_depth_size_inv=[1/this.depthFBO.width,1/this.depthFBO.height],B.u_depth_range_unpack=[2/((me=this.depthRangeFor3D)[1]-me[0]),-1-2*me[0]/(me[1]-me[0])],B.u_occluder_half_size=.5*this.occlusionParams.occluderSize,B.u_occlusion_depth_offset=this.occlusionParams.depthOffset):this.emptyDepthTexture.bind(Q.NEAREST,Q.CLAMP_TO_EDGE),K.activeTexture.set(Q.TEXTURE0),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 hh(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 by=/(#.+)?$/;class q_{constructor(k){this._hashName=k&&encodeURIComponent(k),o.aW(["_getCurrentHash","_onHashChange","_updateHash"],this),this._updateHash=hh(this._updateHashUnthrottled.bind(this),300)}addTo(k){return this._map=k,window.addEventListener("hashchange",this._onHashChange,!1),k.on("moveend",this._updateHash),this}remove(){return this._map?(this._map.off("moveend",this._updateHash),window.removeEventListener("hashchange",this._onHashChange,!1),clearTimeout(this._updateHash()),this._map=void 0,this):this}getHashString(){const k=this._map;if(!k)return"";const T=Ur(k);if(this._hashName){const B=this._hashName;let K=!1;const Q=location.hash.slice(1).split("&").map(oe=>{const me=oe.split("=")[0];return me===B?(K=!0,`${me}=${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(by,this.getHashString()))}}function Ur(L,k){const T=L.getCenter(),B=Math.round(100*L.getZoom())/100,K=Math.ceil((B*Math.LN2+Math.log(512/360/.5))/Math.LN10),Q=Math.pow(10,K),oe=Math.round(T.lng*Q)/Q,me=Math.round(T.lat*Q)/Q,we=L.getBearing(),Me=L.getPitch();let Re=k?`/${oe}/${me}/${B}`:`${B}/${me}/${oe}`;return(we||Me)&&(Re+="/"+Math.round(10*we)/10),Me&&(Re+=`/${Math.round(Me)}`),Re}const Wn={linearity:.3,easing:o.eC(0,0,.3,1)},ia={deceleration:2500,maxSpeed:1400,...Wn},Qi={deceleration:20,maxSpeed:1400,...Wn},xl={deceleration:1e3,maxSpeed:360,...Wn},Jc={deceleration:1e3,maxSpeed:90,...Wn};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,{...ia,...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,xl);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)),me=Q.reduce((we,Me,Re,Ze)=>we.add(Me.div(Ze.length)),new o.P(0,0));super(k,{points:Q,point:me,lngLats:oe,lngLat:T.unproject(me),originalEvent:B}),this._defaultPrevented=!1}}class Er extends o.h{preventDefault(){this._defaultPrevented=!0}get defaultPrevented(){return this._defaultPrevented}constructor(k,T){super("wheel",{originalEvent:T}),this._defaultPrevented=!1}}class I3{constructor(k,T){this._map=k,this._clickTolerance=T.clickTolerance}reset(){this._mousedownPos=void 0}wheel(k){return this._firePreventable(new Er(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 gr(k.type,this._map,k))}touchmove(k){this._map.fire(new gr(k.type,this._map,k))}touchend(k){this._map.fire(new gr(k.type,this._map,k))}touchcancel(k){this._map.fire(new gr(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 Ys{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=me-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 S9(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=S9(B,T)))}touchmove(k,T,B){if(this.aborted||!this.centroid)return;const K=S9(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 B6{constructor(k){this.singleTap=new C9(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 hY{constructor(){this._zoomIn=new B6({numTouches:1,numTaps:2}),this._zoomOut=new B6({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 doe=0,uoe=2,YT={[doe]:1,[uoe]:2},hoe={Control:"ctrlKey",Alt:"altKey",Shift:"shiftKey",Meta:"metaKey"};class mY{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=YT[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=S9(B,T),Q=new o.P(0,0),oe=new o.P(0,0);let me=0;for(const Me in K){const Re=K[Me],Ze=this._touches[Me];Ze&&(Q._add(Re),oe._add(Re.sub(Ze)),me++,K[Me]=Re)}if(this._touches=K,me{this._alertContainer.classList.remove("mapboxgl-touch-pan-blocker-show"),this._alertContainer.removeAttribute("role")},500)}}class E9{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,me=L3(B,T,Q),we=L3(B,T,oe);if(!me||!we)return;const Me=this._aroundCenter?null:me.add(we).div(2);return this._move([me,we],Me,k)}touchend(k,T,B){if(!this._firstTwoTouches)return;const[K,Q]=this._firstTwoTouches,oe=L3(B,T,K),me=L3(B,T,Q);oe&&me||(this._active&&E(),this.reset())}touchcancel(){this.reset()}enable(k){this._enabled=!0,this._aroundCenter=!!k&&k.around==="center"}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}function L3(L,k,T){for(let B=0;BMath.abs(L.x)}class goe extends E9{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,pY(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 pY(k)&&pY(T)&&oe}}const xoe={panStep:100,bearingStep:15,pitchStep:10};class yoe{constructor(){const k=xoe;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:me=>{const we=me.getZoom();me.easeTo({duration:300,easeId:"keyboardHandler",easing:PFe,zoom:T?Math.round(we)+T*(k.shiftKey?2:1):we,bearing:me.getBearing()+B*this._bearingStep,pitch:me.getPitch()+K*this._pitchStep,offset:[-Q*this._panStep,-oe*this._panStep],center:me.getCenter()},{originalEvent:k})}}}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled&&!(this._bearingDisabled&&this._pitchDisabled&&this._panDisabled&&this._zoomDisabled)}isActive(){return this._active}disableRotation(){this._pitchDisabled=!0,this._bearingDisabled=!0}enableRotation(){this._pitchDisabled=!1,this._bearingDisabled=!1}isRotationEnabled(){return!this._pitchDisabled&&!this._bearingDisabled}disablePan(){this._panDisabled=!0}enablePan(){this._panDisabled=!1}isPanEnabled(){return!this._panDisabled}disableZoom(){this._zoomDisabled=!0}enableZoom(){this._zoomDisabled=!1}isZoomEnabled(){return!this._zoomDisabled}disablePitch(){this._pitchDisabled=!0}enablePitch(){this._pitchDisabled=!1}isPitchEnabled(){return!this._pitchDisabled}disableBearing(){this._bearingDisabled=!0}enableBearing(){this._bearingDisabled=!1}isBearingEnabled(){return!this._bearingDisabled}}function PFe(L){return L*(2-L)}const gY=4.000244140625,IFe=1/450,Jy=/(Mac|iPad)/i;class T9{constructor(k,T){this._map=k,this._el=k.getCanvasContainer(),this._handler=T,this._delta=0,this._lastDelta=0,this._defaultZoomRate=.01,this._wheelZoomRate=IFe,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%gY===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)>gY?this._wheelZoomRate:this._defaultZoomRate;let Re=2/(1+Math.exp(-Math.abs(this._delta*Me)));this._delta<0&&Re!==0&&(Re=1/Re);const Ze=T(),Qe=Math.pow(2,Ze),ut=typeof this._targetZoom=="number"?k.zoomScale(this._targetZoom):Qe;this._targetZoom=Math.min(k.maxZoom,Math.max(k.minZoom,k.scaleZoom(ut*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,me=!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):me=!0}else oe=B,me=!0;this._active=!0,me&&(this._active=!1,this._finishTimeout=window.setTimeout(()=>{this._zooming=!1,this._handler._triggerRenderFrame(),delete this._targetZoom,delete this._finishTimeout},200));let we=oe-T();return we*this._lastDelta<0&&(we=0),{noInertia:!0,needsRenderFrame:!me,zoomDelta:we,around:this._aroundPoint,aroundCoord:this._aroundCoord,originalEvent:this._lastWheelEvent}}_smoothOutEasing(k){let T=o.eE;if(this._prevEase){const B=this._prevEase,K=(o.e.now()-B.start)/B.duration,Q=B.easing(K+.01)-B.easing(K),oe=.27/Math.sqrt(Q*Q+1e-4)*.01,me=Math.sqrt(.0729-oe*oe);T=o.eC(oe,me,.25,1)}return this._prevEase={start:o.e.now(),duration:k,easing:T},T}blur(){this.reset()}reset(){this._active=!1}_addScrollZoomBlocker(){this._map&&!this._alertContainer&&(this._alertContainer=g("div","mapboxgl-scroll-zoom-blocker",this._map._container),this._alertContainer.textContent=Jy.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 XT{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 voe{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 R3{constructor(){this._tap=new B6({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 q6{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 LFe{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 RFe{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 M9=L=>L.zoom||L.drag||L.pitch||L.rotate;class DFe extends o.h{}class FFe{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 P9(L){return L.panDelta&&L.panDelta.mag()||L.zoomDelta||L.bearingDelta||L.pitchDelta}class OFe{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 FFe,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 me=K===document?this.handleWindowEvent:this.handleEvent;K.addEventListener(Q,me,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 I3(T,k));const K=T.boxZoom=new Ys(T,k);this._add("boxZoom",K);const Q=new hY,oe=new voe;T.doubleClickZoom=new XT(oe,Q),this._add("tapZoom",Q),this._add("clickZoom",oe);const me=new R3;this._add("tapDragZoom",me);const we=T.touchPitch=new goe(T);this._add("touchPitch",we);const Me=new $6(k),Re=new A9(k);T.dragRotate=new LFe(k,Me,Re),this._add("mouseRotate",Me,["mousePitch"]),this._add("mousePitch",Re,["mouseRotate"]);const Ze=new moe(k),Qe=new foe(T,k);T.dragPan=new q6(B,Ze,Qe),this._add("mousePan",Ze),this._add("touchPan",Qe,["touchZoom","touchRotate"]);const ut=new poe,bt=new U6;T.touchZoomRotate=new RFe(B,bt,ut,me),this._add("touchRotate",ut,["touchPan","touchZoom"]),this._add("touchZoom",bt,["touchPan","touchRotate"]),this._add("blockableMapEvent",new Wu(T));const vt=T.scrollZoom=new T9(T,this);this._add("scrollZoom",vt,["mousePan"]);const Mt=T.keyboard=new yoe;this._add("keyboard",Mt);for(const es of["boxZoom","doubleClickZoom","tapDragZoom","touchPitch","dragRotate","dragPan","touchZoomRotate","scrollZoom","keyboard"])k.interactive&&k[es]&&T[es].enable(k[es])}_add(k,T,B){this._handlers.push({handlerName:k,handler:T,allowed:B}),this._handlersById[k]=T}stop(k="never"){if(!this._updatingCamera&&!(k==="always"||k==="ifPointerDown"&&this._isPointerDown())){for(const{handler:T}of this._handlers)T.reset();this._inertia.clear(),this._fireEvents({},{},!1),this._changes=[],this._originalZoom=void 0}}isActive(){for(const{handler:k}of this._handlers)if(k.isActive())return!0;return!1}isZooming(){return!!this._eventsInProgress.zoom||this._map.scrollZoom.isZooming()}isRotating(){return!!this._eventsInProgress.rotate}isMoving(){return!!M9(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={},me={},we=k.touches?this._getMapTouches(k.touches):void 0,Me=we?P(this._el,we):B?void 0:I(this._el,k);for(const{handlerName:Qe,handler:ut,allowed:bt}of this._handlers){if(!ut.isEnabled())continue;let vt;this._blockedByActive(me,bt,Qe)?ut.reset():ut[T||k.type]&&(vt=ut[T||k.type](k,Me,we),this.mergeHandlerResult(Q,oe,vt,Qe,K),vt&&vt.needsRenderFrame&&this._triggerRenderFrame()),(vt||ut.isActive())&&(me[Qe]=ut)}const Re={};for(const Qe in this._previousActiveHandlers)me[Qe]||(Re[Qe]=K);this._previousActiveHandlers=me,(Object.keys(Re).length||P9(Q))&&(this._changes.push([Q,oe,Re]),this._triggerRenderFrame()),(Object.keys(me).length||P9(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=Qt=>[Qt.x,Qt.y,Qt.z];if((()=>{const Qt=this._eventsInProgress.drag;return Qt&&!this._handlersById[Qt.handlerName].isActive()})()&&!P9(k)){const Qt=Q.zoom;Q.cameraElevationReference="sea",this._originalZoom!=null&&Q._orthographicProjectionAtLowPitch&&Q.projection.name!=="globe"&&Q.pitch===0?(Q.cameraElevationReference="ground",Q.zoom=this._originalZoom):(Q.recenterOnTerrain(),Q.cameraElevationReference="ground"),Qt!==Q.zoom&&this._map._update(!0)}if(Q._isCameraConstrained&&K._stop({keepGesture:"always"}),!P9(k))return void this._fireEvents(T,B,!0);let{panDelta:me,zoomDelta:we,bearingDelta:Me,pitchDelta:Re,around:Ze,aroundCoord:Qe,pinchAround:ut}=k;Q._isCameraConstrained&&(we>0&&(we=0),Q._isCameraConstrained=!1),ut!==void 0&&(Ze=ut),(we||(Qt=>T[Qt]&&!this._eventsInProgress[Qt])("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 bt=[0,0,0];if(me)if(Q.projection.name==="mercator"){const Qt=this._trackingEllipsoid.projectRay(Q.screenPointToMercatorRay(Ze).dir),Lt=this._trackingEllipsoid.projectRay(Q.screenPointToMercatorRay(Ze.sub(me)).dir);bt[0]=Lt[0]-Qt[0],bt[1]=Lt[1]-Qt[1]}else{const Qt=Q.pointCoordinate(Ze);if(Q.projection.name==="globe"){me=me.rotate(-Q.angle);const Lt=Q._pixelsPerMercatorPixel/Q.worldSize;bt[0]=-me.x*o.eF(o.bs(Qt.y))*Lt,bt[1]=-me.y*o.eF(Q.center.lat)*Lt}else{const Lt=Q.pointCoordinate(Ze.sub(me));Qt&&Lt&&(bt[0]=Lt.x-Qt.x,bt[1]=Lt.y-Qt.y)}}const vt=Q.zoom,Mt=[0,0,0];if(we){const Qt=oe(Qe||Q.pointCoordinate3D(Ze)),Lt={dir:o.c9([],o.cv([],Qt,Q._camera.position))};if(Lt.dir[2]<0){const ps=Q.zoomDeltaToMovement(Qt,we);o.dV(Mt,Lt.dir,ps)}}const es=o.dW(bt,bt,Mt);Q._translateCameraConstrained(es),we&&Math.abs(Q.zoom-vt)>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=M9(this._eventsInProgress),Q=M9(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 me={};let we;for(const Re in this._eventsInProgress){const{handlerName:Ze,originalEvent:Qe}=this._eventsInProgress[Re];this._handlersById[Ze].isActive()||(delete this._eventsInProgress[Re],we=T[Ze]||Qe,me[`${Re}end`]=we)}for(const Re in me)this._fireEvent(Re,me[Re]);const Me=M9(this._eventsInProgress);if(B&&(K||Q)&&!Me){this._updatingCamera=!0;const Re=this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions),Ze=Qe=>Qe!==0&&-this._bearingSnap{this._frameId=void 0,this.handleEvent(new DFe("renderFrame",{timeStamp:k})),this._applyChanges()})}_triggerRenderFrame(){this._frameId===void 0&&(this._frameId=this._requestFrame())}}const I9="map.setFreeCameraOptions(...) and map.getFreeCameraOptions() are not yet supported for non-mercator projections.";class zFe 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 me=k.clone(),we=this._extendCameraOptions(oe);me.bearing=K,me.pitch=Q;const Me=o.cZ.convert(T),Re=o.cZ.convert(B),Ze=.5*(Me.lat+Re.lat),Qe=.5*(Me.lng+Re.lng),ut=o.eJ(Ze,Qe),bt=o.c9([],ut),vt=o.c9([],o.eK([],bt,[0,1,0])),Mt=o.eK([],vt,bt),es=[vt[0],vt[1],vt[2],0,Mt[0],Mt[1],Mt[2],0,bt[0],bt[1],bt[2],0,0,0,0,1],Qt=[ut,o.eJ(Me.lat,Me.lng),o.eJ(Re.lat,Me.lng),o.eJ(Re.lat,Re.lng),o.eJ(Me.lat,Re.lng),o.eJ(Ze,Me.lng),o.eJ(Ze,Re.lng),o.eJ(Me.lat,Qe),o.eJ(Re.lat,Qe)];let Lt=o.eL.fromPoints(Qt.map(Hr=>[o.dY(vt,Hr),o.dY(Mt,Hr),o.dY(bt,Hr)]));const ps=o.bI([],Lt.center,es);o.eM(ps)===0&&o.eN(ps,0,0,1),o.c9(ps,ps),o.dV(ps,ps,o.cy),me.center=o.eO(ps);const Hs=me.getWorldToCameraMatrix(),Fs=o.aP(new Float64Array(16),Hs);Lt=o.eL.applyTransform(Lt,o.X([],Hs,es));const nn=this._extendAABB(Lt,me,we,K);if(!nn)return void o.w("Map cannot fit within canvas with the given bounds, padding, and/or offset.");Lt=nn,o.bI(ps,ps,Hs);const $s=.5*(Lt.max[2]-Lt.min[2]),rn=this._minimumAABBFrustumDistance(me,Lt),_n=o.dV([],[0,0,1],$s),Mn=o.dW(_n,ps,_n),Kn=rn+(me.pitch===0?0:o.eP(ps,Mn)),Bn=me.globeCenterInViewSpace,On=o.cv([],ps,[Bn[0],Bn[1],Bn[2]]);o.c9(On,On),o.dV(On,On,Kn);const Rr=o.dW([],ps,On);o.bI(Rr,Rr,Fs);const An=o.bk/o.cy,xr=o.es(Rr),sa=o.c4(Math.max(xr*An-o.bk,Number.EPSILON),0),ka=Math.min(me.zoomFromMercatorZAdjusted(sa),we.maxZoom);return ka>.5*(o.ef+o.b2)?(me.setProjection({name:"mercator"}),me.zoom=ka,this._cameraForBounds(me,T,B,K,Q,oe)):{center:me.center,zoom:ka,bearing:K,pitch:Q}}_extendAABB(k,T,B,K){const Q=.5*((B.padding.left||0)+(B.padding.right||0)),oe=.5*((B.padding.top||0)+(B.padding.bottom||0)),me=oe,we=Q,Me=Q,Re=oe,Ze=T.width-(we+Me),Qe=T.height-(me+Re),ut=o.cv([],k.max,k.min),bt=Math.min(Ze/ut[0],Qe/ut[1]),vt=Math.min(T.scaleZoom(T.scale*bt),B.maxZoom);if(isNaN(vt))return null;const Mt=T.scale/T.zoomScale(vt),es=new o.eL([k.min[0]-we*Mt,k.min[1]-Re*Mt,k.min[2]],[k.max[0]+Me*Mt,k.max[1]+me*Mt,k.max[2]]),Qt=(typeof B.offset.x=="number"&&typeof B.offset.y=="number"?new o.P(B.offset.x,B.offset.y):o.P.convert(B.offset)).rotate(-o.av(K));return es.center[0]-=Qt.x*Mt,es.center[1]+=Qt.y*Mt,es}queryTerrainElevation(k,T){const B=this.transform.elevation;return B?(T={exaggerated:!0,...T},B.getAtPoint(o.bT.fromLngLat(k),null,T.exaggerated)):null}_cameraForBounds(k,T,B,K,Q,oe){if(k.projection.name==="globe")return this._cameraForBoundsOnGlobe(k,T,B,K,Q,oe);const me=k.clone(),we=this._extendCameraOptions(oe);me.bearing=K,me.pitch=Q;const Me=o.cZ.convert(T),Re=o.cZ.convert(B),Ze=new o.cZ(Me.lng,Re.lat),Qe=new o.cZ(Re.lng,Me.lat),ut=me.project(Me),bt=me.project(Re),vt=this.queryTerrainElevation(Me),Mt=this.queryTerrainElevation(Re),es=this.queryTerrainElevation(Ze),Qt=this.queryTerrainElevation(Qe),Lt=[[ut.x,ut.y,Math.min(vt||0,Mt||0,es||0,Qt||0)],[bt.x,bt.y,Math.max(vt||0,Mt||0,es||0,Qt||0)]];let ps=o.eL.fromPoints(Lt);const Hs=me.getWorldToCameraMatrix(),Fs=o.aP(new Float64Array(16),Hs);ps=o.eL.applyTransform(ps,Hs);const nn=this._extendAABB(ps,me,we,K);if(!nn)return void o.w("Map cannot fit within canvas with the given bounds, padding, and/or offset.");ps=nn;const $s=.5*o.cv([],ps.max,ps.min)[2],rn=this._minimumAABBFrustumDistance(me,ps),_n=[0,0,1,0];o.c6(_n,_n,Hs),o.eQ(_n,_n);const Mn=o.dV([],_n,rn+$s),Kn=o.dW([],ps.center,Mn);o.bI(ps.center,ps.center,Fs),o.bI(Kn,Kn,Fs);const Bn=me.unproject(new o.P(ps.center[0],ps.center[1])),On=o.eR(me.projection,Bn),Rr=Math.pow(2,On),An=Math.min(me._zoomFromMercatorZ(Kn[2]*me.pixelsPerMeter*Rr/me.worldSize),we.maxZoom);return me.mercatorFromTransition&&An<.5*(o.ef+o.b2)?(me.setProjection({name:"globe"}),me.zoom=An,this._cameraForBounds(me,T,B,K,Q,oe)):{center:Bn,zoom:An,bearing:K,pitch:Q}}fitBounds(k,T,B){const K=this.cameraForBounds(k,T);return this._fitInternal(K,T,B)}fitScreenCoordinates(k,T,B,K,Q){const oe=o.P.convert(k),me=o.P.convert(T),we=new o.P(Math.min(oe.x,me.x),Math.min(oe.y,me.y)),Me=new o.P(Math.max(oe.x,me.x),Math.max(oe.y,me.y));if(this.transform.projection.name==="mercator"&&this.transform.anyCornerOffEdge(oe,me))return this;const Re=this.transform.pointLocation3D(we),Ze=this.transform.pointLocation3D(Me),Qe=this.transform.pointLocation3D(new o.P(we.x,Me.y)),ut=this.transform.pointLocation3D(new o.P(Me.x,we.y)),bt=[Math.min(Re.lng,Ze.lng,Qe.lng,ut.lng),Math.min(Re.lat,Ze.lat,Qe.lat,ut.lat)],vt=[Math.max(Re.lng,Ze.lng,Qe.lng,ut.lng),Math.max(Re.lat,Ze.lat,Qe.lat,ut.lat)],Mt=K&&K.pitch?K.pitch:this.getPitch(),es=this._cameraForBounds(this.transform,bt,vt,B,Mt,K);return this._fitInternal(es,K,Q)}_fitInternal(k,T,B){return k?(T=Object.assign(k,T)).linear?this.easeTo(T,B):this.flyTo(T,B):this}jumpTo(k,T){this._stop({keepGesture:"ifPointerDown"});const B=k.preloadOnly?this.transform.clone():this.transform;let K=!1,Q=!1,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 me=typeof k.padding=="number"?this._extendPadding(k.padding):k.padding;if(k.padding!=null&&!B.isPaddingEqual(me))if(k.retainPadding===!1){const we=B.clone();we.padding=me,B.setLocationAtPoint(B.center,we.centerPoint)}else B.padding=me;return k.preloadOnly?(this._preloadTiles(B),this):(this.fire(new o.h("movestart",T)).fire(new o.h("move",T)),K&&this.fire(new o.h("zoomstart",T)).fire(new o.h("zoom",T)).fire(new o.h("zoomend",T)),Q&&this.fire(new o.h("rotatestart",T)).fire(new o.h("rotate",T)).fire(new o.h("rotateend",T)),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(I9),this.transform.getFreeCameraOptions()}setFreeCameraOptions(k,T){const B=this.transform;if(!B.projection.supportsFreeCamera)return o.w(I9),this;this.stop();const K=B.zoom,Q=B.pitch,oe=B.bearing;B.setFreeCameraOptions(k);const me=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)),me&&this.fire(new o.h("zoomstart",T)).fire(new o.h("zoom",T)).fire(new o.h("zoomend",T)),Me&&this.fire(new o.h("rotatestart",T)).fire(new o.h("rotate",T)).fire(new o.h("rotateend",T)),we&&this.fire(new o.h("pitchstart",T)).fire(new o.h("pitch",T)).fire(new o.h("pitchend",T)),this.fire(new o.h("moveend",T)),this}easeTo(k,T){this._stop({easeId:k.easeId}),((k={offset:[0,0],duration:500,easing:o.eE,...k}).animate===!1||this._prefersReducedMotion(k))&&(k.duration=0);const B=this.transform,K=this.getZoom(),Q=this.getBearing(),oe=this.getPitch(),me=this.getPadding(),we=this.getVerticalFieldOfView(),Me="zoom"in k?+k.zoom:K,Re="bearing"in k?this._normalizeBearing(k.bearing,Q):Q,Ze="pitch"in k?+k.pitch:oe,Qe="fov"in k?+k.fov:we,ut=this._extendPadding(k.padding),bt=o.P.convert(k.offset);let vt,Mt,es;if(B.projection.name==="globe"){const Bn=o.bT.fromLngLat(B.center),On=bt.rotate(-B.angle);Bn.x+=On.x/B.worldSize,Bn.y+=On.y/B.worldSize;const Rr=Bn.toLngLat(),An=o.cZ.convert(k.center||Rr);this._normalizeCenter(An),vt=B.centerPoint.add(On),Mt=new o.P(Bn.x,Bn.y).mult(B.worldSize),es=new o.P(o.a7(An.lng),o.a8(An.lat)).mult(B.worldSize).sub(Mt)}else{vt=B.centerPoint.add(bt);const Bn=B.pointLocation(vt),On=o.cZ.convert(k.center||Bn);this._normalizeCenter(On),Mt=B.project(Bn),es=B.project(On).sub(Mt)}const Qt=B.zoomScale(Me-K);let Lt,ps;k.around&&(Lt=o.cZ.convert(k.around),ps=B.locationPoint(Lt));const Hs=this._zooming||Me!==K,Fs=this._rotating||Q!==Re,nn=this._pitching||Ze!==oe,$s=Qe!==we,rn=!B.isPaddingEqual(ut),_n=k.retainPadding===!1?B.clone():B,Mn=Bn=>On=>{if(Hs&&(Bn.zoom=o.am(K,Me,On)),Fs&&(Bn.bearing=o.am(Q,Re,On)),nn&&(Bn.pitch=o.am(oe,Ze,On)),$s&&(Bn.fov=o.am(we,Qe,On)),rn&&(_n.interpolatePadding(me,ut,On),vt=_n.centerPoint.add(bt)),Lt)Bn.setLocationAtPoint(Lt,ps);else{const Rr=Bn.zoomScale(Bn.zoom-K),An=Me>K?Math.min(2,Qt):Math.max(.5,Qt),xr=Math.pow(An,1-On),sa=Bn.unproject(Mt.add(es.mult(On*xr)).mult(Rr));Bn.setLocationAtPoint(Bn.renderWorldCopies?sa.wrap():sa,vt)}return k.preloadOnly||this._fireMoveEvents(T),Bn};if(k.preloadOnly){const Bn=this._emulate(Mn,k.duration,B);return this._preloadTiles(Bn),this}const Kn={moving:this._moving,zooming:this._zooming,rotating:this._rotating,pitching:this._pitching};return this._zooming=Hs,this._rotating=Fs,this._pitching=nn,this._padding=rn,this._easeId=k.easeId,this._prepareEase(T,k.noMoveStart,Kn),this._ease(Mn(B),Bn=>{B.cameraElevationReference==="sea"&&B.recenterOnTerrain(),this._afterEase(T,Bn)},k),this}_prepareEase(k,T,B={}){this._moving=!0,this.transform.cameraElevationReference="sea",this.transform._orthographicProjectionAtLowPitch&&this.transform.pitch===0&&this.transform.projection.name!=="globe"&&(this.transform.cameraElevationReference="ground"),T||B.moving||this.fire(new o.h("movestart",k)),this._zooming&&!B.zooming&&this.fire(new o.h("zoomstart",k)),this._rotating&&!B.rotating&&this.fire(new o.h("rotatestart",k)),this._pitching&&!B.pitching&&this.fire(new o.h("pitchstart",k))}_fireMoveEvents(k){this.fire(new o.h("move",k)),this._zooming&&this.fire(new o.h("zoom",k)),this._rotating&&this.fire(new o.h("rotate",k)),this._pitching&&this.fire(new o.h("pitch",k))}_afterEase(k,T){if(this._easeId&&T&&this._easeId===T)return;this._easeId=void 0,this.transform.cameraElevationReference="ground";const B=this._zooming,K=this._rotating,Q=this._pitching;this._moving=!1,this._zooming=!1,this._rotating=!1,this._pitching=!1,this._padding=!1,B&&this.fire(new o.h("zoomend",k)),K&&this.fire(new o.h("rotateend",k)),Q&&this.fire(new o.h("pitchend",k)),this.fire(new o.h("moveend",k))}flyTo(k,T){if(this._prefersReducedMotion(k)){const Wr=o.cB(k,["center","zoom","bearing","pitch","fov","around","padding","retainPadding"]);return this.jumpTo(Wr,T)}this.stop(),k={offset:[0,0],speed:1.2,curve:1.42,easing:o.eE,...k};const B=this.transform,K=this.getZoom(),Q=this.getBearing(),oe=this.getPitch(),me=this.getPadding(),we=this.getVerticalFieldOfView(),Me="zoom"in k?o.b1(+k.zoom,B.minZoom,B.maxZoom):K,Re="bearing"in k?this._normalizeBearing(k.bearing,Q):Q,Ze="pitch"in k?+k.pitch:oe,Qe="fov"in k?+k.fov:we,ut=Qe!==we,bt=this._extendPadding(k.padding),vt=B.zoomScale(Me-K),Mt=o.P.convert(k.offset);let es=B.centerPoint.add(Mt);const Qt=B.pointLocation(es),Lt=o.cZ.convert(k.center||Qt);this._normalizeCenter(Lt);const ps=B.project(Qt),Hs=B.project(Lt).sub(ps);let Fs=k.curve;const nn=Math.max(B.width,B.height),$s=nn/vt,rn=Hs.mag();if("minZoom"in k){const Wr=o.b1(Math.min(k.minZoom,K,Me),B.minZoom,B.maxZoom),Tr=nn/B.zoomScale(Wr-K);Fs=Math.sqrt(Tr/rn*2)}const _n=Fs*Fs;function Mn(Wr){const Tr=($s*$s-nn*nn+(Wr?-1:1)*_n*_n*rn*rn)/(2*(Wr?$s:nn)*_n*rn);return Math.log(Math.sqrt(Tr*Tr+1)-Tr)}function Kn(Wr){return(Math.exp(Wr)-Math.exp(-Wr))/2}function Bn(Wr){return(Math.exp(Wr)+Math.exp(-Wr))/2}const On=Mn(0);let Rr=function(Wr){return Bn(On)/Bn(On+Fs*Wr)},An=function(Wr){return nn*((Bn(On)*(Kn(Tr=On+Fs*Wr)/Bn(Tr))-Kn(On))/_n)/rn;var Tr},xr=(Mn(1)-On)/Fs;if(Math.abs(rn)<1e-6||!isFinite(xr)){if(Math.abs(nn-$s)<1e-6)return this.easeTo(k,T);const Wr=$sk.maxDuration&&(k.duration=0);const sa=Q!==Re,ka=Ze!==oe,Hr=!B.isPaddingEqual(bt),ea=k.retainPadding===!1?B.clone():B,si=Wr=>Tr=>{const Gr=Tr*xr,Ga=1/Rr(Gr);Wr.zoom=Tr===1?Me:K+Wr.scaleZoom(Ga),sa&&(Wr.bearing=o.am(Q,Re,Tr)),ka&&(Wr.pitch=o.am(oe,Ze,Tr)),ut&&(Wr.fov=o.am(we,Qe,Tr)),Hr&&(ea.interpolatePadding(me,bt,Tr),es=ea.centerPoint.add(Mt));const qr=Tr===1?Lt:Wr.unproject(ps.add(Hs.mult(An(Gr))).mult(Ga));return Wr.setLocationAtPoint(Wr.renderWorldCopies?qr.wrap():qr,es),Wr._updateCameraOnTerrain(),k.preloadOnly||this._fireMoveEvents(T),Wr};if(k.preloadOnly){const Wr=this._emulate(si,k.duration,B);return this._preloadTiles(Wr),this}return this._zooming=!0,this._rotating=sa,this._pitching=ka,this._padding=Hr,this._prepareEase(T,!1),this._ease(si(B),()=>this._afterEase(T),k),this}isEasing(){return!!this._easeFrameId}stop(){return this._stop()}_requestRenderFrame(k){}_cancelRenderFrame(k){}_stop({easeId:k,keepGesture:T}={}){if(this._easeFrameId&&(this._cancelRenderFrame(this._easeFrameId),this._easeFrameId=void 0,this._onEaseFrame=void 0),this._onEaseEnd){const K=this._onEaseEnd;this._onEaseEnd=void 0,K.call(this,k)}const B=this.handlers;return B&&B.stop(T),this}_ease(k,T,B){B.animate===!1||B.duration===0?(k(1),T()):(this._easeStart=o.e.now(),this._easeOptions=B,this._onEaseFrame=k,this._onEaseEnd=T,this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback))}_renderFrameCallback(){const k=Math.min((o.e.now()-this._easeStart)/this._easeOptions.duration,1),T=this._onEaseFrame;T&&T(this._easeOptions.easing(k)),k<1?this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback):this.stop()}_normalizeBearing(k,T){k=o.d7(k,-180,180);const B=Math.abs(k-T);return Math.abs(k-360-T)180?-360:B<-180?360:0}_prefersReducedMotion(k){return this._respectPrefersReducedMotion&&o.e.prefersReducedMotion&&!(k&&k.essential)}_emulate(k,T,B){const K=Math.ceil(15*T/1e3),Q=[],oe=k(B.clone());for(let me=0;me<=K;me++){const we=oe(me/K);Q.push(we.clone())}return Q}_preloadTiles(k,T){}}const boe=/^(https?:|mailto:)/i;class QT{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(me=>{const we=me.textContent||"";if(me.tagName!=="A")return void me.replaceWith(...me.childNodes);const Me=me.getAttribute("href");if(!Me||!boe.test(Me))return void me.replaceWith(oe.createTextNode(we));const Re=oe.createElement("a");Re.href=Me,Re.textContent=we,Re.rel="noopener nofollow";const Ze=me.getAttribute("class");Ze&&(Re.className=Ze),me.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 _oe{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 JT{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 woe={"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 V6 extends o.h{constructor(k,T,B,K){const{point:Q,lngLat:oe,originalEvent:me,target:we}=k;super(k.type,{point:Q,lngLat:oe,originalEvent:me,target:we}),this.preventDefault=()=>{k.preventDefault()},this.id=T,this.interaction=B,this.feature=K}}class L9{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 me=new Set;for(const we of T){for(const[Me,Re]of K){if(!Re.target)continue;const Ze=we.variants?we.variants[Me]:null;if(Ze){for(const Qe of Ze){if(Xd(Qe,we,me,Me))continue;const ut=new o.dP(we,Qe),bt=ig(Qe,we,Me);Q&&ut.id!==void 0&&(ut.state=this.map.getFeatureState(ut));const vt=B?this.prevHoveredFeatures.get(bt):null,Mt=new V6(k,Me,Re,ut),es=vt?vt.stop:Re.handler(Mt);if(B&&this.hoveredFeatures.set(bt,{feature:we,stop:es}),es!==!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 V6(k,we,Me,null))!==!1)break}}}function H6(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 joe=/matrix.*\((.+)\)/,Noe={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"},G6={showCompass:!0,showZoom:!0,visualizePitch:!1};class xY{constructor(k,T,B=!1){this._clickTolerance=10,this.element=T,this.mouseRotate=new $6({clickTolerance:k.dragRotate._mouseRotate._clickTolerance}),this.map=k,B&&(this.mousePitch=new A9({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),me=oe&&oe.pitchDelta;me&&B.setPitch(B.getPitch()+me)}}off(){const k=this.element;k.removeEventListener("mousedown",this.mousedown),k.removeEventListener("touchstart",this.touchstart),k.removeEventListener("touchmove",this.touchmove),k.removeEventListener("touchend",this.touchend),k.removeEventListener("touchcancel",this.reset),this.offTemp()}offTemp(){S(),window.removeEventListener("mousemove",this.mousemove),window.removeEventListener("mouseup",this.mouseup)}mousedown(k){this.down({...k,button:k.button,type:k.type,ctrlKey:!0,preventDefault:()=>k.preventDefault()},I(this.element,k)),window.addEventListener("mousemove",this.mousemove),window.addEventListener("mouseup",this.mouseup)}mousemove(k){this.move(k,I(this.element,k))}mouseup(k){this.mouseRotate.mouseupWindow(k),this.mousePitch&&this.mousePitch.mouseupWindow(k),this.offTemp()}touchstart(k){k.targetTouches.length!==1?this.reset():(this._startPos=this._lastPos=P(this.element,k.targetTouches)[0],this.down({type:"mousedown",button:0,ctrlKey:!0,preventDefault:()=>k.preventDefault()},this._startPos))}touchmove(k){k.targetTouches.length!==1?this.reset():(this._lastPos=P(this.element,k.targetTouches)[0],this.move({buttons:1,preventDefault:()=>k.preventDefault()},this._lastPos))}touchend(k){k.targetTouches.length===0&&this._startPos&&this._lastPos&&this._startPos.dist(this._lastPos)T.width||k.y>T.height;T.locationPoint3D(B).distSqr(k)180;){const B=T.locationPoint3D(L);if(B.x>=0&&B.y>=0&&B.x<=T.width&&B.y<=T.height)break;L.lng>T.center.lng?L.lng-=360:L.lng+=360}return L}const W6={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%)"},vY=/\s+/,pf={rotation:0,rotationAlignment:"auto",pitchAlignment:"auto",occludedOpacity:.2,altitude:0};class Hk 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:me=0,rotation:we=pf.rotation,rotationAlignment:Me=pf.rotationAlignment,pitchAlignment:Re=pf.pitchAlignment,occludedOpacity:Ze=pf.occludedOpacity,altitude:Qe=pf.altitude}=k||{};this._anchor=B,this._color=K,this._scale=Q,this._draggable=oe,this._clickTolerance=me,this._rotation=we,this._rotationAlignment=Me,this._pitchAlignment=Re,this._occludedOpacity=Ze,this._altitude=Qe,this._state="inactive",this._isDragging=!1,this._pointerEvents=null,this._updateMoving=()=>this._update(!0),k&&k.element?(this._element=k.element,this._offset=o.P.convert(k&&k.offset||[0,0])):(this._defaultMarker=!0,this._element=this._createDefaultMarker(),this._offset=o.P.convert(k&&k.offset||[0,-14])),this._element.hasAttribute("aria-label")||this._element.setAttribute("aria-label","Map marker"),this._element.hasAttribute("role")||this._element.setAttribute("role","img"),this._element.classList.add("mapboxgl-marker"),this._element.addEventListener("dragstart",bt=>{bt.preventDefault()}),this._element.addEventListener("mousedown",bt=>{bt.preventDefault()});const ut=this._element.classList;for(const bt in W6)ut.remove(`mapboxgl-marker-anchor-${bt}`);ut.add(`mapboxgl-marker-anchor-${this._anchor}`),k&&k.className&&ut.add(...k.className.trim().split(vY)),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) ${W6[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 me=K/oe;return`rotateX(${-Q.y*me}deg) rotateY(${Q.x*me}deg)`}_calculateZTransform(){const k=this._pos,T=this._map;if(!T||!k)return"";let B=0;const K=this.getRotationAlignment();if(K==="map")if(T._showingGlobe()){const Q=T.project(new o.cZ(this._lngLat.lng,this._lngLat.lat+.001),this._altitude),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 me=k.sub(oe),we=o.fa(Math.atan2(me.y,me.x));B=(we>90?we-270:we+90)*(1-Q)}return B+=this._rotation,B?`rotateZ(${B}deg)`:""}_update(k){cancelAnimationFrame(this._updateFrameId);const T=this._map;T&&(T.transform.renderWorldCopies&&(this._lngLat=yY(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}`,V_=["waiting","active","active-error","background","background-error"].map(Hv),nj={positionOptions:{enableHighAccuracy:!1,maximumAge:0,timeout:6e3},fitBoundsOptions:{maxZoom:15},trackUserLocation:!1,showAccuracyCircle:!0,showUserLocation:!0,showUserHeading:!1,showButton:!0,followUserLocation:!0},D3={maxWidth:100,unit:"metric"},eM={kilometer:"km",meter:"m",mile:"mi",foot:"ft","nautical-mile":"nm"},_Y=/\s+/,Il={closeButton:!0,closeOnClick:!0,focusAfterOpen:!0,className:"",maxWidth:"240px",altitude:0},H_=["a[href]","[tabindex]:not([tabindex='-1'])","[contenteditable]:not([contenteditable='false'])","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])"].join(", ");function K6(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 Jd=typeof document<"u"?document.currentScript:null;return o.fd(Jd&&Jd.src&&o.fe(Jd.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 zFe{constructor(L){o.eT.mark(o.eU.create);const k=L;if((L={...Noe,...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={...woe,...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 JT(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 OFe(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 q_(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 QT({customAttribution:L.customAttribution})),this._logoControl=new _oe,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 L9(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(me=>this.getLayer(me));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 me=B(oe.point);me.length?K||(K=!0,T.call(this,new Sl(L,this,oe.originalEvent,{features:me}))):K=!1},mouseout:()=>{K=!1}}}}if(L==="mouseleave"||L==="mouseout"){let K=!1;return{listener:T,targets:k,delegates:{mousemove:me=>{B(me.point).length?K=!0:K&&(K=!1,T.call(this,new Sl(L,this,me.originalEvent)))},mouseout:me=>{K&&(K=!1,T.call(this,new Sl(L,this,me.originalEvent)))}}}}{const K=Q=>{const 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 up(this,T).load(L),this.style.setEventedParent(this,{style:this.style})}return this._updateTerrain(),this}_lazyInitEmptyStyle(){this.style||(this.style=new up(this,{}),this.style.setEventedParent(this,{style:this.style}),this.style.loadEmpty())}getStyle(){if(this.style)return this.style.serialize()}isStyleLoaded(){return this.style?this.style.loaded():(o.w("There is no style added to the map."),!1)}_isValidId(L){return L==null?(this.fire(new o.f(new Error("IDs can't be empty."))),!1):o.dI(L)?(this.fire(new o.f(new Error(`IDs can't contain special symbols: "${L}".`))),!1):L!=="__proto__"&&L!=="constructor"&&L!=="prototype"||(this.fire(new o.f(new Error(`IDs can't be "${L}".`))),!1)}_isTargetValid(L){return"featuresetId"in L?this._isValidId("importId"in L?L.importId:L.featuresetId):"layerId"in L&&this._isValidId(L.layerId)}_areTargetsValid(L){if(Array.isArray(L)){for(const k of L)if(!this._isValidId(k))return!1;return!0}return this._isTargetValid(L)}addSource(L,k){return this._isValidId(L)?(this._lazyInitEmptyStyle(),this.style.addSource(L,k),this._update(!0)):this}isSourceLoaded(L){return!!this._isValidId(L)&&!!this.style&&this.style._isSourceCacheLoaded(L)}areTilesLoaded(){return this.style.areTilesLoaded()}removeSource(L){return this._isValidId(L)?(this.style.removeSource(L),this._updateTerrain(),this._update(!0)):this}getSource(L){return this._isValidId(L)?this.style.getOwnSource(L):null}addImage(L,k,{pixelRatio:T=1,sdf:B=!1,stretchX:K,stretchY:Q,content:oe}={}){this._lazyInitEmptyStyle();const me=o.I.from(L);if(k instanceof HTMLImageElement||ImageBitmap&&k instanceof ImageBitmap){const{width:we,height:Me,data:Re}=o.e.getImageData(k);this.style.addImage(me,{data:new o.b({width:we,height:Me},Re),pixelRatio:T,stretchX:K,stretchY:Q,content: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(me,{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:me}=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(me)),B.usvg=!1,B.icon=void 0,Me=!0):B.data.replace(me,we),this.style.updateImage(T,B,Me)}hasImage(L){return L?!!this.style&&!!this.style.getImage(o.I.from(L)):(this.fire(new o.f(new Error("Missing required image id"))),!1)}removeImage(L){this.style.removeImage(o.I.from(L))}loadImage(L,k){(async()=>{const T=await this._requestManager.transformRequest(L,o.R.Image),{data:B}=await o.a(T);return B})().then(T=>k(null,T)).catch(k)}listImages(){return this.style.listImages().map(L=>L.name)}addModel(L,k){this._lazyInitEmptyStyle(),this.style.addModel(L,k)}hasModel(L){return L?this.style.hasModel(L):(this.fire(new o.f(new Error("Missing required model id"))),!1)}removeModel(L){this.style.removeModel(L)}listModels(){return this.style.listModels()}addLayer(L,k){return this._isValidId(L.id)?(this._lazyInitEmptyStyle(),this.style.addLayer(L,k),this._update(!0)):this}getSlot(L){const k=this.getLayer(L);return k&&k.slot||null}setSlot(L,k){return this.style.setSlot(L,k),this.style.mergeLayers(),this._update(!0)}addImport(L,k){return this._isValidId(L.id)?(this.style.addImport(L,k).catch(T=>this.fire(new o.f(new Error("Failed to add import",T)))),this):this}updateImport(L,k){return typeof k!="string"&&k.id!==L?(this.removeImport(L),this.addImport(k)):(this.style.updateImport(L,k),this._update(!0))}removeImport(L){return this.style.removeImport(L),this}moveImport(L,k){return this.style.moveImport(L,k),this._update(!0)}moveLayer(L,k){return this._isValidId(L)?(this.style.moveLayer(L,k),this._update(!0)):this}removeLayer(L){return this._isValidId(L)?(this.style.removeLayer(L),this._update(!0)):this}getLayer(L){if(!this._isValidId(L))return null;const k=this.style.getOwnLayer(L);return k?k.type==="custom"?k.implementation:k.serialize():void 0}getSlots(){return this.style.getSlots()}setLayerZoomRange(L,k,T){return this._isValidId(L)?(this.style.setLayerZoomRange(L,k,T),this._update(!0)):this}setFilter(L,k,T={}){return this._isValidId(L)?(this.style.setFilter(L,k,T),this._update(!0)):this}getFilter(L){return this._isValidId(L)?this.style.getFilter(L):null}setPaintProperty(L,k,T,B={}){return this._isValidId(L)?(this.style.setPaintProperty(L,k,T,B),this._update(!0)):this}getPaintProperty(L,k){return this._isValidId(L)?this.style.getPaintProperty(L,k):null}setLayoutProperty(L,k,T,B={}){return this._isValidId(L)?(this.style.setLayoutProperty(L,k,T,B),this._update(!0)):this}getLayoutProperty(L,k){return this._isValidId(L)?this.style.getLayoutProperty(L,k):null}getLayerProperty(L,k){return this._isValidId(L)?this.style.getLayerProperty(L,k):null}setLayerProperty(L,k,T,B={}){return this._isValidId(L)?(k==="appearances"&&this._postAddingAppearancesToStyleEvent(),this.style.setLayerProperty(L,k,T,B),this._update(!0)):this}getGlyphsUrl(){return this.style.getGlyphsUrl()}setGlyphsUrl(L){return this.style.setGlyphsUrl(L),this._update(!0)}getSchema(L){return this.style.getSchema(L)}setSchema(L,k){return this.style.setSchema(L,k),this._update(!0)}getConfig(L){return this.style.getConfig(L)}setConfig(L,k){return this.style.setConfig(L,k),this._update(!0)}getConfigProperty(L,k){return this.style.getConfigProperty(L,k)}setConfigProperty(L,k,T){return this.style.setConfigProperty(L,k,T),this._update(!0)}getFeaturesetDescriptors(L){return this.style.getFeaturesetDescriptors(L)}setLights(L){if(this._lazyInitEmptyStyle(),L&&L.length===1&&L[0].type==="flat"){const k=L[0];k.properties?this.style.setFlatLight(k.properties,k.id,{}):this.style.setFlatLight({},"flat")}else this.style.setLights(L),this.painter.terrain&&(this.painter.terrain.invalidateRenderCache=!0);return this._update(!0)}getLights(){const L=this.style.getLights()||[];return L.length===0&&L.push({id:this.style.light.id,type:"flat",properties:this.style.getFlatLight()}),L}setLight(L,k={}){return console.log("The `map.setLight` function is deprecated, prefer using `map.setLights` with `flat` light type instead."),this.setLights([{id:"flat",type:"flat",properties:L}])}getLight(){return console.log("The `map.getLight` function is deprecated, prefer using `map.getLights` instead."),this.style.getFlatLight()}setTerrain(L){return this._lazyInitEmptyStyle(),!L&&this.transform.projection.requiresDraping?this.style.setTerrainForDraping():this.style.setTerrain(L),this._averageElevationLastSampledAt=-1/0,this._update(!0)}getTerrain(){return this.style?this.style.getTerrain():null}setFog(L){return this._lazyInitEmptyStyle(),this.style.setFog(L),this._update(!0)}getFog(){return this.style?this.style.getFog():null}setSnow(L){return this._lazyInitEmptyStyle(),this.style.setSnow(L),this._update(!0)}getSnow(){return this.style?this.style.getSnow():null}setRain(L){return this._lazyInitEmptyStyle(),this.style.setRain(L),this._update(!0)}getRain(){return this.style?this.style.getRain():null}setColorTheme(L){return this._lazyInitEmptyStyle(),this.style.setColorTheme(L),this._update(!0)}setImportColorTheme(L,k){return this._lazyInitEmptyStyle(),this.style.setImportColorTheme(L,k),this._update(!0)}setCamera(L){return this.style.setCamera(L),this._triggerCameraUpdate(L)}getNearClipOffset(){return this.transform.nearClipOffset}setNearClipOffset(L){const k=this.transform.nearClipOffset!==L;return this.transform.nearClipOffset=L,this._update(k)}_triggerCameraUpdate(L){return this._update(this.transform.setOrthographicProjectionAtLowPitch(L["camera-projection"]==="orthographic"))}getCamera(){return this.style.camera}_queryFogOpacity(L){return this.style&&this.style.fog?this.style.fog.getOpacityAtLatLng(o.cZ.convert(L),this.transform):0}setFeatureState(L,k){return L.source&&!this._isValidId(L.source)?this:(this.style.setFeatureState(L,k),this._update())}removeFeatureState(L,k){return L.source&&!this._isValidId(L.source)?this:(this.style.removeFeatureState(L,k),this._update())}getFeatureState(L){return L.source&&!this._isValidId(L.source)?null:this.style.getFeatureState(L)}resetFeatureStates(L){return this.style.resetFeatureStates(L),this._update()}_selectIndoorFloor(L){this.style.indoorManager&&this.style.indoorManager.selectFloor(L)}_setIndoorActiveFloorsVisibility(L){this.style.indoorManager&&this.style.indoorManager.setActiveFloorsVisibility(L)}getIndoorTileOptions(L,k){return this.style&&this.style.isIndoorEnabled()&&this.style.indoorManager?this.style.indoorManager.getIndoorTileOptions(L,k):null}_updateContainerDimensions(){if(!this._container)return;const L=this._container.getBoundingClientRect().width||400,k=this._container.getBoundingClientRect().height||300;let T,B,K,Q=this._container;for(;Q&&(!B||!K);){const oe=window.getComputedStyle(Q).transform;oe&&oe!=="none"&&(T=oe.match(joe)[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 me=this._sourcesDirty||this._styleDirty||this._placementDirty||oe;if(me||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||me||(this._fullyLoaded=!0,o.eT.mark(o.eU.fullLoad),this._performanceMetricsCollection&&o.eZ(this._requestManager._customAccessToken,{width:this.painter.width,height:this.painter.height,interactionRange:this._interactionRange,visibilityHidden:this._visibilityHidden,terrainEnabled:this.painter.style.hasTerrain(),fogEnabled:!!this.painter.style.getFog(),projection:this.getProjection().name,zoom:this.transform.zoom,renderer:this.painter.context.renderer,vendor:this.painter.context.vendor}),this._authenticate())}_forceMarkerAndPopupUpdate(L){for(const k of this._markers)L&&!this.getRenderWorldCopies()&&(k._lngLat=k._lngLat.wrap()),k._update();for(const k of this._popups)!L||this.getRenderWorldCopies()||k._trackPointer||(k._lngLat=k._lngLat.wrap()),k._update()}_updateAverageElevation(L,k=!1){const T=K=>(this.transform.averageElevation=K,this._update(!1),!0);if(!this.painter.averageElevationNeedsEasing())return this.transform.averageElevation!==0&&T(0);const B=this.transform.elevation&&this.transform.elevation.exaggeration()!==this._averageElevationExaggeration;if(B||(k||L-this._averageElevationLastSampledAt>500)&&!this._averageElevation.isEasing(L)){const K=this.transform.averageElevation;let Q=this.transform.sampleAverageElevation();this.transform.elevation!=null&&(this._averageElevationExaggeration=this.transform.elevation.exaggeration()),isNaN(Q)?Q=0:this._averageElevationLastSampledAt=L;const 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 _oe&&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={...G6,...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 xY(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,...nj,...L},o.aW(["_onSuccess","_onError","_onZoom","_finish","_setupUI","_updateCamera","_updateMarker","_updateMarkerRotation","_onDeviceOrientation"],this),this._updateMarkerRotationThrottled=hh(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(...V_);for(const T of bY[L])k.add(Hv(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(Hv("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??nj.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??nj.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??nj.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??nj.fitBoundsOptions,this}setShowUserLocation(L){return this.options.showUserLocation=L??nj.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 Hk({element:this._dotElement,rotationAlignment:"map",pitchAlignment:"map"}),this._circleElement=g("div","mapboxgl-user-location-accuracy-circle"),this._accuracyCircleMarker=new Hk({element:this._circleElement,pitchAlignment:"map"})}_clearWatch(){this._clearRequestTimeout(),this.options.geolocation.clearWatch(this._geolocationWatchID),this._removeDeviceOrientationListener(),this._geolocationWatchID=void 0,this._geolocateButton.classList.remove(Hv("waiting")),this._geolocateButton.setAttribute("aria-pressed","false"),this.options.showUserLocation&&this._updateMarker(null)}},AttributionControl:QT,ScaleControl:class{constructor(L={}){this.options={...D3,...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 me=3.2808*oe;me>5280?this._setScale(L,me/5280,"mile"):this._setScale(L,me,"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 me=Q/oe;return me=me>=10?10:me>=5?5:me>=3?3:me>=2?2:me>=1?1:function(we){const Me=Math.pow(10,Math.ceil(-Math.log(we)/Math.LN10));return Math.round(we*Me)/Me}(me),oe*me}(k),K=B/k;this._container.innerHTML=T!=="nautical-mile"?new Intl.NumberFormat(this._language,{style:"unit",unitDisplay:"short",unit:T}).format(B):`${B} ${eM[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(_Y):[])}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(me)return"bottom-right"}return oe?"left":me?"right":"bottom"}_updateClassList(){const L=this._container;if(!L)return;const k=[...this._classList];k.push("mapboxgl-popup"),this._anchor&&k.push(`mapboxgl-popup-anchor-${this._anchor}`),this._trackPointer&&k.push("mapboxgl-popup-track-pointer"),L.className=k.join(" ")}_update(L){const k=this._map,T=this._content;if(!k||!this._lngLat&&!this._trackPointer||!T)return;let B=this._container;if(B||(B=this._container=g("div","mapboxgl-popup",k.getContainer()),this._tip=g("div","mapboxgl-popup-tip",B),B.appendChild(T)),this.options.maxWidth&&B.style.maxWidth!==this.options.maxWidth&&(B.style.maxWidth=this.options.maxWidth),k.transform.renderWorldCopies&&!this._trackPointer&&(this._lngLat=yY(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=K6(this.options.offset),oe=this._anchor=this._getAnchor(Q.y),me=K6(this.options.offset,oe),we=K.add(me).round();k._requestDomTask(()=>{this._container&&oe&&(this._container.style.transform=`${W6[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(H_);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:Hk,Style:up,LngLat:o.cZ,LngLatBounds:o.eI,Point:o.P,MercatorCoordinate:o.bT,FreeCameraOptions:o.ff,Evented:o.E,config:o.eS,prewarm:function(){cu().acquire(ws)},clearPrewarmedResources:function(){const L=dh;L&&(L.isPreloaded()&&L.numActive()===1?(L.release(ws),dh=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 zt.workerUrl},set workerUrl(L){zt.workerUrl=L},get workerClass(){return zt.workerClass},set workerClass(L){zt.workerClass=L},get dracoUrl(){return o.fp()},set dracoUrl(L){o.fo(L)},get meshoptUrl(){return o.fn()},set meshoptUrl(L){o.fm(L)},get buildingGenUrl(){return o.fl()},set buildingGenUrl(L){o.fk(L)},setNow:o.e.setNow,restoreNow:o.e.restoreNow}});var l=a;return l})})(O7t);var jDs=O7t.exports;const wu=ru(jDs),Qyt={coming_soon:"#3B82F6",office_exclusive:"#6366F1",pre_market:"#06B6D4",active:"#10B981",price_improvement:"#F97316",under_contract:"#8B5CF6",sold:"#6B7280"},Jyt={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 NDs(s){return s>=1e6?`$${(s/1e6).toFixed(1)}M`:`$${(s/1e3).toFixed(0)}K`}function kDs({listings:s,isLoading:t}){const n=Xn(),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;wu.accessToken=l;const h=s.filter(g=>g.latitude!=null&&g.longitude!=null);let m=[-98.5795,39.8283],f=4;if(h.length>0){const g=h.reduce((y,v)=>y+v.longitude,0)/h.length,x=h.reduce((y,v)=>y+v.latitude,0)/h.length;m=[g,x],f=h.length===1?12:10}return a.current=new wu.Map({container:r.current,style:"mapbox://styles/mapbox/light-v11",zoom:f,center:m}),a.current.addControl(new wu.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=Qyt[m.status]||"#10B981",g=((S=m.photos)==null?void 0:S.find(I=>I.is_primary))||((A=m.photos)==null?void 0:A[0]),y=window.location.hostname==="listings.relevelup.com"||window.location.hostname.startsWith("listings.")?`/${m.slug||m.id}`:`/public/listing/${m.slug||m.id}`,v=document.createElement("div");v.className="cursor-pointer",v.innerHTML=`
`;const b=new wu.Popup({offset:25,closeButton:!0,maxWidth:"280px"}).setHTML(`
${g!=null&&g.photo_url?``:""}
${NDs(m.price)}
${m.property_address||""}
${m.city}, ${m.state}
${Jyt[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 wu.Marker(v).setLngLat([m.longitude,m.latitude]).setPopup(b).addTo(a.current);i.current.push(w)}),h.length>1){const m=new wu.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(Qyt).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:Jyt[h]})]},h))}),e.jsx("div",{ref:r,className:"w-full h-[500px] rounded-lg shadow-lg border border-gray-200"})]})}const u7e={active:"Active",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},SDs={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"},b$="#0d0d0d",e0t="#1a1a1a",Pu="#c9a84c",bM="#f0d78c";function B7t(){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}=aDs(),g=j.useMemo(()=>{if(!f)return[];const O=s.trim().toLowerCase(),U=[...f.cities.map(V=>({label:V.label,value:V.city,type:"city",count:V.count})),...f.neighborhoods.map(V=>({label:V.label,value:V.neighborhood,type:"neighborhood",count:V.count})),...f.zips.map(V=>({label:`ZIP ${V.label}`,value:V.zip,type:"zip",count:V.count}))];return(O?U.filter(V=>V.label.toLowerCase().includes(O)||V.value.toLowerCase().includes(O)):U).slice(0,8)},[f,s]);j.useEffect(()=>{const O=U=>{u.current&&!u.current.contains(U.target)&&o(!1)};return document.addEventListener("mousedown",O),()=>document.removeEventListener("mousedown",O)},[]);const{data:x,isLoading:y}=rDs({city:s||void 0,status:h.status||void 0,propertyType:h.propertyType||void 0,minPrice:h.minPrice?Number(h.minPrice):void 0,maxPrice:h.maxPrice?Number(h.maxPrice):void 0}),v=O=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(O),b=()=>{m({status:"",propertyType:"",minPrice:"",maxPrice:""}),t("")},w=s||h.status||h.propertyType||h.minPrice||h.maxPrice,S=typeof window<"u"&&(window.location.hostname==="listings.relevelup.com"||window.location.hostname.startsWith("listings.")),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(_e=>_e.status==="active"),W=U.length>0?U:O,V=new Intl.DateTimeFormat("en-CA",{timeZone:"America/New_York",year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date),[G,Y,X]=V.split("-").map(Number),ae=Math.floor(Date.UTC(G,Y-1,X)/864e5),le=W.length>0?W[ae%W.length]:void 0,ne=O.filter(_e=>!le||_e.id!==le.id),te=Array.from(new Set(O.map(_e=>_e.city).filter(Boolean))).slice(0,8),J=O.filter(_e=>(_e.price||0)>=1e6).length,ce=U.length;return{featured:le,restListings:ne,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:b$,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: ${Pu}; } .lu-gold-line { background: linear-gradient(90deg, transparent, ${Pu}, transparent); } .lu-card-hover { transition: transform .6s cubic-bezier(.2,.7,.2,1), box-shadow .6s; } .lu-card-hover:hover { transform: translateY(-6px); } .lu-img-zoom { transition: transform 1.2s cubic-bezier(.2,.7,.2,1); } .group:hover .lu-img-zoom { transform: scale(1.06); } .lu-hero-title { animation: luFadeUp 1.1s cubic-bezier(.2,.7,.2,1) both; } .lu-hero-sub { animation: luFadeUp 1.1s .15s cubic-bezier(.2,.7,.2,1) both; } .lu-hero-search { animation: luFadeUp 1.1s .3s cubic-bezier(.2,.7,.2,1) both; } .lu-hero-stats { animation: luFadeUp 1.1s .45s cubic-bezier(.2,.7,.2,1) both; } @keyframes luFadeUp { from { opacity: 0; transform: translateY(24px); } to { opacity: 1; transform: none; } } .lu-grain::after { content: ''; position: absolute; inset: 0; pointer-events: none; opacity: .18; background-image: url("data:image/svg+xml;utf8,"); } .lu-marquee { display: flex; gap: 3rem; animation: luMarquee 40s linear infinite; } @keyframes luMarquee { to { transform: translateX(-50%); } } .lu-input-dark { background: rgba(255,255,255,0.06) !important; border-color: rgba(201,168,76,0.25) !important; color: #fff !important; } .lu-input-dark::placeholder { color: rgba(255,255,255,0.5) !important; } `}),e.jsxs("header",{className:"sticky top-0 z-50 backdrop-blur-md",style:{backgroundColor:"rgba(13,13,13,0.75)",borderBottom:"1px solid rgba(201,168,76,0.15)"},children:[e.jsxs("div",{className:"max-w-7xl mx-auto px-6 py-4 flex items-center justify-between",children:[e.jsxs(wr,{to:"/",className:"flex items-center gap-3",children:[e.jsx("img",{src:SG,alt:"LevelUp",className:"h-7"}),e.jsx("span",{className:"hidden sm:inline-block h-5 w-px",style:{background:"rgba(255,255,255,0.2)"}}),e.jsx("span",{className:"hidden sm:inline lu-eyebrow lu-gold",children:"Listings"})]}),e.jsxs("nav",{className:"hidden md:flex items-center gap-8",children:[e.jsx("a",{href:"#featured",className:"text-sm text-white/80 hover:text-white transition",children:"Featured"}),e.jsx("a",{href:"#collection",className:"text-sm text-white/80 hover:text-white transition",children:"Collection"}),e.jsx("a",{href:"#map",className:"text-sm text-white/80 hover:text-white transition",children:"Map"}),e.jsx(wr,{to:"/home-value",className:"text-sm text-white/80 hover:text-white transition",children:"Home Value"}),e.jsx("a",{href:"https://relevelup.com",target:"_blank",rel:"noopener noreferrer",className:"text-sm px-4 py-2 rounded-full transition",style:{border:`1px solid ${Pu}`,color:Pu},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 ${Pu}`,color:Pu},"aria-label":"Toggle menu","aria-expanded":a,children:a?e.jsx(pr,{className:"w-5 h-5"}):e.jsx(ME,{className:"w-5 h-5"})})]}),a&&e.jsx("div",{className:"md:hidden border-t",style:{borderColor:"rgba(201,168,76,0.15)"},children:e.jsxs("nav",{className:"max-w-7xl mx-auto px-6 py-4 flex flex-col gap-1",children:[e.jsx("a",{href:"#featured",onClick:()=>i(!1),className:"py-3 text-white/85 hover:text-white transition border-b",style:{borderColor:"rgba(255,255,255,0.06)"},children:"Featured"}),e.jsx("a",{href:"#collection",onClick:()=>i(!1),className:"py-3 text-white/85 hover:text-white transition border-b",style:{borderColor:"rgba(255,255,255,0.06)"},children:"Collection"}),e.jsx("a",{href:"#map",onClick:()=>i(!1),className:"py-3 text-white/85 hover:text-white transition border-b",style:{borderColor:"rgba(255,255,255,0.06)"},children:"Map"}),e.jsx(wr,{to:"/home-value",onClick:()=>i(!1),className:"py-3 text-white/85 hover:text-white transition border-b",style:{borderColor:"rgba(255,255,255,0.06)"},children:"Home Value"}),e.jsx("a",{href:"https://relevelup.com",target:"_blank",rel:"noopener noreferrer",onClick:()=>i(!1),className:"mt-3 text-center text-sm px-4 py-3 rounded-full",style:{border:`1px solid ${Pu}`,color:Pu},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:wDs,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:Pu}}),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:bM},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 ${Pu}`,backdropFilter:"blur(12px)"},children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Zr,{className:"absolute left-6 top-1/2 -translate-y-1/2 h-5 w-5",style:{color:Pu}}),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(XI,{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:Pu,color:b$},onClick:()=>o(!1),children:[e.jsx(Zr,{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:Pu},children:"Suggestions"}),e.jsx("ul",{className:"max-h-80 overflow-y-auto",children:g.map((O,U)=>e.jsx("li",{children:e.jsxs("button",{type:"button",onMouseEnter:()=>d(U),onClick:()=>{t(O.value),o(!1)},className:"w-full flex items-center justify-between gap-3 px-5 py-3 text-left transition",style:{background:c===U?"rgba(201,168,76,0.12)":"transparent"},children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[O.type==="city"&&e.jsx(ci,{className:"h-4 w-4 shrink-0",style:{color:Pu}}),O.type==="neighborhood"&&e.jsx(ji,{className:"h-4 w-4 shrink-0",style:{color:Pu}}),O.type==="zip"&&e.jsx(va,{className:"h-4 w-4 shrink-0",style:{color:Pu}}),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(u7e).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(SDs).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(pr,{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:bM},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:e0t,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:Pu}})]},U))})}),E&&e.jsx("section",{id:"featured",className:"py-20 md:py-28",children:e.jsxs("div",{className:"max-w-7xl mx-auto px-6",children:[e.jsxs("div",{className:"flex items-end justify-between mb-10 md:mb-14",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[e.jsx(Nn,{className:"h-4 w-4",style:{color:Pu}}),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:bM},children:"standout"}),"."]})]}),e.jsx("div",{className:"hidden md:block h-px flex-1 mx-8 lu-gold-line"})]}),e.jsx(wr,{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:Pu,color:b$},children:u7e[E.status]||"Featured"})]}),e.jsxs("div",{className:"lg:col-span-2 flex flex-col justify-center",children:[e.jsxs("div",{className:"lu-eyebrow text-white/60 mb-4 flex items-center gap-2",children:[e.jsx(ci,{className:"h-3.5 w-3.5",style:{color:Pu}}),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:bM},children:v(E.price)}),e.jsxs("div",{className:"flex items-center gap-6 text-white/70 mb-8",children:[E.bedrooms&&e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(r2,{className:"h-4 w-4",style:{color:Pu}}),E.bedrooms," bd"]}),E.bathrooms&&e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(A0,{className:"h-4 w-4",style:{color:Pu}}),E.bathrooms," ba"]}),E.square_footage&&e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(j_,{className:"h-4 w-4",style:{color:Pu}}),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:Pu},children:["View Residence ",e.jsx(Qa,{className:"h-4 w-4"})]})]})]})})]})}),e.jsx("section",{id:"collection",className:"py-20 md:py-28",style:{background:e0t},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:Pu}}),e.jsx("span",{className:"lu-eyebrow lu-gold",children:"The Collection"}),e.jsx("span",{className:"h-px w-10",style:{background:Pu}})]}),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:bM},children:"carefully considered"}),"."]}),e.jsx("p",{className:"text-white/60 max-w-2xl mx-auto",children:"Browse the full catalogue of LevelUp-represented properties. Filter, refine, and find the one that feels like yours."})]}),y?e.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 gap-8",children:[...Array(6)].map((O,U)=>e.jsxs("div",{className:"space-y-3",children:[e.jsx(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,Y,X;const U=((W=O.photos)==null?void 0:W.find(ae=>ae.is_primary))||((V=O.photos)==null?void 0:V[0]);return e.jsxs(wr,{to: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:Pu,border:`1px solid ${Pu}`},children:u7e[O.status]}),e.jsxs("div",{className:"absolute bottom-4 left-4 right-4 flex items-center gap-4 text-white/90 text-sm opacity-0 group-hover:opacity-100 translate-y-2 group-hover:translate-y-0 transition-all",children:[O.bedrooms&&e.jsxs("span",{children:[O.bedrooms," bd"]}),O.bathrooms&&e.jsxs("span",{children:[O.bathrooms," ba"]}),O.square_footage&&e.jsxs("span",{children:[O.square_footage.toLocaleString()," sf"]})]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"lu-eyebrow text-white/50 mb-2 flex items-center gap-2",children:[e.jsx(ci,{className:"h-3 w-3",style:{color:Pu}}),O.city,O.state?`, ${O.state}`:""]}),e.jsx("div",{className:"lu-serif text-2xl md:text-3xl mb-1",style:{color:bM},children:v(O.price)}),O.property_address&&e.jsx("p",{className:"text-white/70 text-sm truncate",children:O.property_address}),((G=O.agent)==null?void 0:G.name)&&e.jsxs("p",{className:"text-white/40 text-xs mt-3 flex items-center gap-2",children:[e.jsx(ji,{className:"h-3 w-3"}),O.agent.name,(((Y=O.agent.brokerage)==null?void 0:Y.name)||O.agent.brokerage_name)&&e.jsxs("span",{className:"truncate",children:["· ",((X=O.agent.brokerage)==null?void 0:X.name)||O.agent.brokerage_name]})]})]})]},O.id)})}):e.jsxs("div",{className:"text-center py-20",children:[e.jsx("div",{className:"w-20 h-20 mx-auto mb-6 rounded-full flex items-center justify-center",style:{border:`1px solid ${Pu}`},children:e.jsx(va,{className:"h-8 w-8",style:{color:Pu}})}),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:Pu,color:b$},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:Pu}}),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:bM},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(kDs,{listings:x,isLoading:y})})]})}),e.jsxs("section",{className:"relative py-24 md:py-32 overflow-hidden lu-grain",children:[e.jsx("div",{className:"absolute inset-0",style:{background:`radial-gradient(ellipse at center, rgba(201,168,76,0.15) 0%, ${b$} 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:Pu}}),e.jsx("span",{className:"lu-eyebrow lu-gold",children:"For Agents"}),e.jsx("span",{className:"h-px w-10",style:{background:Pu}})]}),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:bM},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:Pu,color:b$},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:SG,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(FRs,{}),e.jsx(ORs,{})]})}const CDs=j.lazy(()=>ri(()=>import("./PublicHomeValue-BcSsbygA.js"),[]));function ADs(){const s=mu(),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(B7t,{}):r==="home-value"||r==="whats-my-home-worth"?e.jsx(j.Suspense,{fallback:e.jsx("div",{}),children:e.jsx(CDs,{})}):r.startsWith("public/")?null:e.jsx(Qtt,{slugOverride:r})}const EDs=j.lazy(()=>ri(()=>import("./CommercialMarketplace-CVy02Z-M.js"),[]));function TDs(){const t=mu().pathname.slice(1);return t?t.startsWith("public/")?null:e.jsx(Qtt,{slugOverride:t}):e.jsx(j.Suspense,{fallback:e.jsx("div",{className:"min-h-screen bg-[#0a0d12]"}),children:e.jsx(EDs,{})})}function qLe({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 $7t=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}),MDs=()=>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}}),PDs=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}),U7t=()=>{const s=Wt();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"]}),re.success("Agent card created")},onError:t=>re.error(t.message)})},q7t=()=>{const s=Wt();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"]}),re.success("Agent card updated")},onError:t=>re.error(t.message)})},ju=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:{}})},IDs=async(s,t)=>{const{error:n}=await q.from("agent_card_leads").insert({card_id:s,...t});if(n)throw n},V7t=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 VLe({open:s,onOpenChange:t,cardId:n,type:r,agentName:a}){const[i,l]=j.useState(""),[o,c]=j.useState(""),[d,u]=j.useState(""),[h,m]=j.useState(""),[f,g]=j.useState(""),[x,y]=j.useState(!1),v=async b=>{if(b.preventDefault(),!i.trim()){re.error("Please enter your name");return}y(!0);try{await IDs(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}),ju(n,"lead_submitted",r),q.functions.invoke("card-lead-notify",{body:{cardId:n,leadType:r,name:i.trim(),email:o.trim()||void 0,phone:d.trim()||void 0,message:f.trim()||void 0,intent:h||void 0}}).catch(w=>console.error("Card lead notify failed:",w)),re.success(r==="booking"?"Request sent! They'll be in touch soon.":r==="connect"?"Info shared! They'll be in touch soon.":"Referral submitted! Thank you."),t(!1),l(""),c(""),u(""),m(""),g("")}catch{re.error("Something went wrong. Please try again.")}finally{y(!1)}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-md rounded-2xl",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:r==="booking"?"Book a Call":r==="connect"?"Connect with Me":"Refer a Friend"}),e.jsx(Pr,{children:r==="booking"?`Let ${a} know you'd like to connect.`:r==="connect"?`Share your info and ${a} will reach out.`:`Know someone who could use ${a}'s help?`})]}),e.jsxs("form",{onSubmit:v,className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"lead-name",children:"Name *"}),e.jsx(pe,{id:"lead-name",value:i,onChange:b=>l(b.target.value),placeholder:"Your name",required:!0})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"lead-phone",children:"Phone"}),e.jsx(pe,{id:"lead-phone",type:"tel",value:d,onChange:b=>u(b.target.value),placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"lead-email",children:"Email"}),e.jsx(pe,{id:"lead-email",type:"email",value:o,onChange:b=>c(b.target.value),placeholder:"you@example.com"})]}),r==="booking"&&e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"lead-intent",children:"I'm looking to..."}),e.jsxs(ms,{value:h,onValueChange:m,children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Select one"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"buy",children:"Buy a home"}),e.jsx(Ge,{value:"sell",children:"Sell my home"}),e.jsx(Ge,{value:"both",children:"Buy & Sell"}),e.jsx(Ge,{value:"other",children:"Something else"})]})]})]}),r!=="connect"&&e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"lead-message",children:r==="referral"?"Tell us about them":"Message (optional)"}),e.jsx(pe,{id:"lead-message",value:f,onChange:b=>g(b.target.value),placeholder:r==="referral"?"Their name, phone, situation...":"Anything you'd like us to know"})]}),e.jsx($,{type:"submit",className:"w-full rounded-2xl",disabled:x,children:x?"Sending...":"Submit"})]})]})})}const LDs=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}),RDs=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}),DDs=()=>{const s=Wt();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]}),re.success("Block added")},onError:t=>re.error(t.message)})},FDs=()=>{const s=Wt();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"]}),re.success("Block updated")},onError:t=>re.error(t.message)})},ODs=()=>{const s=Wt();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"]}),re.success("Block removed")},onError:t=>re.error(t.message)})};function zDs(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 BDs(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 $Ds={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 UDs({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=BDs(n.video_url),i=r||!!a,l=r?zDs(n.video_url):a||n.video_url;return e.jsx("div",{className:$Ds[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 qDs={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 VDs({block:s,variant:t}){const r=s.config.testimonials||[],[a,i]=j.useState(0);if(r.length===0)return null;const l=qDs[t],o=r[a];return e.jsxs("div",{className:l.container,children:[e.jsxs("div",{className:l.card,children:[e.jsx(h2,{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 HDs={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 GDs({block:s,variant:t}){const r=s.config.tags||[];if(r.length===0)return null;const a=HDs[t];return e.jsx("div",{className:a.container,children:r.map((i,l)=>e.jsx("span",{className:a.tag,children:i},l))})}const WDs={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 KDs({block:s,cardId:t,variant:n}){const a=s.config.links||[];if(a.length===0)return null;const i=WDs[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:()=>ju(t,"button_click",`custom_link_${l.label}`),className:i.link,children:[e.jsx("span",{children:l.label}),e.jsx(Fr,{className:`h-4 w-4 ${i.icon}`})]},o))})}const nGe={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 YDs({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 XDs({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=nGe[l.platform.toLowerCase()];return!c||!l.url?null:e.jsx("a",{href:l.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>ju(t,"button_click",`social_${l.platform}`),className:i.linkClass,title:c.label,children:e.jsx(YDs,{path:c.icon,color:c.color})},o)})})]})}function HLe({cardId:s,variant:t}){const{data:n}=LDs(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(UDs,{block:l,variant:t},l.id);case"testimonials":return e.jsx(VDs,{block:l,variant:t},l.id);case"specialties":return e.jsx(GDs,{block:l,variant:t},l.id);case"custom_links":return e.jsx(KDs,{block:l,cardId:s,variant:t},l.id);default:return null}}),i&&e.jsx(XDs,{block:i,cardId:s,variant:t})]})}async function QDs(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 JDs(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 GLe(s){const{first:t,last:n}=JDs(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 QDs(s.avatarUrl);if(o){const d={"image/jpeg":"JPEG","image/jpg":"JPEG","image/png":"PNG","image/gif":"GIF","image/webp":"JPEG"}[o.mimeType]||"JPEG";r.push(`PHOTO;ENCODING=b;TYPE=${d}:${o.base64}`)}}r.push("END:VCARD");const a=new Blob([r.join(`\r `)],{type:"text/vcard"}),i=URL.createObjectURL(a),l=document.createElement("a");l.href=i,l.download=`${s.name.replace(/\s+/g,"_")}.vcf`,l.click(),URL.revokeObjectURL(i),re.success("Contact saved!")}function eFs({card:s}){var v;const[t,n]=j.useState(!1),[r,a]=j.useState("booking"),i=((v=s.profile)==null?void 0:v.name)||"Agent",l=i.split(" ").map(b=>b[0]).join("").toUpperCase().slice(0,2),o=(b,w)=>{ju(s.id,"button_click",b),w()},c=()=>o("call",()=>{var b;(b=s.profile)!=null&&b.phone?window.location.href=`tel:${s.profile.phone}`:re.error("Phone number not available")}),d=()=>o("text",()=>{var b;(b=s.profile)!=null&&b.phone?window.location.href=`sms:${s.profile.phone}`:re.error("Phone number not available")}),u=()=>o("email",()=>{var b;(b=s.profile)!=null&&b.email?window.location.href=`mailto:${s.profile.email}`:re.error("Email not available")}),h=()=>{s.booking_url?o("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),n(!0),ju(s.id,"button_click","book"))},m=()=>{var b,w;ju(s.id,"contact_saved"),GLe({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()=>{ju(s.id,"share_event");const b=`https://cards.relevelup.com/${s.slug}`,w="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${i}`,text:w,url:b})}catch{}else await navigator.clipboard.writeText(b),re.success("Link copied!")},g=()=>{a("referral"),n(!0),ju(s.id,"button_click","refer")},x=()=>{a("connect"),n(!0),ju(s.id,"button_click","connect")},y={instagram:"📸",facebook:"📘",linkedin:"💼",twitter:"🐦",youtube:"🎬",tiktok:"🎵"};return e.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 via-white to-slate-50",children:[e.jsxs("div",{className:"max-w-md mx-auto px-5 py-10",children:[e.jsxs("div",{className:"text-center mb-8",children:[s.show_photo&&e.jsxs(Oa,{className:"h-28 w-28 mx-auto mb-4 ring-4 ring-white shadow-lg",children:[e.jsx(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(eo,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs font-medium",children:"Text"})]}),e.jsxs($,{onClick:u,className:"flex flex-col items-center gap-1.5 h-auto py-4 bg-primary hover:bg-primary/90 text-primary-foreground rounded-2xl shadow-sm",children:[e.jsx(mn,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs font-medium",children:"Email"})]})]}),e.jsxs($,{onClick:h,className:"w-full h-12 text-base font-semibold rounded-2xl shadow-sm mb-6",variant:"outline",children:[e.jsx(Ta,{className:"h-5 w-5 mr-2"}),s.custom_cta_label||"Book a Call"]}),s.show_credentials&&s.review_snippet&&e.jsx("div",{className:"flex items-center justify-center gap-4 mb-6 text-sm text-slate-600",children:e.jsxs("div",{className:"text-center flex items-center gap-1",children:[e.jsx(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(qLe,{card:s,variant:"standard"}),e.jsx(HLe,{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(xi,{className:"h-4 w-4 mr-3 text-primary"}),"Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs($,{variant:"ghost",onClick:()=>{ju(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(Fd,{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:()=>ju(s.id,"button_click",`social_${b.platform}`),className:"h-10 w-10 rounded-full bg-slate-100 hover:bg-slate-200 flex items-center justify-center text-lg transition-colors",children:y[b.platform.toLowerCase()]||"🔗"},w))}),e.jsx("div",{className:"text-center",children:e.jsx("p",{className:"text-xs text-slate-400",children:"Powered by LevelUp"})})]}),e.jsx(VLe,{open:t,onOpenChange:n,cardId:s.id,type:r,agentName:i})]})}function tFs({card:s}){var v;const[t,n]=j.useState(!1),[r,a]=j.useState("booking"),i=((v=s.profile)==null?void 0:v.name)||"Agent",l=i.split(" ").map(b=>b[0]).join("").toUpperCase().slice(0,2),o=(b,w)=>{ju(s.id,"button_click",b),w()},c=()=>o("call",()=>{var b;(b=s.profile)!=null&&b.phone?window.location.href=`tel:${s.profile.phone}`:re.error("Phone number not available")}),d=()=>o("text",()=>{var b;(b=s.profile)!=null&&b.phone?window.location.href=`sms:${s.profile.phone}`:re.error("Phone number not available")}),u=()=>o("email",()=>{var b;(b=s.profile)!=null&&b.email?window.location.href=`mailto:${s.profile.email}`:re.error("Email not available")}),h=()=>{s.booking_url?o("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),n(!0),ju(s.id,"button_click","book"))},m=()=>{var b,w;ju(s.id,"contact_saved"),GLe({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()=>{ju(s.id,"share_event");const b=`https://cards.relevelup.com/${s.slug}`,w="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${i}`,text:w,url:b})}catch{}else await navigator.clipboard.writeText(b),re.success("Link copied!")},g=()=>{a("referral"),n(!0),ju(s.id,"button_click","refer")},x=()=>{a("connect"),n(!0),ju(s.id,"button_click","connect")},y={instagram:"📸",facebook:"📘",linkedin:"💼",twitter:"🐦",youtube:"🎬",tiktok:"🎵"};return e.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-[#0f1419] via-[#1a1f2e] to-[#0f1419]",children:[e.jsxs("div",{className:"max-w-md mx-auto px-5 py-10",children:[e.jsx("div",{className:"w-16 h-0.5 bg-gradient-to-r from-[#c9a84c] to-[#e8d48b] mx-auto mb-8"}),e.jsxs("div",{className:"text-center mb-8",children:[s.show_photo&&e.jsxs(Oa,{className:"h-32 w-32 mx-auto mb-5 ring-2 ring-[#c9a84c]/40 shadow-2xl",children:[e.jsx(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:eo,label:"Text",handler:d},{icon:mn,label:"Email",handler:u}].map(({icon:b,label:w,handler:S})=>e.jsxs("button",{onClick:S,className:"flex flex-col items-center gap-1.5 py-4 bg-[#1e2636] hover:bg-[#252d3f] border border-[#c9a84c]/20 rounded-xl transition-colors",children:[e.jsx(b,{className:"h-5 w-5 text-[#c9a84c]"}),e.jsx("span",{className:"text-xs font-medium text-[#e2e8f0]",children:w})]},w))}),e.jsxs("button",{onClick:h,className:"w-full h-12 text-base font-semibold rounded-xl mb-6 bg-gradient-to-r from-[#c9a84c] to-[#e8d48b] text-[#0f1419] hover:opacity-90 transition-opacity flex items-center justify-center gap-2",children:[e.jsx(Ta,{className:"h-5 w-5"}),s.custom_cta_label||"Book a Call"]}),s.show_credentials&&s.review_snippet&&e.jsx("div",{className:"flex items-center justify-center gap-4 mb-6 text-sm",children:e.jsxs("div",{className:"text-center flex items-center gap-1",children:[e.jsx(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(qLe,{card:s,variant:"luxury"}),e.jsx(HLe,{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(xi,{className:"h-4 w-4 text-[#c9a84c]"})," Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs("button",{onClick:()=>{ju(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(Fd,{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:()=>ju(s.id,"button_click",`social_${b.platform}`),className:"h-10 w-10 rounded-full bg-[#1e2636] border border-[#c9a84c]/20 hover:border-[#c9a84c]/50 flex items-center justify-center text-lg transition-colors",children:y[b.platform.toLowerCase()]||"🔗"},w))}),e.jsx("div",{className:"text-center",children:e.jsx("p",{className:"text-xs text-[#4a5568]",children:"Powered by LevelUp"})})]}),e.jsx(VLe,{open:t,onOpenChange:n,cardId:s.id,type:r,agentName:i})]})}function sFs({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)=>{ju(s.id,"button_click",I),P()},u=()=>d("call",()=>{var I;(I=s.profile)!=null&&I.phone?window.location.href=`tel:${s.profile.phone}`:re.error("Phone number not available")}),h=()=>d("text",()=>{var I;(I=s.profile)!=null&&I.phone?window.location.href=`sms:${s.profile.phone}`:re.error("Phone number not available")}),m=()=>d("email",()=>{var I;(I=s.profile)!=null&&I.email?window.location.href=`mailto:${s.profile.email}`:re.error("Email not available")}),f=()=>{s.booking_url?d("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),n(!0),ju(s.id,"button_click","book"))},g=()=>{var I,P;ju(s.id,"contact_saved"),GLe({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()=>{ju(s.id,"share_event");const I=`https://cards.relevelup.com/${s.slug}`,P="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${i}`,text:P,url:I})}catch{}else await navigator.clipboard.writeText(I),re.success("Link copied!")},y=()=>{a("referral"),n(!0),ju(s.id,"button_click","refer")},v=()=>{a("connect"),n(!0),ju(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:eo,label:"Text",handler:h},{icon:mn,label:"Email",handler:m}].map(({icon:I,label:P,handler:R})=>e.jsxs("button",{onClick:R,className:"flex flex-col items-center gap-1.5 py-4 text-white rounded-2xl transition-opacity font-bold hover:opacity-85",style:{backgroundColor:o.dark},children:[e.jsx(I,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:P})]},P))}),e.jsxs("button",{onClick:f,className:"w-full h-14 text-base font-black rounded-2xl mb-6 text-white transition-opacity hover:opacity-90 flex items-center justify-center gap-2 uppercase tracking-wide",style:{backgroundColor:o.button},children:[e.jsx(Ta,{className:"h-5 w-5"}),s.custom_cta_label||"Book a Call"]}),s.show_credentials&&s.review_snippet&&e.jsx("div",{className:"flex items-center justify-center gap-5 mb-6",children:s.review_snippet&&e.jsxs("div",{className:"text-center flex items-center gap-1",children:[e.jsx(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(qLe,{card:s,variant:"bold"}),e.jsx(HLe,{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(xi,{className:"h-4 w-4",style:{color:o.accent}})," Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs("button",{onClick:()=>{ju(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: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(Yn,{className:"h-4 w-4",style:{color:o.accent}})," Refer a Friend"]}),e.jsxs("button",{onClick:v,className:"w-full flex items-center gap-3 h-12 px-4 rounded-2xl hover:bg-gray-100 transition-colors text-sm font-bold",style:{color:o.dark},children:[e.jsx(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(Fd,{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:()=>ju(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(VLe,{open:t,onOpenChange:n,cardId:s.id,type:r,agentName:i})]})}function nFs({card:s}){var v;const[t,n]=j.useState(!1),[r,a]=j.useState("booking"),i=((v=s.profile)==null?void 0:v.name)||"Agent",l=i.split(" ").map(b=>b[0]).join("").toUpperCase().slice(0,2),o=(b,w)=>{ju(s.id,"button_click",b),w()},c=()=>o("call",()=>{var b;(b=s.profile)!=null&&b.phone?window.location.href=`tel:${s.profile.phone}`:re.error("Phone number not available")}),d=()=>o("text",()=>{var b;(b=s.profile)!=null&&b.phone?window.location.href=`sms:${s.profile.phone}`:re.error("Phone number not available")}),u=()=>o("email",()=>{var b;(b=s.profile)!=null&&b.email?window.location.href=`mailto:${s.profile.email}`:re.error("Email not available")}),h=()=>{s.booking_url?o("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),n(!0),ju(s.id,"button_click","book"))},m=()=>{var b,w;ju(s.id,"contact_saved"),GLe({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()=>{ju(s.id,"share_event");const b=`https://cards.relevelup.com/${s.slug}`,w="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${i}`,text:w,url:b})}catch{}else await navigator.clipboard.writeText(b),re.success("Link copied!")},g=()=>{a("referral"),n(!0),ju(s.id,"button_click","refer")},x=()=>{a("connect"),n(!0),ju(s.id,"button_click","connect")},y={instagram:"📸",facebook:"📘",linkedin:"💼",twitter:"🐦",youtube:"🎬",tiktok:"🎵"};return e.jsxs("div",{className:"min-h-screen bg-[#f5f1eb]",children:[e.jsx("div",{className:"bg-[#1b3a4b] h-2"}),e.jsxs("div",{className:"max-w-md mx-auto px-5 py-10",children:[e.jsxs("div",{className:"text-center mb-8",children:[s.show_photo&&e.jsxs(Oa,{className:"h-28 w-28 mx-auto mb-4 ring-4 ring-white shadow-lg",children:[e.jsx(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:eo,label:"Text",handler:d},{icon:mn,label:"Email",handler:u}].map(({icon:b,label:w,handler:S})=>e.jsxs("button",{onClick:S,className:"flex flex-col items-center gap-1.5 py-4 bg-white hover:bg-[#e8e3db] border border-[#d4cfc5] rounded-lg transition-colors shadow-sm",children:[e.jsx(b,{className:"h-5 w-5 text-[#1b3a4b]"}),e.jsx("span",{className:"text-xs font-semibold text-[#1b3a4b]",children:w})]},w))}),e.jsxs("button",{onClick:h,className:"w-full h-12 text-base font-semibold rounded-lg mb-6 bg-[#1b3a4b] hover:bg-[#264d61] text-white transition-colors flex items-center justify-center gap-2 shadow-sm",children:[e.jsx(Ta,{className:"h-5 w-5"}),s.custom_cta_label||"Book a Call"]}),s.show_credentials&&s.review_snippet&&e.jsx("div",{className:"bg-white rounded-lg border border-[#d4cfc5] p-4 mb-6 shadow-sm",children:e.jsx("div",{className:"flex items-center justify-center gap-6",children:e.jsxs("div",{className:"text-center flex items-center gap-1",children:[e.jsx(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(qLe,{card:s,variant:"classic"}),e.jsx(HLe,{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(xi,{className:"h-4 w-4 text-[#5a7a6f]"})," Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs("button",{onClick:()=>{ju(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(Fd,{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:()=>ju(s.id,"button_click",`social_${b.platform}`),className:"h-10 w-10 rounded-full bg-white border border-[#d4cfc5] hover:bg-[#e8e3db] flex items-center justify-center text-lg transition-colors shadow-sm",children:y[b.platform.toLowerCase()]||"🔗"},w))}),e.jsx("div",{className:"text-center",children:e.jsx("p",{className:"text-xs text-[#a0aec0]",children:"Powered by LevelUp"})})]}),e.jsx(VLe,{open:t,onOpenChange:n,cardId:s.id,type:r,agentName:i})]})}function Jtt({card:s}){switch(s.theme){case"luxury":return e.jsx(tFs,{card:s});case"bold":return e.jsx(sFs,{card:s});case"classic":return e.jsx(nFs,{card:s});case"standard":default:return e.jsx(eFs,{card:s})}}function rFs(){const s=mu();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(aFs,{slug:t})}function aFs({slug:s}){return e.jsx(iFs,{slug:s})}function iFs({slug:s}){var i;const{data:t,isLoading:n,error:r}=$7t(s);if(j.useEffect(()=>{t!=null&&t.id&&ju(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(Jtt,{card:t})]})}function H7t({presentationId:s,ctaLabel:t,agentName:n,prefillName:r,prefillEmail:a,prefillPhone:i}){const[l,o]=j.useState(r||""),[c,d]=j.useState(a||""),[u,h]=j.useState(i||""),[m,f]=j.useState(""),[g,x]=j.useState(""),[y,v]=j.useState(!1),[b,w]=j.useState(!1),S=async A=>{if(A.preventDefault(),!l.trim()){re.error("Please enter your name");return}v(!0);try{const{error:E}=await q.from("smart_presentation_leads").insert({presentation_id:s,name:l.trim(),email:c.trim()||null,phone:u.trim()||null,intent:m||null,message:g.trim()||null});if(E)throw E;try{await q.rpc("log_presentation_view",{p_presentation_id:s,p_section_index:null,p_cta_clicked:!0,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:null})}catch{}q.functions.invoke("presentation-lead-notify",{body:{presentationId:s,name:l.trim(),email:c.trim()||void 0,phone:u.trim()||void 0,intent:m||void 0,message:g.trim()||void 0}}).catch(I=>console.error("Presentation lead notify failed:",I)),w(!0)}catch{re.error("Something went wrong. Please try again.")}finally{v(!1)}};return b?e.jsxs("div",{className:"text-center py-8",children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-emerald-100 flex items-center justify-center mx-auto mb-4",children:e.jsx(ca,{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:y,children:y?"Sending...":t})]})}function oFs(){const s=mu();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(lFs,{shareToken:t})}function lFs({shareToken:s}){var g;const[t,n]=j.useState(null),[r,a]=j.useState(!0),[i,l]=j.useState(0),[o,c]=j.useState(!1);j.useEffect(()=>{d()},[s]);const d=async()=>{const{data:x,error:y}=await q.from("smart_presentations").select("*").eq("share_token",s).eq("status","published").single();if(y||!x){c(!0),a(!1);return}const{data:v}=await q.from("profiles").select("name, email, phone, avatar_url, title, brokerage_id").eq("id",x.owner_user_id).single();let b;if(v!=null&&v.brokerage_id){const{data:S}=await q.from("brokerages").select("name").eq("id",v.brokerage_id).single();b=(S==null?void 0:S.name)||void 0}let w=null;if(x.contact_id){const{data:S}=await q.from("innercircle_contacts").select("first_name, last_name, email, phone").eq("id",x.contact_id).single();w=S}n({...x,owner_name:v==null?void 0:v.name,owner_email:v==null?void 0:v.email,owner_phone:v==null?void 0:v.phone,owner_avatar:v==null?void 0:v.avatar_url,owner_title:(v==null?void 0:v.title)||void 0,brokerage_name:b,contact_name:w?[w.first_name,w.last_name].filter(Boolean).join(" "):void 0,contact_email:(w==null?void 0:w.email)||void 0,contact_phone:(w==null?void 0:w.phone)||void 0}),a(!1);try{await q.rpc("log_presentation_view",{p_presentation_id:x.id,p_section_index:0,p_cta_clicked:!1,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null})}catch{}},u=async()=>{if(t){try{await q.rpc("log_presentation_view",{p_presentation_id:t.id,p_section_index:null,p_cta_clicked:!0,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:null})}catch{}t.cta_url&&window.open(t.cta_url,"_blank")}},h=x=>{const y=x.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/)([a-zA-Z0-9_-]+)/);if(y)return`https://www.youtube.com/embed/${y[1]}?rel=0`;if(x.includes("iframe.mediadelivery.net/play/")){const w=x.replace("/play/","/embed/"),S=w.includes("?")?"&":"?";return`${w}${S}responsive=true`}if(x.includes("iframe.mediadelivery.net")){const w=x.includes("?")?"&":"?";return`${x}${w}responsive=true`}const v=x.match(/loom\.com\/share\/([a-zA-Z0-9]+)/);if(v)return`https://www.loom.com/embed/${v[1]}`;const b=x.match(/video\.bunnycdn\.com\/play\/(\d+)\/([a-f0-9-]+)/);return b?`https://iframe.mediadelivery.net/embed/${b[1]}/${b[2]}?responsive=true`:x};if(r)return e.jsx("div",{className:"min-h-screen bg-white flex items-center justify-center",children:e.jsxs("div",{className:"space-y-4 w-full max-w-2xl px-4",children:[e.jsx(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,y)=>e.jsx("button",{onClick:()=>l(y),className:Pt("w-full text-left p-4 rounded-xl border transition-all",i===y?"border-blue-500 bg-blue-50 shadow-sm":"border-gray-200 bg-white hover:border-blue-200 hover:bg-blue-50/50"),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs("span",{className:"text-blue-600 font-bold text-sm mt-0.5",children:[String(y+1).padStart(2,"0"),"."]}),e.jsxs("div",{children:[e.jsx("span",{className:"mr-2",children:x.icon}),e.jsx("span",{className:"font-semibold text-gray-900",children:x.title}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:x.description})]})]})},y))})]}),e.jsxs("div",{className:"mt-12 max-w-md mx-auto bg-white rounded-2xl border border-gray-200 shadow-sm p-6 text-center",children:[t.owner_avatar&&e.jsx("img",{src:t.owner_avatar,alt:t.owner_name||"Agent",className:"h-20 w-20 rounded-full object-cover mx-auto mb-3 border-2 border-gray-100"}),e.jsx("h3",{className:"text-lg font-bold text-gray-900",children:t.owner_name}),t.owner_title&&e.jsx("p",{className:"text-sm text-gray-500",children:t.owner_title}),t.brokerage_name&&e.jsx("p",{className:"text-sm text-gray-500",children:t.brokerage_name}),e.jsxs("div",{className:"mt-3 flex flex-col items-center gap-1 text-sm text-gray-600",children:[t.owner_phone&&e.jsx("a",{href:`tel:${t.owner_phone}`,className:"hover:text-blue-600 transition-colors",children:t.owner_phone}),t.owner_email&&e.jsx("a",{href:`mailto:${t.owner_email}`,className:"hover:text-blue-600 transition-colors",children:t.owner_email})]})]}),t.cta_label&&e.jsxs("div",{className:"text-center mt-8 py-8",children:[e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-4",children:"Ready to Get Started?"}),(g=t.cta_url)!=null&&g.trim()?e.jsxs($,{size:"lg",onClick:u,className:"text-lg px-8 py-6 rounded-xl bg-blue-600 hover:bg-blue-700 text-white shadow-lg",children:[t.cta_label,e.jsx(Fr,{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(H7t,{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 cFs(){const{user:s}=bs(),t=Sa(),{data:n}=zw();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 Ukr(s){const{user:t}=bs();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 G7t(s){const{user:t}=bs(),n=Wt();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 dFs(){const s=Wt(),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 W7t(){const s=Wt();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 uFs(){const s=Wt();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 K7t(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 hFs(s){const{user:t}=bs();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 mFs(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 fFs(){return mt({mutationFn:async s=>{const{error:t}=await q.from("open_house_survey_responses").insert(s);if(t)throw t}})}function pFs(s){const{user:t}=bs();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 gFs(){const s=Wt();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 xFs(){const s=Wt();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 yFs(){const s=Wt();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 vFs(){const s=Wt();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 bFs(){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 _Fs(){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 wFs(){return mt({mutationFn:async s=>{await q.rpc("increment_open_house_scan",{_slug:s})}})}async function Y7t(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 jFs(s){const{user:t}=bs();return st({queryKey:["open-house-rooms",s],queryFn:()=>Y7t(s),enabled:!!t&&!!s})}function NFs(s){return st({queryKey:["public-open-house-rooms",s],queryFn:()=>Y7t(s),enabled:!!s})}function kFs(){const s=Wt();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 SFs(){const s=Wt();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 CFs(){const s=Wt();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 AFs(){const s=Wt();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 EFs(){const s=Wt();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 TFs(){const s=Wt();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 MFs(){const s=Wt();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 PFs(s){const{user:t}=bs();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 IFs(){const s=Wt();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 LFs=Object.defineProperty,EL=(s,t)=>LFs(s,"name",{value:t,configurable:!0}),est="Switch",[RFs,qkr]=tp(est),[DFs,tst]=RFs(est);function Z7t(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]=hy({prop:n,defaultProp:a??!1,onChange:c,caller:est}),[g,x]=j.useState(null),[y,v]=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:y,setBubbleInput:v};return e.jsx(DFs,{scope:t,...E,children:Q7t(h)?h(E):r})}EL(Z7t,"SwitchProvider");var FFs="SwitchTrigger",OFs=j.forwardRef(EL(function({__scopeSwitch:t,onClick:n,...r},a){const{control:i,form:l,value:o,disabled:c,checked:d,required:u,setControl:h,setChecked:m,hasConsumerStoppedPropagationRef:f,onUserInteraction:g,isFormControl:x,bubbleInput:y}=tst(FFs,t),v=Vo(a,h),b=j.useRef(d);return j.useEffect(()=>{const w=l?i==null?void 0:i.ownerDocument.getElementById(l):i==null?void 0:i.form;if(w instanceof HTMLFormElement){const S=EL(()=>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":sst(d),"data-disabled":c?"":void 0,disabled:c,value:o,...r,ref:v,onClick:Ra(n,w=>{g(),m(S=>!S),y&&x&&(f.current=w.isPropagationStopped(),f.current||w.stopPropagation())})})},"SwitchTrigger")),X7t=j.forwardRef(EL(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(Z7t,{__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(OFs,{...m,ref:n,__scopeSwitch:r}),f&&e.jsx(UFs,{__scopeSwitch:r})]})})},"Switch")),zFs="SwitchThumb",BFs=j.forwardRef(EL(function(t,n){const{__scopeSwitch:r,...a}=t,i=tst(zFs,r);return e.jsx(Ei.span,{"data-state":sst(i.checked),"data-disabled":i.disabled?"":void 0,...a,ref:n})},"SwitchThumb")),$Fs="SwitchBubbleInput",UFs=j.forwardRef(EL(function({__scopeSwitch:t,onClick:n,...r},a){const{control:i,hasConsumerStoppedPropagationRef:l,userInteractionCount:o,checked:c,defaultChecked:d,required:u,disabled:h,name:m,value:f,form:g,bubbleInput:x,setBubbleInput:y}=tst($Fs,t),v=Vo(a,y),b=WW(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:v,onClick:Ra(n,I=>{w.current&&I.stopPropagation()}),style:{...r.style,...b,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})},"SwitchBubbleInput"));function Q7t(s){return typeof s=="function"}EL(Q7t,"isFunction");function sst(s){return s?"checked":"unchecked"}EL(sst,"getState");const Sn=j.forwardRef(({className:s,...t},n)=>e.jsx(X7t,{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(BFs,{className:Pt("pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0")})}));Sn.displayName=X7t.displayName;const qFs=["Excellent","Good","Neutral","Bad","Very Bad"],VFs=[5,4,3,2,1];function HFs({questions:s,visitorId:t,onComplete:n,onSkip:r}){const a=fFs(),[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"}),qFs.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}),VFs.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(Ls,{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 rGe(s){return/iframe\.mediadelivery\.net\/embed\//.test(s)}function GFs({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:[rGe(m.url)?e.jsx("div",{className:"absolute inset-0 bg-slate-900"}):e.jsx("video",{src:m.url,className:"w-full h-full object-cover"}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/30 group-hover:bg-black/50 transition",children:e.jsx("div",{className:"w-12 h-12 rounded-full bg-white/90 flex items-center justify-center",children:e.jsx(ua,{className:"h-5 w-5 text-slate-900"})})})]}):e.jsx("img",{src:m.url,alt:i.name,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"})},m.id))})]}),l&&i&&e.jsxs("div",{className:"fixed inset-0 z-50 bg-black/95 flex items-center justify-center p-6 cursor-zoom-out",onClick:c,children:[e.jsxs("div",{className:"absolute top-5 left-1/2 -translate-x-1/2 px-3 py-1.5 rounded-full bg-white/10 backdrop-blur-sm text-white/80 text-xs font-medium",children:[i.name," — ",(r??0)+1," / ",o]}),e.jsx("button",{onClick:m=>{m.stopPropagation(),c()},className:"absolute top-5 right-5 h-10 w-10 rounded-full bg-white/10 hover:bg-white/20 text-white text-xl flex items-center justify-center transition","aria-label":"Close",children:"×"}),o>1&&e.jsx("button",{onClick:m=>{m.stopPropagation(),d()},className:"absolute left-5 top-1/2 -translate-y-1/2 h-12 w-12 rounded-full bg-white/10 hover:bg-white/20 text-white flex items-center justify-center transition","aria-label":"Previous",children:e.jsx(kd,{className:"h-6 w-6"})}),l.kind==="video"?rGe(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 WFs({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"?rGe(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 h7e={question:{label:"Ask a Question",title:"Ask the agent",placeholder:"What would you like to know about the home?",icon:eo},showing:{label:"Schedule a Showing",title:"Request a private showing",placeholder:"Anything specific to focus on during the showing? (optional)",icon:Ta},disclosure:{label:"Request Disclosures",title:"Request seller disclosures",placeholder:"Any specific documents? (optional)",icon:Jr},offer:{label:"I'm Interested — Let's Talk",title:"Express interest / make an offer",placeholder:"Tell the agent about your interest or any offer thoughts.",icon:nu}},KFs=["Seller's Property Disclosure","HOA Documents & Bylaws","Inspection Reports","Title / CC&Rs","Utility & Tax History"];function YFs(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(ke=>ke[0]).join("").slice(0,2))||"?",c=s.brand_color_override||null,[d,u]=j.useState(null),[h,m]=j.useState(""),[f,g]=j.useState(r||""),[x,y]=j.useState(a||""),[v,b]=j.useState(!1),[w,S]=j.useState(null),[A,E]=j.useState(""),[I,P]=j.useState(""),[R,D]=j.useState(""),[O,U]=j.useState([]),[W,V]=j.useState(""),[G,Y]=j.useState(""),[X,ae]=j.useState(""),[le,ne]=j.useState(""),te=YFs(s.price),J=s.tour_mode==="rooms",{data:ce=[]}=NFs(J?s.id:void 0),_e=[s.enable_question&&"question",s.enable_showing&&"showing",s.enable_disclosures&&"disclosure",s.enable_offer&&"offer"].filter(Boolean),he=ke=>{u(ke),m(""),E(""),P(""),D(""),U([]),V(""),Y(""),ae(""),ne("")},ue=()=>{u(null)},ve=ke=>{U(Be=>Be.includes(ke)?Be.filter(Ne=>Ne!==ke):[...Be,ke])},Ee=ke=>ke==="showing"?{preferred_date:A||null,preferred_time:I||null,alternate_date:R||null}:ke==="disclosure"?{requested_documents:O}:ke==="offer"?{offer_amount:W||null,financing:G||null,timeline:X||null,pre_approved:le||null}:{},Se=d?d==="showing"?!!A:d==="question"?h.trim().length>0:!0:!1,Le=async()=>{if(d){if(i){_a({title:"Preview mode",description:"Lead not sent — this is just a preview."}),S(d),setTimeout(()=>{u(null),S(null)},1500);return}b(!0);try{const ke=Ee(d),{error: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,...ke}});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:ke}}).catch(()=>{}),S(d),_a({title:"Sent!",description:"The agent has been notified."}),setTimeout(()=>{ue(),S(null)},1400)}catch(ke){_a({title:"Something went wrong",description:ke.message,variant:"destructive"})}finally{b(!1)}}};return e.jsxs("div",{className:"min-h-screen bg-slate-950 text-white",children:[e.jsxs("div",{className:"relative w-full aspect-video bg-slate-900 md:max-h-[70vh]",children:[s.hero_video_url?e.jsx("video",{src:s.hero_video_url,poster:s.hero_video_thumbnail_url||s.photo_url||void 0,controls:!0,playsInline:!0,className:"w-full h-full object-cover"}):s.photo_url?e.jsx("img",{src:s.photo_url,alt:s.property_address,className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-white/40",children:"No tour video yet"}),e.jsx("div",{className:"absolute inset-x-0 bottom-0 h-32 bg-gradient-to-t from-slate-950 to-transparent pointer-events-none"})]}),e.jsxs("div",{className:"max-w-3xl mx-auto px-5 pb-32 -mt-10 relative z-10",children:[e.jsxs("div",{className:"bg-slate-900/80 backdrop-blur-md border border-white/10 rounded-2xl p-6 shadow-2xl",children:[e.jsx("h1",{className:"text-2xl font-bold leading-tight",children:s.property_address}),s.city&&e.jsxs("p",{className:"text-sm text-white/60 mt-1 flex items-center gap-1",children:[e.jsx(ci,{className:"h-3.5 w-3.5"}),s.city,s.state?`, ${s.state}`:""," ",s.zip]}),te&&e.jsx("p",{className:"text-3xl font-bold text-white mt-3",children:te}),e.jsxs("div",{className:"flex flex-wrap gap-4 mt-4 text-sm text-white/80",children:[s.beds!=null&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(r2,{className:"h-4 w-4"}),s.beds," bd"]}),s.baths!=null&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(A0,{className:"h-4 w-4"}),s.baths," ba"]}),s.sqft!=null&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(j_,{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(mn,{className:"h-4 w-4"})})]})]}),J&&ce.length>0&&e.jsxs("div",{className:"mt-8",children:[e.jsx(GFs,{rooms:ce}),e.jsx(WFs,{rooms:ce})]}),_e.length>0&&e.jsx("div",{className:"mt-5 grid grid-cols-1 sm:grid-cols-2 gap-3",children:_e.map(ke=>{const Be=h7e[ke],Ne=Be.icon;return e.jsxs("button",{onClick:()=>he(ke),className:"flex items-center gap-3 p-4 rounded-xl bg-white text-slate-900 hover:bg-white/90 transition-colors text-left",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg flex items-center justify-center shrink-0",style:c?{backgroundColor:`${c}1a`,color:c}:{backgroundColor:"#f1f5f9",color:"#334155"},children:e.jsx(Ne,{className:"h-5 w-5"})}),e.jsx("span",{className:"font-medium text-sm",children:Be.label})]},ke)})}),e.jsx("p",{className:"text-center text-white/30 text-xs mt-8",children:"Powered by LevelUp Virtual Open House"})]}),e.jsx(Gy,{open:!!d,onOpenChange:ke=>!ke&&ue(),children:e.jsx(my,{side:"bottom",className:"rounded-t-2xl max-h-[92vh] overflow-y-auto",children:d&&e.jsxs(e.Fragment,{children:[e.jsxs(L0,{className:"text-left",children:[e.jsx(R0,{children:h7e[d].title}),e.jsxs(DB,{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:ke=>g(ke.target.value),placeholder:"you@example.com",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Phone"}),e.jsx(pe,{type:"tel",value:x,onChange:ke=>y(ke.target.value),placeholder:"(555) 123-4567",className:"mt-1"})]})]}),d==="showing"&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Preferred date *"}),e.jsx(pe,{type:"date",value:A,onChange:ke=>E(ke.target.value),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Preferred time"}),e.jsx(pe,{type:"time",value:I,onChange:ke=>P(ke.target.value),className:"mt-1"})]})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Alternate date (optional)"}),e.jsx(pe,{type:"date",value:R,onChange:ke=>D(ke.target.value),className:"mt-1"})]})]}),d==="disclosure"&&e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Which documents? (select all that apply)"}),e.jsx("div",{className:"mt-2 space-y-2",children:KFs.map(ke=>e.jsxs("label",{className:"flex items-center gap-2 text-sm cursor-pointer",children:[e.jsx(ai,{checked:O.includes(ke),onCheckedChange:()=>ve(ke)}),e.jsx("span",{children:ke})]},ke))})]}),d==="offer"&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Estimated offer"}),e.jsx(pe,{value:W,onChange:ke=>V(ke.target.value),placeholder:"$",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Financing"}),e.jsxs(ms,{value:G,onValueChange:Y,children:[e.jsx(us,{className:"mt-1",children:e.jsx(fs,{placeholder:"Select..."})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"Cash",children:"Cash"}),e.jsx(Ge,{value:"Conventional",children:"Conventional"}),e.jsx(Ge,{value:"FHA",children:"FHA"}),e.jsx(Ge,{value:"VA",children:"VA"}),e.jsx(Ge,{value:"Other",children:"Other"})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Timeline"}),e.jsxs(ms,{value:X,onValueChange:ae,children:[e.jsx(us,{className:"mt-1",children:e.jsx(fs,{placeholder:"Select..."})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"ASAP",children:"ASAP"}),e.jsx(Ge,{value:"30 days",children:"30 days"}),e.jsx(Ge,{value:"60 days",children:"60 days"}),e.jsx(Ge,{value:"90+ days",children:"90+ days"})]})]})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Pre-approved?"}),e.jsxs(ms,{value:le,onValueChange:ne,children:[e.jsx(us,{className:"mt-1",children:e.jsx(fs,{placeholder:"Select..."})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"Yes",children:"Yes"}),e.jsx(Ge,{value:"No",children:"No"}),e.jsx(Ge,{value:"In progress",children:"In progress"})]})]})]})]})]}),e.jsxs("div",{children:[e.jsxs(ee,{className:"text-xs",children:["Message",d==="question"?" *":" (optional)"]}),e.jsx(Ls,{value:h,onChange:ke=>m(ke.target.value),placeholder:h7e[d].placeholder,rows:4,className:"mt-1"})]}),e.jsx($,{onClick:Le,disabled:v||!Se,className:"w-full h-12 text-white hover:opacity-90",style:c?{backgroundColor:c}:void 0,children:v?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):"Send to agent"})]})]})})})]})}const XFs=z2({first_name:vl().trim().min(1,"First name is required").max(50),last_name:vl().trim().max(50).optional(),email:vl().trim().email("Please enter a valid email").max(255).optional().or(yx("")),phone:vl().trim().max(20).optional().or(yx(""))}),QFs=[{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 J7t({slug:s}={}){var ze;const t=Wi(),n=s||t.slug,[r]=gc(),a=r.get("kiosk")==="1"||r.get("mode")==="kiosk",i=8,{data:l,isLoading:o,error:c}=K7t(n),d=bFs(),u=_Fs(),h=wFs(),m=j.useRef(!1),[f,g]=j.useState("welcome"),[x,y]=j.useState(null),[v,b]=j.useState({first_name:"",last_name:"",email:"",phone:"",visitor_address:""}),[w,S]=j.useState(""),[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(()=>{y(null),b({first_name:"",last_name:"",email:"",phone:"",visitor_address:""}),S(""),E(!1),P(!1),D(""),U(""),V(i),g(a?"info":"welcome")},[a]),Y=j.useCallback((qe,dt)=>{l!=null&&l.id&&q.functions.invoke("guestbook-lead-notify",{body:{open_house_id:l.id,visitor_id:qe,first_name:dt.first_name??v.first_name,last_name:dt.last_name??v.last_name,email:dt.email??v.email,phone:dt.phone??v.phone,visitor_intent:dt.visitor_intent??w,message:dt.message,wants_market_updates:dt.wants_market_updates??A,has_agent:dt.has_agent??I,working_with_agent_name:dt.working_with_agent_name??R,visitor_address:dt.visitor_address??v.visitor_address}}).catch(Xe=>console.error("Guest book lead notify failed:",Xe))},[l==null?void 0:l.id,v,w,A,I,R]);j.useEffect(()=>{if(!a||f!=="done")return;V(i);const qe=setInterval(()=>{V(dt=>dt<=1?(clearInterval(qe),G(),0):dt-1)},1e3);return()=>clearInterval(qe)},[a,f,G]),j.useEffect(()=>{if(!a)return;g(dt=>dt==="welcome"?"info":dt);let qe=null;return(async()=>{var dt,Xe;try{qe=await((Xe=(dt=navigator.wakeLock)==null?void 0:dt.request)==null?void 0:Xe.call(dt,"screen"))}catch{}})(),()=>{var dt;try{(dt=qe==null?void 0:qe.release)==null||dt.call(qe)}catch{}}},[a]);const X=j.useCallback(()=>{var dt;const qe=document.documentElement;document.fullscreenElement||(dt=qe.requestFullscreen||qe.webkitRequestFullscreen)==null||dt.call(qe).catch(()=>{})},[]),{data:ae,isLoading:le}=mFs(l==null?void 0:l.id),ne=!!(l!=null&&l.enable_survey),te=(l==null?void 0:l.ask_visitor_intent)!==!1,J=(l==null?void 0:l.ask_visitor_address)===!0;j.useEffect(()=>{if(!n||!(l!=null&&l.id)||m.current)return;const qe=`oh_scan_${l.id}`;if(sessionStorage.getItem(qe)){m.current=!0;return}m.current=!0,sessionStorage.setItem(qe,"1"),h.mutate(n)},[n,l==null?void 0:l.id]),j.useEffect(()=>{f==="pending_survey"&&(le||g(ne&&((ae==null?void 0:ae.length)??0)>0?"survey":"done"))},[f,le,ne,ae]);const ce=qe=>{if(!qe)return"";const[dt,Xe]=qe.split(":"),at=parseInt(dt),rt=at>=12?"PM":"AM";return`${at>12?at-12:at||12}:${Xe} ${rt}`},_e=async()=>{U("");const qe=XFs.safeParse(v);if(!qe.success){U(qe.error.issues[0].message);return}if(!v.email&&!v.phone){U("Please provide either an email or phone number");return}const dt=(l==null?void 0:l.kind)==="virtual";let Xe=null;if(!x&&(l!=null&&l.id))try{const at=await d.mutateAsync({open_house_id:l.id,first_name:v.first_name.trim(),last_name:v.last_name.trim()||void 0,email:v.email.trim()||void 0,phone:v.phone.trim()||void 0,visitor_address:J&&v.visitor_address.trim()?v.visitor_address.trim():void 0,wants_market_updates:A,has_agent:I,working_with_agent_name:I&&R.trim()?R.trim():void 0,partial_signin:dt?!1:te});Xe=at.id,y(at.id)}catch{if(dt){U("We could not start the virtual tour. Please try again.");return}}if(dt){te?g("intent"):(Xe&&Y(Xe,{}),g("done"));return}if(!te){Xe&&Y(Xe,{}),ne?!le&&ae&&ae.length>0?g("survey"):g("pending_survey"):g("done");return}g("intent")},he=async qe=>{S(qe);try{let dt=x;if(dt?await u.mutateAsync({visitor_id:dt,visitor_intent:qe,wants_market_updates:A,has_agent:I,working_with_agent_name:I&&R.trim()?R.trim():null,partial_signin:!1}):(dt=(await d.mutateAsync({open_house_id:l.id,first_name:v.first_name.trim(),last_name:v.last_name.trim()||void 0,email:v.email.trim()||void 0,phone:v.phone.trim()||void 0,visitor_address:J&&v.visitor_address.trim()?v.visitor_address.trim():void 0,visitor_intent:qe,wants_market_updates:A,has_agent:I,working_with_agent_name:I&&R.trim()?R.trim():void 0,partial_signin:!1})).id,y(dt)),dt&&Y(dt,{visitor_intent:qe,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}ne?!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,ve=((ze=ue==null?void 0:ue.name)==null?void 0:ze.split(" ").map(qe=>qe[0]).join("").slice(0,2))||"?",Ee=l.event_type==="community",Se=l.kind==="virtual",Le=typeof window<"u"&&new URLSearchParams(window.location.search).get("preview")==="1";if(Se&&(Le||f==="done"))return!Le&&!x?e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 flex items-center justify-center",children:e.jsx("div",{className:"w-10 h-10 border-4 border-white/20 border-t-white rounded-full animate-spin"})}):e.jsxs(e.Fragment,{children:[e.jsxs(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"})]}),Le&&e.jsx("div",{className:"fixed top-3 left-1/2 -translate-x-1/2 z-[100] bg-amber-500 text-white text-xs font-semibold px-3 py-1.5 rounded-full shadow-lg pointer-events-none",children:"Agent Preview Mode — visitors won't see this"}),e.jsx(ZFs,{openHouse:l,visitorId:Le?"preview":x,visitorName:Le?"Preview Visitor":`${v.first_name} ${v.last_name}`.trim(),visitorEmail:Le?"":v.email,visitorPhone:Le?"":v.phone,previewMode:Le})]});const ke=`${Se?"Virtual Open House":Ee?"Community Event":"Open House"} — ${l.property_address}`,Ne=[[l.city,l.state].filter(Boolean).join(", "),l.event_date?en(new Date(l.event_date+"T00:00:00"),"EEE, MMM d"):null,ue!=null&&ue.name?`Hosted by ${ue.name}`:null].filter(Boolean).join(" · "),Ae=l.photo_url||"",Ce=Ae&&Ae.includes("/storage/v1/object/public/")?Ae.replace("/object/public/","/render/image/public/")+"?width=1200&height=630&resize=cover":Ae||"https://dashboard.relevelup.com/og-image.png",Ve=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:ke}),e.jsx("meta",{name:"description",content:Ne||`Sign in to ${l.property_address}`}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:title",content:ke}),e.jsx("meta",{property:"og:description",content:Ne||`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:Ve}),e.jsx("meta",{property:"og:site_name",content:"ReLevel Up"}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),e.jsx("meta",{name:"twitter:title",content:ke}),e.jsx("meta",{name:"twitter:description",content:Ne||`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:ve})]}),e.jsx("p",{className:"text-white/60 text-sm",children:ue==null?void 0:ue.name}),(ue==null?void 0:ue.title)&&e.jsx("p",{className:"text-white/40 text-xs",children:ue.title})]}),e.jsxs("div",{className:"bg-white rounded-2xl shadow-2xl overflow-hidden",children:[l.photo_url&&e.jsxs("div",{className:"relative h-44 sm:h-52 overflow-hidden",children:[e.jsx("img",{src:l.photo_url,alt:l.property_address,className:"w-full h-full object-cover"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-slate-900/80 via-slate-900/20 to-transparent"}),e.jsxs("div",{className:"absolute bottom-0 left-0 right-0 px-6 pb-4",children:[e.jsx("h1",{className:"text-white font-bold text-lg leading-tight drop-shadow-md",children:l.property_address}),e.jsxs("div",{className:"flex flex-wrap gap-3 mt-1.5 text-white/70 text-xs",children:[l.city&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ci,{className:"h-3 w-3"}),l.city,l.state?`, ${l.state}`:""," ",l.zip]}),!Se&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ta,{className:"h-3 w-3"}),en(new Date(l.event_date+"T00:00:00"),"MMM d, yyyy")]}),l.start_time&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(da,{className:"h-3 w-3"}),ce(l.start_time),l.end_time?` – ${ce(l.end_time)}`:""]})]})]})]})]}),!l.photo_url&&e.jsx("div",{className:"bg-gradient-to-r from-slate-800 to-slate-700 px-6 py-5",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-white/10 flex items-center justify-center shrink-0 mt-0.5",children:Ee?e.jsx(ji,{className:"h-5 w-5 text-white"}):e.jsx(va,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-white font-bold text-lg leading-tight",children:l.property_address}),e.jsxs("div",{className:"flex flex-wrap gap-3 mt-2 text-white/60 text-xs",children:[l.city&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ci,{className:"h-3 w-3"}),l.city,l.state?`, ${l.state}`:""," ",l.zip]}),!Se&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ta,{className:"h-3 w-3"}),en(new Date(l.event_date+"T00:00:00"),"MMM d, yyyy")]}),l.start_time&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(da,{className:"h-3 w-3"}),ce(l.start_time),l.end_time?` – ${ce(l.end_time)}`:""]})]})]})]})]})}),e.jsxs("div",{className:"p-6",children:[f==="welcome"&&e.jsxs("div",{className:"text-center space-y-6",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-bold text-slate-900 mb-2",children:"Welcome!"}),e.jsx("p",{className:"text-slate-500 text-sm",children:l.agent_greeting||"Please sign in below."})]}),e.jsxs($,{onClick:()=>g("info"),className:"w-full h-14 text-base bg-slate-900 hover:bg-slate-800 text-white rounded-xl",children:["Sign In ",e.jsx(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:v.first_name,onChange:qe=>b(dt=>({...dt,first_name:qe.target.value})),placeholder:"First",className:"mt-1 h-12 rounded-xl border-slate-200 text-base",autoFocus:!0})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-slate-600 text-xs",children:"Last Name"}),e.jsx(pe,{value:v.last_name,onChange:qe=>b(dt=>({...dt,last_name:qe.target.value})),placeholder:"Last",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-slate-600 text-xs",children:"Email"}),e.jsx(pe,{type:"email",value:v.email,onChange:qe=>b(dt=>({...dt,email:qe.target.value})),placeholder:"your@email.com",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-slate-600 text-xs",children:"Phone"}),e.jsx(pe,{type:"tel",value:v.phone,onChange:qe=>b(dt=>({...dt,phone:qe.target.value})),placeholder:"(555) 123-4567",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]}),J&&e.jsxs("div",{children:[e.jsx(ee,{className:"text-slate-600 text-xs",children:"Your Home Address"}),e.jsx(pe,{value:v.visitor_address,onChange:qe=>b(dt=>({...dt,visitor_address:qe.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:qe=>E(qe.target.checked),className:"rounded border-slate-300 text-slate-900 focus:ring-slate-500"}),e.jsx("span",{className:"text-sm text-slate-600",children:"Send me market updates for this area"})]}),e.jsxs("div",{className:"space-y-2 pt-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm text-slate-600",children:"Already working with an agent?"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs font-medium text-slate-400",children:I?"Yes":"No"}),e.jsx(Sn,{checked:I,onCheckedChange:P})]})]}),I&&e.jsx(pe,{value:R,onChange:qe=>D(qe.target.value),placeholder:"Agent's name",className:"mt-1 h-10 rounded-xl border-slate-200 text-sm"})]}),O&&e.jsx("p",{className:"text-destructive text-sm",children:O}),e.jsxs($,{onClick:_e,className:"w-full h-14 text-base bg-slate-900 hover:bg-slate-800 text-white rounded-xl",children:["Continue ",e.jsx(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:QFs.map(qe=>e.jsxs("button",{onClick:()=>he(qe.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:qe.emoji}),e.jsx("span",{className:"text-sm font-medium text-slate-700 group-hover:text-slate-900",children:qe.label})]},qe.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(HFs,{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, ",v.first_name,". ",Ee?"Enjoy the event!":"Enjoy the open house!"]})]}),(l==null?void 0:l.disclosure_pdf_url)&&e.jsxs("a",{href:`https://docs.google.com/gview?url=${encodeURIComponent(l.disclosure_pdf_url)}&embedded=true`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 px-5 py-3 rounded-xl bg-slate-100 hover:bg-slate-200 text-slate-800 font-medium text-sm transition-colors",children:[e.jsx(Jr,{className:"h-4 w-4"}),"View Seller's Disclosures"]}),(ue==null?void 0:ue.name)&&e.jsxs("p",{className:"text-sm text-slate-400",children:["Your host today: ",e.jsx("strong",{className:"text-slate-600",children:ue.name})]}),a&&e.jsxs("div",{className:"pt-4 space-y-3",children:[e.jsx($,{onClick:G,className:"w-full h-14 text-base font-semibold rounded-xl",children:"Sign in next visitor"}),e.jsxs("p",{className:"text-xs text-slate-400",children:["Ready for the next visitor in ",W,"s…"]})]})]})]})]}),e.jsx("p",{className:"text-center text-white/30 text-xs mt-6",children:"Powered by LevelUp Guest Book"}),a&&e.jsxs("div",{className:"fixed top-3 right-3 flex items-center gap-2 z-50",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full bg-white/10 backdrop-blur-sm text-white/80 text-[11px] px-2.5 py-1 border border-white/10",children:[e.jsx(aV,{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(RJ,{className:"h-3 w-3"})})]})]})})]})}function JFs(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 eOs(){const s=Wt();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 tOs(s){const t=Wt();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 sOs(s){const t=Wt();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 nOs=z2({first_name:vl().trim().min(1,"First name is required").max(50),last_name:vl().trim().max(50).optional(),email:vl().trim().email("Please enter a valid email").max(255),phone:vl().trim().max(20).optional().or(yx("")),message:vl().trim().max(500).optional().or(yx(""))}),m7e=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}`},rOs=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 eBt({slug:s}={}){const t=Wi(),n=s||t.slug,{data:r,isLoading:a,error:i}=K7t(n),l=eOs(),[o,c]=j.useState({first_name:"",last_name:"",email:"",phone:"",message:""}),[d,u]=j.useState(!1),[h,m]=j.useState(""),[f,g]=j.useState(""),[x,y]=j.useState(!1),v=j.useMemo(()=>rOs(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=nOs.safeParse(o);if(!P.success){g(P.error.issues[0].message);return}try{await l.mutateAsync({open_house_id:r.id,first_name:o.first_name.trim(),last_name:o.last_name.trim()||void 0,email:o.email.trim(),phone:o.phone.trim()||void 0,has_agent:d,working_with_agent_name:d&&h.trim()?h.trim():void 0,message:o.message.trim()||void 0}),y(!0)}catch(R){g((R==null?void 0:R.message)||"Something went wrong. Please try again.")}},E=j.useMemo(()=>{if(!r||!v)return"";const P=V=>String(V).padStart(2,"0"),R=`${v.getFullYear()}${P(v.getMonth()+1)}${P(v.getDate())}`,D=(r.start_time||"12:00").slice(0,5).replace(":","")+"00",O=(r.end_time||"14:00").slice(0,5).replace(":","")+"00",U=encodeURIComponent(`Open House — ${r.property_address}`),W=encodeURIComponent([r.property_address,S,r.zip].filter(Boolean).join(", "));return`https://calendar.google.com/calendar/render?action=TEMPLATE&text=${U}&dates=${R}T${D}/${R}T${O}&location=${W}`},[r,v,S]);if(a)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-[#0f1c22]",children:e.jsx("div",{className:"h-10 w-10 rounded-full border-2 border-white/20 border-t-white animate-spin"})});if(i||!r)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-[#0f1c22] p-6 text-center",children:e.jsxs("div",{className:"text-white/80",children:[e.jsx(va,{className:"h-8 w-8 mx-auto mb-3 opacity-50"}),e.jsx("h1",{className:"text-xl font-semibold mb-1",children:"Open house not found"}),e.jsx("p",{className:"text-sm text-white/50",children:"This RSVP link may have expired."})]})});const I=`https://www.google.com/maps/search/?api=1&query=${encodeURIComponent([r.property_address,S,r.zip].filter(Boolean).join(", "))}`;return e.jsxs("div",{className:"min-h-screen bg-[#f6f2ee]",children:[e.jsxs(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}${v?` on ${en(v,"EEEE, MMMM d")}`:""}.`})]}),e.jsxs("header",{className:"relative",children:[e.jsxs("div",{className:"relative h-[46vh] min-h-[320px] w-full overflow-hidden bg-[#1b3a4b]",children:[b&&e.jsx("img",{src:b,alt:r.property_address,className:"absolute inset-0 h-full w-full object-cover"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-[#0f1c22] via-[#0f1c22]/55 to-[#0f1c22]/25"}),e.jsx("div",{className:"absolute inset-x-0 bottom-0 p-6 sm:p-10",children:e.jsxs("div",{className:"mx-auto max-w-3xl",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.35em] text-[#d4b978] mb-3",children:"Open House"}),e.jsx("h1",{className:"font-serif text-3xl sm:text-4xl font-bold text-white leading-tight",children:r.property_address}),S&&e.jsxs("p",{className:"mt-1 text-white/70",children:[S," ",r.zip||""]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-x-5 gap-y-2 text-sm text-white/85",children:[v&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Ta,{className:"h-4 w-4 text-[#d4b978]"}),en(v,"EEEE, MMMM d, yyyy")]}),r.start_time&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(da,{className:"h-4 w-4 text-[#d4b978]"}),m7e(r.start_time),r.end_time?` – ${m7e(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(Dce,{icon:e.jsx(va,{className:"h-4 w-4"}),label:"Price",value:`$${Number(r.price).toLocaleString()}`}):null,r.beds?e.jsx(Dce,{icon:e.jsx(A4,{className:"h-4 w-4"}),label:"Beds",value:String(r.beds)}):null,r.baths?e.jsx(Dce,{icon:e.jsx(A0,{className:"h-4 w-4"}),label:"Baths",value:String(r.baths)}):null,r.sqft?e.jsx(Dce,{icon:e.jsx(P4,{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 ",v?en(v,"EEEE, MMMM d"):"soon",r.start_time?` at ${m7e(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(bv,{className:"mr-2 h-4 w-4"}),"Add to calendar"]})}),e.jsx($,{asChild:!0,variant:"outline",children:e.jsxs("a",{href:I,target:"_blank",rel:"noreferrer",children:[e.jsx(ci,{className:"mr-2 h-4 w-4"}),"Get directions"]})})]})]}):e.jsxs("div",{className:"p-6 sm:p-8",children:[e.jsx("h2",{className:"font-serif text-2xl font-semibold text-[#1b3a4b]",children:"Reserve your spot"}),e.jsx("p",{className:"mt-1 text-sm text-[#5b6b72]",children:"Let us know you're coming and we'll save you a spot and send a reminder."}),e.jsxs("div",{className:"mt-6 grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"rsvp-first",children:"First name *"}),e.jsx(pe,{id:"rsvp-first",value:o.first_name,onChange:P=>c(R=>({...R,first_name:P.target.value})),className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"rsvp-last",children:"Last name"}),e.jsx(pe,{id:"rsvp-last",value:o.last_name,onChange:P=>c(R=>({...R,last_name:P.target.value})),className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"rsvp-email",children:"Email *"}),e.jsx(pe,{id:"rsvp-email",type:"email",value:o.email,onChange:P=>c(R=>({...R,email:P.target.value})),className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"rsvp-phone",children:"Phone"}),e.jsx(pe,{id:"rsvp-phone",type:"tel",value:o.phone,onChange:P=>c(R=>({...R,phone:P.target.value})),className:"h-11"})]})]}),e.jsxs("div",{className:"mt-4 rounded-xl border border-[#e4dcd3] bg-[#faf7f4] p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-[#1b3a4b]",children:"Are you working with an agent?"}),e.jsx("p",{className:"text-xs text-[#7a888e]",children:"So we can respect your existing representation."})]}),e.jsx(Sn,{checked:d,onCheckedChange:u})]}),d&&e.jsx(pe,{value:h,onChange:P=>m(P.target.value),placeholder:"Your agent's name (optional)",className:"mt-3 h-10 bg-white"})]}),e.jsxs("div",{className:"mt-4 space-y-1.5",children:[e.jsx(ee,{htmlFor:"rsvp-msg",children:"Anything you'd like us to know?"}),e.jsx(Ls,{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(ci,{className:"h-4 w-4"}),"Get directions to ",r.property_address]})})]})]})}function Dce({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 Vkr(s){const{user:t}=bs();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 Hkr(){const s=Wt(),{user:t}=bs();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 Gkr(){const s=Wt();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 aOs(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 K4=(s,t,n)=>n>t?t:n{};const TL={},tBt=s=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(s),sBt=s=>typeof s=="object"&&s!==null,nBt=s=>/^0[^.\s]+$/u.test(s);function rBt(s){let t;return()=>(t===void 0&&(t=s()),t)}const tk=s=>s,Vae=(...s)=>s.reduce((t,n)=>r=>n(t(r))),Jte=(s,t,n)=>{const r=t-s;return r?(n-s)/r:1};class ost{constructor(){this.subscriptions=[]}add(t){return ist(this.subscriptions,t),()=>MEe(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,UN=s=>s/1e3,aBt=(s,t)=>t?s*(1e3/t):0,iBt=(s,t,n)=>(((1-3*n+3*t)*s+(3*n-6*t))*s+3*t)*s,oOs=1e-7,lOs=12;function cOs(s,t,n,r,a){let i,l,o=0;do l=t+(n-t)/2,i=iBt(l,r,a)-s,i>0?n=l:t=l;while(Math.abs(i)>oOs&&++ocOs(i,0,1,s,n);return i=>i===0||i===1?i:iBt(a(i),t,r)}const oBt=s=>t=>t<=.5?s(2*t)/2:(2-s(2*(1-t)))/2,lBt=s=>t=>1-s(1-t),cBt=Hae(.33,1.53,.69,.99),lst=lBt(cBt),dBt=oBt(lst),uBt=s=>s>=1?1:(s*=2)<1?.5*lst(s):.5*(2-Math.pow(2,-10*(s-1))),cst=s=>1-Math.sin(Math.acos(s)),hBt=lBt(cst),mBt=oBt(cst),dOs=Hae(.42,0,1,1),uOs=Hae(0,0,.58,1),fBt=Hae(.42,0,.58,1),hOs=s=>Array.isArray(s)&&typeof s[0]!="number",pBt=s=>Array.isArray(s)&&typeof s[0]=="number",mOs={linear:tk,easeIn:dOs,easeInOut:fBt,easeOut:uOs,circIn:cst,circInOut:mBt,circOut:hBt,backIn:lst,backInOut:dBt,backOut:cBt,anticipate:uBt},fOs=s=>typeof s=="string",t0t=s=>{if(pBt(s)){KLe(s.length===4);const[t,n,r,a]=s;return Hae(t,n,r,a)}else if(fOs(s))return mOs[s];return s},Fce=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function pOs(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 gOs=40;function gBt(s,t){let n=!1,r=!0;const a={delta:0,timestamp:0,isProcessing:!1},i=()=>n=!0,l=Fce.reduce((w,S)=>(w[S]=pOs(i),w),{}),{setup:o,read:c,resolveKeyframes:d,preUpdate:u,update:h,preRender:m,render:f,postRender:g}=l,x=()=>{const w=TL.useManualTiming,S=w?a.timestamp:performance.now();n=!1,w||(a.delta=r?1e3/60:Math.max(Math.min(S-a.timestamp,gOs),1)),a.timestamp=S,a.isProcessing=!0,o.process(a),c.process(a),d.process(a),u.process(a),h.process(a),m.process(a),f.process(a),g.process(a),a.isProcessing=!1,n&&t&&(r=!1,s(x))},y=()=>{n=!0,r=!0,a.isProcessing||s(x)};return{schedule:Fce.reduce((w,S)=>{const A=l[S];return w[S]=(E,I=!1,P=!1)=>(n||y(),A.schedule(E,I,P)),w},{}),cancel:w=>{for(let S=0;S(X4e===void 0&&p_.set(nb.isProcessing||TL.useManualTiming?nb.timestamp:performance.now()),X4e),set:s=>{X4e=s,queueMicrotask(xOs)}},xBt=s=>t=>typeof t=="string"&&t.startsWith(s),yBt=xBt("--"),yOs=xBt("var(--"),dst=s=>yOs(s)?vOs.test(s.split("/*")[0].trim()):!1,vOs=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu;function s0t(s){return typeof s!="string"?!1:s.split("/*")[0].includes("var(--")}const sK={test:s=>typeof s=="number",parse:parseFloat,transform:s=>s},ese={...sK,transform:s=>K4(0,1,s)},Oce={...sK,default:1},gee=s=>Math.round(s*1e5)/1e5,ust=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function bOs(s){return s==null}const _Os=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,hst=(s,t)=>n=>!!(typeof n=="string"&&_Os.test(n)&&n.startsWith(s)||t&&!bOs(n)&&Object.prototype.hasOwnProperty.call(n,t)),vBt=(s,t,n)=>r=>{if(typeof r!="string")return r;const[a,i,l,o]=r.match(ust);return{[s]:parseFloat(a),[t]:parseFloat(i),[n]:parseFloat(l),alpha:o!==void 0?parseFloat(o):1}},wOs=s=>K4(0,255,s),p7e={...sK,transform:s=>Math.round(wOs(s))},o8={test:hst("rgb","red"),parse:vBt("red","green","blue"),transform:({red:s,green:t,blue:n,alpha:r=1})=>"rgba("+p7e.transform(s)+", "+p7e.transform(t)+", "+p7e.transform(n)+", "+gee(ese.transform(r))+")"};function jOs(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 aGe={test:hst("#"),parse:jOs,transform:o8.transform},Gae=s=>({test:t=>typeof t=="string"&&t.endsWith(s)&&t.split(" ").length===1,parse:parseFloat,transform:t=>`${t}${s}`}),xA=Gae("deg"),F4=Gae("%"),Bo=Gae("px"),NOs=Gae("vh"),kOs=Gae("vw"),n0t={...F4,parse:s=>F4.parse(s)/100,transform:s=>F4.transform(s*100)},WU={test:hst("hsl","hue"),parse:vBt("hue","saturation","lightness"),transform:({hue:s,saturation:t,lightness:n,alpha:r=1})=>"hsla("+Math.round(s)+", "+F4.transform(gee(t))+", "+F4.transform(gee(n))+", "+gee(ese.transform(r))+")"},Ly={test:s=>o8.test(s)||aGe.test(s)||WU.test(s),parse:s=>o8.test(s)?o8.parse(s):WU.test(s)?WU.parse(s):aGe.parse(s),transform:s=>typeof s=="string"?s:s.hasOwnProperty("red")?o8.transform(s):WU.transform(s),getAnimatableNone:s=>{const t=Ly.parse(s);return t.alpha=0,Ly.transform(t)}},SOs=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function COs(s){var t,n;return isNaN(s)&&typeof s=="string"&&(((t=s.match(ust))==null?void 0:t.length)||0)+(((n=s.match(SOs))==null?void 0:n.length)||0)>0}const bBt="number",_Bt="color",AOs="var",EOs="var(",r0t="${}",TOs=/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 CG(s){const t=s.toString(),n=[],r={color:[],number:[],var:[]},a=[];let i=0;const o=t.replace(TOs,c=>(Ly.test(c)?(r.color.push(i),a.push(_Bt),n.push(Ly.parse(c))):c.startsWith(EOs)?(r.var.push(i),a.push(AOs),n.push(c)):(r.number.push(i),a.push(bBt),n.push(parseFloat(c))),++i,r0t)).split(r0t);return{values:n,split:o,indexes:r,types:a}}function MOs(s){return CG(s).values}function wBt({split:s,types:t}){const n=s.length;return r=>{let a="";for(let i=0;itypeof s=="number"?0:Ly.test(s)?Ly.getAnimatableNone(s):s,LOs=(s,t)=>typeof s=="number"?t!=null&&t.trim().endsWith("/")?s:0:IOs(s);function ROs(s){const t=CG(s);return wBt(t)(t.values.map((r,a)=>LOs(r,t.split[a])))}const aC={test:COs,parse:MOs,createTransformer:POs,getAnimatableNone:ROs};function g7e(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 DOs({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=g7e(c,o,s+1/3),i=g7e(c,o,s),l=g7e(c,o,s-1/3)}return{red:Math.round(a*255),green:Math.round(i*255),blue:Math.round(l*255),alpha:r}}function PEe(s,t){return n=>n>0?t:s}const jf=(s,t,n)=>s+(t-s)*n,x7e=(s,t,n)=>{const r=s*s,a=n*(t*t-r)+r;return a<0?0:Math.sqrt(a)},FOs=[aGe,o8,WU],OOs=s=>FOs.find(t=>t.test(s));function a0t(s){const t=OOs(s);if(!t)return!1;let n=t.parse(s);return t===WU&&(n=DOs(n)),n}const i0t=(s,t)=>{const n=a0t(s),r=a0t(t);if(!n||!r)return PEe(s,t);const a={...n};return i=>(a.red=x7e(n.red,r.red,i),a.green=x7e(n.green,r.green,i),a.blue=x7e(n.blue,r.blue,i),a.alpha=jf(n.alpha,r.alpha,i),o8.transform(a))},iGe=new Set(["none","hidden"]);function zOs(s,t){return iGe.has(s)?n=>n<=0?s:t:n=>n>=1?t:s}function BOs(s,t){return n=>jf(s,t,n)}function mst(s){return typeof s=="number"?BOs:typeof s=="string"?dst(s)?PEe:Ly.test(s)?i0t:qOs:Array.isArray(s)?jBt:typeof s=="object"?Ly.test(s)?i0t:$Os:PEe}function jBt(s,t){const n=[...s],r=n.length,a=s.map((i,l)=>mst(i)(i,t[l]));return i=>{for(let l=0;l{for(const i in r)n[i]=r[i](a);return n}}function UOs(s,t){const n=[],r={color:0,var:0,number:0};for(let a=0;a{const n=aC.createTransformer(t),r=CG(s),a=CG(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?iGe.has(s)&&!a.values.length||iGe.has(t)&&!r.values.length?zOs(s,t):Vae(jBt(UOs(r,a),a.values),n):PEe(s,t)};function NBt(s,t,n){return typeof s=="number"&&typeof t=="number"&&typeof n=="number"?jf(s,t,n):mst(s)(s,t)}const VOs=s=>{const t=({timestamp:n})=>s(n);return{start:(n=!0)=>kf.update(t,n),stop:()=>ML(t),now:()=>nb.isProcessing?nb.timestamp:p_.now()}},kBt=(s,t,n=10)=>{let r="";const a=Math.max(Math.round(t/n),2);for(let i=0;i=IEe?1/0:t}function HOs(s,t=100,n){const r=n({...s,keyframes:[0,t]}),a=Math.min(fst(r),IEe);return{type:"keyframes",ease:i=>r.next(a*i).value/t,duration:UN(a)}}const fx={stiffness:100,damping:10,mass:1,velocity:0,duration:800,bounce:.3,visualDuration:.3,restSpeed:{granular:.01,default:2},restDelta:{granular:.005,default:.5},minDuration:.01,maxDuration:10,minDamping:.05,maxDamping:1};function oGe(s,t){return s*Math.sqrt(1-t*t)}const GOs=12;function WOs(s,t,n){let r=n;for(let a=1;a{const u=d*l,h=u*s,m=u-n,f=oGe(d,l),g=Math.exp(-h);return y7e-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=oGe(Math.pow(d,2),l);return(-a(d)+y7e>0?-1:1)*((m-f)*g)/x}):(a=d=>{const u=Math.exp(-d*s),h=(d-n)*s+1;return-y7e+u*h},i=d=>{const u=Math.exp(-d*s),h=(n-d)*(s*s);return u*h});const o=5/s,c=WOs(a,i,o);if(s=f2(s),isNaN(c))return{stiffness:fx.stiffness,damping:fx.damping,duration:s};{const d=Math.pow(c,2)*r;return{stiffness:d,damping:l*2*Math.sqrt(r*d),duration:s}}}const YOs=["duration","bounce"],ZOs=["stiffness","damping","mass"];function o0t(s,t){return t.some(n=>s[n]!==void 0)}function XOs(s){let t={velocity:fx.velocity,stiffness:fx.stiffness,damping:fx.damping,mass:fx.mass,isResolvedFromDuration:!1,...s};if(!o0t(s,ZOs)&&o0t(s,YOs))if(t.velocity=0,s.visualDuration){const n=s.visualDuration,r=2*Math.PI/(n*1.2),a=r*r,i=2*K4(.05,1,1-(s.bounce||0))*Math.sqrt(a);t={...t,mass:fx.mass,stiffness:a,damping:i}}else{const n=KOs({...s,velocity:0});t={...t,...n,mass:fx.mass},t.isResolvedFromDuration=!0}return t}function LEe(s=fx.visualDuration,t=fx.bounce){const n=typeof s!="object"?{visualDuration:s,keyframes:[0,1],bounce:t}:s;let{restSpeed:r,restDelta:a}=n;const i=n.keyframes[0],l=n.keyframes[n.keyframes.length-1],o={done:!1,value:i},{stiffness:c,damping:d,mass:u,duration:h,velocity:m,isResolvedFromDuration:f}=XOs({...n,velocity:-UN(n.velocity||0)}),g=m||0,x=d/(2*Math.sqrt(c*u)),y=l-i,v=UN(Math.sqrt(c/u)),b=Math.abs(y)<5;r||(r=b?fx.restSpeed.granular:fx.restSpeed.default),a||(a=b?fx.restDelta.granular:fx.restDelta.default);let w,S,A,E,I,P;if(x<1)A=oGe(v,x),E=(g+x*v*y)/A,w=D=>{const O=Math.exp(-x*v*D);return l-O*(E*Math.sin(A*D)+y*Math.cos(A*D))},I=x*v*E+y*A,P=x*v*y-E*A,S=D=>Math.exp(-x*v*D)*(I*Math.sin(A*D)+P*Math.cos(A*D));else if(x===1){w=O=>l-Math.exp(-v*O)*(y+(g+v*y)*O);const D=g+v*y;S=O=>Math.exp(-v*O)*(v*D*O-g)}else{const D=v*Math.sqrt(x*x-1);w=V=>{const G=Math.exp(-x*v*V),Y=Math.min(D*V,300);return l-G*((g+x*v*y)*Math.sinh(Y)+D*y*Math.cosh(Y))/D};const O=(g+x*v*y)/D,U=x*v*O-y*D,W=x*v*y-O*D;S=V=>{const G=Math.exp(-x*v*V),Y=Math.min(D*V,300);return G*(U*Math.sinh(Y)+W*Math.cosh(Y))}}const R={calculatedDuration:f&&h||null,velocity:D=>f2(S(D)),next:D=>{if(!f&&x<1){const U=Math.exp(-x*v*D),W=Math.sin(A*D),V=Math.cos(A*D),G=l-U*(E*W+y*V),Y=f2(U*(I*W+P*V));return o.done=Math.abs(Y)<=r&&Math.abs(l-G)<=a,o.value=o.done?l:G,o}const O=w(D);if(f)o.done=D>=h;else{const U=f2(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(fst(R),IEe),O=kBt(U=>R.next(D*U).value,D,30);return D+"ms "+O},toTransition:()=>{}};return R}LEe.applyToOptions=s=>{const t=HOs(s,100,LEe);return s.ease=t.ease,s.duration=f2(t.duration),s.type="keyframes",s};const QOs=5;function SBt(s,t,n){const r=Math.max(t-QOs,0);return aBt(n-s(r),t-r)}function lGe({keyframes:s,velocity:t=0,power:n=.8,timeConstant:r=325,bounceDamping:a=10,bounceStiffness:i=500,modifyTarget:l,min:o,max:c,restDelta:d=.5,restSpeed:u}){const h=s[0],m={done:!1,value:h},f=P=>o!==void 0&&Pc,g=P=>o===void 0?c:c===void 0||Math.abs(o-P)-x*Math.exp(-P/r),w=P=>v+b(P),S=P=>{const R=b(P),D=w(P);m.done=Math.abs(R)<=d,m.value=m.done?v:D};let A,E;const I=P=>{f(m.value)&&(A=P,E=LEe({keyframes:[m.value,g(m.value)],velocity:SBt(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 JOs(s,t,n){const r=[],a=n||TL.mix||NBt,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=JOs(t,r,a),c=o.length,d=u=>{if(l&&u1)for(;hd(K4(s[0],s[i-1],u)):d}function t8s(s,t){const n=s[s.length-1];for(let r=1;r<=t;r++){const a=Jte(0,t,r);s.push(jf(n,1,a))}}function s8s(s){const t=[0];return t8s(t,s.length-1),t}function n8s(s,t){return s.map(n=>n*t)}function r8s(s,t){return s.map(()=>t||fBt).splice(0,s.length-1)}function xee({duration:s=300,keyframes:t,times:n,ease:r="easeInOut"}){const a=hOs(r)?r.map(t0t):t0t(r),i={done:!1,value:t[0]},l=n8s(n&&n.length===t.length?n:s8s(t),s),o=e8s(l,t,{ease:Array.isArray(a)?a:r8s(t,a)});return{calculatedDuration:s,next:c=>(i.value=o(c),i.done=c>=s,i)}}const a8s=s=>s!==null;function YLe(s,{repeat:t,repeatType:n="loop"},r,a=1){const i=s.filter(a8s),o=a<0||t&&n!=="loop"&&t%2===1?0:i.length-1;return!o||r===void 0?i[o]:r}const i8s={decay:lGe,inertia:lGe,tween:xee,keyframes:xee,spring:LEe};function CBt(s){typeof s.type=="string"&&(s.type=i8s[s.type])}class pst{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 o8s=s=>s/100;class REe extends pst{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!==p_.now()&&this.tick(p_.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;CBt(t);const{type:n=xee,repeat:r=0,repeatDelay:a=0,repeatType:i,velocity:l=0}=t;let{keyframes:o}=t;const c=n||xee;c!==xee&&typeof o[0]!="number"&&(this.mixKeyframes=Vae(o8s,NBt(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=fst(d));const{calculatedDuration:u}=d;this.calculatedDuration=u,this.resolvedDuration=u+a,this.totalDuration=this.resolvedDuration*(r+1)-a,this.generator=d}updateTime(t){const n=Math.round(t-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=n}tick(t,n=!1){const{generator:r,totalDuration:a,mixKeyframes:i,mirroredGenerator:l,resolvedDuration:o,calculatedDuration:c}=this;if(this.startTime===null)return r.next(0);const{delay:d=0,keyframes:u,repeat:h,repeatType:m,repeatDelay:f,type:g,onUpdate:x,finalKeyframe:y}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,t):this.speed<0&&(this.startTime=Math.min(t-a/this.speed,this.startTime)),n?this.currentTime=t:this.updateTime(t);const v=this.currentTime-d*(this.playbackSpeed>=0?1:-1),b=this.playbackSpeed>=0?v<0:v>a;this.currentTime=Math.max(v,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=a);let w=this.currentTime,S=r;if(h){const P=Math.min(this.currentTime,a)/o;let R=Math.floor(P),D=P%1;!D&&P>=1&&(D=1),D===1&&R--,R=Math.min(R,h+1),!!(R%2)&&(m==="reverse"?(D=1-D,f&&(D-=f/o)):m==="mirror"&&(S=l)),w=K4(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!==lGe&&(A.value=YLe(u,this.options,y,this.speed)),x&&x(A.value),I&&this.finish(),A}then(t,n){return this.finished.then(t,n)}get duration(){return UN(this.calculatedDuration)}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+UN(t)}get time(){return UN(this.currentTime)}set time(t){t=f2(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 SBt(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(p_.now()),this.playbackSpeed=t,n&&this.driver&&(this.time=UN(this.currentTime))}play(){var a,i;if(this.isStopped)return;const{driver:t=VOs,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(p_.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 l8s(s){for(let t=1;ts*180/Math.PI,cGe=s=>{const t=l8(Math.atan2(s[1],s[0]));return dGe(t)},c8s={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:s=>(Math.abs(s[0])+Math.abs(s[3]))/2,rotate:cGe,rotateZ:cGe,skewX:s=>l8(Math.atan(s[1])),skewY:s=>l8(Math.atan(s[2])),skew:s=>(Math.abs(s[1])+Math.abs(s[2]))/2},dGe=s=>(s=s%360,s<0&&(s+=360),s),l0t=cGe,c0t=s=>Math.sqrt(s[0]*s[0]+s[1]*s[1]),d0t=s=>Math.sqrt(s[4]*s[4]+s[5]*s[5]),d8s={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:c0t,scaleY:d0t,scale:s=>(c0t(s)+d0t(s))/2,rotateX:s=>dGe(l8(Math.atan2(s[6],s[5]))),rotateY:s=>dGe(l8(Math.atan2(-s[2],s[0]))),rotateZ:l0t,rotate:l0t,skewX:s=>l8(Math.atan(s[4])),skewY:s=>l8(Math.atan(s[1])),skew:s=>(Math.abs(s[1])+Math.abs(s[4]))/2};function uGe(s){return s.includes("scale")?1:0}function hGe(s,t){if(!s||s==="none")return uGe(t);const n=s.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let r,a;if(n)r=d8s,a=n;else{const o=s.match(/^matrix\(([-\d.e\s,]+)\)$/u);r=c8s,a=o}if(!a)return uGe(t);const i=r[t],l=a[1].split(",").map(h8s);return typeof i=="function"?i(l):l[i]}const u8s=(s,t)=>{const{transform:n="none"}=getComputedStyle(s);return hGe(n,t)};function h8s(s){return parseFloat(s.trim())}const nK=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],rK=new Set([...nK,"pathRotation"]),u0t=s=>s===sK||s===Bo,m8s=new Set(["x","y","z"]),f8s=nK.filter(s=>!m8s.has(s));function p8s(s){const t=[];return f8s.forEach(n=>{const r=s.getValue(n);r!==void 0&&(t.push([n,r.get()]),r.set(n.startsWith("scale")?1:0))}),t}const gI={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})=>hGe(t,"x"),y:(s,{transform:t})=>hGe(t,"y")};gI.translateX=gI.x;gI.translateY=gI.y;const o7=new Set;let mGe=!1,fGe=!1,pGe=!1;function ABt(){if(fGe){const s=Array.from(o7).filter(r=>r.needsMeasurement),t=new Set(s.map(r=>r.element)),n=new Map;t.forEach(r=>{const a=p8s(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)})}fGe=!1,mGe=!1,o7.forEach(s=>s.complete(pGe)),o7.clear()}function EBt(){o7.forEach(s=>{s.readKeyframes(),s.needsMeasurement&&(fGe=!0)})}function g8s(){pGe=!0,EBt(),ABt(),pGe=!1}class gst{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?(o7.add(this),mGe||(mGe=!0,kf.read(EBt),kf.resolveKeyframes(ABt))):(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])}l8s(t)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(t=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,t),o7.delete(this)}cancel(){this.state==="scheduled"&&(o7.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const x8s=s=>s.startsWith("--");function TBt(s,t,n){x8s(t)?s.style.setProperty(t,n):s.style[t]=n}const y8s={};function MBt(s,t){const n=rBt(s);return()=>y8s[t]??n()}const v8s=MBt(()=>window.ScrollTimeline!==void 0,"scrollTimeline"),PBt=MBt(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),iQ=([s,t,n,r])=>`cubic-bezier(${s}, ${t}, ${n}, ${r})`,h0t={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:iQ([0,.65,.55,1]),circOut:iQ([.55,0,1,.45]),backIn:iQ([.31,.01,.66,-.59]),backOut:iQ([.33,1.53,.69,.99])};function IBt(s,t){if(s)return typeof s=="function"?PBt()?kBt(s,t):"ease-out":pBt(s)?iQ(s):Array.isArray(s)?s.map(n=>IBt(n,t)||h0t.easeOut):h0t[s]}function b8s(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=IBt(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 LBt(s){return typeof s=="function"&&"applyToOptions"in s}function _8s({type:s,...t}){return LBt(s)&&PBt()?s.applyToOptions(t):(t.duration??(t.duration=300),t.ease??(t.ease="easeOut"),t)}class RBt extends pst{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,KLe(typeof t.type!="string");const d=_8s(t);this.animation=b8s(n,r,a,d,i),d.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!i){const u=YLe(a,this.options,o,this.speed);this.updateMotionValue&&this.updateMotionValue(u),TBt(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 UN(Number(t))}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+UN(t)}get time(){return UN(Number(this.animation.currentTime)||0)}set time(t){const n=this.finishedTime!==null;this.manualStartTime=null,this.finishedTime=null,this.animation.currentTime=f2(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&&v8s()?(this.animation.timeline=t,n&&(this.animation.rangeStart=n),r&&(this.animation.rangeEnd=r),tk):a(this)}}const DBt={anticipate:uBt,backInOut:dBt,circInOut:mBt};function w8s(s){return s in DBt}function j8s(s){typeof s.ease=="string"&&w8s(s.ease)&&(s.ease=DBt[s.ease])}const v7e=10;class N8s extends RBt{constructor(t){j8s(t),CBt(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 REe({...l,autoplay:!1}),c=Math.max(v7e,p_.now()-this.startTime),d=K4(0,v7e,c-v7e),u=o.sample(c).value,{name:h}=this.options;i&&h&&TBt(i,h,u),n.setWithVelocity(o.sample(Math.max(0,c-d)).value,u,d),o.stop()}}const m0t=(s,t)=>t==="zIndex"?!1:!!(typeof s=="number"||Array.isArray(s)||typeof s=="string"&&(aC.test(s)||s==="0")&&!s.startsWith("url("));function k8s(s){const t=s[0];if(s.length===1)return!0;for(let n=0;nObject.hasOwnProperty.call(Element.prototype,"animate"));function M8s(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 T8s()&&n&&(FBt.has(n)||E8s.has(n)&&A8s(o))&&(n!=="transform"||!u)&&!d&&!r&&a!=="mirror"&&i!==0&&l!=="inertia"}const P8s=40;class I8s extends pst{constructor({autoplay:t=!0,delay:n=0,type:r="keyframes",repeat:a=0,repeatDelay:i=0,repeatType:l="loop",keyframes:o,name:c,motionValue:d,element:u,...h}){var g;super(),this.stop=()=>{var x,y;this._animation&&(this._animation.stop(),(x=this.stopTimeline)==null||x.call(this)),(y=this.keyframeResolver)==null||y.cancel()},this.createdAt=p_.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)||gst;this.keyframeResolver=new f(o,(x,y,v)=>this.onKeyframesResolved(x,y,m,!v),c,d,u),(g=this.keyframeResolver)==null||g.scheduleResolve()}onKeyframesResolved(t,n,r,a){var v,b;this.keyframeResolver=void 0;const{name:i,type:l,velocity:o,delay:c,isHandoff:d,onUpdate:u}=r;this.resolvedAt=p_.now();let h=!0;S8s(t,i,l,o)||(h=!1,(TL.instantAnimations||!c)&&(u==null||u(YLe(t,r,n))),t[0]=t[t.length-1],gGe(r),r.repeat=0);const f={startTime:a?this.resolvedAt?this.resolvedAt-this.createdAt>P8s?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...r,keyframes:t},g=h&&!d&&M8s(f),x=(b=(v=f.motionValue)==null?void 0:v.owner)==null?void 0:b.current;let y;if(g)try{y=new N8s({...f,element:x})}catch{y=new REe(f)}else y=new REe(f);y.finished.then(()=>{this.notifyFinished()}).catch(tk),this.pendingTimeline&&(this.stopTimeline=y.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=y}get finished(){return this._animation?this.animation.finished:this._finished}then(t,n){return this.finished.finally(t).then(()=>{})}get animation(){var t;return this._animation||((t=this.keyframeResolver)==null||t.resume(),g8s()),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 OBt(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 f0t=30,L8s=s=>!isNaN(parseFloat(s));class R8s{constructor(t,n={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=r=>{var i;const a=p_.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=p_.now(),this.canTrackVelocity===null&&t!==void 0&&(this.canTrackVelocity=L8s(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 ost);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=p_.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||t-this.updatedAt>f0t)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,f0t);return aBt(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 AG(s,t){return new R8s(s,t)}function zBt(s,t){if(s!=null&&s.inherit&&t){const{inherit:n,...r}=s;return{...t,...r}}return s}function xst(s,t){const n=(s==null?void 0:s[t])??(s==null?void 0:s.default)??s;return n!==s?zBt(n,s):n}const D8s={type:"spring",stiffness:500,damping:25,restSpeed:10},F8s=s=>({type:"spring",stiffness:550,damping:s===0?2*Math.sqrt(550):30,restSpeed:10}),O8s={type:"keyframes",duration:.8},z8s={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},B8s=(s,{keyframes:t})=>t.length>2?O8s:rK.has(s)?s.startsWith("scale")?F8s(t[1]):D8s:z8s,$8s=new Set(["when","delay","delayChildren","staggerChildren","staggerDirection","repeat","repeatType","repeatDelay","from","elapsed"]);function U8s(s){for(const t in s)if(!$8s.has(t))return!0;return!1}const yst=(s,t,n,r={},a,i)=>l=>{const o=xst(r,s)||{},c=o.delay||r.delay||0;let{elapsed:d=0}=r;d=d-f2(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};U8s(o)||Object.assign(u,B8s(s,u)),u.duration&&(u.duration=f2(u.duration)),u.repeatDelay&&(u.repeatDelay=f2(u.repeatDelay)),u.from!==void 0&&(u.keyframes[0]=u.from);let h=!1;if((u.type===!1||u.duration===0&&!u.repeatDelay)&&(gGe(u),u.delay===0&&(h=!0)),(TL.instantAnimations||TL.skipAnimations||a!=null&&a.shouldSkipAnimations||o.skipAnimations)&&(h=!0,gGe(u),u.delay=0),u.allowFlatten=!o.type&&!o.ease,h&&!i&&t.get()!==void 0){const m=YLe(u.keyframes,o);if(m!==void 0){kf.update(()=>{u.onUpdate(m),u.onComplete()});return}}return o.isSync?new REe(u):new I8s(u)},q8s=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function V8s(s){const t=q8s.exec(s);if(!t)return[,];const[,n,r,a]=t;return[`--${n??r}`,a]}function BBt(s,t,n=1){const[r,a]=V8s(s);if(!r)return;const i=window.getComputedStyle(t).getPropertyValue(r);if(i){const l=i.trim();return tBt(l)?parseFloat(l):l}return dst(a)?BBt(a,t,n+1):a}function p0t(s){const t=[{},{}];return s==null||s.values.forEach((n,r)=>{t[0][r]=n.get(),t[1][r]=n.getVelocity()}),t}function vst(s,t,n,r){if(typeof t=="function"){const[a,i]=p0t(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]=p0t(r);t=t(n!==void 0?n:s.custom,a,i)}return t}function l7(s,t,n){const r=s.getProps();return vst(r,t,n!==void 0?n:r.custom,s)}const $Bt=new Set(["width","height","top","left","right","bottom",...nK]),xGe=s=>Array.isArray(s);function H8s(s,t,n){s.hasValue(t)?s.getValue(t).set(n):s.addValue(t,AG(n))}function G8s(s){return xGe(s)?s[s.length-1]||0:s}function W8s(s,t){const n=l7(s,t);let{transitionEnd:r={},transition:a={},...i}=n||{};i={...i,...r};for(const l in i){const o=G8s(i[l]);H8s(s,l,o)}}const hb=s=>!!(s&&s.getVelocity);function K8s(s){return!!(hb(s)&&s.add)}function yGe(s,t){const n=s.getValue("willChange");if(K8s(n))return n.add(t);if(!n&&TL.WillChange){const r=new TL.WillChange("auto");s.addValue("willChange",r),r.add(t)}}function bst(s){return s.replace(/([A-Z])/g,t=>`-${t.toLowerCase()}`)}const Y8s="framerAppearId",UBt="data-"+bst(Y8s);function qBt(s){return s.props[UBt]}function Z8s({protectedKeys:s,needsAnimating:t},n){const r=s.hasOwnProperty(n)&&t[n]!==!0;return t[n]=!1,r}function VBt(s,t,{delay:n=0,transitionOverride:r,type:a}={}){let{transition:i,transitionEnd:l,...o}=t;const c=s.getDefaultTransition();i=i?zBt(i,c):c;const d=i==null?void 0:i.reduceMotion,u=i==null?void 0:i.skipAnimations;r&&(i=r);const h=[],m=a&&s.animationState&&s.animationState.getState()[a],f=i==null?void 0:i.path;f&&f.animateVisualElement(s,o,i,n,h);for(const g in o){const x=s.getValue(g,s.latestValues[g]??null),y=o[g];if(y===void 0||m&&Z8s(m,g))continue;const v={delay:n,...xst(i||{},g)};u&&(v.skipAnimations=!0);const b=x.get();if(b!==void 0&&!x.isAnimating()&&!Array.isArray(y)&&y===b&&!v.velocity){kf.update(()=>x.set(y));continue}let w=!1;if(window.MotionHandoffAnimation){const E=qBt(s);if(E){const I=window.MotionHandoffAnimation(E,g,kf);I!==null&&(v.startTime=I,w=!0)}}yGe(s,g);const S=d??s.shouldReduceMotion;x.start(yst(g,x,y,S&&$Bt.has(g)?{type:!1}:v,s,w));const A=x.animation;A&&h.push(A)}if(l){const g=()=>kf.update(()=>{l&&W8s(s,l)});h.length?Promise.all(h).then(g):g()}return h}function vGe(s,t,n={}){var c;const r=l7(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(VBt(s,r,n)):()=>Promise.resolve(),l=s.variantChildren&&s.variantChildren.size?(d=0)=>{const{delayChildren:u=0,staggerChildren:h,staggerDirection:m}=a;return X8s(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 X8s(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(vGe(c,t,{...l,delay:n+(typeof r=="function"?0:r)+OBt(s.variantChildren,c,r,a,i)}).then(()=>c.notify("AnimationComplete",t)));return Promise.all(o)}function Q8s(s,t,n={}){s.notify("AnimationStart",t);let r;if(Array.isArray(t)){const a=t.map(i=>vGe(s,i,n));r=Promise.all(a)}else if(typeof t=="string")r=vGe(s,t,n);else{const a=typeof t=="function"?l7(s,t,n.custom):t;r=Promise.all(VBt(s,a,n))}return r.then(()=>{s.notify("AnimationComplete",t)})}const J8s={test:s=>s==="auto",parse:s=>s},HBt=s=>t=>t.test(s),GBt=[sK,Bo,F4,xA,kOs,NOs,J8s],g0t=s=>GBt.find(HBt(s));function ezs(s){return typeof s=="number"?s===0:s!==null?s==="none"||s==="0"||nBt(s):!0}const tzs=new Set(["brightness","contrast","saturate","opacity"]);function szs(s){const[t,n]=s.slice(0,-1).split("(");if(t==="drop-shadow")return s;const[r]=n.match(ust)||[];if(!r)return s;const a=n.replace(r,"");let i=tzs.has(t)?1:0;return r!==n&&(i*=100),t+"("+i+a+")"}const nzs=/\b([a-z-]*)\(.*?\)/gu,bGe={...aC,getAnimatableNone:s=>{const t=s.match(nzs);return t?t.map(szs).join(" "):s}},_Ge={...aC,getAnimatableNone:s=>{const t=aC.parse(s);return aC.createTransformer(s)(t.map(r=>typeof r=="number"?0:typeof r=="object"?{...r,alpha:1}:r))}},x0t={...sK,transform:Math.round},rzs={rotate:xA,pathRotation:xA,rotateX:xA,rotateY:xA,rotateZ:xA,scale:Oce,scaleX:Oce,scaleY:Oce,scaleZ:Oce,skew:xA,skewX:xA,skewY:xA,distance:Bo,translateX:Bo,translateY:Bo,translateZ:Bo,x:Bo,y:Bo,z:Bo,perspective:Bo,transformPerspective:Bo,opacity:ese,originX:n0t,originY:n0t,originZ:Bo},DEe={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,...rzs,zIndex:x0t,fillOpacity:ese,strokeOpacity:ese,numOctaves:x0t},azs={...DEe,color:Ly,backgroundColor:Ly,outlineColor:Ly,fill:Ly,stroke:Ly,borderColor:Ly,borderTopColor:Ly,borderRightColor:Ly,borderBottomColor:Ly,borderLeftColor:Ly,filter:bGe,WebkitFilter:bGe,mask:_Ge,WebkitMask:_Ge},WBt=s=>azs[s],izs=new Set([bGe,_Ge]);function KBt(s,t){let n=WBt(s);return izs.has(n)||(n=aC),n.getAnimatableNone?n.getAnimatableNone(t):void 0}const ozs=new Set(["auto","none","0"]);function lzs(s,t,n){let r=0,a;for(;r{t.getValue(c).set(d)}),this.resolveNoneKeyframes()}}const _st=["borderTopLeftRadius","borderTopRightRadius","borderBottomRightRadius","borderBottomLeftRadius"];function wst(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 wGe=(s,t)=>t&&typeof s=="number"?t.transform(s):s;function Q4e(s){return sBt(s)&&"offsetHeight"in s&&!("ownerSVGElement"in s)}const{schedule:jst}=gBt(queueMicrotask,!1),dS={x:!1,y:!1};function YBt(){return dS.x||dS.y}function dzs(s){return s==="x"||s==="y"?dS[s]?null:(dS[s]=!0,()=>{dS[s]=!1}):dS.x||dS.y?null:(dS.x=dS.y=!0,()=>{dS.x=dS.y=!1})}function ZBt(s,t){const n=wst(s),r=new AbortController,a={passive:!0,...t,signal:r.signal};return[n,a,()=>r.abort()]}function uzs(s){return!(s.pointerType==="touch"||YBt())}function hzs(s,t,n={}){const[r,a,i]=ZBt(s,n);return r.forEach(l=>{let o=!1,c=!1,d;const u=()=>{l.removeEventListener("pointerleave",g)},h=y=>{d&&(d(y),d=void 0),u()},m=y=>{o=!1,window.removeEventListener("pointerup",m),window.removeEventListener("pointercancel",m),c&&(c=!1,h(y))},f=()=>{o=!0,window.addEventListener("pointerup",m,a),window.addEventListener("pointercancel",m,a)},g=y=>{if(y.pointerType!=="touch"){if(o){c=!0;return}h(y)}},x=y=>{if(!uzs(y))return;c=!1;const v=t(l,y);typeof v=="function"&&(d=v,l.addEventListener("pointerleave",g,a))};l.addEventListener("pointerenter",x,a),l.addEventListener("pointerdown",f,a)}),i}const XBt=(s,t)=>t?s===t?!0:XBt(s,t.parentElement):!1,Nst=s=>s.pointerType==="mouse"?typeof s.button!="number"||s.button<=0:s.isPrimary!==!1,mzs=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function fzs(s){return mzs.has(s.tagName)||s.isContentEditable===!0}const pzs=new Set(["INPUT","SELECT","TEXTAREA"]);function gzs(s){return pzs.has(s.tagName)||s.isContentEditable===!0}const J4e=new WeakSet;function y0t(s){return t=>{t.key==="Enter"&&s(t)}}function b7e(s,t){s.dispatchEvent(new PointerEvent("pointer"+t,{isPrimary:!0,bubbles:!0}))}const xzs=(s,t)=>{const n=s.currentTarget;if(!n)return;const r=y0t(()=>{if(J4e.has(n))return;b7e(n,"down");const a=y0t(()=>{b7e(n,"up")}),i=()=>b7e(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 v0t(s){return Nst(s)&&!YBt()}const b0t=new WeakSet;function yzs(s,t,n={}){const[r,a,i]=ZBt(s,n),l=o=>{const c=o.currentTarget;if(!v0t(o)||b0t.has(o))return;J4e.add(c),n.stopPropagation&&b0t.add(o);const d=t(c,o),u={...a,capture:!0},h=(g,x)=>{window.removeEventListener("pointerup",m,u),window.removeEventListener("pointercancel",f,u),J4e.has(c)&&J4e.delete(c),v0t(g)&&typeof d=="function"&&d(g,{success:x})},m=g=>{h(g,c===window||c===document||n.useGlobalTarget||XBt(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),Q4e(o)&&(o.addEventListener("focus",d=>xzs(d,a)),!fzs(o)&&!o.hasAttribute("tabindex")&&(o.tabIndex=0))}),i}function kst(s){return sBt(s)&&"ownerSVGElement"in s}const e3e=new WeakMap;let HM;const QBt=(s,t,n)=>(r,a)=>a&&a[0]?a[0][s+"Size"]:kst(r)&&"getBBox"in r?r.getBBox()[t]:r[n],vzs=QBt("inline","width","offsetWidth"),bzs=QBt("block","height","offsetHeight");function _zs({target:s,borderBoxSize:t}){var n;(n=e3e.get(s))==null||n.forEach(r=>{r(s,{get width(){return vzs(s,t)},get height(){return bzs(s,t)}})})}function wzs(s){s.forEach(_zs)}function jzs(){typeof ResizeObserver>"u"||(HM=new ResizeObserver(wzs))}function Nzs(s,t){HM||jzs();const n=wst(s);return n.forEach(r=>{let a=e3e.get(r);a||(a=new Set,e3e.set(r,a)),a.add(t),HM==null||HM.observe(r)}),()=>{n.forEach(r=>{const a=e3e.get(r);a==null||a.delete(t),a!=null&&a.size||HM==null||HM.unobserve(r)})}}const t3e=new Set;let KU;function kzs(){KU=()=>{const s={get width(){return window.innerWidth},get height(){return window.innerHeight}};t3e.forEach(t=>t(s))},window.addEventListener("resize",KU)}function Szs(s){return t3e.add(s),KU||kzs(),()=>{t3e.delete(s),!t3e.size&&typeof KU=="function"&&(window.removeEventListener("resize",KU),KU=void 0)}}function _0t(s,t){return typeof s=="function"?Szs(s):Nzs(s,t)}function Czs(s){return kst(s)&&s.tagName==="svg"}const Azs=[...GBt,Ly,aC],Ezs=s=>Azs.find(HBt(s)),w0t=()=>({translate:0,scale:1,origin:0,originPoint:0}),YU=()=>({x:w0t(),y:w0t()}),j0t=()=>({min:0,max:0}),u0=()=>({x:j0t(),y:j0t()}),Tzs=new WeakMap;function ZLe(s){return s!==null&&typeof s=="object"&&typeof s.start=="function"}function tse(s){return typeof s=="string"||Array.isArray(s)}const Sst=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],Cst=["initial",...Sst];function XLe(s){return ZLe(s.animate)||Cst.some(t=>tse(s[t]))}function JBt(s){return!!(XLe(s)||s.variants)}function Mzs(s,t,n){for(const r in t){const a=t[r],i=n[r];if(hb(a))s.addValue(r,a);else if(hb(i))s.addValue(r,AG(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,AG(l!==void 0?l:a,{owner:s}))}}for(const r in n)t[r]===void 0&&s.removeValue(r);return t}const jGe={current:null},e9t={current:!1},Pzs=typeof window<"u";function Izs(){if(e9t.current=!0,!!Pzs)if(window.matchMedia){const s=window.matchMedia("(prefers-reduced-motion)"),t=()=>jGe.current=s.matches;s.addEventListener("change",t),t()}else jGe.current=!1}const N0t=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];let FEe={};function t9t(s){FEe=s}function Lzs(){return FEe}class Rzs{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=gst,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=p_.now();this.renderScheduledAtthis.bindToMotionValue(i,a)),this.reducedMotionConfig==="never"?this.shouldReduceMotion=!1:this.reducedMotionConfig==="always"?this.shouldReduceMotion=!0:(e9t.current||Izs(),this.shouldReduceMotion=jGe.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(),ML(this.notifyUpdate),ML(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&&FBt.has(t)&&this.current instanceof HTMLElement){const{factory:l,keyframes:o,times:c,ease:d,duration:u}=n.accelerate,h=new RBt({element:this.current,name:t,keyframes:o,times:c,ease:d,duration:f2(u)}),m=l(h);this.valueSubscriptions.set(t,()=>{m(),h.cancel()});return}const r=rK.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 FEe){const n=FEe[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):u0()}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=AG(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"&&(tBt(r)||nBt(r))?r=parseFloat(r):!Ezs(r)&&aC.test(n)&&(r=KBt(t,n)),this.setBaseTarget(t,hb(r)?r.get():r)),hb(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=vst(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&&!hb(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 ost),this.events[t].add(n)}notify(t,...n){this.events[t]&&this.events[t].notify(...n)}scheduleRenderMicrotask(){jst.render(this.render)}}class s9t extends Rzs{constructor(){super(...arguments),this.KeyframeResolver=czs}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;hb(t)&&(this.childSubscription=t.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}}class o6{constructor(t){this.isMounted=!1,this.node=t}update(){}}function n9t({top:s,left:t,right:n,bottom:r}){return{x:{min:t,max:n},y:{min:s,max:r}}}function Dzs({x:s,y:t}){return{top:t.min,right:s.max,bottom:t.max,left:s.min}}function Fzs(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 _7e(s){return s===void 0||s===1}function NGe({scale:s,scaleX:t,scaleY:n}){return!_7e(s)||!_7e(t)||!_7e(n)}function IO(s){return NGe(s)||r9t(s)||s.z||s.rotate||s.rotateX||s.rotateY||s.skewX||s.skewY}function r9t(s){return k0t(s.x)||k0t(s.y)}function k0t(s){return s&&s!=="0%"}function OEe(s,t,n){const r=s-n,a=t*r;return n+a}function S0t(s,t,n,r,a){return a!==void 0&&(s=OEe(s,a,r)),OEe(s,n,r)+t}function kGe(s,t=0,n=1,r,a){s.min=S0t(s.min,t,n,r,a),s.max=S0t(s.max,t,n,r,a)}function a9t(s,{x:t,y:n}){kGe(s.x,t.translate,t.scale,t.originPoint),kGe(s.y,n.translate,n.scale,n.originPoint)}const C0t=.999999999999,A0t=1.0000000000001;function Ozs(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;cC0t&&(t.x=1),t.yC0t&&(t.y=1)}function n4(s,t){s.min+=t,s.max+=t}function E0t(s,t,n,r,a=.5){const i=jf(s.min,s.max,a);kGe(s,t,n,i,r)}function T0t(s,t){return typeof s=="string"?parseFloat(s)/100*(t.max-t.min):s}function s3e(s,t,n){const r=n??s;E0t(s.x,T0t(t.x,r.x),t.scaleX,t.scale,t.originX),E0t(s.y,T0t(t.y,r.y),t.scaleY,t.scale,t.originY)}function i9t(s,t){return n9t(Fzs(s.getBoundingClientRect(),t))}function zzs(s,t,n){const r=i9t(s,n),{scroll:a}=t;return a&&(n4(r.x,a.offset.x),n4(r.y,a.offset.y)),r}const Bzs={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},$zs=nK.length;function Uzs(s,t,n){let r="",a=!0;for(let l=0;l<$zs;l++){const o=nK[l],c=s[o];if(c===void 0)continue;let d=!0;if(typeof c=="number")d=c===(o.startsWith("scale")?1:0);else{const u=parseFloat(c);d=o.startsWith("scale")?u===1:u===0}if(!d||n){const u=wGe(c,DEe[o]);if(!d){a=!1;const h=Bzs[o]||o;r+=`${h}(${u}) `}n&&(t[o]=u)}}const i=s.pathRotation;return i&&(a=!1,r+=`rotate(${wGe(i,DEe.pathRotation)}) `),r=r.trim(),n?r=n(t,a?"":r):a&&(r="none"),r}function Ast(s,t,n){const{style:r,vars:a,transformOrigin:i}=s;let l=!1,o=!1;for(const c in t){const d=t[c];if(rK.has(c)){l=!0;continue}else if(yBt(c)){a[c]=d;continue}else{const u=wGe(d,DEe[c]);c.startsWith("origin")?(o=!0,i[c]=u):r[c]=u}}if(t.transform||(l||n?r.transform=Uzs(t,s.transform,n):r.transform&&(r.transform="none")),o){const{originX:c="50%",originY:d="50%",originZ:u=0}=i;r.transformOrigin=`${c} ${d} ${u}`}}function o9t(s,{style:t,vars:n},r,a){const i=s.style;let l;for(l in t)i[l]=t[l];a==null||a.applyProjectionStyles(i,r);for(l in n)i.setProperty(l,n[l])}function M0t(s,t){return t.max===t.min?0:s/(t.max-t.min)*100}const CZ={correct:(s,t)=>{if(!t.target)return s;if(typeof s=="string")if(Bo.test(s))s=parseFloat(s);else return s;const n=M0t(s,t.target.x),r=M0t(s,t.target.y);return`${n}% ${r}%`}},qzs={correct:(s,{treeScale:t,projectionDelta:n})=>{const r=s,a=aC.parse(s);if(a.length>5)return r;const i=aC.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)}},SGe={borderRadius:{...CZ,applyTo:[..._st]},borderTopLeftRadius:CZ,borderTopRightRadius:CZ,borderBottomLeftRadius:CZ,borderBottomRightRadius:CZ,boxShadow:qzs};function l9t(s,{layout:t,layoutId:n}){return rK.has(s)||s.startsWith("origin")||(t||n!==void 0)&&(!!SGe[s]||s==="opacity")}function Est(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)(hb(r[o])||a&&hb(a[o])||l9t(o,s)||((l=n==null?void 0:n.getValue(o))==null?void 0:l.liveStyle)!==void 0)&&(i[o]=r[o]);return i}function Vzs(s){return window.getComputedStyle(s)}class Hzs extends s9t{constructor(){super(...arguments),this.type="html",this.renderInstance=o9t}mount(t){KLe(!!t.style),super.mount(t)}readValueFromInstance(t,n){var r;if(rK.has(n))return(r=this.projection)!=null&&r.isProjecting?uGe(n):u8s(t,n);{const a=Vzs(t),i=(yBt(n)?a.getPropertyValue(n):a[n])||0;return typeof i=="string"?i.trim():i}}measureInstanceViewportBox(t,{transformPagePoint:n}){return i9t(t,n)}build(t,n,r){Ast(t,n,r.transformTemplate)}scrapeMotionValuesFromProps(t,n,r){return Est(t,n,r)}}const Gzs={offset:"stroke-dashoffset",array:"stroke-dasharray"},Wzs={offset:"strokeDashoffset",array:"strokeDasharray"};function Kzs(s,t,n=1,r=0,a=!0){s.pathLength=1;const i=a?Gzs:Wzs;s[i.offset]=`${-r}`,s[i.array]=`${t} ${n}`}const Yzs=["offsetDistance","offsetPath","offsetRotate","offsetAnchor"];function c9t(s,{attrX:t,attrY:n,attrScale:r,pathLength:a,pathSpacing:i=1,pathOffset:l=0,...o},c,d,u){if(Ast(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 Yzs)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&&Kzs(h,a,i,l,!1)}const d9t=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"]),u9t=s=>typeof s=="string"&&s.toLowerCase()==="svg";function Zzs(s,t,n,r){o9t(s,t,void 0,r);for(const a in t.attrs)s.setAttribute(d9t.has(a)?a:bst(a),t.attrs[a])}function h9t(s,t,n){const r=Est(s,t,n);for(const a in s)if(hb(s[a])||hb(t[a])){const i=nK.indexOf(a)!==-1?"attr"+a.charAt(0).toUpperCase()+a.substring(1):a;r[i]=s[a]}return r}class Xzs extends s9t{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=u0}getBaseTargetFromProps(t,n){return t[n]}readValueFromInstance(t,n){if(rK.has(n)){const r=WBt(n);return r&&r.default||0}return n=d9t.has(n)?n:bst(n),t.getAttribute(n)}scrapeMotionValuesFromProps(t,n,r){return h9t(t,n,r)}build(t,n,r){c9t(t,n,this.isSVGTag,r.transformTemplate,r.style)}renderInstance(t,n,r,a){Zzs(t,n,r,a)}mount(t){this.isSVGTag=u9t(t.tagName),super.mount(t)}}const Qzs=Cst.length;function m9t(s){if(!s)return;if(!s.isControllingVariants){const n=s.parent?m9t(s.parent)||{}:{};return s.props.initial!==void 0&&(n.initial=s.props.initial),n}const t={};for(let n=0;nPromise.all(t.map(({animation:n,options:r})=>Q8s(s,n,r)))}function s7s(s){let t=t7s(s),n=P0t(),r=!0,a=!1;const i=d=>(u,h)=>{var f;const m=l7(s,h,d==="exit"?(f=s.presenceContext)==null?void 0:f.custom:void 0);if(m){const{transition:g,transitionEnd:x,...y}=m;u={...u,...y,...x}}return u};function l(d){t=d(s)}function o(d){const{props:u}=s,h=m9t(s.parent)||{},m=[],f=new Set;let g={},x=1/0;for(let v=0;vx&&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],ne=W[ae];if(g.hasOwnProperty(ae))continue;let te=!1;xGe(le)&&xGe(ne)?te=!f9t(le,ne)||P:te=le!==ne,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 Y=I&&P;R&&(!Y||D)&&m.push(...O.map(ae=>{const le={type:b};if(typeof ae=="string"&&(r||a)&&!Y&&s.manuallyAnimateOnMount&&s.parent){const{parent:ne}=s,te=l7(ne,ae);if(ne.enteringChildren&&te){const{delayChildren:J}=te.transition||{};le.delay=OBt(ne.enteringChildren,s,J)}}return{animation:ae,options:le}}))}if(f.size){const v={};if(typeof u.initial!="boolean"){const b=l7(s,Array.isArray(u.initial)?u.initial[0]:u.initial);b&&b.transition&&(v.transition=b.transition)}f.forEach(b=>{const w=s.getBaseTarget(b),S=s.getValue(b);S&&(S.liveStyle=!0),v[b]=w??null}),m.push({animation:v})}let y=!!m.length;return r&&(u.initial===!1||u.initial===u.animate)&&!s.manuallyAnimateOnMount&&(y=!1),r=!1,a=!1,y?t(m):Promise.resolve()}function c(d,u){var m;if(n[d].isActive===u)return Promise.resolve();(m=s.variantChildren)==null||m.forEach(f=>{var g;return(g=f.animationState)==null?void 0:g.setActive(d,u)}),n[d].isActive=u;const h=o(d);for(const f in n)n[f].protectedKeys={};return h}return{animateChanges:o,setActive:c,setAnimateFunction:l,getState:()=>n,reset:()=>{n=P0t(),a=!0}}}function n7s(s,t){return typeof t=="string"?t!==s:Array.isArray(t)?!f9t(t,s):!1}function mR(s=!1){return{isActive:s,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function P0t(){return{animate:mR(!0),whileInView:mR(),whileHover:mR(),whileTap:mR(),whileDrag:mR(),whileFocus:mR(),exit:mR()}}function CGe(s,t){s.min=t.min,s.max=t.max}function Jk(s,t){CGe(s.x,t.x),CGe(s.y,t.y)}function I0t(s,t){s.translate=t.translate,s.scale=t.scale,s.originPoint=t.originPoint,s.origin=t.origin}const p9t=1e-4,r7s=1-p9t,a7s=1+p9t,g9t=.01,i7s=0-g9t,o7s=0+g9t;function g_(s){return s.max-s.min}function l7s(s,t,n){return Math.abs(s-t)<=n}function L0t(s,t,n,r=.5){s.origin=r,s.originPoint=jf(t.min,t.max,s.origin),s.scale=g_(n)/g_(t),s.translate=jf(n.min,n.max,s.origin)-s.originPoint,(s.scale>=r7s&&s.scale<=a7s||isNaN(s.scale))&&(s.scale=1),(s.translate>=i7s&&s.translate<=o7s||isNaN(s.translate))&&(s.translate=0)}function yee(s,t,n,r){L0t(s.x,t.x,n.x,r?r.originX:void 0),L0t(s.y,t.y,n.y,r?r.originY:void 0)}function R0t(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+g_(t)}function c7s(s,t,n,r){R0t(s.x,t.x,n.x,r==null?void 0:r.x),R0t(s.y,t.y,n.y,r==null?void 0:r.y)}function D0t(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+g_(t)}function zEe(s,t,n,r){D0t(s.x,t.x,n.x,r==null?void 0:r.x),D0t(s.y,t.y,n.y,r==null?void 0:r.y)}function F0t(s,t,n,r,a){return s-=t,s=OEe(s,1/n,r),a!==void 0&&(s=OEe(s,1/a,r)),s}function d7s(s,t=0,n=1,r=.5,a,i=s,l=s){if(F4.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=F0t(s.min,t,n,o,a),s.max=F0t(s.max,t,n,o,a)}function O0t(s,t,[n,r,a],i,l){d7s(s,t[n],t[r],t[a],t.scale,i,l)}const u7s=["x","scaleX","originX"],h7s=["y","scaleY","originY"];function z0t(s,t,n,r){O0t(s.x,t,u7s,n?n.x:void 0,r?r.x:void 0),O0t(s.y,t,h7s,n?n.y:void 0,r?r.y:void 0)}function B0t(s){return s.translate===0&&s.scale===1}function x9t(s){return B0t(s.x)&&B0t(s.y)}function $0t(s,t){return s.min===t.min&&s.max===t.max}function m7s(s,t){return $0t(s.x,t.x)&&$0t(s.y,t.y)}function U0t(s,t){return Math.round(s.min)===Math.round(t.min)&&Math.round(s.max)===Math.round(t.max)}function y9t(s,t){return U0t(s.x,t.x)&&U0t(s.y,t.y)}function q0t(s){return g_(s.x)/g_(s.y)}function V0t(s,t){return s.translate===t.translate&&s.scale===t.scale&&s.originPoint===t.originPoint}function _5(s){return[s("x"),s("y")]}function f7s(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 p7s=_st.length,H0t=s=>typeof s=="string"?parseFloat(s):s,G0t=s=>typeof s=="number"||Bo.test(s);function g7s(s,t,n,r,a,i){a?(s.opacity=jf(0,n.opacity??1,x7s(r)),s.opacityExit=jf(t.opacity??1,0,y7s(r))):i&&(s.opacity=jf(t.opacity??1,n.opacity??1,r));for(let l=0;lrt?1:n(Jte(s,t,r))}function v7s(s,t,n){const r=hb(s)?s:AG(s);return r.start(yst("",r,t,n)),r.animation}function sse(s,t,n,r={passive:!0}){return s.addEventListener(t,n,r),()=>s.removeEventListener(t,n,r)}const b7s=(s,t)=>s.depth-t.depth;class _7s{constructor(){this.children=[],this.isDirty=!1}add(t){ist(this.children,t),this.isDirty=!0}remove(t){MEe(this.children,t),this.isDirty=!0}forEach(t){this.isDirty&&this.children.sort(b7s),this.isDirty=!1,this.children.forEach(t)}}function w7s(s,t){const n=p_.now(),r=({timestamp:a})=>{const i=a-n;i>=t&&(ML(r),s(i-t))};return kf.setup(r,!0),()=>ML(r)}function n3e(s){return hb(s)?s.get():s}class j7s{constructor(){this.members=[]}add(t){ist(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&&(MEe(this.members,r),r.unmount())}t.scheduleRender()}remove(t){if(MEe(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 r3e={hasAnimatedSinceResize:!0,hasEverUpdated:!1},w7e=["","X","Y","Z"],N7s=1e3;let k7s=0;function j7e(s,t,n,r){const{latestValues:a}=t;a[s]&&(n[s]=a[s],t.setStaticValue(s,0),r&&(r[s]=0))}function b9t(s){if(s.hasCheckedOptimisedAppear=!0,s.root===s)return;const{visualElement:t}=s.options;if(!t)return;const n=qBt(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&&b9t(r)}function _9t({attachResizeListener:s,defaultParent:t,measureScroll:n,checkIsScrollRoot:r,resetTransform:a}){return class{constructor(l={},o=t==null?void 0:t()){this.id=k7s++,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(A7s),this.nodes.forEach(L7s),this.nodes.forEach(R7s),this.nodes.forEach(E7s)},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=w7s(m,250),r3e.hasAnimatedSinceResize&&(r3e.hasAnimatedSinceResize=!1,this.nodes.forEach(Z0t)))})}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()||B7s,{onLayoutAnimationStart:x,onLayoutAnimationComplete:y}=d.getProps(),v=!this.targetLayout||!y9t(this.targetLayout,f),b=!h&&m;if(this.options.layoutRoot||this.resumeFrom||b||h&&(v||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const w={...xst(g,"layout"),onPlay:x,onComplete:y};(d.shouldReduceMotion||this.options.layoutRoot)&&(w.delay=0,w.type=!1),this.startAnimation(w),this.setAnimationOrigin(u,b,w.path)}else h||Z0t(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(),ML(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(D7s),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&&b9t(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&&!g_(this.snapshot.measuredBox.x)&&!g_(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):(X0t(m.x,l.x,I),X0t(m.y,l.y,I)),this.setTargetDelta(m),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(zEe(f,this.layout.layoutBox,this.relativeParent.layout.layoutBox,this.options.layoutAnchor||void 0),O7s(this.relativeTarget,this.relativeTargetOrigin,f,I),S&&m7s(this.relativeTarget,S)&&(this.isProjectionDirty=!1),S||(S=u0()),Jk(S,this.relativeTarget)),y&&(this.animationValues=h,g7s(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&&(ML(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=kf.update(()=>{r3e.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=AG(0)),this.motionValue.jump(0,!1),this.currentAnimation=v7s(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(N7s),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&&w9t(this.options.animationType,this.layout.layoutBox,d.layoutBox)){c=this.target||u0();const h=g_(this.layout.layoutBox.x);c.x.min=l.target.x.min,c.x.max=c.x.min+h;const m=g_(this.layout.layoutBox.y);c.y.min=l.target.y.min,c.y.max=c.y.min+m}Jk(o,c),s3e(o,u),yee(this.projectionDeltaWithTransform,this.layoutCorrected,o,u)}}registerSharedNode(l,o){this.sharedNodes.has(l)||this.sharedNodes.set(l,new j7s),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&&j7e("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(K0t),this.root.sharedNodes.clear()}}}function S7s(s){s.updateLayout()}function C7s(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")_5(h=>{const m=l?t.measuredBox[h]:t.layoutBox[h],f=g_(m);m.min=r[h].min,m.max=m.min+f});else if(i==="x"||i==="y"){const h=i==="x"?"y":"x";CGe(l?t.measuredBox[h]:t.layoutBox[h],r[h])}else w9t(i,t.layoutBox,r)&&_5(h=>{const m=l?t.measuredBox[h]:t.layoutBox[h],f=g_(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=YU();yee(o,r,t.layoutBox);const c=YU();l?yee(c,s.applyTransform(a,!0),t.measuredBox):yee(c,r,t.layoutBox);const d=!x9t(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=u0();zEe(x,t.layoutBox,m.layoutBox,g);const y=u0();zEe(y,r,f.layoutBox,g),y9t(x,y)||(u=!0),h.options.layoutRoot&&(s.relativeTarget=y,s.relativeTargetOrigin=x,s.relativeParent=h)}}}s.notifyListeners("didUpdate",{layout:r,snapshot:t,delta:c,layoutDelta:o,hasLayoutChanged:d,hasRelativeLayoutChanged:u})}else if(s.isLead()){const{onExitComplete:r}=s.options;r&&r()}s.options.transition=void 0}function A7s(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 E7s(s){s.isProjectionDirty=s.isSharedProjectionDirty=s.isTransformDirty=!1}function T7s(s){s.clearSnapshot()}function K0t(s){s.clearMeasurements()}function M7s(s){s.isLayoutDirty=!0,s.updateLayout()}function Y0t(s){s.isLayoutDirty=!1}function P7s(s){s.isAnimationBlocked&&s.layout&&!s.isLayoutDirty&&(s.snapshot=s.layout,s.isLayoutDirty=!0)}function I7s(s){const{visualElement:t}=s.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify("BeforeLayoutMeasure"),s.resetTransform()}function Z0t(s){s.finishAnimation(),s.targetDelta=s.relativeTarget=s.target=void 0,s.isProjectionDirty=!0}function L7s(s){s.resolveTargetDelta()}function R7s(s){s.calcProjection()}function D7s(s){s.resetSkewAndRotation()}function F7s(s){s.removeLeadSnapshot()}function X0t(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 Q0t(s,t,n,r){s.min=jf(t.min,n.min,r),s.max=jf(t.max,n.max,r)}function O7s(s,t,n,r){Q0t(s.x,t.x,n.x,r),Q0t(s.y,t.y,n.y,r)}function z7s(s){return s.animationValues&&s.animationValues.opacityExit!==void 0}const B7s={duration:.45,ease:[.4,0,.1,1]},J0t=s=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(s),evt=J0t("applewebkit/")&&!J0t("chrome/")?Math.round:tk;function tvt(s){s.min=evt(s.min),s.max=evt(s.max)}function $7s(s){tvt(s.x),tvt(s.y)}function w9t(s,t,n){return s==="position"||s==="preserve-aspect"&&!l7s(q0t(t),q0t(n),.2)}function U7s(s){var t;return s!==s.root&&((t=s.scroll)==null?void 0:t.wasRoot)}const q7s=_9t({attachResizeListener:(s,t)=>sse(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}),N7e={current:void 0},j9t=_9t({measureScroll:s=>({x:s.scrollLeft,y:s.scrollTop}),defaultParent:()=>{if(!N7e.current){const s=new q7s({});s.mount(window),s.setOptions({layoutScroll:!0}),N7e.current=s}return N7e.current},resetTransform:(s,t)=>{s.style.transform=t!==void 0?t:"none"},checkIsScrollRoot:s=>window.getComputedStyle(s).position==="fixed"}),Tst=j.createContext({transformPagePoint:s=>s,isStatic:!1,reducedMotion:"never"});function svt(s,t){if(typeof s=="function")return s(t);s!=null&&(s.current=t)}function V7s(...s){return t=>{let n=!1;const r=s.map(a=>{const i=svt(a,t);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let a=0;a{const{width:f,height:g,top:x,left:y,right:v,bottom:b,direction:w}=c.current;if(t||i===!1||!o.current||!f||!g)return;const S=w==="rtl",A=n==="left"?S?`right: ${v}`:`left: ${y}`:S?`left: ${y}`:`right: ${v}`,E=r==="bottom"?`bottom: ${b}`:`top: ${x}`;o.current.dataset.motionPopId=l;const I=document.createElement("style");d&&(I.nonce=d);const P=a??document.head;return P.appendChild(I),I.sheet&&I.sheet.insertRule(` [data-motion-pop-id="${l}"] { position: absolute !important; width: ${f}px !important; height: ${g}px !important; ${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(G7s,{isPresent:t,childRef:o,sizeRef:c,pop:i,children:i===!1?s:j.cloneElement(s,{ref:h})})}const K7s=({children:s,initial:t,isPresent:n,onExitComplete:r,custom:a,presenceAffectsLayout:i,mode:l,anchorX:o,anchorY:c,root:d})=>{const u=rst(Y7s),h=j.useId(),m=j.useRef(n),f=j.useRef(r);ast(()=>{m.current=n,f.current=r});let g=!0,x=j.useMemo(()=>(g=!1,{id:h,initial:t,isPresent:n,custom:a,onExitComplete:y=>{u.set(y,!0);for(const v of u.values())if(!v)return;r&&r()},register:y=>(u.set(y,!1),()=>{var v;u.delete(y),!m.current&&!u.size&&((v=f.current)==null||v.call(f))})}),[n,u,r]);return i&&g&&(x={...x}),j.useMemo(()=>{u.forEach((y,v)=>u.set(v,!1))},[n]),j.useEffect(()=>{!n&&!u.size&&r&&r()},[n]),s=e.jsx(W7s,{pop:l==="popLayout",isPresent:n,anchorX:o,anchorY:c,root:d,children:s}),e.jsx(WLe.Provider,{value:x,children:s})};function Y7s(){return new Map}function N9t(s=!0){const t=j.useContext(WLe);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 zce=s=>s.key||"";function nvt(s){const t=[];return j.Children.forEach(s,n=>{j.isValidElement(n)&&t.push(n)}),t}const aK=({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]=N9t(l),m=j.useMemo(()=>nvt(s),[s]),f=l&&!u?[]:m.map(zce),g=j.useRef(!0),x=j.useRef(m),y=rst(()=>new Map),v=j.useRef(new Set),[b,w]=j.useState(m),[S,A]=j.useState(m);ast(()=>{g.current=!1,x.current=m;for(let P=0;P{const R=zce(P),D=l&&!u?!1:m===S||f.includes(R),O=()=>{if(v.current.has(R))return;if(y.has(R))v.current.add(R),y.set(R,!0);else return;let U=!0;y.forEach(W=>{W||(U=!1)}),U&&(I==null||I(),A(x.current),l&&(h==null||h()),r&&r())};return e.jsx(K7s,{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)})})},k9t=j.createContext({strict:!1}),rvt={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 avt=!1;function Z7s(){if(avt)return;const s={};for(const t in rvt)s[t]={isEnabled:n=>rvt[t].some(r=>!!n[r])};t9t(s),avt=!0}function S9t(){return Z7s(),Lzs()}function X7s(s){const t=S9t();for(const n in s)t[n]={...t[n],...s[n]};t9t(t)}const Q7s=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 BEe(s){return s.startsWith("while")||s.startsWith("drag")&&s!=="draggable"||s.startsWith("layout")||s.startsWith("onTap")||s.startsWith("onPan")||s.startsWith("onLayout")||Q7s.has(s)}let C9t=s=>!BEe(s);function J7s(s){typeof s=="function"&&(C9t=t=>t.startsWith("on")?!BEe(t):s(t))}try{J7s(require("@emotion/is-prop-valid").default)}catch{}function eBs(s,t,n){const r={};for(const a in s)a==="values"&&typeof s.values=="object"||hb(s[a])||(C9t(a)||n===!0&&BEe(a)||!t&&!BEe(a)||s.draggable&&a.startsWith("onDrag"))&&(r[a]=s[a]);return r}const QLe=j.createContext({});function tBs(s,t){if(XLe(s)){const{initial:n,animate:r}=s;return{initial:n===!1||tse(n)?n:void 0,animate:tse(r)?r:void 0}}return s.inherit!==!1?t:{}}function sBs(s){const{initial:t,animate:n}=tBs(s,j.useContext(QLe));return j.useMemo(()=>({initial:t,animate:n}),[ivt(t),ivt(n)])}function ivt(s){return Array.isArray(s)?s.join(" "):s}const Mst=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function A9t(s,t,n){for(const r in t)!hb(t[r])&&!l9t(r,n)&&(s[r]=t[r])}function nBs({transformTemplate:s},t){return j.useMemo(()=>{const n=Mst();return Ast(n,t,s),Object.assign({},n.vars,n.style)},[t])}function rBs(s,t){const n=s.style||{},r={};return A9t(r,n,s),Object.assign(r,nBs(s,t)),r}function aBs(s,t){const n={},r=rBs(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 E9t=()=>({...Mst(),attrs:{}});function iBs(s,t,n,r){const a=j.useMemo(()=>{const i=E9t();return c9t(i,t,u9t(r),s.transformTemplate,s.style),{...i.attrs,style:{...i.style}}},[t]);if(s.style){const i={};A9t(i,s.style,s),a.style={...i,...a.style}}return a}const oBs=["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 Pst(s){return typeof s!="string"||s.includes("-")?!1:!!(oBs.indexOf(s)>-1||/[A-Z]/u.test(s))}function lBs(s,t,n,{latestValues:r},a,i=!1,l){const c=(l??Pst(s)?iBs:aBs)(t,r,a,s),d=eBs(t,typeof s=="string",i),u=s!==j.Fragment?{...d,...c,ref:n}:{},{children:h}=t,m=j.useMemo(()=>hb(h)?h.get():h,[h]);return j.createElement(s,{...u,children:m})}function cBs({scrapeMotionValuesFromProps:s,createRenderState:t},n,r,a){return{latestValues:dBs(n,r,a,s),renderState:t()}}function dBs(s,t,n,r){const a={},i=r(s,{});for(const m in i)a[m]=n3e(i[m]);let{initial:l,animate:o}=s;const c=XLe(s),d=JBt(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"&&!ZLe(h)){const m=Array.isArray(h)?h:[h];for(let f=0;f(t,n)=>{const r=j.useContext(QLe),a=j.useContext(WLe),i=()=>cBs(s,t,r,a);return n?i():rst(i)},uBs=T9t({scrapeMotionValuesFromProps:Est,createRenderState:Mst}),hBs=T9t({scrapeMotionValuesFromProps:h9t,createRenderState:E9t}),mBs=Symbol.for("motionComponentSymbol");function fBs(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 M9t=j.createContext({});function pU(s){return s&&typeof s=="object"&&Object.prototype.hasOwnProperty.call(s,"current")}function pBs(s,t,n,r,a,i){var w,S;const{visualElement:l}=j.useContext(QLe),o=j.useContext(k9t),c=j.useContext(WLe),d=j.useContext(Tst),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(M9t);g&&!g.projection&&a&&(g.type==="html"||g.type==="svg")&&gBs(m.current,n,a,x);const y=j.useRef(!1);j.useInsertionEffect(()=>{g&&y.current&&g.update(n,c)});const v=n[UBt],b=j.useRef(!!v&&typeof window<"u"&&!((w=window.MotionHandoffIsComplete)!=null&&w.call(window,v))&&((S=window.MotionHasOptimisedAnimation)==null?void 0:S.call(window,v)));return ast(()=>{f.current=!0,g&&(y.current=!0,window.MotionIsMounted=!0,g.updateFeatures(),g.scheduleRenderMicrotask(),b.current&&g.animationState&&g.animationState.animateChanges())}),j.useEffect(()=>{g&&(!b.current&&g.animationState&&g.animationState.animateChanges(),b.current&&(queueMicrotask(()=>{var A;(A=window.MotionHandoffMarkAsComplete)==null||A.call(window,v)}),b.current=!1),g.enteringChildren=void 0)}),g}function gBs(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:P9t(s.parent)),s.projection.setOptions({layoutId:a,layout:i,alwaysMeasureLayout:!!l||o&&pU(o),visualElement:s,animationType:typeof i=="string"?i:"both",initialPromotionConfig:r,crossfade:h,layoutScroll:c,layoutRoot:d,layoutAnchor:u})}function P9t(s){if(s)return s.options.allowProjection!==!1?s.projection:P9t(s.parent)}function k7e(s,{forwardMotionProps:t=!1,type:n}={},r,a){r&&X7s(r);const i=n?n==="svg":Pst(s),l=i?hBs:uBs;function o(d,u){let h;const m={...j.useContext(Tst),...d,layoutId:xBs(d)},{isStatic:f}=m,g=sBs(d),x=l(d,f);if(!f&&typeof window<"u"){yBs();const y=vBs(m);h=y.MeasureLayout,g.visualElement=pBs(s,x,m,a,y.ProjectionNode,i)}return e.jsxs(QLe.Provider,{value:g,children:[h&&g.visualElement?e.jsx(h,{visualElement:g.visualElement,...m}):null,lBs(s,d,fBs(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[mBs]=s,c}function xBs({layoutId:s}){const t=j.useContext(nst).id;return t&&s!==void 0?t+"-"+s:s}function yBs(s,t){j.useContext(k9t).strict}function vBs(s){const t=S9t(),{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 bBs(s,t){if(typeof Proxy>"u")return k7e;const n=new Map,r=(i,l)=>k7e(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,k7e(l,void 0,s,t)),n.get(l))})}const _Bs=(s,t)=>t.isSVG??Pst(s)?new Xzs(t):new Hzs(t,{allowProjection:s!==j.Fragment});class wBs extends o6{constructor(t){super(t),t.animationState||(t.animationState=s7s(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();ZLe(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 jBs=0;class NBs extends o6{constructor(){super(...arguments),this.id=jBs++,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=l7(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 kBs={animation:{Feature:wBs},exit:{Feature:NBs}};function Wae(s){return{point:{x:s.pageX,y:s.pageY}}}const SBs=s=>t=>Nst(t)&&s(t,Wae(t));function vee(s,t,n,r){return sse(s,t,SBs(n),r)}const I9t=({current:s})=>s?s.ownerDocument.defaultView:null,ovt=(s,t)=>Math.abs(s-t);function CBs(s,t){const n=ovt(s.x,t.x),r=ovt(s.y,t.y);return Math.sqrt(n**2+r**2)}const lvt=new Set(["auto","scroll"]);class L9t{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=Bce(this.lastRawMoveEventInfo,this.transformPagePoint));const g=S7e(this.lastMoveEventInfo,this.history),x=this.startEvent!==null,y=CBs(g.offset,{x:0,y:0})>=this.distanceThreshold;if(!x&&!y)return;const{point:v}=g,{timestamp:b}=nb;this.history.push({...v,timestamp:b});const{onStart:w,onMove:S}=this.handlers;x||(w&&w(this.lastMoveEvent,g),this.startEvent=this.lastMoveEvent),S&&S(this.lastMoveEvent,g)},this.handlePointerMove=(g,x)=>{this.lastMoveEvent=g,this.lastRawMoveEventInfo=x,this.lastMoveEventInfo=Bce(x,this.transformPagePoint),kf.update(this.updatePoint,!0)},this.handlePointerUp=(g,x)=>{this.end();const{onEnd:y,onSessionEnd:v,resumeAnimation:b}=this.handlers;if((this.dragSnapToOrigin||!this.startEvent)&&b&&b(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const w=S7e(g.type==="pointercancel"?this.lastMoveEventInfo:Bce(x,this.transformPagePoint),this.history);this.startEvent&&y&&y(g,w),v&&v(g,w)},!Nst(t))return;this.dragSnapToOrigin=i,this.handlers=n,this.transformPagePoint=r,this.distanceThreshold=l,this.contextWindow=a||window;const c=Wae(t),d=Bce(c,this.transformPagePoint),{point:u}=d,{timestamp:h}=nb;this.history=[{...u,timestamp:h}];const{onSessionStart:m}=n;m&&m(t,S7e(d,this.history));const f={passive:!0,capture:!0};this.removeListeners=Vae(vee(this.contextWindow,"pointermove",this.handlePointerMove,f),vee(this.contextWindow,"pointerup",this.handlePointerUp,f),vee(this.contextWindow,"pointercancel",this.handlePointerUp,f)),o&&this.startScrollTracking(o)}startScrollTracking(t){let n=t.parentElement;for(;n;){const r=getComputedStyle(n);(lvt.has(r.overflowX)||lvt.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(),ML(this.updatePoint)}}function Bce(s,t){return t?{point:t(s.point)}:s}function cvt(s,t){return{x:s.x-t.x,y:s.y-t.y}}function S7e({point:s},t){return{point:s,delta:cvt(s,R9t(t)),offset:cvt(s,ABs(t)),velocity:EBs(t,.1)}}function ABs(s){return s[0]}function R9t(s){return s[s.length-1]}function EBs(s,t){if(s.length<2)return{x:0,y:0};let n=s.length-1,r=null;const a=R9t(s);for(;n>=0&&(r=s[n],!(a.timestamp-r.timestamp>f2(t)));)n--;if(!r)return{x:0,y:0};r===s[0]&&s.length>2&&a.timestamp-r.timestamp>f2(t)*2&&(r=s[1]);const i=UN(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 TBs(s,{min:t,max:n},r){return t!==void 0&&sn&&(s=r?jf(n,s,r.max):Math.min(s,n)),s}function dvt(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 MBs(s,{top:t,left:n,bottom:r,right:a}){return{x:dvt(s.x,n,a),y:dvt(s.y,t,r)}}function uvt(s,t){let n=t.min-s.min,r=t.max-s.max;return t.max-t.minr?n=Jte(t.min,t.max-r,s.min):r>a&&(n=Jte(s.min,s.max-a,t.min)),K4(0,1,n)}function LBs(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 AGe=.35;function RBs(s=AGe){return s===!1?s=0:s===!0&&(s=AGe),{x:hvt(s,"left","right"),y:hvt(s,"top","bottom")}}function hvt(s,t,n){return{min:mvt(s,t),max:mvt(s,n)}}function mvt(s,t){return typeof s=="number"?s:s[t]||0}const DBs=new WeakMap;class FBs{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=u0(),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(Wae(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=dzs(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),_5(v=>{let b=this.getAxisMotionValue(v).get()||0;if(F4.test(b)){const{projection:w}=this.visualElement;if(w&&w.layout){const S=w.layout.layoutBox[v];S&&(b=g_(S)*(parseFloat(b)/100))}}this.originPoint[v]=b}),x&&kf.update(()=>x(h,m),!1,!0),yGe(this.visualElement,"transform");const{animationState:y}=this.visualElement;y&&y.setActive("whileDrag",!0)},o=(h,m)=>{this.latestPointerEvent=h,this.latestPanInfo=m;const{dragPropagation:f,dragDirectionLock:g,onDirectionLock:x,onDrag:y}=this.getProps();if(!f&&!this.openDragLock)return;const{offset:v}=m;if(g&&this.currentDirection===null){this.currentDirection=zBs(v),this.currentDirection!==null&&x&&x(this.currentDirection);return}this.updateAxis("x",m.point,v),this.updateAxis("y",m.point,v),this.visualElement.render(),y&&kf.update(()=>y(h,m),!1,!0)},c=(h,m)=>{this.latestPointerEvent=h,this.latestPanInfo=m,this.stop(h,m),this.latestPointerEvent=null,this.latestPanInfo=null},d=()=>{const{dragSnapToOrigin:h}=this.getProps();(h||this.constraints)&&this.startAnimation({x:0,y:0})},{dragSnapToOrigin:u}=this.getProps();this.panSession=new L9t(t,{onSessionStart:i,onStart:l,onMove:o,onSessionEnd:c,resumeAnimation:d},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:u,distanceThreshold:r,contextWindow:I9t(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||!$ce(t,a,this.currentDirection))return;const i=this.getAxisMotionValue(t);let l=this.originPoint[t]+r[t];this.constraints&&this.constraints[t]&&(l=TBs(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&&pU(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):t&&r?this.constraints=MBs(r.layoutBox,t):this.constraints=!1,this.elastic=RBs(n),a!==this.constraints&&!pU(t)&&r&&this.constraints&&!this.hasMutatedConstraints&&_5(l=>{this.constraints!==!1&&this.getAxisMotionValue(l)&&(this.constraints[l]=LBs(r.layoutBox[l],this.constraints[l]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:n}=this.getProps();if(!t||!pU(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=zzs(r,a.root,this.visualElement.getTransformPagePoint());let l=PBs(a.layout.layoutBox,i);if(n){const o=n(Dzs(l));this.hasMutatedConstraints=!!o,o&&(l=n9t(o))}return l}startAnimation(t){const{drag:n,dragMomentum:r,dragElastic:a,dragTransition:i,dragSnapToOrigin:l,onDragTransitionEnd:o}=this.getProps(),c=this.constraints||{},d=_5(u=>{if(!$ce(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 yGe(this.visualElement,t),r.start(yst(t,r,0,n,this.visualElement,!1))}stopAnimation(){_5(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){_5(n=>{const{drag:r}=this.getProps();if(!$ce(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(!pU(n)||!r||!this.constraints)return;this.stopAnimation();const a={x:0,y:0};_5(l=>{const o=this.getAxisMotionValue(l);if(o&&this.constraints!==!1){const c=o.get();a[l]=IBs({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(),_5(l=>{if(!$ce(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;DBs.set(this.visualElement,this);const t=this.visualElement.current,n=vee(t,"pointerdown",d=>{const{drag:u,dragListener:h=!0}=this.getProps(),m=d.target,f=m!==t&&gzs(m);u&&h&&!f&&this.start(d)});let r;const a=()=>{const{dragConstraints:d}=this.getProps();pU(d)&&d.current&&(this.constraints=this.resolveRefConstraints(),r||(r=OBs(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=sse(window,"resize",()=>this.scalePositionWithinConstraints()),c=i.addEventListener("didUpdate",({delta:d,hasLayoutChanged:u})=>{this.isDragging&&u&&(_5(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=AGe,dragMomentum:o=!0}=t;return{...t,drag:n,dragDirectionLock:r,dragPropagation:a,dragConstraints:i,dragElastic:l,dragMomentum:o}}}function fvt(s){let t=!0;return()=>{if(t){t=!1;return}s()}}function OBs(s,t,n){const r=_0t(s,fvt(n)),a=_0t(t,fvt(n));return()=>{r(),a()}}function $ce(s,t,n){return(t===!0||t===s)&&(n===null||n===s)}function zBs(s,t=10){let n=null;return Math.abs(s.y)>t?n="y":Math.abs(s.x)>t&&(n="x"),n}class BBs extends o6{constructor(t){super(t),this.removeGroupControls=tk,this.removeListeners=tk,this.controls=new FBs(t)}mount(){const{dragControls:t}=this.node.getProps();t&&(this.removeGroupControls=t.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||tk}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 C7e=s=>(t,n)=>{s&&kf.update(()=>s(t,n),!1,!0)};class $Bs extends o6{constructor(){super(...arguments),this.removePointerDownListener=tk}onPointerDown(t){this.session=new L9t(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:I9t(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:n,onPan:r,onPanEnd:a}=this.node.getProps();return{onSessionStart:C7e(t),onStart:C7e(n),onMove:C7e(r),onEnd:(i,l)=>{delete this.session,a&&kf.postRender(()=>a(i,l))}}}mount(){this.removePointerDownListener=vee(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 A7e=!1;class UBs 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),A7e&&i.root.didUpdate(),i.addEventListener("animationComplete",()=>{this.safeToRemove()}),i.setOptions({...i.options,layoutDependency:this.props.layoutDependency,onExitComplete:()=>this.safeToRemove()})),r3e.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}),A7e=!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(),jst.postRender(()=>{!r.currentAnimation&&r.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:r}=this.props,{projection:a}=t;A7e=!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 D9t(s){const[t,n]=N9t(),r=j.useContext(nst);return e.jsx(UBs,{...s,layoutGroup:r,switchLayoutGroup:j.useContext(M9t),isPresent:t,safeToRemove:n})}const qBs={pan:{Feature:$Bs},drag:{Feature:BBs,ProjectionNode:j9t,MeasureLayout:D9t}};function pvt(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,Wae(t)))}class VBs extends o6{mount(){const{current:t}=this.node;t&&(this.unmount=hzs(t,(n,r)=>(pvt(this.node,r,"Start"),a=>pvt(this.node,a,"End"))))}unmount(){}}class HBs extends o6{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=Vae(sse(this.node.current,"focus",()=>this.onFocus()),sse(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function gvt(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,Wae(t)))}class GBs extends o6{mount(){const{current:t}=this.node;if(!t)return;const{globalTapTarget:n,propagate:r}=this.node.props;this.unmount=yzs(t,(a,i)=>(gvt(this.node,i,"Start"),(l,{success:o})=>gvt(this.node,l,o?"End":"Cancel")),{useGlobalTarget:n,stopPropagation:(r==null?void 0:r.tap)===!1})}unmount(){}}const EGe=new WeakMap,E7e=new WeakMap,WBs=s=>{const t=EGe.get(s.target);t&&t(s)},KBs=s=>{s.forEach(WBs)};function YBs({root:s,...t}){const n=s||document;E7e.has(n)||E7e.set(n,{});const r=E7e.get(n),a=JSON.stringify(t);return r[a]||(r[a]=new IntersectionObserver(KBs,{root:s,...t})),r[a]}function ZBs(s,t,n){const r=YBs(t);return EGe.set(s,n),r.observe(s),()=>{EGe.delete(s),r.unobserve(s)}}const XBs={some:0,all:1};class QBs extends o6{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:XBs[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(JBs(t,n))&&this.startObserver()}unmount(){var t;(t=this.stopObserver)==null||t.call(this),this.hasEnteredView=!1,this.isInView=!1}}function JBs({viewport:s={}},{viewport:t={}}={}){return n=>s[n]!==t[n]}const e9s={inView:{Feature:QBs},tap:{Feature:GBs},focus:{Feature:HBs},hover:{Feature:VBs}},t9s={layout:{ProjectionNode:j9t,MeasureLayout:D9t}},s9s={...kBs,...e9s,...qBs,...t9s},Br=bBs(s9s,_Bs),n9s={some:0,all:1};function r9s(s,t,{root:n,margin:r,amount:a="some"}={}){const i=wst(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:n9s[a]});return i.forEach(d=>c.observe(d)),()=>c.disconnect()}function a9s(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 r9s(s.current,c,d)},[t,s,n,a,r]),l}function i9s(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 xvt(s){return s.visitor_intent==="buying"&&!s.has_agent}function o9s({token:s}={}){var f;const t=Wi(),n=s||t.token,{data:r,isLoading:a,isError:i}=aOs(n);Wt();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(xvt).length)||0,m=g=>{if(!g)return"";const[x,y]=g.split(":"),v=parseInt(x);return`${v>12?v-12:v||12}:${y} ${v>=12?"PM":"AM"}`};return e.jsxs("div",{className:"fixed inset-0 bg-gradient-to-br from-slate-950 via-slate-900 to-slate-950 flex flex-col",children:[e.jsxs("div",{className:"border-b border-white/10 px-4 sm:px-6 py-3 flex items-center justify-between bg-black/30 backdrop-blur-xl",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-emerald-400 animate-pulse"}),e.jsx("span",{className:"text-xs font-medium text-emerald-400 uppercase tracking-wider",children:"Live · Co-Host View"})]}),e.jsx("h1",{className:"text-white font-bold text-sm sm:text-base truncate",children:c.property_address})]}),e.jsxs("div",{className:"flex items-center gap-4 sm:gap-6 text-white/70",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(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:en(new Date(c.event_date+"T00:00:00"),"EEEE, MMMM d, yyyy")}),c.start_time&&e.jsxs("span",{children:[m(c.start_time),c.end_time?` – ${m(c.end_time)}`:""]})]}),e.jsx(uo,{className:"flex-1 p-4 sm:p-6",children:o!=null&&o.length?e.jsx("div",{className:"space-y-2 max-w-3xl mx-auto",children:e.jsx(aK,{children:o.map((g,x)=>{var b;const y=i9s(g.visitor_intent),v=xvt(g);return e.jsxs(Br.div,{initial:{opacity:0,x:-40,scale:.95},animate:{opacity:1,x:0,scale:1},transition:{duration:.4,delay:x*.05},className:`flex items-center gap-4 p-4 rounded-xl border ${v?"bg-orange-500/10 border-orange-500/30":"bg-white/5 border-white/10"}`,children:[e.jsx("div",{className:`w-11 h-11 rounded-full flex items-center justify-center text-lg font-bold shrink-0 ${v?"bg-gradient-to-br from-orange-500 to-amber-500 text-white":"bg-white/10 text-white/80"}`,children:(b=g.first_name[0])==null?void 0:b.toUpperCase()}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("span",{className:"font-semibold text-white truncate",children:[g.first_name," ",g.last_name||""]}),v&&e.jsx($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 ${y.color}`,children:[y.emoji," ",y.label]}),e.jsx("span",{className:"text-white/30 text-xs",children:en(new Date(g.created_at),"h:mm a")})]})]})]},g.id)})})}):e.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-center py-20",children:[e.jsx("div",{className:"w-20 h-20 rounded-full bg-white/5 flex items-center justify-center mb-4",children:e.jsx(_b,{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 l9s(){const t=mu().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(o9s,{token:n})}if(t.startsWith("rsvp/")){const n=t.slice(5);if(n)return e.jsx(eBt,{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(J7t,{slug:t})}function c9s({dealData:s,agentProfile:t,welcomeMessage:n,isWon:r,branding:a}){var d;const i=s!=null&&s.property_address?`${s.property_address}, ${s.city||""}, ${s.state||""}`.replace(/,\s*,/g,",").replace(/,\s*$/,""):null,l=(a==null?void 0:a.logo_url)||null,o=(a==null?void 0:a.cover_photo_url)||null,c=(a==null?void 0:a.tagline)||"Your Real Estate Concierge";return e.jsxs("div",{className:"relative overflow-hidden",children:[e.jsxs("div",{className:"relative px-4 pt-10 pb-20",children:[o&&e.jsx("div",{className:"absolute inset-0",style:{backgroundImage:`url(${o})`,backgroundSize:"cover",backgroundPosition:"center",filter:"var(--portal-hero-filter-mobile)"}}),e.jsx("div",{className:"absolute inset-0",style:{background:o?"var(--portal-hero-scrim-mobile)":"radial-gradient(ellipse 100% 70% at 50% 0%, hsl(var(--portal-gold) / 0.12), transparent 60%), linear-gradient(180deg, hsl(0 0% 7%), hsl(0 0% 4%))"}}),e.jsx("div",{className:"absolute inset-0 opacity-[0.05]",style:{backgroundImage:"radial-gradient(circle at 25% 25%, hsl(var(--portal-gold)) 1px, transparent 1px)",backgroundSize:"32px 32px"}}),e.jsxs("div",{className:"relative text-center max-w-lg mx-auto",children:[l&&e.jsx(Br.div,{initial:{opacity:0,y:-8},animate:{opacity:1,y:0},transition:{duration:.5},className:"mb-6 flex justify-center",children:e.jsx("div",{className:"rounded-xl px-4 py-2.5",style:{background:"hsl(0 0% 100% / 0.06)",backdropFilter:"blur(8px)",border:"1px solid hsl(var(--portal-gold) / 0.2)"},children:e.jsx("img",{src:l,alt:"Brand",className:"h-9 max-w-[160px] object-contain"})})}),t&&e.jsxs(Br.div,{initial:{opacity:0,y:8},animate:{opacity:1,y:0},transition:{duration:.5,delay:.05},className:"mb-6",children:[t.avatar_url?e.jsx("div",{className:"w-20 h-20 mx-auto mb-3 relative",children:e.jsx("div",{className:"absolute inset-0 rounded-full",style:{background:"var(--portal-gradient-gold)",padding:"2px"},children:e.jsx("img",{src:t.avatar_url,alt:t.name,className:"w-full h-full rounded-full object-cover",style:{background:"hsl(var(--portal-surface))"}})})}):e.jsx("div",{className:"w-20 h-20 mx-auto mb-3 rounded-full flex items-center justify-center portal-serif text-3xl",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.3)",color:"var(--portal-hero-accent)"},children:((d=t.name)==null?void 0:d.charAt(0))||"?"}),e.jsx("p",{className:"portal-serif text-lg",style:{color:"var(--portal-hero-ink)"},children:t.name}),e.jsx("p",{className:"text-[10px] mt-1 tracking-[0.22em] uppercase",style:{color:"var(--portal-hero-ink-dim)"},children:c})]}),e.jsxs(Br.div,{initial:{opacity:0,y:8},animate:{opacity:1,y:0},transition:{duration:.6,delay:.1},children:[e.jsxs("div",{className:"inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-[10px] tracking-[0.2em] uppercase mb-4",style:{background:"hsl(var(--portal-gold) / 0.08)",border:"1px solid hsl(var(--portal-gold) / 0.25)",color:"var(--portal-hero-accent)"},children:[e.jsx(va,{className:"w-3 h-3"}),(s==null?void 0:s.deal_type)==="listing"?"Sale":(s==null?void 0:s.deal_type)==="buy-side"?"Purchase":"Transaction",r&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"opacity-50",children:"·"}),"Complete"]})]}),e.jsx("h1",{className:"portal-serif text-[2.5rem] leading-[1.05] mb-3",style:{color:"var(--portal-hero-ink)"},children:(s==null?void 0:s.deal_name)||"Your Transaction"}),e.jsx("div",{className:"portal-hairline w-24 mx-auto mb-4"}),i&&e.jsxs("div",{className:"flex items-center justify-center gap-1.5 text-sm",style:{color:"var(--portal-hero-ink-muted)"},children:[e.jsx(ci,{className:"w-3.5 h-3.5",style:{color:"var(--portal-hero-accent)"}}),e.jsx("span",{children:i})]}),n&&e.jsxs("p",{className:"mt-6 text-sm leading-relaxed max-w-md mx-auto italic portal-serif",style:{color:"var(--portal-hero-ink-muted)",fontSize:"1.05rem"},children:["“",n,"”"]})]})]})]}),t&&e.jsx("div",{className:"max-w-lg mx-auto px-4 -mt-10 relative z-10",children:e.jsx("div",{className:"rounded-2xl p-3",style:{background:"hsl(var(--portal-surface))",border:"1px solid hsl(var(--portal-gold) / 0.2)",boxShadow:"var(--portal-shadow-tile)"},children:e.jsxs("div",{className:"flex items-center justify-center gap-2",children:[t.phone&&e.jsxs("a",{href:`tel:${t.phone}`,className:"flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-xl transition-colors",style:{background:"hsl(var(--portal-gold) / 0.06)",color:"var(--portal-hero-accent)",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:[e.jsx(Da,{className:"w-4 h-4"}),e.jsx("span",{className:"text-sm font-medium",children:"Call"})]}),t.email&&e.jsxs("a",{href:`mailto:${t.email}`,className:"flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-xl transition-colors",style:{background:"hsl(var(--portal-gold) / 0.06)",color:"var(--portal-hero-accent)",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:[e.jsx(mn,{className:"w-4 h-4"}),e.jsx("span",{className:"text-sm font-medium",children:"Email"})]}),t.phone&&e.jsxs("a",{href:`sms:${t.phone}`,className:"flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-xl transition-colors",style:{background:"hsl(var(--portal-gold) / 0.06)",color:"var(--portal-hero-accent)",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:[e.jsx(Ah,{className:"w-4 h-4"}),e.jsx("span",{className:"text-sm font-medium",children:"Text"})]})]})})})]})}function F9t({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=dk(a,new Date);if(D4(a)&&!_v(a))return null;const o=_v(a),c=o?"0":String(Math.max(0,l)),d=Math.max(4,Math.min(100,(60-Math.min(60,l))/60*100));return e.jsxs("div",{className:"portal-tile p-8 text-center",children:[e.jsx("p",{className:"portal-eyebrow mb-4",children:o?"The Moment Has Arrived":"Countdown to Closing"}),o?e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"portal-serif text-5xl mb-2",style:{color:"hsl(var(--portal-gold))"},children:"Closing Day"}),e.jsxs("p",{className:"text-sm mt-3",style:{color:"hsl(var(--portal-ink-muted))"},children:["Congratulations",n?`, ${n.split(" ")[0]}`:"","."]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-baseline justify-center gap-3",children:[e.jsx(Br.span,{initial:{opacity:0,y:8},animate:{opacity:1,y:0},transition:{duration:.6},className:"portal-serif tabular-nums leading-none",style:{fontSize:"5.5rem",color:"hsl(var(--portal-gold))",textShadow:"0 0 40px hsl(var(--portal-gold) / 0.4)"},children:c}),e.jsx("span",{className:"portal-serif",style:{fontSize:"1.5rem",color:"hsl(var(--portal-ink-muted))"},children:l===1?"day":"days"})]}),e.jsx("div",{className:"portal-hairline w-16 mx-auto my-4"}),e.jsx("p",{className:"text-xs tracking-[0.2em] uppercase",style:{color:"hsl(var(--portal-ink-muted))"},children:"Until you hold the keys"}),e.jsx("div",{className:"mt-6 mx-auto max-w-[260px]",children:e.jsx("div",{className:"h-[2px] rounded-full overflow-hidden",style:{background:"hsl(var(--portal-gold) / 0.15)"},children:e.jsx(Br.div,{initial:{width:0},animate:{width:`${d}%`},transition:{duration:1.2,ease:"easeOut"},className:"h-full rounded-full",style:{background:"var(--portal-gradient-gold)",boxShadow:"0 0 12px hsl(var(--portal-gold) / 0.6)"}})})})]})]})}function O9t({journeyStages:s,currentIndex:t}){return s.length===0?null:e.jsxs("div",{children:[e.jsx("p",{className:"portal-eyebrow mb-2",children:"The Journey"}),e.jsx("h2",{className:"portal-serif text-2xl mb-6",style:{color:"hsl(var(--portal-ink))"},children:"Your path to the keys"}),e.jsx("div",{className:"relative",children:s.map((n,r)=>{const a=rt;return e.jsxs(Br.div,{initial:{opacity:0,x:-6},animate:{opacity:1,x:0},transition:{duration:.35,delay:r*.05},className:"flex items-start gap-4 relative",children:[r{var l,o;if(i.includes("youtube.com/watch")){const c=new URL(i).searchParams.get("v");return c?`https://www.youtube.com/embed/${c}`:null}if(i.includes("youtu.be/")){const c=(l=i.split("youtu.be/")[1])==null?void 0:l.split("?")[0];return c?`https://www.youtube.com/embed/${c}`:null}if(i.includes("loom.com/share/")){const c=(o=i.split("loom.com/share/")[1])==null?void 0:o.split("?")[0];return c?`https://www.loom.com/embed/${c}`:null}return i};return e.jsxs("div",{children:[e.jsx("p",{className:"portal-eyebrow mb-2",children:"Right Now"}),e.jsx("h4",{className:"portal-serif text-3xl mb-2 portal-gold-underline",style:{color:"hsl(var(--portal-ink))"},children:s.label}),e.jsx("p",{className:"text-sm leading-relaxed mt-4",style:{color:"hsl(var(--portal-ink-muted))"},children:s.description}),t&&e.jsxs("div",{className:"mt-5 rounded-xl p-4",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:[e.jsx("p",{className:"portal-eyebrow mb-2",children:"Note From Your Agent"}),e.jsxs("p",{className:"text-sm leading-relaxed portal-serif italic",style:{color:"hsl(var(--portal-ink))",fontSize:"1rem"},children:["“",t,"”"]})]}),n&&e.jsxs("div",{className:"mt-5 rounded-xl p-4",style:{background:"linear-gradient(135deg, hsl(var(--portal-gold) / 0.08), hsl(var(--portal-gold) / 0.02))",border:"1px solid hsl(var(--portal-gold) / 0.25)"},children:[e.jsx("p",{className:"portal-eyebrow mb-2",children:"What’s Next"}),e.jsx("p",{className:"text-sm leading-relaxed",style:{color:"hsl(var(--portal-ink))"},children:n})]}),r&&e.jsx("div",{className:"mt-5 rounded-xl overflow-hidden aspect-video relative group",style:{background:"hsl(var(--portal-bg))",border:"1px solid hsl(var(--portal-gold) / 0.2)"},children:e.jsx("iframe",{src:a(r)||r,className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,title:"Next step video"})})]})}function 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 yvt(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 d9s=[{key:"contract_date",label:"Contract Accepted",icon:KN},{key:"earnest_money_due_date",label:"Earnest Money",icon:nu},{key:"inspection_date",label:"Inspection",icon:Zr},{key:"inspection_contingency_date",label:"Inspection Deadline",icon:Jr},{key:"appraisal_date",label:"Appraisal",icon:va},{key:"loan_approval_date",label:"Loan Approval",icon:Oq},{key:"title_docs_due_date",label:"Title & Disclosures",icon:Jr},{key:"final_walkthrough_date",label:"Final Walkthrough",icon:GI},{key:"target_close_date",label:"Target Close",icon:Ta}];function u9s(s,t){const n=en(t,"yyyyMMdd");return`https://calendar.google.com/calendar/render?${new URLSearchParams({action:"TEMPLATE",text:s,dates:`${n}/${n}`,details:"Added from your Client Portal"}).toString()}`}function h9s(s,t){const n=en(t,"yyyyMMdd");return`data:text/calendar;charset=utf-8,${encodeURIComponent(`BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT DTSTART;VALUE=DATE:${n} DTEND;VALUE=DATE:${n} SUMMARY:${s} DESCRIPTION:Added from your Client Portal END:VEVENT END:VCALENDAR`)}`}function B9t({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=d9s.map(f=>f.key==="target_close_date"&&c?{...f,label:"Closed",date:c,done:!0}:{...f,date:o[f.key],done:d.includes(f.key)}).filter(f=>!!f.date);if(u.length===0)return null;const h=(f,g,x)=>{const y=kh(g);if(x==="google")window.open(u9s(f,y),"_blank");else{const v=h9s(f,y),b=document.createElement("a");b.href=v,b.download=`${f.replace(/\s+/g,"-").toLowerCase()}.ics`,b.click()}},m=u.filter(f=>f.done).length;return e.jsxs("div",{children:[e.jsx("p",{className:"portal-eyebrow mb-2",children:"Milestones"}),e.jsxs("div",{className:"flex items-baseline justify-between gap-3 mb-5 flex-wrap",children:[e.jsx("h2",{className:"portal-serif text-2xl",style:{color:"hsl(var(--portal-ink))"},children:"Key dates"}),e.jsxs("span",{className:"text-[11px] tracking-[0.18em] uppercase",style:{color:"hsl(var(--portal-ink-dim))"},children:[m," of ",u.length," complete"]})]}),e.jsxs("div",{className:"space-y-4 relative",children:[e.jsx("div",{className:"absolute left-[10px] top-2 bottom-2 w-[1px]",style:{background:"hsl(var(--portal-gold) / 0.18)"}}),u.map(({label:f,date:g,done:x,icon:y})=>{const v=kh(g),b=D4(v)&&!_v(v),w=_v(v),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(ca,{className:"w-3 h-3",style:{color:"hsl(var(--portal-surface))"}}):e.jsx(y,{className:"w-3 h-3",style:{color:"hsl(var(--portal-gold))"}})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-[10px] tracking-[0.22em] uppercase",style:{color:"hsl(var(--portal-ink-dim))"},children:f}),e.jsx("p",{className:"portal-serif mt-0.5",style:{fontSize:"1.15rem",color:x?"hsl(var(--portal-ink-muted))":"hsl(var(--portal-ink))"},children:en(v,"MMM d, yyyy")}),e.jsx("span",{className:"inline-block mt-1 text-[9px] tracking-[0.2em] uppercase px-2 py-0.5 rounded-full",style:{color:x||w?"hsl(var(--portal-gold))":"hsl(var(--portal-ink-dim))",border:`1px solid hsl(var(--portal-gold) / ${x||w?.5:.18})`},children: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(bv,{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 $9t({documents:s}){const t=r=>r<1024?`${r} B`:r<1048576?`${(r/1024).toFixed(0)} KB`:`${(r/1048576).toFixed(1)} MB`,n=async r=>{const{data:a}=await q.storage.from("deal-files").createSignedUrl(r.storage_path,300);a!=null&&a.signedUrl&&window.open(a.signedUrl,"_blank")};return e.jsxs("div",{children:[e.jsx("p",{className:"portal-eyebrow mb-2",children:"Paperwork"}),e.jsx("h2",{className:"portal-serif text-2xl mb-5",style:{color:"hsl(var(--portal-ink))"},children:"Documents"}),e.jsx("div",{className:"space-y-2",children:s.map(r=>e.jsxs("button",{onClick:()=>n(r),className:"w-full flex items-center gap-3 p-3 rounded-xl transition-all text-left group",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.08)"},onMouseEnter:a=>{a.currentTarget.style.borderColor="hsl(var(--portal-gold) / 0.35)"},onMouseLeave:a=>{a.currentTarget.style.borderColor="hsl(var(--portal-gold) / 0.08)"},children:[e.jsx("div",{className:"w-10 h-10 rounded-lg flex items-center justify-center flex-shrink-0",style:{background:"hsl(var(--portal-gold) / 0.08)",border:"1px solid hsl(var(--portal-gold) / 0.2)"},children:e.jsx(Jr,{className:"w-4 h-4",style:{color:"hsl(var(--portal-gold))"}})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm portal-serif truncate",style:{color:"hsl(var(--portal-ink))",fontSize:"1rem"},children:r.file_name}),e.jsx("p",{className:"text-[10px] tracking-widest uppercase mt-0.5",style:{color:"hsl(var(--portal-ink-dim))"},children:t(r.file_size)})]}),e.jsx(xi,{className:"w-4 h-4 flex-shrink-0",style:{color:"hsl(var(--portal-gold) / 0.5)"}})]},r.id))})]})}function U9t({slug:s,wrapper:t}){const n=Xn(),[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){re.error((h==null?void 0:h.message)||"Could not open the document")}finally{a(null)}},d=e.jsxs("div",{children:[e.jsx("p",{className:"portal-eyebrow mb-2",children:"Needs you"}),e.jsx("h2",{className:"portal-serif text-2xl mb-5",style:{color:"hsl(var(--portal-ink))"},children:"Documents to sign"}),e.jsxs("div",{className:"space-y-2",children:[l.map(u=>e.jsxs("button",{onClick:()=>c(u.id),disabled:r===u.id,className:"w-full flex items-center gap-3 p-3 rounded-xl transition-all text-left",style:{background:"hsl(var(--portal-gold) / 0.1)",border:"1px solid hsl(var(--portal-gold) / 0.4)"},children:[e.jsx("div",{className:"w-10 h-10 rounded-lg flex items-center justify-center flex-shrink-0",style:{background:"hsl(var(--portal-gold) / 0.14)",border:"1px solid hsl(var(--portal-gold) / 0.3)"},children:r===u.id?e.jsx(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(da,{className:"w-4 h-4",style:{color:"hsl(var(--portal-ink-muted))"}})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm portal-serif truncate",style:{color:"hsl(var(--portal-ink-muted))",fontSize:"1rem"},children:u.title}),e.jsx("p",{className:"text-[10px] tracking-widest uppercase mt-0.5",style:{color:"hsl(var(--portal-ink-dim))"},children:u.my_status==="signed"?"You signed — waiting on others":"Waiting on another signer"})]})]},u.id))]})]});return t?t(d):d}function q9t({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(zy,{className:"w-3.5 h-3.5",style:{color:"hsl(var(--portal-gold))"}}):e.jsx(Uy,{className:"w-3.5 h-3.5",style:{color:"hsl(var(--portal-gold))"}})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[e.jsx("h3",{className:"portal-serif",style:{fontSize:r===0?"1.4rem":"1.15rem",color:"hsl(var(--portal-ink))"},children:n.title}),e.jsx("span",{className:"text-[10px] tracking-[0.2em] uppercase flex-shrink-0",style:{color:"hsl(var(--portal-ink-dim))"},children:en(new Date(n.created_at),"MMM d")})]}),n.content&&e.jsx("p",{className:`text-sm mt-2 leading-relaxed ${r===0?"italic portal-serif":""}`,style:{color:"hsl(var(--portal-ink-muted))",fontSize:r===0?"1rem":"0.875rem"},children:r===0?`“${n.content}”`:n.content}),n.video_url&&e.jsx("div",{className:"mt-3 rounded-xl overflow-hidden aspect-video",style:{background:"hsl(var(--portal-bg))",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:e.jsx("iframe",{src:t(n.video_url)||n.video_url,className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,title:n.title})})]})]})},n.id))})]})}const iK=[{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"}],m9s=[{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 f9s(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 p9s(){const s=Sa(),{brokerageId:t}=bs();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 g9s(){const s=Wt();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 V9t(){const s=Wt();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 x9s(){const s=Sa(),t=Wt();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 H9t(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 vvt(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 G9t(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 W9t({portalId:s,ownerUserId:t,currentStage:n,brandingColor:r,layout:a="list"}){const{data:i=[],isLoading:l}=H9t({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);vvt({vendorId:b.id,portalId:s,agentUserId:t,actionTaken:b.action_type}),w&&window.open(w,b.action_type==="call"||b.action_type==="email"||b.action_type==="quote"?"_self":"_blank")},h=b=>{const w=d(b,b.action_type);return[{action:"website",label:"Website",icon:e.jsx(dl,{className:"w-3.5 h-3.5"})},{action:"email",label:"Email",icon:e.jsx(mn,{className:"w-3.5 h-3.5"})},{action:"call",label:"Call",icon:e.jsx(Da,{className:"w-3.5 h-3.5"})},{action:"book",label:"Book",icon:e.jsx(Ta,{className:"w-3.5 h-3.5"})}].filter(A=>A.action!==b.action_type).map(A=>{const E=d(b,A.action);return!E||E===w?null:e.jsxs("button",{onClick:()=>{vvt({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(Ta,{className:"w-3.5 h-3.5"});case"call":return e.jsx(Da,{className:"w-3.5 h-3.5"});case"email":case"quote":return e.jsx(mn,{className:"w-3.5 h-3.5"});case"website":return e.jsx(dl,{className:"w-3.5 h-3.5"})}},g=b=>{var w;return((w=iK.find(S=>S.value===b))==null?void 0:w.label)||b},x=e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg flex items-center justify-center",style:{backgroundColor:`${c}15`,color:c},children:e.jsx(Nn,{className:"w-4 h-4"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"font-semibold text-slate-800",children:"Trusted Partners"}),e.jsx("p",{className:"text-xs text-slate-500",children:"My personally-vetted recommendations for you"})]})]}),y=o.some(b=>b.disclosure_text)&&e.jsx("div",{className:"mt-4 pt-3 border-t border-slate-100 space-y-1",children:o.filter(b=>b.disclosure_text).map(b=>e.jsxs("p",{className:"text-[10px] text-slate-400",children:[e.jsxs("span",{className:"font-medium",children:[b.company||b.name,":"]})," ",b.disclosure_text]},b.id))});if(a==="grid")return e.jsxs(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))}),y]});const v=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(v).map(([b,w])=>e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-slate-400 font-medium mb-2",children:g(b)}),e.jsx("div",{className:"space-y-2",children:w.map(S=>e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-xl bg-slate-50 hover:bg-slate-100 transition-colors",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-white border border-slate-200 flex items-center justify-center overflow-hidden shrink-0",children:S.logo_url?e.jsx("img",{src:S.logo_url,alt:S.name,className:"w-full h-full object-cover"}):e.jsx("span",{className:"text-sm font-semibold text-slate-500",children:S.name.charAt(0)})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm text-slate-800 truncate",children:S.company||S.name}),S.company&&S.name&&e.jsx("p",{className:"text-xs text-slate-500 truncate",children:S.name}),S.description&&e.jsx("p",{className:"text-xs text-slate-500 truncate mt-0.5",children:S.description})]}),e.jsxs($,{size:"sm",onClick:()=>u(S),style:{backgroundColor:c},className:"text-white hover:opacity-90 shrink-0",children:[f(S),e.jsx("span",{className:"ml-1.5 text-xs",children:m(S)})]})]},S.id))})]},b))}),y]})}function y9s(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 v9s(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 K9t({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=y9s(t);j.useEffect(()=>{h.current||(h.current=!0,q.from("portal_referral_clicks").insert({portal_id:s,owner_user_id:n,click_type:"card_view",user_agent:navigator.userAgent.slice(0,500)}).then(()=>{}))},[s,n]);const f=async E=>{await q.from("portal_referral_clicks").insert({portal_id:s,owner_user_id:n,click_type:E,user_agent:navigator.userAgent.slice(0,500)})},g=()=>`${l?`Hey, it's ${l}!`:"Hey!"} I just had an amazing experience working with ${i||"my real estate agent"} on my home. If you or someone you know is thinking about buying or selling, here's their referral link: ${m}`,x=async()=>{await navigator.clipboard.writeText(m),u(!0),f("copy_link"),setTimeout(()=>u(!1),2e3)},y=()=>{f("share_sms");const E=encodeURIComponent(g());window.location.href=`sms:?&body=${E}`},v=()=>{f("share_email");const E=encodeURIComponent("A referral you'll thank me for"),I=encodeURIComponent(g());window.location.href=`mailto:?subject=${E}&body=${I}`},b=()=>{f("open_form"),window.open(m,"_blank")},w=a||"Know someone buying or selling?",S=c?v9s(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(Nn,{className:"w-4 h-4 text-[#406E71]"}),e.jsxs("p",{className:"text-sm font-medium text-slate-700",children:["A message from ",i||"your agent"]})]})}),e.jsx("div",{className:"aspect-video bg-slate-900",children: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(ul,{className:"w-3 h-3"}),"Referral Program"]}),e.jsx("h3",{className:"text-xl font-bold leading-tight mb-2 font-serif",children:w}),r&&e.jsxs("p",{className:"text-sm text-white/85 mb-1",children:[e.jsx("span",{className:"font-semibold text-white",children:"Your reward:"})," ",r]}),e.jsxs("p",{className:"text-sm text-white/70 mb-5 leading-relaxed",children:["The biggest compliment you can give ",i||"us"," is sending a friend or family member."]}),e.jsxs("button",{onClick:b,className:"w-full bg-white text-[#2a4c64] font-semibold rounded-xl py-3.5 px-4 flex items-center justify-center gap-2 shadow-md hover:bg-white/95 active:scale-[0.99] transition-all",children:["Refer a Friend",e.jsx(Qa,{className:"w-4 h-4"})]}),e.jsxs("div",{className:"mt-4 grid grid-cols-3 gap-2",children:[e.jsxs("button",{onClick:y,className:"flex items-center justify-center gap-1.5 bg-white/10 hover:bg-white/20 backdrop-blur-sm rounded-lg py-2.5 text-xs font-medium transition-colors",children:[e.jsx(Ah,{className:"w-3.5 h-3.5"}),"Text"]}),e.jsxs("button",{onClick:v,className:"flex items-center justify-center gap-1.5 bg-white/10 hover:bg-white/20 backdrop-blur-sm rounded-lg py-2.5 text-xs font-medium transition-colors",children:[e.jsx(mn,{className:"w-3.5 h-3.5"}),"Email"]}),e.jsxs("button",{onClick:x,className:"flex items-center justify-center gap-1.5 bg-white/10 hover:bg-white/20 backdrop-blur-sm rounded-lg py-2.5 text-xs font-medium transition-colors",children:[d?e.jsx(ca,{className:"w-3.5 h-3.5"}):e.jsx(Ha,{className:"w-3.5 h-3.5"}),d?"Copied":"Copy"]})]})]})]}),o&&e.jsx("a",{href:o,target:"_blank",rel:"noopener noreferrer",onClick:()=>f("review_click"),className:"block bg-white border border-slate-200 hover:border-amber-300 hover:bg-amber-50/30 rounded-2xl p-4 transition-colors",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"text-2xl",children:"⭐"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-semibold text-slate-800",children:"Loved working together?"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Leave a quick review — it means the world."})]}),e.jsx(Qa,{className:"w-4 h-4 text-slate-400"})]})})]})}function Y9t(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 Z9t(){const s=Wt();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 b9s(){const s=Wt();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 X9t(){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 Q9t({portalId:s,clientName:t,agentName:n,agentAvatar:r,deviceFingerprint:a}){const{data:i,isLoading:l}=Y9t(s),o=Z9t(),[c,d]=j.useState(""),u=`portal_msg_name_${s}`,[h,m]=j.useState(()=>localStorage.getItem(u)||t||""),f=j.useRef(null);j.useEffect(()=>{var y;(y=f.current)==null||y.scrollIntoView({block:"nearest"})},[i==null?void 0:i.length]);const g=async()=>{const y=c.trim();if(!y)return;const v=(h||t||"").trim();if(!v){re.error("Please add your name first");return}try{localStorage.setItem(u,v),await o.mutateAsync({portalId:s,senderType:"client",senderName:v,body:y,deviceFingerprint:a,portalUrl:window.location.href}),d(""),re.success("Message sent")}catch(b){re.error((b==null?void 0:b.message)||"Could not send your message")}},x="hsl(var(--portal-gold))";return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(eo,{className:"w-4 h-4",style:{color:x}}),e.jsx("h2",{className:"portal-serif",style:{fontSize:"1.35rem",color:"hsl(var(--portal-ink))"},children:"Messages"})]}),e.jsx("div",{className:"portal-hairline mb-4"}),e.jsxs("div",{className:"space-y-3 max-h-[340px] overflow-y-auto pr-1",children:[l&&e.jsx("div",{className:"flex justify-center py-6",children:e.jsx(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(y=>{const v=y.sender_type==="agent";return e.jsx("div",{className:`flex ${v?"justify-start":"justify-end"}`,children:e.jsxs("div",{className:"max-w-[85%] rounded-2xl px-4 py-3",style:{background:v?"hsl(var(--portal-surface-2))":"hsl(var(--portal-gold) / 0.12)",border:`1px solid ${v?"hsl(var(--portal-gold) / 0.12)":"hsl(var(--portal-gold) / 0.28)"}`},children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[v&&r&&e.jsx("img",{src:r,alt:n||"Agent",className:"w-5 h-5 rounded-full object-cover"}),e.jsxs("span",{className:"text-[11px] uppercase tracking-[0.14em]",style:{color:"hsl(var(--portal-ink-dim))"},children:[v?n||"Your agent":y.sender_name||"You"," ·"," ",en(new Date(y.created_at),"MMM d, h:mm a")]})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap leading-relaxed",style:{color:"hsl(var(--portal-ink))"},children:y.body})]})},y.id)}),e.jsx("div",{ref:f})]}),e.jsxs("div",{className:"mt-4 space-y-2",children:[!t&&e.jsx("input",{value:h,onChange:y=>m(y.target.value),placeholder:"Your name",className:"w-full rounded-xl px-3 py-2 text-sm outline-none",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.18)",color:"hsl(var(--portal-ink))"}}),e.jsx("textarea",{value:c,onChange:y=>d(y.target.value),rows:3,placeholder:`Write a message to ${n||"your agent"}...`,className:"w-full rounded-xl px-3 py-2 text-sm outline-none resize-none",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.18)",color:"hsl(var(--portal-ink))"}}),e.jsxs("button",{onClick:g,disabled:o.isPending||!c.trim(),className:"w-full flex items-center justify-center gap-2 rounded-xl py-2.5 text-sm font-medium transition-opacity disabled:opacity-50",style:{background:"hsl(var(--portal-gold) / 0.16)",border:"1px solid hsl(var(--portal-gold) / 0.35)",color:x},children:[o.isPending?e.jsx(Ct,{className:"w-4 h-4 animate-spin"}):e.jsx(Kr,{className:"w-4 h-4"}),"Send message"]})]})]})}function _9s(s){return s==="buy-side"?"Home Search in Progress":s==="listing"?"Your Home Is On The Market":"Active Phase"}function w9s(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 j9s={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. 🎉"}},J9t=["Lead","Consultation","Agreement Signed","Active","Under Contract","Closing","Closed Won"];function JLe(s){return J9t.map(t=>{if(t==="Active")return{key:"Active",label:_9s(s),description:w9s(s)};const n=j9s[t];return{key:t,label:n.label,description:n.description}})}function $Ee(s){if(!s)return 0;const t=J9t.indexOf(s);return t>=0?t:0}function N9s({portal:s,linkedPortal:t,activePortal:n,activeTab:r,onTabChange:a,agentProfile:i,branding:l,updates:o,documents:c}){var G,Y,X;const d=(l==null?void 0:l.cover_photo_url)||null,u=(l==null?void 0:l.logo_url)||null,h=(l==null?void 0:l.tagline)||"Your Real Estate Concierge",m=n==null?void 0:n.deal_pipeline,f=m==null?void 0:m.deal_pipeline_stages,g=f==null?void 0:f.is_won_stage,x=m==null?void 0:m.deal_type,y=n==null?void 0:n.stage_mapping;let v=JLe(x);y&&y.length>0&&(v=y.map((ae,le)=>{var ne,te;return{key:`custom-${le}`,label:ae.label||((ne=v[le])==null?void 0:ne.label)||`Stage ${le+1}`,description:ae.description||((te=v[le])==null?void 0:te.description)||"",video_url:ae.video_url||void 0}}));const b=y&&y.length>0?Math.min($Ee(f==null?void 0:f.name),v.length-1):$Ee(f==null?void 0:f.name),w=v[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=(Y=t==null?void 0:t.deal_pipeline)==null?void 0:Y.deal_type,D=ae=>ae==="listing"?"Your Sale":ae==="buy-side"?"Your Purchase":"Transaction",O=v.length>1?Math.round((b+1)/v.length*100):0,{data:U=[]}=H9t({id:n==null?void 0:n.id,owner_user_id:n==null?void 0:n.owner_user_id}),W=U.some(ae=>!ae.stage_filter||ae.stage_filter.length===0||!(f!=null&&f.name)?!0:ae.stage_filter.includes(f.name)),V=()=>{var ae;(ae=document.getElementById("trusted-vendors"))==null||ae.scrollIntoView({behavior:"smooth",block:"start"})};return e.jsxs("div",{className:"min-h-screen relative",style:{background:"var(--portal-gradient-noir)"},children:[e.jsx("div",{className:"pointer-events-none absolute inset-x-0 top-0 h-[600px] opacity-70",style:{background:"radial-gradient(ellipse 70% 100% at 50% 0%, hsl(var(--portal-gold) / 0.08), transparent 60%)"}}),e.jsxs("div",{className:"relative max-w-[1400px] mx-auto px-8 py-8",children:[e.jsxs(Br.div,{initial:{opacity:0,y:-6},animate:{opacity:1,y:0},transition:{duration:.4},className:"flex items-center justify-between mb-8",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[u?e.jsx("div",{className:"rounded-lg px-3 py-1.5",style:{background:"hsl(0 0% 100% / 0.04)",border:"1px solid hsl(var(--portal-gold) / 0.2)"},children:e.jsx("img",{src:u,alt:"Brand",className:"h-8 max-w-[140px] object-contain"})}):e.jsx("div",{className:"w-10 h-10 rounded-lg flex items-center justify-center portal-serif text-xl",style:{background:"var(--portal-gradient-gold)",color:"hsl(var(--portal-bg))"},children:"✦"}),e.jsxs("div",{children:[e.jsx("p",{className:"portal-eyebrow",children:"Private Client Portal"}),e.jsx("p",{className:"portal-serif mt-0.5",style:{fontSize:"1.1rem",color:"hsl(var(--portal-ink))"},children:n!=null&&n.client_name?`Welcome, ${n.client_name.split(" ")[0]}`:"Your transaction"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-[10px] tracking-[0.22em] uppercase",style:{color:"hsl(var(--portal-ink-dim))"},children:[e.jsx(Tf,{className:"w-3 h-3",style:{color:"hsl(var(--portal-gold))"}}),"Secure & Encrypted"]})]}),e.jsxs(Br.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{duration:.6,ease:"easeOut"},className:"relative overflow-hidden rounded-3xl mb-8",style:{minHeight:380,border:"1px solid hsl(var(--portal-gold) / 0.25)",boxShadow:"var(--portal-shadow-luxe)"},children:[d?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"absolute inset-0",style:{backgroundImage:`url(${d})`,backgroundSize:"cover",backgroundPosition:"center",filter:"var(--portal-hero-filter)"}}),e.jsx("div",{className:"absolute inset-0",style:{background:"var(--portal-hero-scrim)"}})]}):e.jsx("div",{className:"absolute inset-0",style:{background:"var(--portal-hero-fallback)"}}),e.jsx("div",{className:"absolute top-0 left-0 right-0 h-[1px]",style:{background:"linear-gradient(90deg, transparent, hsl(var(--portal-gold) / 0.6), transparent)"}}),e.jsxs("div",{className:"relative grid grid-cols-3 gap-8 p-12",children:[e.jsxs("div",{className:"col-span-2 flex flex-col justify-end",children:[e.jsxs("div",{className:"inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-[10px] tracking-[0.22em] uppercase mb-6 self-start",style:{background:"hsl(0 0% 0% / 0.28)",backdropFilter:"blur(6px)",border:"1px solid var(--portal-hero-accent)",color:"var(--portal-hero-accent)"},children:[e.jsx(va,{className:"w-3 h-3"}),x==="listing"?"Sale":x==="buy-side"?"Purchase":"Transaction",g&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"opacity-50 mx-1",children:"·"}),"Complete"]})]}),e.jsx("h1",{className:"portal-serif leading-[0.95] mb-4",style:{fontSize:"4.5rem",color:"var(--portal-hero-ink)",textShadow:"var(--portal-hero-text-shadow)"},children:(m==null?void 0:m.deal_name)||"Your Transaction"}),e.jsx("div",{className:"portal-hairline w-32 mb-5"}),E&&e.jsxs("div",{className:"flex items-center gap-2",style:{color:"var(--portal-hero-ink-muted)",textShadow:"var(--portal-hero-text-shadow)"},children:[e.jsx(ci,{className:"w-4 h-4",style:{color:"var(--portal-hero-accent)"}}),e.jsx("span",{className:"text-base",children:E})]}),(n==null?void 0:n.welcome_message)&&e.jsxs("p",{className:"mt-6 portal-serif italic leading-relaxed max-w-2xl",style:{color:"var(--portal-hero-ink-muted)",fontSize:"1.15rem",textShadow:"var(--portal-hero-text-shadow)"},children:["“",n.welcome_message,"”"]})]}),e.jsxs("div",{className:"flex flex-col items-center justify-center",children:[e.jsx(k9s,{pct:O}),e.jsx("p",{className:"portal-eyebrow mt-4",style:{color:"var(--portal-hero-accent)"},children:"Journey Progress"}),e.jsxs("p",{className:"portal-serif mt-1",style:{fontSize:"1.1rem",color:"var(--portal-hero-ink)",textShadow:"var(--portal-hero-text-shadow)"},children:["Stage ",b+1," of ",v.length]})]})]}),e.jsx("div",{className:"absolute bottom-0 left-0 right-0 h-[1px]",style:{background:"linear-gradient(90deg, transparent, hsl(var(--portal-gold) / 0.4), transparent)"}})]}),I&&e.jsx("div",{className:"inline-flex gap-1 rounded-xl p-1 mb-8",style:{background:"hsl(var(--portal-surface))",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:["primary","linked"].map(ae=>{const le=ae==="primary"?P:R,ne=r===ae;return e.jsx("button",{onClick:()=>a(ae),className:"portal-serif px-5 py-2 rounded-lg transition-all",style:{fontSize:"1rem",background:ne?"hsl(var(--portal-surface-3))":"transparent",color:ne?"hsl(var(--portal-gold))":"hsl(var(--portal-ink-muted))",borderBottom:ne?"1px solid hsl(var(--portal-gold))":"1px solid transparent"},children:D(le)},ae)})}),e.jsxs(Br.div,{initial:"hidden",animate:"show",variants:{hidden:{},show:{transition:{staggerChildren:.06}}},className:"grid grid-cols-12 gap-5",children:[e.jsx("aside",{className:"col-span-3 space-y-5",children:e.jsxs("div",{className:"sticky top-6 space-y-5",children:[e.jsxs(e5,{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(T7e,{href:`tel:${i.phone}`,icon:Da,label:"Call",sub:i.phone}),(i==null?void 0:i.phone)&&e.jsx(T7e,{href:`sms:${i.phone}`,icon:Ah,label:"Text message"}),(i==null?void 0:i.email)&&e.jsx(T7e,{href:`mailto:${i.email}`,icon:mn,label:"Email",sub:i.email})]})]}),e.jsxs(e5,{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(M7e,{icon:Ta,label:"Target close",value:bvt(m.target_close_date)}),(m==null?void 0:m.contract_date)&&e.jsx(M7e,{icon:da,label:"Under contract",value:bvt(m.contract_date)}),e.jsx(M7e,{icon:wl,label:"Progress",value:`${O}%`})]})]})]})}),e.jsxs("main",{className:"col-span-6 space-y-5",children:[A&&e.jsx(K9t,{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(F9t,{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(e5,{children:e.jsx(z9t,{currentStage:w,nextStepText:n.next_step_text,nextStepVideoUrl:S||n.next_step_video_url})}),e.jsx(e5,{children:e.jsx(O9t,{journeyStages:v,currentIndex:b})}),o&&o.length>0&&e.jsx(e5,{children:e.jsx(q9t,{updates:o})}),(n==null?void 0:n.id)&&e.jsx(e5,{children:e.jsx(Q9t,{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(e5,{children:e.jsx(B9t,{deal:m,portal:n})}),(n==null?void 0:n.slug)&&e.jsx(U9t,{slug:n.slug,wrapper:ae=>e.jsx(e5,{children:ae})}),c&&c.length>0&&e.jsx(e5,{children:e.jsx($9t,{documents:c})}),W&&e.jsx(e5,{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(sV,{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(W9t,{portalId:n.id,ownerUserId:n.owner_user_id,currentStage:f==null?void 0:f.name,brandingColor:"hsl(var(--portal-gold))",layout:"grid"})})]})]})}function e5({children:s}){return e.jsx(Br.div,{variants:{hidden:{opacity:0,y:10},show:{opacity:1,y:0,transition:{duration:.45,ease:"easeOut"}}},className:"portal-tile p-6",children:s})}function T7e({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 M7e({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 k9s({pct:s}){const a=2*Math.PI*78,i=a-s/100*a;return e.jsxs("div",{className:"relative",style:{width:170,height:170},children:[e.jsxs("svg",{width:170,height:170,className:"-rotate-90",children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"portal-progress-gold",x1:"0%",y1:"0%",x2:"100%",y2:"100%",children:[e.jsx("stop",{offset:"0%",stopColor:"var(--portal-hero-accent)"}),e.jsx("stop",{offset:"100%",stopColor:"var(--portal-hero-ink)"})]})}),e.jsx("circle",{cx:170/2,cy:170/2,r:78,stroke:"hsl(0 0% 100% / 0.22)",strokeWidth:2,fill:"none"}),e.jsx(Br.circle,{cx:170/2,cy:170/2,r:78,stroke:"url(#portal-progress-gold)",strokeWidth:3,strokeLinecap:"round",fill:"none",initial:{strokeDashoffset:a},animate:{strokeDashoffset:i},transition:{duration:1.4,ease:"easeOut"},strokeDasharray:a,style:{filter:"drop-shadow(0 0 6px hsl(0 0% 0% / 0.45))"}})]}),e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:[e.jsx("span",{className:"portal-serif tabular-nums leading-none",style:{fontSize:"3rem",color:"var(--portal-hero-ink)",textShadow:"var(--portal-hero-text-shadow)"},children:s}),e.jsx("span",{className:"text-[10px] tracking-[0.25em] uppercase mt-1",style:{color:"var(--portal-hero-ink-dim)",textShadow:"var(--portal-hero-text-shadow)"},children:"percent"})]})]})}function bvt(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 S9s({portal:s,dealData:t,agentProfile:n,customQuestions:r,deviceFingerprint:a,onComplete:i}){var y,v;const[l,o]=j.useState({first_name:((y=s.client_name)==null?void 0:y.split(" ")[0])||"",last_name:((v=s.client_name)==null?void 0:v.split(" ").slice(1).join(" "))||"",email:s.client_email||"",phone:s.client_phone||"",preferred_contact_method:"email",client_role:"buyer",notes:"",spouse_first_name:"",spouse_last_name:"",spouse_email:"",spouse_phone:""}),[c,d]=j.useState({}),[u,h]=j.useState(!1),m=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),re.error("Something went wrong. Please try again.")}}),f=t!=null&&t.property_address?`${t.property_address}, ${t.city||""}, ${t.state||""}`:null,g="mt-1 rounded-xl bg-white text-slate-900 placeholder:text-slate-400 border-slate-200 focus-visible:ring-slate-400",x="mt-1 w-full rounded-xl border border-slate-200 bg-white text-slate-900 placeholder:text-slate-400 px-3 py-2 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-slate-400";return e.jsx("div",{className:"max-w-md mx-auto px-4 py-10",children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-xl ring-1 ring-slate-200 p-6 sm:p-8",children:[e.jsxs("div",{className:"text-center mb-8",children:[(n==null?void 0:n.avatar_url)&&e.jsx("img",{src:n.avatar_url,alt:n.name,className:"w-16 h-16 rounded-full border-2 border-slate-200 mx-auto mb-3 object-cover"}),e.jsx("h1",{className:"text-2xl font-bold text-slate-900",children:"Welcome to Your Portal"}),f&&e.jsxs("div",{className:"flex items-center justify-center gap-1 text-slate-500 text-sm mt-1",children:[e.jsx(ci,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:f.replace(/,\s*,/g,",").replace(/,\s*$/,"")})]}),e.jsx("p",{className:"text-sm text-slate-600 mt-2",children:"Please fill in your details to access your transaction portal."})]}),e.jsxs("form",{onSubmit:b=>{b.preventDefault(),m.mutate()},className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs font-medium text-slate-700",children:"First Name *"}),e.jsx(pe,{required:!0,value:l.first_name,onChange:b=>o(w=>({...w,first_name:b.target.value})),className:g,placeholder:"John"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs font-medium text-slate-700",children:"Last Name"}),e.jsx(pe,{value:l.last_name,onChange:b=>o(w=>({...w,last_name:b.target.value})),className:g,placeholder:"Doe"})]})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs font-medium text-slate-700",children:"Email"}),e.jsx(pe,{type:"email",value:l.email,onChange:b=>o(w=>({...w,email:b.target.value})),className:g,placeholder:"john@example.com"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs font-medium text-slate-700",children:"Phone"}),e.jsx(pe,{type:"tel",value:l.phone,onChange:b=>o(w=>({...w,phone:b.target.value})),className:g,placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs font-medium text-slate-700",children:"Preferred Contact Method"}),e.jsx("div",{className:"flex gap-2 mt-1.5",children:[{value:"email",label:"Email"},{value:"call",label:"Phone"},{value:"text",label:"Text"}].map(b=>e.jsx("button",{type:"button",onClick:()=>o(w=>({...w,preferred_contact_method:b.value})),className:`px-3.5 py-1.5 rounded-full text-xs font-medium border transition-colors ${l.preferred_contact_method===b.value?"bg-slate-800 text-white border-slate-800":"bg-white text-slate-600 border-slate-200 hover:border-slate-300"}`,children:b.label},b.value))})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs font-medium text-slate-700",children:"Your Role"}),e.jsx("div",{className:"flex gap-2 mt-1.5",children:["buyer","seller","both"].map(b=>e.jsx("button",{type:"button",onClick:()=>o(w=>({...w,client_role:b})),className:`px-3.5 py-1.5 rounded-full text-xs font-medium border transition-colors ${l.client_role===b?"bg-slate-800 text-white border-slate-800":"bg-white text-slate-600 border-slate-200 hover:border-slate-300"}`,children:b.charAt(0).toUpperCase()+b.slice(1)},b))})]}),r.map(b=>e.jsxs("div",{children:[e.jsxs(ee,{className:"text-xs font-medium text-slate-700",children:[b.question_text," ",b.is_required&&"*"]}),b.field_type==="text"&&e.jsx(pe,{required:b.is_required,value:c[b.id]||"",onChange:w=>d(S=>({...S,[b.id]:w.target.value})),className:g}),b.field_type==="textarea"&&e.jsx("textarea",{required:b.is_required,value:c[b.id]||"",onChange:w=>d(S=>({...S,[b.id]:w.target.value})),className:`${x} min-h-[80px]`}),b.field_type==="dropdown"&&e.jsxs("select",{required:b.is_required,value:c[b.id]||"",onChange:w=>d(S=>({...S,[b.id]:w.target.value})),className:`${x} h-10`,children:[e.jsx("option",{value:"",children:"Select..."}),(b.options||[]).map(w=>e.jsx("option",{value:w,children:w},w))]}),b.field_type==="toggle"&&e.jsx("div",{className:"mt-1.5 flex gap-2",children:["Yes","No"].map(w=>e.jsx("button",{type:"button",onClick:()=>d(S=>({...S,[b.id]:w})),className:`px-3.5 py-1.5 rounded-full text-xs font-medium border transition-colors ${c[b.id]===w?"bg-slate-800 text-white border-slate-800":"bg-white text-slate-600 border-slate-200"}`,children:w},w))})]},b.id)),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs font-medium text-slate-700",children:"Notes for your agent"}),e.jsx("textarea",{value:l.notes,onChange:b=>o(w=>({...w,notes:b.target.value})),className:`${x} min-h-[60px]`,placeholder:"Anything you'd like your agent to know..."})]}),s.allow_spouse&&e.jsxs("div",{children:[e.jsx("button",{type:"button",onClick:()=>h(!u),className:"text-sm text-blue-600 hover:text-blue-700 font-medium",children:u?"− Remove spouse/partner":"+ Add spouse/partner"}),u&&e.jsxs("div",{className:"mt-3 p-4 bg-slate-50 rounded-xl border border-slate-200 space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs font-medium text-slate-700",children:"First Name"}),e.jsx(pe,{value:l.spouse_first_name,onChange:b=>o(w=>({...w,spouse_first_name:b.target.value})),className:g})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs font-medium text-slate-700",children:"Last Name"}),e.jsx(pe,{value:l.spouse_last_name,onChange:b=>o(w=>({...w,spouse_last_name:b.target.value})),className:g})]})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs font-medium text-slate-700",children:"Email"}),e.jsx(pe,{type:"email",value:l.spouse_email,onChange:b=>o(w=>({...w,spouse_email:b.target.value})),className:g})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs font-medium text-slate-700",children:"Phone"}),e.jsx(pe,{type:"tel",value:l.spouse_phone,onChange:b=>o(w=>({...w,spouse_phone:b.target.value})),className:g})]})]})]}),e.jsx($,{type:"submit",disabled:m.isPending||!l.first_name,className:"w-full h-12 rounded-full text-sm font-semibold bg-slate-900 hover:bg-slate-800",children:m.isPending?"Submitting...":"Access My Portal"})]})]})})}function C9s(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 e$t(){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 A9s(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 E9s(){const s=Sa(),t=Wt();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 t$t(s,t,n){var o;const r=((o=t.name.split(".").pop())==null?void 0:o.toLowerCase())||"png",a=`${s}/${n}-${Date.now()}.${r}`,{error:i}=await q.storage.from("portal-branding").upload(a,t,{upsert:!0,cacheControl:"3600"});if(i)throw i;const{data:l}=q.storage.from("portal-branding").getPublicUrl(a);return l.publicUrl}function T9s(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 M9s(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 s$t({slug:s}){var le,ne,te,J,ce,_e;const[t,n]=j.useState(!1),[r,a]=j.useState("primary"),[i]=j.useState(()=>{const he=`portal_fp_${s}`;let ue=localStorage.getItem(he);return ue||(ue=localStorage.getItem("portal_fp"),ue?localStorage.setItem(he,ue):(ue=crypto.randomUUID(),localStorage.setItem(he,ue),localStorage.setItem("portal_fp",ue))),ue});j.useEffect(()=>(document.body.classList.add("client-portal-page"),()=>document.body.classList.remove("client-portal-page")),[]);const{data:l,isLoading:o,error:c}=T9s(s,!0),d=l==null?void 0:l.linked_portal_id,{data:u}=M9s(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:he,error:ue}=await q.from("deal_pipeline_stages").select("*").eq("owner_user_id",h).order("sort_order",{ascending:!0});if(ue)throw ue;return he},enabled:!!h}),{data:f}=st({queryKey:["portal-agent",h],queryFn:async()=>{const{data:he,error:ue}=await q.from("profiles").select("id, name, avatar_url, phone, email").eq("id",h).single();if(ue)throw ue;return he},enabled:!!h}),{data:g}=A9s(h),x=r==="linked"&&u?u:l,y=x==null?void 0:x.id,v=C9s(g,x==null?void 0:x.branding_override),b=v.portal_theme==="azure"?"azure":"noir";j.useEffect(()=>{const he=`portal-theme-${b}`;return document.body.classList.add(he),()=>document.body.classList.remove(he)},[b]);const{data:w}=st({queryKey:["portal-updates-public",y],queryFn:async()=>{const{data:he,error:ue}=await q.from("portal_updates").select("*").eq("portal_id",y).order("created_at",{ascending:!1});if(ue)throw ue;return he},enabled:!!y}),S=(ne=x==null?void 0:x.deal_pipeline)==null?void 0:ne.id,{data:A}=st({queryKey:["portal-documents",S],queryFn:async()=>{const{data:he,error:ue}=await q.from("deal_files").select("*").eq("deal_id",S).eq("visible_on_portal",!0).order("created_at",{ascending:!1});if(ue)throw ue;return he},enabled:!!S}),E=l==null?void 0:l.id,I=E?`portal_onboarded_${E}_${i}`:null,P=I?localStorage.getItem(I)==="1":!1,{data:R,isLoading:D}=st({queryKey:["portal-onboarding-check",E,i],queryFn:async()=>{const{data:he,error:ue}=await q.from("portal_onboarding_submissions").select("id").eq("portal_id",E).eq("device_fingerprint",i).maybeSingle();if(ue)throw ue;return he&&I&&localStorage.setItem(I,"1"),he},enabled:!!E&&!!(l!=null&&l.require_onboarding)&&!P,staleTime:5*60*1e3}),O=!!(l!=null&&l.require_onboarding)&&!P&&!R&&!t,{data:U}=st({queryKey:["portal-custom-questions-public",h],queryFn:async()=>{const{data:he,error:ue}=await q.from("portal_custom_questions").select("*").eq("owner_user_id",h).eq("is_active",!0).order("sort_order",{ascending:!0});if(ue)throw ue;return he},enabled:!!h&&O}),W=P||!!R||t||!(l!=null&&l.require_onboarding);if(o||l!=null&&l.require_onboarding&&!P&&D)return e.jsx("div",{className:"min-h-screen flex items-center justify-center",style:{background:"hsl(var(--portal-bg))"},children:e.jsx(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 he=l==null?void 0:l.deal_pipeline;return e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-slate-100",children:e.jsx(S9s,{portal:l,dealData:he,agentProfile:f,customQuestions:U||[],deviceFingerprint:i,onComplete:()=>{I&&localStorage.setItem(I,"1"),n(!0)}})})}const V=(te=l==null?void 0:l.deal_pipeline)==null?void 0:te.deal_type,G=(J=u==null?void 0:u.deal_pipeline)==null?void 0:J.deal_type,Y=!!u,X=he=>he==="listing"?"Your Sale":he==="buy-side"?"Your Purchase":"Transaction",ae=he=>he==="listing"?e.jsx(va,{className:"w-3.5 h-3.5"}):e.jsx(w_,{className:"w-3.5 h-3.5"});return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"hidden lg:block",children:e.jsx(N9s,{portal:l,linkedPortal:u,activePortal:x,activeTab:r,onTabChange:a,agentProfile:f,branding:v,updates:w,documents:A})}),e.jsxs("div",{className:"lg:hidden min-h-screen pb-16",style:{background:"var(--portal-gradient-noir)"},children:[e.jsx(c9s,{dealData:x==null?void 0:x.deal_pipeline,agentProfile:f,welcomeMessage:(x==null?void 0:x.welcome_message)||v.welcome_message,isWon:(_e=(ce=x==null?void 0:x.deal_pipeline)==null?void 0:ce.deal_pipeline_stages)==null?void 0:_e.is_won_stage,branding:v}),e.jsxs("div",{className:"max-w-lg mx-auto px-4 space-y-5 mt-8",children:[Y&&e.jsx("div",{className:"flex gap-1 rounded-xl p-1",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:["primary","linked"].map(he=>{const ue=r===he,ve=he==="primary"?V:G;return e.jsxs("button",{onClick:()=>a(he),className:"flex-1 flex items-center justify-center gap-1.5 rounded-lg py-2.5 text-sm font-medium transition-all portal-serif",style:{background:ue?"hsl(var(--portal-surface-3))":"transparent",color:ue?"hsl(var(--portal-gold))":"hsl(var(--portal-ink-muted))",boxShadow:ue?"0 1px 0 hsl(var(--portal-gold) / 0.3) inset":"none"},children:[ae(ve),e.jsx("span",{style:{fontSize:"1rem"},children:X(ve)})]},he)})}),e.jsx(P9s,{portal:x,updates:w,documents:A,agentProfile:f}),y&&e.jsx("div",{className:"rounded-2xl p-5",style:{background:"hsl(var(--portal-surface))",border:"1px solid hsl(var(--portal-gold) / 0.14)"},children:e.jsx(Q9t,{portalId:y,clientName:x==null?void 0:x.client_name,agentName:f==null?void 0:f.name,agentAvatar:f==null?void 0:f.avatar_url,deviceFingerprint:i})}),e.jsxs("div",{className:"text-center pt-8 pb-2 space-y-3",children:[e.jsx("div",{className:"portal-hairline w-16 mx-auto"}),e.jsxs("div",{className:"flex items-center justify-center gap-1.5",style:{color:"hsl(var(--portal-ink-dim))"},children:[e.jsx(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 P9s({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=JLe(c);d&&d.length>0&&(u=d.map((x,y)=>{var v,b;return{key:`custom-${y}`,label:x.label||((v=u[y])==null?void 0:v.label)||`Stage ${y+1}`,description:x.description||((b=u[y])==null?void 0:b.description)||"",video_url:x.video_url||void 0}}));const h=d&&d.length>0?Math.min($Ee(l==null?void 0:l.name),u.length-1):$Ee(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(K9t,{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(F9t,{targetCloseDate:i==null?void 0:i.target_close_date,actualCloseDate:i==null?void 0:i.actual_close_date,clientName:s.client_name}),e.jsx(O9t,{journeyStages:u,currentIndex:h}),m&&e.jsx(z9t,{currentStage:m,nextStepText:s.next_step_text,nextStepVideoUrl:f||s.next_step_video_url}),e.jsx(B9t,{deal:i,portal:s}),(s==null?void 0:s.slug)&&e.jsx(U9t,{slug:s.slug}),n&&n.length>0&&e.jsx($9t,{documents:n}),(s==null?void 0:s.id)&&(s==null?void 0:s.owner_user_id)&&e.jsx(W9t,{portalId:s.id,ownerUserId:s.owner_user_id,currentStage:l==null?void 0:l.name}),t&&t.length>0&&e.jsx(q9t,{updates:t})]})}function n$t({slug:s}){const t=Wi(),n=s||t.slug,[r,a]=j.useState(!1),[i,l]=j.useState(!1),[o,c]=j.useState(""),[d,u]=j.useState(""),[h,m]=j.useState(""),[f,g]=j.useState(""),[x,y]=j.useState(""),[v,b]=j.useState("buying"),[w,S]=j.useState("");j.useEffect(()=>(document.body.classList.add("client-portal-page"),()=>document.body.classList.remove("client-portal-page")),[]);const{data: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()){re.error("Please enter your friend's name");return}if(!f.trim()&&!x.trim()){re.error("Please add at least an email or phone for your friend");return}a(!0);try{const{error:O}=await q.from("portal_referrals").insert({portal_id: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:v,friend_message:w.trim()||null});if(O)throw O;l(!0)}catch(O){re.error(O.message||"Could not submit referral")}finally{a(!1)}};return E?e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center",children:e.jsx(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(ca,{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(ul,{className:"w-7 h-7 text-white/70"})}),e.jsxs("div",{className:"inline-flex items-center gap-1.5 bg-white/10 backdrop-blur-sm rounded-full px-3 py-1 text-xs font-medium text-white/90 mb-2",children:[e.jsx(ul,{className:"w-3 h-3"})," Referral"]}),e.jsx("h1",{className:"text-2xl font-bold tracking-tight mb-1 font-serif",children: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=>y(D.target.value),placeholder:"(555) 123-4567",className:"mt-1"})]})]}),e.jsx("p",{className:"text-[11px] text-slate-400",children:"Add at least an email or phone so we can reach them."}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm",children:"They're interested in..."}),e.jsx("div",{className:"mt-2 grid grid-cols-2 gap-2",children:[{v:"buying",l:"Buying"},{v:"selling",l:"Selling"},{v:"both",l:"Both"},{v:"unsure",l:"Not sure"}].map(D=>e.jsx("button",{type:"button",onClick:()=>b(D.v),className:`rounded-lg border px-3 py-2 text-sm font-medium transition-colors ${v===D.v?"bg-[#406E71] text-white border-[#406E71]":"bg-white text-slate-600 border-slate-200 hover:border-slate-300"}`,children:D.l},D.v))})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"friend_message",className:"text-sm",children:"A note (optional)"}),e.jsx("textarea",{id:"friend_message",value:w,onChange:D=>S(D.target.value),placeholder:"They're moving from Boston in the spring...",rows:3,className:"mt-1 w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"})]})]})]}),e.jsxs("div",{className:"border-t pt-4",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-slate-500 mb-3",children:"Your info"}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"referrer_name",className:"text-sm",children:"Your name"}),e.jsx(pe,{id:"referrer_name",value:o,onChange:D=>c(D.target.value),placeholder: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(ul,{className:"w-4 h-4"}),r?"Sending...":"Send Referral"]}),e.jsx("p",{className:"text-[11px] text-center text-slate-400",children:"By submitting, you confirm your friend has agreed to be contacted."})]})})]})}function I9s(){const t=mu().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(n$t,{slug:n[1]}):t.includes("/")?e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Page Not Found"}),e.jsx("p",{className:"text-slate-500",children:"This portal link doesn't look right."})]})}):e.jsx(s$t,{slug:t})}function L9s(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 UEe({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(()=>L9s(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 r$t({comp:s,open:t,onClose:n}){var d;const[r,a]=j.useState(0);if(!s)return null;const i=Array.isArray(s.photos)?s.photos.filter(Boolean):[],l=s.soldPrice||s.price,o=s.sqft&&l?Math.round(l/s.sqft):null,c=u=>{if(!u)return null;const[h,m,f]=u.split(/[-/T]/);return h?`${m}/${f}/${h}`:null};return e.jsx(zs,{open:t,onOpenChange:u=>{u||n()},children:e.jsxs(Os,{className:"max-w-4xl max-h-[90vh] overflow-y-auto p-0",children:[e.jsxs(Us,{className:"px-6 pt-6 pb-2",children:[e.jsx(Bs,{className:"text-xl",children:s.address}),e.jsxs("div",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[e.jsx(ci,{className:"w-3.5 h-3.5"}),s.city,", ",s.state," ",s.zip]})]}),i.length>0?e.jsxs("div",{className:"px-6",children:[e.jsx(UEe,{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(UEe,{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(nu,{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(P7e,{label:"Active",date:c(s.listDate),active:!0}),e.jsx(P7e,{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(P7e,{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(Uce,{icon:e.jsx(r2,{className:"w-4 h-4"}),label:"Beds",value:s.bedrooms??"—"}),e.jsx(Uce,{icon:e.jsx(A0,{className:"w-4 h-4"}),label:"Baths",value:s.bathrooms??"—"}),e.jsx(Uce,{icon:e.jsx(P4,{className:"w-4 h-4"}),label:"SqFt",value:((d=s.sqft)==null?void 0:d.toLocaleString())??"—"}),e.jsx(Uce,{icon:e.jsx(Ta,{className:"w-4 h-4"}),label:"Year Built",value:s.yearBuilt??"—"})]}),e.jsxs("div",{className:"px-6 pt-4 grid sm:grid-cols-2 gap-x-6 gap-y-2 text-sm",children:[e.jsx(Y1,{label:"MLS #",value:s.mlsNumber}),e.jsx(Y1,{label:"Property Type",value:s.propertySubType||s.propertyType}),e.jsx(Y1,{label:"Lot Size",value:s.lotSize}),e.jsx(Y1,{label:"Garage",value:s.garageSpaces}),e.jsx(Y1,{label:"Stories",value:s.stories}),e.jsx(Y1,{label:"HOA",value:s.hoaFee?`$${s.hoaFee}/${(s.hoaFrequency||"mo").toLowerCase()}`:null}),e.jsx(Y1,{label:"Tax (annual)",value:s.taxAmount?`$${s.taxAmount.toLocaleString()}`:null}),e.jsx(Y1,{label:"Heating",value:s.heating}),e.jsx(Y1,{label:"Cooling",value:s.cooling}),e.jsx(Y1,{label:"Parking",value:s.parking}),e.jsx(Y1,{label:"Elementary",value:s.elementarySchool}),e.jsx(Y1,{label:"Middle",value:s.middleSchool}),e.jsx(Y1,{label:"High",value:s.highSchool}),e.jsx(Y1,{label:"Listed By",value:s.listAgentFullName}),e.jsx(Y1,{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 Uce({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 Y1({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 P7e({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 qce({to:s,durationMs:t=1400,prefix:n="",suffix:r="",className:a,delayMs:i=0}){const[l,o]=j.useState(0),c=j.useRef(null);return j.useEffect(()=>{if(!Number.isFinite(s))return;let d=0;const u=0,h=f=>1-Math.pow(1-f,3),m=setTimeout(()=>{const f=g=>{d||(d=g);const x=g-d,y=Math.min(1,x/t);o(Math.round(u+(s-u)*h(y))),y<1&&(c.current=requestAnimationFrame(f))};c.current=requestAnimationFrame(f)},i);return()=>{clearTimeout(m),c.current&&cancelAnimationFrame(c.current)}},[s,t,i]),e.jsxs("span",{className:a,children:[n,l.toLocaleString(),r]})}function R9s({low:s,likely:t,high:n,defaultMortgage:r=0,defaultCommissionPct:a=6,defaultClosingPct:i=1}){const[l,o]=j.useState(t),[c,d]=j.useState(r),[u,h]=j.useState(a),[m,f]=j.useState(i),{commission:g,closing:x,net:y}=j.useMemo(()=>{const w=Math.round(l*u/100),S=Math.round(l*m/100);return{commission:w,closing:S,net:Math.max(0,l-w-S-(c||0))}},[l,u,m,c]),v=w=>`$${w.toLocaleString()}`,b=n>s?(l-s)/(n-s)*100:50;return e.jsxs(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(Ie,{className:"p-6 space-y-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-end justify-between mb-3",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"List price"}),e.jsx("span",{className:"text-3xl font-bold tabular-nums",children:v(l)})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Nx,{value:[l],min:s,max:n,step:1e3,onValueChange:([w])=>o(w)}),e.jsxs("div",{className:"flex justify-between text-[10px] text-muted-foreground mt-2",children:[e.jsx("span",{children:v(s)}),e.jsxs("span",{children:["Suggested ",v(t)]}),e.jsx("span",{children:v(n)})]})]}),e.jsx("div",{className:"mt-2 h-1.5 rounded-full bg-muted overflow-hidden",children:e.jsx("div",{className:"h-full bg-gradient-to-r from-emerald-500 via-primary to-amber-500 transition-all",style:{width:`${Math.min(100,Math.max(0,b))}%`}})})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Mortgage payoff"}),e.jsx(pe,{type:"number",inputMode:"numeric",value:c||"",placeholder:"$0",onChange:w=>d(Number(w.target.value)||0)})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Commission %"}),e.jsx(pe,{type:"number",step:"0.25",value:u,onChange:w=>h(Number(w.target.value)||0)})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Closing costs %"}),e.jsx(pe,{type:"number",step:"0.25",value:m,onChange:w=>f(Number(w.target.value)||0)})]})]}),e.jsxs("div",{className:"rounded-xl border bg-card overflow-hidden",children:[e.jsxs("div",{className:"px-5 py-4 grid grid-cols-2 gap-y-2 text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Sale price"}),e.jsx("span",{className:"text-right tabular-nums font-medium",children:v(l)}),e.jsxs("span",{className:"text-muted-foreground",children:["Commission (",u,"%)"]}),e.jsxs("span",{className:"text-right tabular-nums text-rose-600",children:["−",v(g)]}),e.jsxs("span",{className:"text-muted-foreground",children:["Closing (",m,"%)"]}),e.jsxs("span",{className:"text-right tabular-nums text-rose-600",children:["−",v(x)]}),c>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-muted-foreground",children:"Mortgage payoff"}),e.jsxs("span",{className:"text-right tabular-nums text-rose-600",children:["−",v(c)]})]})]}),e.jsxs("div",{className:"bg-gradient-to-r from-emerald-500/10 to-primary/10 px-5 py-4 border-t flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(r7,{className:"w-5 h-5 text-emerald-600"}),e.jsx("span",{className:"font-semibold",children:"Your estimated walk-away"})]}),e.jsx("span",{className:"text-2xl font-bold tabular-nums text-emerald-700",children:v(y)})]})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground leading-relaxed",children:"This is a rough estimate to help you think through pricing. Actual proceeds depend on title fees, prorations, repairs, and other items your agent will walk through in detail."})]})]})}function a$t({tokenOverride:s}={}){var Le,Fe,ke,Be,Ne,Ae,Ce,Ve,ze,qe,dt,Xe;const t=Wi(),n=s??t.token,[r,a]=j.useState(null),[i,l]=j.useState(null),[o,c]=j.useState([]),[d,u]=j.useState(!0),[h,m]=j.useState(""),[f,g]=j.useState(""),[x,y]=j.useState(""),[v,b]=j.useState(!1),[w,S]=j.useState(!1),[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(pt=>pt.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 Y=r.subject||{},X=(Le=r.settings)==null?void 0:Le.personalVideo,ae=(Fe=Y.photos)==null?void 0:Fe[0],le=r.contact_first_name?r.contact_first_name:null,ne=((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,_e=r.price_low??null,he=r.price_likely??null,ue=r.price_high??null,ve=_e&&he&&ue,Ee=he&&Y.sqft?Math.round(he/Y.sqft):null,Se=Ee&&G?Math.round((Ee-G)/G*100):null;return e.jsxs("div",{className:"min-h-screen bg-background pb-28 md:pb-0",children:[i&&e.jsx("div",{className:"border-b bg-card sticky top-0 z-40 backdrop-blur supports-[backdrop-filter]:bg-card/80",children:e.jsxs("div",{className:"container mx-auto max-w-6xl px-4 md:px-6 py-3 flex items-center gap-3",children:[i.avatar_url?e.jsx("img",{src:i.avatar_url,alt:i.name,className:"w-10 h-10 rounded-full object-cover ring-2 ring-primary/20"}):e.jsx("div",{className:"w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center font-semibold text-primary text-sm",children:ne}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-semibold leading-tight truncate text-sm",children:i.name}),(i.title||i.brokerage_name)&&e.jsxs("div",{className:"text-[11px] text-muted-foreground flex items-center gap-1 truncate",children:[i.brokerage_name&&e.jsx(ji,{className:"w-3 h-3 shrink-0"}),e.jsx("span",{className:"truncate",children:[i.title,i.brokerage_name].filter(Boolean).join(" · ")})]})]}),e.jsxs("div",{className:"hidden md:flex items-center gap-2",children:[te&&e.jsx($,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:te,children:[e.jsx(Da,{className:"w-4 h-4 mr-1"}),"Call"]})}),J&&e.jsx($,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:J,children:[e.jsx(mn,{className:"w-4 h-4 mr-1"}),"Email"]})})]})]})}),e.jsxs("div",{className:"relative overflow-hidden",children:[ae?e.jsxs("div",{className:"absolute inset-0",children:[e.jsx("img",{src:ae,alt:Y.address,className:"w-full h-full object-cover scale-110 animate-[kenburns_18s_ease-out_infinite_alternate]",style:{animation:"kenburns 22s ease-in-out infinite alternate"}}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-slate-950/85 via-slate-900/75 to-primary/60"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-background via-background/20 to-transparent"})]}):e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-primary/30 via-primary/10 to-background"}),e.jsx("style",{children:` @keyframes kenburns { 0% { transform: scale(1.08) translate(0, 0); } 100% { transform: scale(1.18) translate(-1.5%, -1%); } } `}),e.jsx("div",{className:"relative container mx-auto max-w-6xl px-4 md:px-8 pt-12 md:pt-20 pb-16 md:pb-24",children:e.jsxs("div",{className:"grid md:grid-cols-5 gap-8 items-center",children:[e.jsxs("div",{className:`${X!=null&&X.url?"md:col-span-3":"md:col-span-5"} text-white animate-fade-in`,children:[e.jsxs($e,{className:"mb-4 bg-white/15 text-white border-white/20 backdrop-blur-sm hover:bg-white/20",children:[e.jsx(Nn,{className:"w-3 h-3 mr-1"}),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:Y.address}),e.jsxs("p",{className:"text-white/70 mt-2 text-base md:text-lg flex items-center gap-2",children:[e.jsx(ci,{className:"w-4 h-4"}),Y.city,", ",Y.state," ",Y.zip]}),ve&&e.jsxs("div",{className:"mt-8 md:mt-10",children:[e.jsx("p",{className:"text-xs uppercase tracking-[0.2em] text-white/60 mb-2",children:"Estimated Value"}),e.jsx("div",{className:"flex items-baseline gap-4 flex-wrap",children:e.jsx("div",{className:"text-5xl md:text-7xl font-bold tabular-nums",children:e.jsx(qce,{to:he,prefix:"$",durationMs:1600,delayMs:250})})}),e.jsxs("div",{className:"mt-4 flex items-center gap-3 md:gap-6 text-sm text-white/80",children:[e.jsxs("div",{children:[e.jsx("span",{className:"block text-[11px] uppercase tracking-wider text-white/50",children:"Low"}),e.jsx("span",{className:"tabular-nums font-medium",children:e.jsx(qce,{to:_e,prefix:"$",delayMs:500})})]}),e.jsx("div",{className:"h-8 w-px bg-white/20"}),e.jsxs("div",{children:[e.jsx("span",{className:"block text-[11px] uppercase tracking-wider text-white/50",children:"Likely"}),e.jsx("span",{className:"tabular-nums font-medium",children:e.jsx(qce,{to:he,prefix:"$",delayMs:650})})]}),e.jsx("div",{className:"h-8 w-px bg-white/20"}),e.jsxs("div",{children:[e.jsx("span",{className:"block text-[11px] uppercase tracking-wider text-white/50",children:"High"}),e.jsx("span",{className:"tabular-nums font-medium",children:e.jsx(qce,{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(zu,{className:"w-7 h-7 md:w-8 md:h-8 ml-1",fill:"currentColor"})}),e.jsxs("p",{className:"mt-4 text-sm font-medium tracking-wide",children:["A message from ",((ke=i==null?void 0:i.name)==null?void 0:ke.split(" ")[0])||"your agent"]})]})]})})]})})]}),R&&(X==null?void 0:X.url)&&e.jsx("div",{className:"fixed inset-0 z-50 bg-black/90 flex items-center justify-center p-4 animate-fade-in",onClick:()=>D(!1),children:e.jsxs("div",{className:"relative w-full max-w-4xl",onClick: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:Y.bedrooms??"—"},{label:"Baths",value:Y.bathrooms??"—"},{label:"Sq Ft",value:((Be=Y.sqft)==null?void 0:Be.toLocaleString())??"—"},{label:"Year Built",value:Y.yearBuilt??"—"}].map((at,rt)=>e.jsx(je,{className:"shadow-lg animate-fade-in",style:{animationDelay:`${rt*80}ms`},children:e.jsxs(Ie,{className:"p-4 md:p-6 text-center",children:[e.jsx("div",{className:"text-2xl md:text-3xl font-bold",children:at.value}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1 uppercase tracking-wider",children:at.label})]})},rt))}),((Ae=(Ne=r.settings)==null?void 0:Ne.priceOverride)==null?void 0:Ae.enabled)&&((Ve=(Ce=r.settings)==null?void 0:Ce.priceOverride)==null?void 0:Ve.note)&&e.jsx(je,{className:"border-primary/30 bg-gradient-to-br from-primary/5 to-transparent",children:e.jsxs(Ie,{className:"p-6 md:p-8",children:[e.jsx("p",{className:"text-xs uppercase tracking-widest text-primary font-semibold mb-2",children:"A note from your agent"}),e.jsx("p",{className:"text-base md:text-lg leading-relaxed whitespace-pre-wrap text-foreground/90",children:r.settings.priceOverride.note})]})}),ve&&e.jsx(R9s,{low:_e,likely:he,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(Ie,{className:"p-6 md:p-8",children:[e.jsx("p",{className:"text-xs uppercase tracking-widest text-primary font-semibold mb-2",children:"Why this price"}),e.jsx("h2",{className:"text-2xl md:text-3xl font-bold mb-3",children:"The market is talking."}),e.jsxs("p",{className:"text-muted-foreground leading-relaxed",children:["Based on ",e.jsxs("strong",{className:"text-foreground",children:[o.length," comparable ",o.length===1?"home":"homes"]})," in ",Y.city,", the median sale rate is ",e.jsxs("strong",{className:"text-foreground",children:["$",G,"/sqft"]}),". Applied to your home's ",(ze=Y.sqft)==null?void 0:ze.toLocaleString()," sqft, the comps support a value near ",e.jsxs("strong",{className:"text-foreground",children:["$",(G*(Y.sqft||0)).toLocaleString()]}),". Your agent's suggested price reflects local nuance and condition."]})]})}),e.jsx(je,{className:"bg-gradient-to-br from-primary/10 to-primary/5 border-primary/20",children:e.jsxs(Ie,{className:"p-6 md:p-8 h-full flex flex-col justify-center",children:[e.jsx("p",{className:"text-xs uppercase tracking-widest text-muted-foreground mb-1",children:"Your home"}),e.jsxs("div",{className:"text-3xl font-bold tabular-nums",children:["$",Ee,e.jsx("span",{className:"text-base font-normal text-muted-foreground",children:"/sqft"})]}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-3",children:["Neighborhood avg: ",e.jsxs("span",{className:"font-medium text-foreground",children:["$",G,"/sqft"]})]}),Se!==null&&Se!==0&&e.jsxs("p",{className:`text-sm font-medium mt-1 ${Se>0?"text-emerald-600":"text-rose-600"}`,children:[Se>0?"▲":"▼"," ",Math.abs(Se),"% ",Se>0?"above":"below"," the median"]})]})})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-baseline justify-between mb-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs uppercase tracking-widest text-primary font-semibold",children:"Homes like yours"}),e.jsx("h2",{className:"text-2xl md:text-3xl font-bold",children:"The Comparables"})]}),e.jsxs($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 pt;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(UEe,{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(Ie,{className:"p-4",children:[e.jsx("div",{className:"font-semibold leading-tight truncate",children:Ke.address}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[Ke.city,", ",Ke.state]}),e.jsx("div",{className:"flex justify-between items-center mt-3 text-sm",children:e.jsxs("span",{className:"text-muted-foreground",children:[Ke.bedrooms??"?","bd · ",Ke.bathrooms??"?","ba · ",((pt=Ke.sqft)==null?void 0:pt.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(r$t,{comp:A!==null?(qe=o[A])==null?void 0:qe.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(Ie,{className:"p-6 md:p-8 space-y-5",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs uppercase tracking-widest text-primary font-semibold mb-1",children:"Your turn"}),e.jsxs("h2",{className:"text-2xl md:text-3xl font-bold",children:["What do you think",le?`, ${le}`:"","?"]}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:["One tap. ",((dt=i==null?void 0:i.name)==null?void 0:dt.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:qy,label:"Seems fair"},{kind:"lower",icon:sC,label:"I'd price lower"},{kind:"higher",icon:Zl,label:"I'd price higher"},{kind:"ready_to_list",icon:vb,label:"Ready to list"},{kind:"want_walkthrough",icon:Ca,label:"Want a walkthrough"},{kind:"need_time",icon:Ta,label:"Need more time"},{kind:"have_questions",icon:e4,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! ",((Xe=i==null?void 0:i.name)==null?void 0:Xe.split(" ")[0])||"Your agent"," was notified and will get back to you shortly."]}):e.jsxs(e.Fragment,{children:[W&&e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2 mb-2",children:[e.jsx("input",{className:"border rounded-md p-2 text-sm bg-background",placeholder:"Your name",value:f,onChange: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=>y(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()||v,className:"mt-2",children:v?"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:ne}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-xs uppercase tracking-widest text-muted-foreground",children:"Prepared by"}),e.jsx("h2",{className:"text-2xl md:text-3xl font-bold mt-1",children:i.name}),(i.title||i.brokerage_name)&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:[i.title,i.brokerage_name].filter(Boolean).join(" · ")}),i.bio&&e.jsx("p",{className:"text-sm text-muted-foreground mt-3 leading-relaxed",children:i.bio}),e.jsxs("div",{className:"flex flex-wrap gap-2 mt-4",children:[te&&e.jsx($,{asChild:!0,children:e.jsxs("a",{href:te,children:[e.jsx(Da,{className:"w-4 h-4 mr-2"}),i.phone]})}),J&&e.jsx($,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:J,children:[e.jsx(mn,{className:"w-4 h-4 mr-2"}),"Email"]})}),i.website_url&&e.jsx($,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:i.website_url,target:"_blank",rel:"noreferrer",children:[e.jsx(dl,{className:"w-4 h-4 mr-2"}),"Website"]})})]})]})]})})})]}),i&&(te||ce||J)&&e.jsxs("div",{className:"md:hidden fixed bottom-0 left-0 right-0 bg-card/95 backdrop-blur border-t shadow-2xl z-50 px-3 py-3 flex gap-2",style:{paddingBottom:"calc(0.75rem + env(safe-area-inset-bottom))"},children:[te&&e.jsx($,{className:"flex-1",asChild:!0,children:e.jsxs("a",{href:te,children:[e.jsx(Da,{className:"w-4 h-4 mr-1.5"}),"Call"]})}),ce&&e.jsx($,{variant:"outline",className:"flex-1",asChild:!0,children:e.jsxs("a",{href:ce,children:[e.jsx(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(mn,{className:"w-4 h-4 mr-1.5"}),"Email"]})})]})]})}function D9s(){const t=mu().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(a$t,{tokenOverride:t})}const TGe="levelup_affiliate_ref",F9s=30,O9s=()=>{const[s]=gc();j.useEffect(()=>{const t=s.get("ref");if(t){const n={code:t.toUpperCase(),timestamp:Date.now()};localStorage.setItem(TGe,JSON.stringify(n)),console.log("[Affiliate] Stored referral code:",t)}},[s])},z9s=()=>{try{const s=localStorage.getItem(TGe);if(!s)return null;const t=JSON.parse(s),n=F9s*24*60*60*1e3;return Date.now()-t.timestamp>n?(localStorage.removeItem(TGe),console.log("[Affiliate] Referral code expired"),null):t.code}catch{return null}},qEe="/assets/levelup-logo-header-_ZX7DvlA.png",B9s="/assets/scale-your-team-ku4MPatU.png";function $9s({open:s,onOpenChange:t}){return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-3xl max-h-[90vh] overflow-hidden",children:[e.jsx(Us,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-[#4a6b6d]/10 rounded-lg",children:e.jsx(ji,{className:"h-5 w-5 text-[#4a6b6d]"})}),e.jsxs("div",{children:[e.jsx(Bs,{children:"Schedule a Brokerage Interest Meeting"}),e.jsx(Pr,{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 Kae="/assets/mission_control-BJ-Kz8rX.png",e6e="/assets/crm-CsLftmB2.png",t6e="/assets/deal_pipeline-XYgypvwv.png",s6e="/assets/staging_studio-5iLDjnv0.png",n6e="/assets/coaching-CSQEA81I.png",r6e="/assets/marketing_studio-Brx1ZOnN.png",U9s=[{key:"dashboard",label:"Agent Command Center",caption:"Your entire day — smart queue, calendar and pipeline in one view.",src:Kae},{key:"crm",label:"CRM & Contact Hub",caption:"Contacts, tags, follow-ups and deal history, always one click away.",src:e6e},{key:"pipeline",label:"Deal Pipeline",caption:"Every active deal with tasks, forms and commission tracking built in.",src:t6e},{key:"staging",label:"Staging Studio",caption:"AI photo staging — MLS-ready before/afters in minutes.",src:s6e},{key:"coaching",label:"Coaching",caption:"Book live coaching sessions with Google Meet created automatically.",src:n6e},{key:"marketing",label:"Marketing Studio",caption:"Templates, social posts, reels and print — all branded to you.",src:r6e}];function q9s({slot:s}){return e.jsxs("figure",{className:"rounded-2xl overflow-hidden border border-white/10 bg-white/5 backdrop-blur-sm shadow-2xl",children:[e.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-2 border-b border-white/10",children:[e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-red-400/80"}),e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-amber-400/80"}),e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-green-400/80"}),e.jsx("span",{className:"ml-3 text-[11px] rounded px-2 py-0.5 bg-white/10 text-white/70",children:"dashboard.relevelup.com"})]}),s.src?e.jsx("img",{src:s.src,alt:`LevelUp ${s.label} screenshot`,className:"w-full h-auto block",loading:"lazy"}):e.jsxs("div",{className:"w-full aspect-[16/10] flex flex-col items-center justify-center gap-3 bg-white/5",children:[e.jsx(Nn,{className:"h-8 w-8 text-white/40"}),e.jsx("p",{className:"text-sm font-medium text-white/60",children:s.label}),e.jsx("p",{className:"text-xs px-6 text-center text-white/40",children:"Screenshot placeholder"})]}),e.jsxs("figcaption",{className:"px-4 py-3 text-sm text-white/80",children:[e.jsx("span",{className:"font-semibold text-white",children:s.label})," — ",s.caption]})]})}const J2={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"]}},V9s=[{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:Ta,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:Jr,title:"Resource Kits",description:"Downloadable toolkits with scripts, checklists, guides, and everything you need to close more deals."},{icon:ul,title:"Social Swag",description:"Fresh social media content and designs updated regularly to help you stand out online."}],H9s=[{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:nh,items:["Custom lead websites","Open House Guest Book","RSVP pages","Resource landing pages","Listing Revival™","FSBO Breakthrough","Attract system"]},{category:"CRM & Deals",icon:Cv,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:ey,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:ji,items:["Manager dashboard","Team analytics","Agent onboarding","Office form libraries","Listing Exchange","Brand kits","Recruiting pipeline"]}],G9s=[{icon:Yn,title:"Contact Management",description:"Organize your sphere into relationship tiers—Top 25, Past Clients, Referral Partners, and more."},{icon:Nn,title:"Smart Touchpoint Plans",description:"Automated action plans that tell you exactly who to contact and how, based on relationship type."},{icon:Da,title:"One-Tap Actions",description:"Call, text, or email contacts directly with pre-written scripts tailored to each relationship."},{icon:Fg,title:"Birthday & Anniversary Alerts",description:"Never miss an important date—get reminders for birthdays and home anniversaries."},{icon:ci,title:"Pop-by Map",description:"See all your contacts on a map and plan efficient pop-by routes in your area."},{icon: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:eg,title:"Daily Action Cards",description:"Wake up to a prioritized list of exactly who to reach out to today."}],W9s=[{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."}],K9s=()=>{const{user:s,loading:t}=bs(),n=Xn(),[r]=gc();j.useEffect(()=>{const I=window.location.host==="listings.relevelup.com",P=window.location.pathname==="/";if(I&&P){n("/public/listings",{replace:!0});return}},[n]);const[a,i]=j.useState(null),[l,o]=j.useState(null),[c,d]=j.useState(!1),[u,h]=j.useState(""),[m,f]=j.useState(""),[g,x]=j.useState(""),[y,v]=j.useState(!1),[b,w]=j.useState(!1),S=(I,P=!1)=>{o({tier:I,skipTrial:P}),d(!0)};O9s(),j.useEffect(()=>{const I=window.location.host==="listings.relevelup.com",P=location.pathname.startsWith("/public/");!t&&s&&!I&&!P&&n("/dashboard")},[s,t,n,location.pathname]),j.useEffect(()=>{r.get("canceled")==="true"&&re.error("Checkout was canceled. Feel free to try again when you're ready!")},[r]);const A=async(I,P=!1)=>{if(!u){re.error("Please enter your email address");return}if(!m.trim()){re.error("Please enter your full name");return}v(!0),i(I+(P?"_direct":""));const R=z9s();try{const{data:D,error:O}=await q.functions.invoke("create-checkout",{body:{tier:I,email:u,name:m.trim(),couponCode:g.trim()||void 0,skipTrial:P,referralCode:R}});if(O)throw O;if(D!=null&&D.url)window.open(D.url,"_blank","noopener,noreferrer"),re.success("Checkout opened in a new tab");else throw new Error("No checkout URL returned")}catch(D){console.error("Checkout error:",D),re.error(D.message||"Failed to start checkout. Please try again.")}finally{v(!1),i(null),d(!1),o(null)}},E=()=>{l&&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:qEe,alt:"LevelUp",className:"h-8 md:h-10"})}),e.jsxs("div",{className:"flex items-center gap-2 md:gap-4",children:[e.jsx($,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>{var I;return(I=document.getElementById("features"))==null?void 0:I.scrollIntoView({behavior:"smooth"})},children:"Features"}),e.jsx($,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>{var I;return(I=document.getElementById("pricing"))==null?void 0:I.scrollIntoView({behavior:"smooth"})},children:"Pricing"}),e.jsx($,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>n("/blog"),children:"Blog"}),e.jsx($,{onClick:()=>n("/auth"),className:"bg-white text-[#4a6b6d] hover:bg-gray-100 font-medium shadow-md",children:"Sign In"})]})]})}),e.jsxs("section",{className:"relative overflow-hidden bg-[#0f2530]",children:[e.jsx("style",{children:` @keyframes hero-float { 0%,100% { transform: translateY(0px); } 50% { transform: translateY(-12px); } } @keyframes hero-float-slow { 0%,100% { transform: translateY(0px); } 50% { transform: translateY(-8px); } } @keyframes hero-glow { 0%,100% { opacity: 0.55; } 50% { opacity: 0.9; } } `}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-b from-[#122c3a] via-[#16384a] to-[#0f2530]"}),e.jsx("div",{className:"absolute -top-40 left-1/2 -translate-x-1/2 h-[560px] w-[900px] rounded-full bg-[#4aa8a0]/25 blur-[140px] animate-[hero-glow_7s_ease-in-out_infinite]"}),e.jsx("div",{className:"absolute top-1/3 -left-40 h-[420px] w-[420px] rounded-full bg-[#2a6f8a]/20 blur-[120px]"}),e.jsx("div",{className:"absolute top-1/4 -right-40 h-[420px] w-[420px] rounded-full bg-[#c9a84c]/10 blur-[120px]"}),e.jsx("div",{className:"absolute inset-0 opacity-[0.12] bg-[linear-gradient(to_right,rgba(255,255,255,0.5)_1px,transparent_1px),linear-gradient(to_bottom,rgba(255,255,255,0.5)_1px,transparent_1px)] bg-[size:56px_56px] [mask-image:radial-gradient(ellipse_75%_65%_at_50%_35%,black,transparent)]"}),e.jsx("div",{className:"absolute inset-x-0 bottom-0 h-40 bg-gradient-to-t from-[#0f2530] to-transparent"}),e.jsxs("div",{className:"container mx-auto px-4 relative",children:[e.jsxs("div",{className:"max-w-5xl mx-auto text-center pt-20 md:pt-28 pb-10 space-y-8",children:[e.jsx("div",{className:"flex justify-center animate-fade-in",children:e.jsxs("span",{className:"inline-flex items-center gap-2 rounded-full border border-white/15 bg-white/5 backdrop-blur-sm px-4 py-1.5 text-xs md:text-sm font-semibold tracking-wide text-white/85 shadow-lg",children:[e.jsx(Nn,{className:"h-3.5 w-3.5 text-[#7fd4cc]"}),"The Agent Operating System — coaching, CRM & marketing in one"]})}),e.jsxs("h1",{className:"text-4xl sm:text-5xl md:text-7xl font-sans font-bold tracking-tight text-white leading-[1.05] animate-fade-in",children:["The tools you need",e.jsx("br",{className:"hidden sm:block"})," to get it done.",e.jsx("span",{className:"block mt-3 bg-gradient-to-r from-[#8fe0d6] via-[#5cc0b6] to-[#e6c878] bg-clip-text text-transparent",children:"The platform to keep it going."})]}),e.jsx("p",{className:"text-base md:text-xl text-white/65 max-w-2xl mx-auto leading-relaxed animate-fade-in",children:"Weekly coaching, a smart CRM, done-for-you marketing and AI tools — everything a modern agent runs on, in one login."}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center items-center pt-2 animate-fade-in",children:[e.jsxs($,{size:"lg",onClick:()=>{var I;return(I=document.getElementById("free-trial"))==null?void 0:I.scrollIntoView({behavior:"smooth"})},className:"px-8 py-7 text-lg font-semibold bg-white text-[#122c3a] hover:bg-white/90 shadow-[0_0_40px_-8px_rgba(140,220,210,0.6)] transition-all hover:scale-105 group rounded-full",children:["Start Your Free Trial",e.jsx(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(eg,{className:"h-4 w-4 text-[#7fd4cc]"})," New tools added every month"]}),e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(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:Kae,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(Ta,{className:"h-5 w-5 text-white/80"})}),e.jsxs("span",{children:[e.jsx("span",{className:"block text-sm font-semibold text-white",children:"Coaching booked"}),e.jsx("span",{className:"block text-xs text-white/55",children:"Meet link added automatically"})]})]})]})]})]})]}),e.jsx("section",{className:"py-20 bg-background",children:e.jsx("div",{className:"container mx-auto px-4",children:e.jsxs("div",{className:"max-w-4xl mx-auto text-center space-y-8",children:[e.jsx("h2",{className:"text-3xl md:text-5xl leading-tight font-sans font-semibold text-secondary",children:"We help brokerages and agents grow with training, tools, and built-in execution."}),e.jsxs("div",{className:"space-y-2 text-lg text-muted-foreground",children:[e.jsx("p",{children:"Agents get weekly coaching + plug-and-play marketing."}),e.jsx("p",{children:"Brokerages get higher adoption, consistency, and real engagement."})]}),e.jsx("p",{className:"text-2xl md:text-4xl text-[#4a6b6d] pt-4 font-sans font-bold",children:"LEVELUP EQUIPS BOTH TO THRIVE."}),e.jsx("p",{className:"text-lg text-muted-foreground",children:"Learn how we support agents and empower brokerages to grow—together."}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center pt-4",children:[e.jsxs($,{size:"lg",variant:"outline",onClick:()=>{var I;return(I=document.getElementById("brokerage"))==null?void 0:I.scrollIntoView({behavior:"smooth"})},className:"border-[#4a6b6d] text-[#4a6b6d] hover:bg-[#4a6b6d]/5",children:[e.jsx(ji,{className:"mr-2 h-5 w-5"}),"Brokerage Partnership"]}),e.jsxs($,{size:"lg",onClick:()=>{var I;return(I=document.getElementById("pricing"))==null?void 0:I.scrollIntoView({behavior:"smooth"})},className:"bg-[#4a6b6d] hover:bg-[#3d5a5c]",children:[e.jsx(sl,{className:"mr-2 h-5 w-5"}),"Individual Membership"]})]})]})})}),e.jsx("section",{id:"features",className:"py-20 bg-muted/30",children:e.jsxs("div",{className:"container mx-auto px-4",children:[e.jsxs("div",{className:"text-center max-w-3xl mx-auto mb-16",children:[e.jsxs("span",{className:"inline-flex items-center gap-2 px-4 py-1.5 rounded-full bg-[#4a6b6d]/10 text-[#4a6b6d] text-sm font-semibold mb-5",children:[e.jsx(M4,{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:V9s.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(Ie,{children:e.jsx("p",{className:"text-muted-foreground leading-relaxed",children:I.description})})]},P))}),e.jsxs("div",{className:"mt-14 max-w-6xl mx-auto rounded-3xl bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] p-8 md:p-12 relative overflow-hidden shadow-2xl",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"text-center mb-10",children:[e.jsx("h3",{className:"text-2xl md:text-3xl font-bold text-white font-sans",children:"...and that's just the beginning"}),e.jsx("p",{className:"text-white/60 mt-2",children:"Dozens of purpose-built tools, all included with membership."})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-x-10 gap-y-8",children:H9s.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(ca,{className:"h-3.5 w-3.5 text-emerald-300 shrink-0"}),P]},P))})]},I.category))}),e.jsxs("p",{className:"text-center text-white/50 text-sm mt-10 flex items-center justify-center gap-2",children:[e.jsx(Nn,{className:"h-4 w-4"}),"New tools added every month — membership keeps getting more valuable."]})]})]})]})}),e.jsxs("section",{className:"py-20 bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),e.jsxs("div",{className:"container mx-auto px-4 relative",children:[e.jsxs("div",{className:"text-center max-w-3xl mx-auto mb-14",children:[e.jsx("span",{className:"text-sm font-semibold tracking-[0.15em] uppercase text-white/70",children:"See it in action"}),e.jsx("h2",{className:"text-3xl md:text-5xl font-bold text-white mt-4 tracking-tight font-sans",children:"A real platform, not another course"}),e.jsx("p",{className:"text-white/60 mt-4 max-w-2xl mx-auto text-lg",children:"This is what members open every morning."})]}),e.jsx("div",{className:"grid md:grid-cols-2 gap-8 md:gap-10 max-w-6xl mx-auto",children:U9s.map(I=>e.jsx(q9s,{slot:I},I.key))})]})]}),e.jsxs("section",{id:"agent-os",className:"py-20 bg-gradient-to-br from-[#4a6b6d] to-[#3d5a5c] relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),e.jsxs("div",{className:"container mx-auto px-4 relative",children:[e.jsxs("div",{className:"text-center max-w-3xl mx-auto mb-16",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-4 py-2 rounded-full bg-white/10 text-white text-sm font-medium mb-6",children:[e.jsx(Nn,{className:"w-4 h-4"}),"Included with Membership"]}),e.jsxs("h2",{className:"text-3xl mb-6 text-white font-sans font-bold md:text-6xl",children:["Meet ",e.jsx("span",{className:"italic",children:"Agent OS"})]}),e.jsx("p",{className:"text-lg text-white/80",children:"Your relationship-first operating system. Never forget a follow-up, track every touchpoint, and turn your sphere into a referral machine."})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 max-w-6xl mx-auto",children:G9s.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(Ie,{children:e.jsx("p",{className:"text-white/70 text-sm leading-relaxed",children:I.description})})]},P))}),e.jsx("div",{className:"text-center mt-12",children:e.jsxs($,{size:"lg",onClick:()=>{var I;return(I=document.getElementById("pricing"))==null?void 0:I.scrollIntoView({behavior:"smooth"})},className:"bg-white text-[#4a6b6d] hover:bg-white/90 shadow-xl transition-all hover:scale-105",children:["Get Agent OS with Your Membership",e.jsx(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(ji,{className:"w-4 h-4"}),"For Brokerages"]}),e.jsxs("h2",{className:"text-3xl font-sans font-bold md:text-6xl",children:["Empower Your"," ",e.jsx("span",{className:"italic text-[#4a6b6d]",children:"Entire Team"})]}),e.jsx("p",{className:"text-lg text-muted-foreground",children:"Give every agent on your team access to world-class training and resources. Track performance, streamline onboarding, and watch your brokerage thrive."}),e.jsx("ul",{className:"space-y-4",children:["Dedicated brokerage manager dashboard","Invite and manage agents with one click","Exclusive brokerage-only resources","Team analytics and performance tracking","Simplified agent onboarding","Share resources across your team"].map((I,P)=>e.jsxs("li",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-[#4a6b6d]/10 flex items-center justify-center flex-shrink-0",children:e.jsx(ca,{className:"w-4 h-4 text-[#4a6b6d]"})}),e.jsx("span",{className:"text-foreground",children:I})]},P))}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 mt-4",children:[e.jsxs($,{size:"lg",onClick:()=>{var I;return(I=document.getElementById("pricing"))==null?void 0:I.scrollIntoView({behavior:"smooth"})},className:"bg-[#4a6b6d] hover:bg-[#3d5a5c]",children:["See Brokerage Plans",e.jsx(Di,{className:"ml-2 w-5 h-5"})]}),e.jsxs($,{size:"lg",variant:"outline",onClick:()=>w(!0),className:"border-[#4a6b6d] text-[#4a6b6d] hover:bg-[#4a6b6d]/10",children:[e.jsx(Ta,{className:"mr-2 w-5 h-5"}),"Schedule Info Session"]})]})]}),e.jsx("div",{className:"relative hidden md:block",children:e.jsx("img",{src:B9s,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:W9s.map((I,P)=>e.jsx(je,{className:"bg-muted/30 border-0",children:e.jsxs(Ie,{className:"pt-8",children:[e.jsx("div",{className:"flex gap-1 mb-4",children:[1,2,3,4,5].map(R=>e.jsx(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:J2.individual_agent.name})]}),e.jsxs("div",{className:"flex items-baseline gap-1 mt-4",children:[e.jsx("span",{className:"text-5xl font-bold",children:J2.individual_agent.price}),e.jsx("span",{className:"text-muted-foreground text-lg",children:J2.individual_agent.period})]}),e.jsx(Gn,{className:"text-base mt-2",children:J2.individual_agent.description}),e.jsxs("div",{className:"inline-flex items-center gap-2 px-4 py-2 rounded-full bg-green-500/10 text-green-600 text-sm font-medium mt-4",children:[e.jsx(da,{className:"w-4 h-4"}),J2.individual_agent.trial]})]}),e.jsx(Ie,{className:"flex-1 pt-0",children:e.jsx("ul",{className:"space-y-3",children:J2.individual_agent.features.map((I,P)=>e.jsxs("li",{className:"flex items-center gap-3",children:[e.jsx(ca,{className:"w-5 h-5 text-[#4a6b6d] flex-shrink-0"}),e.jsx("span",{children:I})]},P))})}),e.jsxs(yEe,{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(ji,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsxs("div",{children:[e.jsx(Et,{className:"text-xl font-sans",children:J2.brokerage_over_25.name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:J2.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:J2.brokerage_over_25.price}),e.jsx("span",{className:"text-muted-foreground text-lg",children:J2.brokerage_over_25.period})]}),e.jsx(Gn,{className:"text-base mt-2",children:J2.brokerage_over_25.description})]}),e.jsx(Ie,{className:"flex-1 pt-0",children:e.jsx("ul",{className:"space-y-3",children:J2.brokerage_over_25.features.map((I,P)=>e.jsxs("li",{className:"flex items-center gap-3",children:[e.jsx(ca,{className:"w-5 h-5 text-[#4a6b6d] flex-shrink-0"}),e.jsx("span",{children:I})]},P))})}),e.jsx(yEe,{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(Ie,{className:"p-6 flex items-start gap-4",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-[#4a6b6d]/10 flex items-center justify-center shrink-0",children:e.jsx(ji,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsx("p",{className:"text-foreground font-medium leading-relaxed",children:"LevelUp serves all brokerages."})]})}),e.jsx(je,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:e.jsxs(Ie,{className:"p-6 flex items-start gap-4",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-[#4a6b6d]/10 flex items-center justify-center shrink-0",children:e.jsx(pc,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsx("p",{className:"text-foreground font-medium leading-relaxed",children:"LevelUp does not share member information with any brokerage."})]})}),e.jsx(je,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:e.jsxs(Ie,{className:"p-6 flex items-start gap-4",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-[#4a6b6d]/10 flex items-center justify-center shrink-0",children:e.jsx(m2,{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(Ie,{className:"p-6 flex items-start gap-4",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-[#4a6b6d]/10 flex items-center justify-center shrink-0",children:e.jsx(Jr,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsx("p",{className:"text-foreground font-medium leading-relaxed",children:"LevelUp does not use LevelUp events, trainings, webinars, CRM data, or member lists for recruiting purposes."})]})})]})]})})}),e.jsxs("section",{className:"py-20 bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),e.jsx("div",{className:"container mx-auto px-4 relative",children:e.jsxs("div",{className:"max-w-4xl mx-auto text-center space-y-8",children:[e.jsx("h2",{className:"text-3xl text-white font-sans md:text-5xl",children:"Ready to Level Up?"}),e.jsx("p",{className:"text-lg text-white/80 max-w-2xl mx-auto",children:"Join thousands of agents who are closing more deals, saving time, and growing their business with LevelUp."}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center",children:[e.jsxs($,{size:"lg",onClick:()=>{var I;return(I=document.getElementById("pricing"))==null?void 0:I.scrollIntoView({behavior:"smooth"})},className:"px-10 py-7 text-lg font-semibold bg-white text-[#4a6b6d] hover:bg-white/90 shadow-2xl transition-all hover:scale-105",children:["Start Your Free Trial",e.jsx(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:qEe,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($9s,{open:b,onOpenChange:w}),e.jsx(zs,{open:c,onOpenChange:d,children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsx(Bs,{className:"text-xl font-sans font-semibold",children:"Enter your details to get started"}),e.jsx(Pr,{children:(l==null?void 0:l.tier)==="individual_agent"&&!(l!=null&&l.skipTrial)?"Start your 7-day free trial":(l==null?void 0:l.tier)==="individual_agent"?"Subscribe to Individual Agent":"Subscribe to Brokerage"})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{children:[e.jsxs(ee,{htmlFor:"dialog-name",children:["Full Name ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(pe,{id:"dialog-name",type:"text",placeholder:"John Smith",value:m,onChange:I=>f(I.target.value),className:"mt-1",required:!0})]}),e.jsxs("div",{children:[e.jsxs(ee,{htmlFor:"dialog-email",children:["Email Address ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(pe,{id:"dialog-email",type:"email",placeholder:"you@example.com",value:u,onChange:I=>h(I.target.value),className:"mt-1",required:!0})]}),e.jsxs("div",{children:[e.jsxs(ee,{htmlFor:"dialog-coupon",children:["Discount Code ",e.jsx("span",{className:"text-muted-foreground",children:"(Optional)"})]}),e.jsx(pe,{id:"dialog-coupon",type:"text",placeholder:"Enter discount code",value:g,onChange:I=>x(I.target.value),className:"mt-1"})]})]}),e.jsx($,{className:"w-full py-6 text-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:E,disabled:y,children:y?"Loading...":"Continue to Checkout"})]})})]})},_vt=()=>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(wr,{to:"/mcp-data-use",className:"text-primary hover:underline",children:"MCP data use"})," ","page."]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"5. AI Content Generation"}),e.jsxs("p",{children:["When a member asks for generated copy (listing descriptions, emails, social posts, print collateral, campaign letters), the request is sent to the ",e.jsx("strong",{children:"Lovable AI Gateway"})," and the model provider behind it. That request contains the property details supplied for the task and a brand block with the agent's name, brokerage, phone, email, website, license and any compliance line. Contact records, visitor lists and lead lists are not sent for generation. Nothing is sent to a model provider for read-only tools or for ordinary use of the app."]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"6. Who Receives Information"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Infrastructure providers"})," that host our application, database, storage and email/SMS delivery."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Payment processor"})," for subscriptions and purchases."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"The AI client a member connects"})," (OpenAI/ChatGPT or another MCP client), as described in section 4."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"The Lovable AI Gateway and its model provider"}),", only for generation requests, as described in section 5."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Third-party services a member connects"})," — for example Google (calendar and sign-in), Gmail, Meta/Facebook and Instagram, YouTube, Canva, Stripe, and CRM imports such as BoldTrail or Lofty — and only when that integration is invoked. Each is governed by its own privacy policy."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"The public"}),", for pages a member publishes: open house sign-in pages, landing pages, property websites and public listing pages."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Other LevelUp members"}),", for listings a member publishes to the shared Listing Exchange (listing details, photos and agent/brokerage attribution). Contacts, leads and pipeline data are never shared this way."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Brokerage managers, team leaders, assigned assistants and coaches"}),", limited to the data their role is granted."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"LevelUp administrators"}),", who may act on behalf of a member for support and setup; those actions are recorded in the audit log with the target member."]}),e.jsxs("li",{children:[e.jsx("strong",{className:"text-foreground",children:"Legal recipients"}),", where disclosure is required by law or needed to protect rights and safety."]})]}),e.jsx("p",{className:"mt-3",children:"We do not sell, rent or trade personal information."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"7. Retention"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Account, contact, deal, listing, campaign, visitor and lead records are kept for as long as the account is active, until the member deletes them, or until the account is deleted."}),e.jsx("li",{children:"MCP audit log entries are kept for security and support purposes. They are not purged automatically on a fixed schedule; they can be removed on request."}),e.jsx("li",{children:"Short-lived rate-limit counters expire within minutes."}),e.jsx("li",{children:"Billing and tax records are kept as long as the law requires."}),e.jsx("li",{children:"Backups are cycled on our provider's schedule, so deleted data can persist in backups for a limited period after deletion."})]}),e.jsxs("p",{className:"mt-3",children:["We do not promise an automatic timed purge that we do not operate; see"," ",e.jsx(wr,{to:"/data-deletion",className:"text-primary hover:underline",children:"Data Deletion"})," ","for how requests are handled."]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"8. Your Choices and Rights"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Access, correct or delete records from within the app."}),e.jsx("li",{children:"Connect or disconnect any integration, including the MCP connector, at any time."}),e.jsx("li",{children:"Review connector activity in the MCP activity log."}),e.jsx("li",{children:"Mark a contact as opted out of marketing email, and opt out of SMS by replying STOP."}),e.jsxs("li",{children:["Request access, correction, export or deletion by emailing ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"}),"."]})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"9. Data Security"}),e.jsx("p",{children:"We use access controls, row-level database security scoped to each member, OAuth-based authentication for connectors, per-member rate limiting and audit logging. No method of transmission or storage is completely secure."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"10. SMS / Text Messaging Program (LevelUp Account & Lead Alerts)"}),e.jsx("p",{children:"If you opt in, we use your mobile number to send SMS account notifications, real-time lead alerts, service updates and support messages related to your LevelUp account."}),e.jsx("p",{className:"mt-3",children:"No mobile information will be shared with third parties or affiliates for marketing or promotional purposes. Text messaging originator opt-in data and consent will not be shared with any third parties, except with the vendors and aggregators that deliver the messages on our behalf."}),e.jsx("p",{className:"mt-3",children:"Message frequency varies. Message and data rates may apply. Reply STOP to opt out and HELP for help."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"11. LevelUp SmartSign (Property Information by Text)"}),e.jsxs("p",{children:["LevelUp SmartSign is operated by ",e.jsx("strong",{children:"LevelUp Consulting Group"}),". Consumers text a property code displayed on a real estate sign to ",e.jsx("strong",{children:"859-413-5013"})," to request information about that property. LevelUp is the sender of these messages; independent real estate agents do not send messages through the SmartSign number. This program is separate from the LevelUp account and lead alert SMS program described in section 10, and consent to one is not consent to the other."]}),e.jsxs("p",{className:"mt-3",children:[e.jsx("strong",{className:"text-foreground",children:"What we collect:"})," your mobile phone number, the property code you text, the content of your messages, and the details of your inquiry (such as the property you asked about, your questions, and any name or showing preference you provide)."]}),e.jsxs("p",{className:"mt-3",children:[e.jsx("strong",{className:"text-foreground",children:"How we use it:"})," to respond to your inquiry with listing information, answer questions about the property, assist with showing requests, provide support, keep records of your messaging preferences and opt-outs, and meet legal and carrier requirements."]}),e.jsxs("p",{className:"mt-3",children:[e.jsx("strong",{className:"text-foreground",children:"Service providers:"})," messaging providers — including ",e.jsx("strong",{children:"Telnyx"})," — and our hosting and database providers process this information solely to deliver and operate the service on our behalf."]}),e.jsxs("p",{className:"mt-3",children:[e.jsx("strong",{className:"text-foreground",children:"Sharing with an agent:"})," we ask for your separate, specific permission before sharing your inquiry or contact details with a named agent. We identify the actual agent and brokerage first. If you agree, we share your name, phone number and property inquiry with that agent so they can respond to your request. This consumer-requested handoff is not a transfer of your SMS consent: the agent does not receive permission to send you marketing texts, and your LevelUp SmartSign consent does not carry over to them. Agreeing to an agent contacting you also does not enroll you in LevelUp marketing."]}),e.jsxs("p",{className:"mt-3",children:[e.jsx("strong",{className:"text-foreground",children:"Marketing is separate:"})," requesting property information does not enroll you in promotional or marketing texts. Marketing texts require a separate affirmative opt-in, and you can stop them at any time by replying STOP."]}),e.jsxs("p",{className:"mt-3",children:[e.jsx("strong",{className:"text-foreground",children:"No sale or sharing for third-party marketing:"})," we do not sell your information, and no mobile information, SMS opt-in data or consent is shared with third parties or affiliates for their own promotional or marketing purposes. The only recipients are the service providers that deliver the service on our behalf, and — with your separate permission — the specific agent you asked to hear from."]}),e.jsxs("p",{className:"mt-3",children:["Message frequency varies. Message and data rates may apply. Reply STOP to opt out or HELP for help. See the"," ",e.jsx(wr,{to:"/sms-opt-in",className:"text-primary hover:underline",children:"SMS opt-in page"})," ","and"," ",e.jsx(wr,{to:"/terms-of-service",className:"text-primary hover:underline",children:"Terms of Service"})," ","for program details."]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"12. Children"}),e.jsx("p",{children:"LevelUp is a business tool and is not directed to children under 16."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"13. Changes to This Policy"}),e.jsx("p",{children:'We will update this page when our practices change and revise the "Last updated" date above.'})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"14. Contact Us"}),e.jsxs("p",{children:["Questions about this policy:"," ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"}),"."]})]})]})]})})]}),wvt=()=>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"})]})]})]})]})})]}),Y9s=()=>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(wr,{to:"/privacy-policy",className:"text-primary hover:underline",children:"Privacy Policy"})," and the"," ",e.jsx(wr,{to:"/mcp-data-use",className:"text-primary hover:underline",children:"MCP data use"})," page, or contact"," ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"}),"."]})]})]})]})})]}),jvt=()=>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(wr,{to:"/privacy-policy",className:"text-primary hover:underline",children:"Privacy Policy"})," and"," ",e.jsx(wr,{to:"/data-deletion",className:"text-primary hover:underline",children:"Data Deletion"})," pages, or contact"," ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"}),"."]})]})]})]})})]}),Nvt="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.",X9s=z2({name:vl().trim().max(200).optional().or(yx("")),phone:vl().trim().min(10,"Enter a valid mobile number").max(30).regex(/^[+\d\s()\-.]+$/,"Enter a valid mobile number"),email:vl().trim().email("Enter a valid email").max(320).optional().or(yx(""))}),Q9s=z2({name:vl().trim().min(1,"Name is required").max(200),phone:vl().trim().min(10,"Enter a valid mobile number").max(30).regex(/^[+\d\s()\-.]+$/,"Enter a valid mobile number"),email:vl().trim().email("Enter a valid email").max(320).optional().or(yx(""))});function J9s(){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=Xn(),[x,y]=j.useState(""),[v,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){re.error("Please check the marketing consent box to enroll.");return}const V=X9s.safeParse({name:x,phone:v,email:w});if(!V.success){re.error(((X=V.error.issues[0])==null?void 0:X.message)??"Please check your inputs.");return}P(!0);const{data:G,error:Y}=await q.functions.invoke("smartsign-marketing-optin",{body:{name:V.data.name||null,phone:V.data.phone,email:V.data.email||null,consent:!0,source_url:window.location.href}});if(P(!1),Y||!(G!=null&&G.ok)){re.error("We could not record your opt-in. Please try again.");return}D(!0),re.success("Your SmartSign marketing opt-in was recorded.")},U=async W=>{var Y;if(W.preventDefault(),!l){re.error("Please check the consent box to opt in.");return}const V=Q9s.safeParse({name:s,phone:n,email:a});if(!V.success){re.error(((Y=V.error.issues[0])==null?void 0:Y.message)??"Please check your inputs.");return}d(!0);const{error:G}=await q.from("sms_opt_in_consents").insert({name:V.data.name,phone:V.data.phone,email:V.data.email||null,consent_text:Nvt,source:"web_form",user_agent:navigator.userAgent.slice(0,500)});if(d(!1),G){re.error("Something went wrong. Please try again.");return}h(!0)};return e.jsxs("div",{className:"min-h-screen bg-gradient-to-br from-background via-background to-muted/30 py-10 px-4",children:[e.jsxs(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(eo,{className:"w-7 h-7"})}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold tracking-tight",children:"LevelUp — SMS Programs"}),e.jsxs("p",{className:"text-muted-foreground mt-3 max-w-xl mx-auto",children:["LevelUp runs two separate text messaging programs. ",e.jsx("strong",{children:"LevelUp SmartSign"})," ","lets home shoppers text a property code from a real estate sign to get information about that property. ",e.jsx("strong",{children:"LevelUp Account & Lead Alerts"})," sends LevelUp members notifications about their own account. Each has its own number and its own consent."]})]}),e.jsxs(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(XJ,{className:"w-5 h-5"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-semibold leading-tight",children:"LevelUp SmartSign"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Property information by text · Operated by LevelUp Consulting Group"})]})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"LevelUp SmartSign lets you request information about a home by texting the property code shown on the real estate sign. LevelUp responds with listing information, answers questions about the property, and can help with showing requests. LevelUp is the sender of these messages — independent real estate agents do not send messages through the LevelUp SmartSign number."}),e.jsxs("div",{className:"mt-5 rounded-lg border border-primary/30 bg-primary/5 p-4",children:[e.jsx("p",{className:"text-base font-semibold text-foreground",children:"Text the property code shown on the sign to 859-413-5013 to request information about that property from LevelUp SmartSign."}),e.jsxs("p",{className:"mt-3 text-xs leading-relaxed text-muted-foreground",children:["By texting a property code, you request SMS responses from LevelUp SmartSign about that property and your inquiry. Message frequency varies. Message and data rates may apply. Reply STOP to opt out or HELP for help. Requesting property information does not subscribe you to marketing updates. See our"," ",e.jsx(wr,{to:"/privacy-policy",className:"text-primary underline underline-offset-2",children:"Privacy Policy"})," ","and"," ",e.jsx(wr,{to:"/terms-of-service",className:"text-primary underline underline-offset-2",children:"Terms of Service"}),"."]})]}),e.jsxs("div",{className:"mt-6",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground mb-2",children:"Example sign — illustration only"}),e.jsxs("div",{className:"rounded-xl border-2 border-dashed border-primary/40 bg-background p-5 text-center",children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-[0.2em] text-primary",children:"LevelUp SmartSign"}),e.jsx("p",{className:"mt-3 text-sm font-medium text-foreground",children:"Text"}),e.jsx("p",{className:"text-3xl font-bold tracking-tight text-foreground",children:"1234"}),e.jsx("p",{className:"text-sm font-medium text-foreground",children:"to"}),e.jsx("p",{className:"text-2xl font-bold tracking-tight text-primary",children:"859-413-5013"}),e.jsx("p",{className:"mt-3 text-[11px] leading-relaxed text-muted-foreground",children:"Msg frequency varies. Msg & data rates may apply. Reply STOP to opt out, HELP for help. Requesting property info does not subscribe you to marketing."})]}),e.jsxs("p",{className:"mt-2 text-xs text-muted-foreground",children:[e.jsx("strong",{children:"1234 is an example property code used for illustration only."})," It is not an active listing and texting it will not return property information. Real property codes appear on the physical sign at the property."]})]}),e.jsxs("div",{className:"mt-8 space-y-4",children:[e.jsx("h3",{className:"text-base font-semibold text-foreground",children:"Three separate choices — each one is its own decision"}),e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-4",children:[e.jsx("p",{className:"text-sm font-semibold text-foreground",children:"1. Property information you requested"}),e.jsx("p",{className:"mt-1.5 text-sm text-muted-foreground",children:"When you text a property code, you are asking LevelUp SmartSign to reply about that property and your inquiry. That is all it does. It does not automatically enroll you in promotional or marketing updates. Reply STOP at any time to stop messages, or HELP for help."})]}),e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-4",children:[e.jsx("p",{className:"text-sm font-semibold text-foreground",children:"2. Optional LevelUp SmartSign marketing updates"}),e.jsx("p",{className:"mt-1.5 text-sm text-muted-foreground",children:"Marketing texts require a separate, affirmative choice that you make on purpose. They are never bundled with a property inquiry and are never combined with permission for an agent to contact you."}),R?e.jsxs("div",{className:"mt-4 rounded-md border border-primary/30 bg-primary/5 p-4",children:[e.jsx("p",{className:"text-sm font-semibold text-foreground",children:"Your marketing opt-in has been recorded."}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"We saved your number, the exact disclosure you agreed to, and the time of your consent. You can reply STOP to any message to opt out, or HELP for help."})]}):e.jsxs("form",{onSubmit:O,className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"mkt-name",children:"Full name (optional)"}),e.jsx(pe,{id:"mkt-name",value:x,onChange:W=>y(W.target.value),maxLength:200,autoComplete:"name",className:"mt-1.5"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"mkt-phone",children:"Mobile number"}),e.jsx(pe,{id:"mkt-phone",type:"tel",value:v,onChange:W=>b(W.target.value),maxLength:30,placeholder:"(555) 123-4567",autoComplete:"tel",className:"mt-1.5"})]})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"mkt-email",children:"Email (optional)"}),e.jsx(pe,{id:"mkt-email",type:"email",value:w,onChange:W=>S(W.target.value),maxLength:320,autoComplete:"email",className:"mt-1.5"})]}),e.jsx("div",{className:"rounded-md border bg-background p-3",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(ai,{id:"mkt-consent",checked: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:Nvt})]})}),e.jsxs("div",{className:"text-xs text-muted-foreground space-y-1",children:[e.jsxs("p",{children:["By submitting, you agree to our"," ",e.jsx(wr,{to:"/terms-of-service",className:"text-primary underline underline-offset-2",children:"SMS Terms & Conditions"})," ","and"," ",e.jsx(wr,{to:"/privacy-policy",className:"text-primary underline underline-offset-2",children:"Privacy Policy"}),"."]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Message types:"})," account notifications, real-time lead alerts, service updates, customer support."," ",e.jsx("strong",{children:"Frequency:"})," varies."," ",e.jsx("strong",{children:"Msg & data rates may apply."})," ","Reply ",e.jsx("strong",{children:"STOP"})," to opt out, ",e.jsx("strong",{children:"HELP"})," for help."]}),e.jsx("p",{children:"No mobile information will be shared with third parties or affiliates for marketing or promotional purposes. Text messaging originator opt-in data and consent will not be shared with any third parties."})]}),e.jsx($,{type:"submit",disabled:!l||c,className:"w-full",size:"lg",children:c?"Submitting…":"Opt in to SMS"}),e.jsx($,{type:"button",variant:"outline",size:"lg",className:"w-full",disabled:c,onClick:()=>f(!0),children:"Skip SMS / Continue without text alerts"}),e.jsx("p",{className:"text-xs text-center text-muted-foreground",children:"Skipping records no consent and does not limit your access to LevelUp."}),e.jsxs("div",{className:"flex items-center justify-center gap-2 text-xs text-muted-foreground pt-2",children:[e.jsx(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 a6e="/assets/levelup-logo-horizontal-DEFNc0ms.png",e$s=z2({email:vl().email("Invalid email address"),password:vl().min(6,"Password must be at least 6 characters")}),i$t="https://dashboard.relevelup.com",Vce="/oauth-connect",t$s=`${i$t}/profile?reset=true`,a3e="levelupOAuthRouteHistory";function kvt(s){return s.startsWith("/")&&!s.startsWith("//")&&!s.includes("://")}function s$s(s){const t=Date.now(),n=15e3;try{const i=[...JSON.parse(sessionStorage.getItem(a3e)??"[]").filter(o=>t-o.ato.route));return i.length>=6&&l.has("auth")&&l.has("consent")}catch{return sessionStorage.setItem(a3e,JSON.stringify([{route:s,at:t}])),!1}}function n$s(){sessionStorage.removeItem(a3e)}const r$s=()=>{const{signIn:s,user:t,loading:n}=bs(),r=(t==null?void 0:t.id)??null,a=Xn(),[i]=gc(),l=i.get("authorization_id")??"",o=i.get("next")??"",[c,d]=j.useState(!1),[u,h]=j.useState({}),[m,f]=j.useState(""),[g,x]=j.useState(!1),[y,v]=j.useState(!1),[b,w]=j.useState(null),[S,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 Y="";try{Y=sessionStorage.getItem("accountPausedReason")||""}catch{}return Y?`Your account is paused. ${Y}`:"Your account is paused. Please contact LevelUp support to reactivate it."}),U=j.useRef(!1);j.useEffect(()=>{if(l&&window.location.hostname==="tile-portal.lovable.app"){const Y=new URL("/auth",i$t);Y.searchParams.set("next",`${Vce}?authorization_id=${encodeURIComponent(l)}`),window.location.replace(Y.toString());return}if(l){const Y=`${Vce}?authorization_id=${encodeURIComponent(l)}`;sessionStorage.setItem("redirectAfterLogin",Y);return}o&&kvt(o)&&sessionStorage.setItem("redirectAfterLogin",o)},[l,o]),j.useEffect(()=>{if(n||!r||U.current)return;const Y=l?`${Vce}?authorization_id=${encodeURIComponent(l)}`:sessionStorage.getItem("redirectAfterLogin")||"/dashboard";if(!kvt(Y)){sessionStorage.removeItem("redirectAfterLogin"),U.current=!0,a("/dashboard",{replace:!0});return}const X=Y.startsWith(Vce)||Y.startsWith("/oauth/consent")||Y.startsWith("/.lovable/oauth/consent");if(X&&s$s("auth")){w("We couldn't complete the OAuth sign-in handoff because the browser kept bouncing between sign-in and consent. Please refresh this page and try Connect again.");return}U.current=!0,X||(n$s(),sessionStorage.removeItem("redirectAfterLogin")),a(Y,{replace:!0})},[l,n,a,r]);const W=async Y=>{Y.preventDefault(),h({}),O(null),A(null),I(!1),d(!0);const X=new FormData(Y.currentTarget),ae=X.get("email"),le=X.get("password");try{e$s.parse({email:ae,password:le}),await s(ae,le)}catch(ne){if(ne instanceof GEs){const te={};ne.issues.forEach(J=>{J.path[0]&&(te[J.path[0]]=J.message)}),h(te)}else if(ne instanceof Error&&ne.name==="AccountPaused")O(ne.message);else if(ae)try{const{data:te}=await q.functions.invoke("account-activation-status",{body:{email:ae}});te!=null&&te.needsActivation&&A(ae)}catch{}}finally{d(!1)}},V=async()=>{if(S){R(!0);try{const{data:Y,error:X}=await q.functions.invoke("send-password-reset",{body:{email:S,variant:"activation"}});if(X)throw X;if((Y==null?void 0:Y.sent)===!1)throw new Error("We couldn't send the activation email. Please try again in a moment or contact support.");I(!0),re.success("Activation email sent! Check your inbox.")}catch(Y){re.error(Y instanceof Error?Y.message:"Failed to send activation email")}finally{R(!1)}}},G=async()=>{if(!m){re.error("Please enter your email address");return}x(!0);try{const{data:Y,error:X}=await q.functions.invoke("send-password-reset",{body:{email:m.trim().toLowerCase(),redirectTo:t$s}});if(X)throw X;if((Y==null?void 0:Y.sent)===!1){re.error("We couldn't find a LevelUp account for that email. Double-check the address, or email hello@relevelup.com and we'll help.");return}re.success("Password reset email sent! Check your inbox."),v(!1),f("")}catch(Y){re.error(Y instanceof Error?Y.message:"Failed to send reset email")}finally{x(!1)}};return e.jsxs("div",{className:"min-h-screen relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-[#4a6b6d] via-[#3d5a5c] to-[#2a4347]",children:e.jsxs("div",{className:"absolute inset-0 opacity-30",children:[e.jsx("div",{className:"absolute top-0 left-0 w-96 h-96 bg-white/10 rounded-full blur-3xl animate-pulse"}),e.jsx("div",{className:"absolute bottom-0 right-0 w-96 h-96 bg-white/5 rounded-full blur-3xl animate-pulse",style:{animationDelay:"1s"}}),e.jsx("div",{className:"absolute top-1/2 left-1/2 w-64 h-64 bg-white/5 rounded-full blur-3xl animate-pulse",style:{animationDelay:"2s"}})]})}),e.jsxs("div",{className:"relative z-10 flex flex-col min-h-screen",children:[e.jsx("header",{className:"p-6",children:e.jsxs(wr,{to:"/",className:"inline-flex items-center gap-2 text-sm text-white/80 hover:text-white transition-colors",children:[e.jsx(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:a6e,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(Gn,{className:"text-gray-600",children:b||"Sign in to access your dashboard"})]}),e.jsxs(Ie,{children:[D&&e.jsxs("div",{className:"mb-4 rounded-lg border border-amber-300 bg-amber-50 p-4 text-left",children:[e.jsx("p",{className:"text-sm font-semibold text-amber-900",children:"Account paused"}),e.jsx("p",{className:"mt-1 text-sm text-amber-800",children:D}),e.jsx("a",{href:"mailto:support@relevelup.com",className:"mt-2 inline-block text-sm font-medium text-amber-900 underline",children:"Contact support"})]}),S&&e.jsxs("div",{className:"mb-4 rounded-lg border border-[#4a6b6d]/30 bg-[#f2f7f7] p-4 text-left",children:[e.jsx("p",{className:"text-sm font-semibold text-[#2a4347]",children:"You haven't set a password yet"}),e.jsx("p",{className:"mt-1 text-sm text-gray-700",children:E?`We just emailed ${S} a link to set your password and sign in. Check your inbox (and spam folder).`:`Your LevelUp account for ${S} is ready — it just needs a password. We'll email you a link to set one.`}),!E&&e.jsx($,{type:"button",onClick:V,disabled:P,className:"mt-3 bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white",children:P?"Sending...":"Email me a set-password link"})]}),e.jsxs("form",{onSubmit:W,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"signin-email",className:"text-gray-700",children:"Email"}),e.jsx(pe,{id:"signin-email",name:"email",type:"email",placeholder:"your@email.com",required:!0,className:"border-gray-300 focus:border-[#4a6b6d] focus:ring-[#4a6b6d]"}),u.email&&e.jsx("p",{className:"text-sm text-red-600",children:u.email})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"signin-password",className:"text-gray-700",children:"Password"}),e.jsx(pe,{id:"signin-password",name:"password",type:"password",required:!0,className:"border-gray-300 focus:border-[#4a6b6d] focus:ring-[#4a6b6d]"}),u.password&&e.jsx("p",{className:"text-sm text-red-600",children:u.password})]}),e.jsx($,{type:"submit",className:"w-full bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white font-semibold py-6 text-lg transition-all duration-200 shadow-lg hover:shadow-xl",disabled:c,children:c?"Signing in...":"Sign In"}),e.jsxs(zs,{open:y,onOpenChange:v,children:[e.jsx(jl,{asChild:!0,children:e.jsx($,{variant:"link",className:"w-full text-sm text-[#4a6b6d] hover:text-[#3d5a5c]",children:"Forgot password?"})}),e.jsxs(Os,{className:"bg-white",children:[e.jsxs(Us,{children:[e.jsx(Bs,{className:"text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:"Reset Password"}),e.jsx(Pr,{className:"text-gray-600",children:"Enter your email address and we'll send you a link to reset your password."})]}),e.jsxs("div",{className:"space-y-4 pt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"reset-email",className:"text-gray-700",children:"Email"}),e.jsx(pe,{id:"reset-email",type:"email",placeholder:"your@email.com",value:m,onChange:Y=>f(Y.target.value),className:"border-gray-300 focus:border-[#4a6b6d] focus:ring-[#4a6b6d]"})]}),e.jsx($,{onClick:G,className:"w-full bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white",disabled:g,children:g?"Sending...":"Send Reset Link"})]})]})]})]})]})]}),e.jsxs("p",{className:"text-center text-white/70 text-sm mt-6",children:["Don't have an account?"," ",e.jsx(wr,{to:"/",className:"text-white hover:underline font-medium",children:"View Plans"})]})]})})]})]})},Svt=()=>q.auth.oauth,a$s="https://dashboard.relevelup.com",i$s="/oauth-connect",i3e="levelupOAuthRouteHistory",o$s="https://relzejiswnotikjgvjhz.supabase.co/auth/v1",l$s="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM";function c$s(s){return s.startsWith("/")&&!s.startsWith("//")&&!s.includes("://")}function d$s(s){const t=Date.now(),n=15e3;try{const i=[...JSON.parse(sessionStorage.getItem(i3e)??"[]").filter(o=>t-o.ato.route));return i.length>=6&&l.has("auth")&&l.has("consent")}catch{return sessionStorage.setItem(i3e,JSON.stringify([{route:s,at:t}])),!1}}function u$s(){sessionStorage.removeItem(i3e)}async function Cvt(s,t,n){const r=await fetch(`${o$s}${s}`,{...n,headers:{Authorization:`Bearer ${t}`,apikey:l$s,"Content-Type":"application/json",...(n==null?void 0:n.headers)??{}}}),a=await r.json().catch(()=>null);return r.ok?{data:a,error:null}:{data:null,error:{message:(a==null?void 0:a.msg)??(a==null?void 0:a.message)??(a==null?void 0:a.error_description)??(a==null?void 0:a.error)??"Authorization request failed."}}}function I7e(){var x;const{user:s,session:t,loading:n}=bs(),r=(s==null?void 0:s.id)??null,a=(t==null?void 0:t.access_token)??null,[i]=gc(),l=i.get("authorization_id")??"",[o,c]=j.useState(null),[d,u]=j.useState(null),[h,m]=j.useState(!1);j.useEffect(()=>{let y=!0;return(async()=>{if(!l){u("Missing authorization_id");return}const v=`${i$s}?authorization_id=${encodeURIComponent(l)}`;if(window.location.hostname==="tile-portal.lovable.app"){window.location.href=`${a$s}${v}`;return}if(n)return;if(!r){if(d$s("consent")){u("We couldn't complete the OAuth sign-in handoff because the browser kept bouncing between sign-in and consent. Please refresh this page and try Connect again.");return}c$s(v)&&sessionStorage.setItem("redirectAfterLogin",v),window.location.replace(`/auth?next=${encodeURIComponent(v)}`);return}if(!a)return;u$s(),sessionStorage.removeItem("redirectAfterLogin");const b=Svt(),{data:w,error:S}=b?await b.getAuthorizationDetails(l):await Cvt(`/oauth/authorizations/${encodeURIComponent(l)}`,a);if(!y)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)})(),()=>{y=!1}},[a,l,n,r]);async function f(y){if(!(t!=null&&t.access_token)){u("Your sign-in session is not ready yet. Please refresh and try again.");return}m(!0);const v=Svt(),{data:b,error:w}=v?y?await v.approveAuthorization(l,{skipBrowserRedirect:!0}):await v.denyAuthorization(l,{skipBrowserRedirect:!0}):await Cvt(`/oauth/authorizations/${encodeURIComponent(l)}/consent`,t.access_token,{method:"POST",body:JSON.stringify({action:y?"approve":"deny"})});if(w){m(!1),u(w.message);return}const S=(b==null?void 0:b.redirect_url)??(b==null?void 0:b.redirect_to);if(!S){m(!1),u("No redirect returned by the authorization server.");return}window.location.href=S}if(d)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsx(je,{className:"w-full max-w-md",children:e.jsxs(St,{children:[e.jsx(Et,{children:"Authorization error"}),e.jsx(Gn,{children:d})]})})});if(!o)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsx(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(Gn,{children:[g," is requesting access to use LevelUp tools on your behalf. You can revoke access at any time."]})]}),e.jsxs(Ie,{className:"flex gap-3 justify-end",children:[e.jsx($,{variant:"outline",disabled:h,onClick:()=>f(!1),children:"Deny"}),e.jsx($,{disabled:h,onClick:()=>f(!0),children:h?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):"Approve"})]})]})})}const h$s="https://chatgpt.com/plugins/plugin_asdk_app_6a7b9baf757081918ac4ab6fcbdb2639?q=levelup",Avt="https://relzejiswnotikjgvjhz.supabase.co/functions/v1/mcp",m$s="https://tile-portal.lovable.app/mcp-oauth-bridge.html",f$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'."}],p$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 g$s(){const[s,t]=j.useState(!1),n=async()=>{try{await navigator.clipboard.writeText(Avt),t(!0),re.success("MCP URL copied to clipboard"),setTimeout(()=>t(!1),2e3)}catch{re.error("Could not copy URL")}};return e.jsx(Vs,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-8 max-w-3xl mx-auto",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 rounded-lg bg-primary/10",children:e.jsx(E4,{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(Nn,{className:"h-5 w-5 text-primary"}),"Install from the ChatGPT Store"]}),e.jsx(Gn,{children:"The easiest way to connect. Tap the button below, then install the LevelUp plugin in ChatGPT."})]}),e.jsx(Ie,{children:e.jsx($,{asChild:!0,size:"lg",className:"w-full sm:w-auto",children:e.jsxs("a",{href:h$s,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Fr,{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(Gn,{children:"Share these steps with any agent who wants to connect via the plugin store."})]}),e.jsx(Ie,{children:e.jsx("ol",{className:"space-y-4",children:f$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(Gn,{children:"Only use this if you are adding LevelUp as a custom MCP server instead of installing the store plugin."})]}),e.jsxs(Ie,{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("code",{className:"flex-1 block rounded-md bg-muted px-3 py-2 text-sm break-all",children:Avt}),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(Ha,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"rounded-lg border border-destructive/30 bg-destructive/5 p-4 text-sm",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(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:m$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:p$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(Gn,{children:"The connector acts as you. Before connecting, review exactly which data it can reach, who receives it, how long it is kept and how to disconnect."})]}),e.jsxs(Ie,{className:"flex flex-wrap gap-4 text-sm",children:[e.jsx("a",{href:"/mcp-data-use",className:"text-primary underline underline-offset-4",children:"MCP data use"}),e.jsx("a",{href:"/privacy-policy",className:"text-primary underline underline-offset-4",children:"Privacy Policy"}),e.jsx("a",{href:"/data-deletion",className:"text-primary underline underline-offset-4",children:"Data deletion"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Fr,{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 x$s=()=>{const[s]=gc(),t=s.get("tier"),n=t==null?void 0:t.includes("brokerage");return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-background via-primary/5 to-secondary/10 flex items-center justify-center p-4",children:e.jsxs(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(Gn,{className:"text-lg",children:"Your subscription has been activated successfully."})]}),e.jsxs(Ie,{className:"space-y-6",children:[e.jsxs("div",{className:"p-4 rounded-lg bg-primary/10 border border-primary/20 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-primary",children:[e.jsx(mn,{className:"w-5 h-5"}),e.jsx("span",{className:"font-semibold",children:"Check your email to sign in"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"We've sent you an email with a secure link to access your account. Click the link in your email to get started."})]}),n?e.jsxs("div",{className:"space-y-3",children:[e.jsx("h3",{className:"font-semibold",children:"What's next?"}),e.jsxs("ul",{className:"space-y-2 text-sm text-muted-foreground",children:[e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"font-bold text-primary",children:"1."}),"Click the link in your email to sign in"]}),e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"font-bold text-primary",children:"2."}),"Create and name your brokerage"]}),e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"font-bold text-primary",children:"3."}),"Set your password and complete your profile"]}),e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"font-bold text-primary",children:"4."}),"Start inviting agents to join your team"]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsx("h3",{className:"font-semibold",children:"What's next?"}),e.jsxs("ul",{className:"space-y-2 text-sm text-muted-foreground",children:[e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"font-bold text-primary",children:"1."}),"Click the link in your email to sign in"]}),e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"font-bold text-primary",children:"2."}),"Set your password and complete your profile"]}),e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"font-bold text-primary",children:"3."}),"Start exploring templates, training videos, and more!"]})]}),e.jsx("p",{className:"text-sm text-green-600 font-medium mt-4",children:"🎉 Your 7-day free trial has started!"})]}),e.jsx("div",{className:"p-3 rounded-lg bg-muted/50 text-center",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Didn't receive the email? Check your spam folder or contact support."})})]})]})})},y$s=()=>{const{user:s}=bs(),[t,n]=j.useState(!1),[r,a]=j.useState(null),[i,l]=j.useState(""),o=async u=>{var h;if(!(s!=null&&s.email)){re.error("Please sign in to upgrade");return}n(!0),a(u);try{const{data:m,error:f}=await q.functions.invoke("create-checkout",{body:{tier:u,email:s.email,name:((h=s.user_metadata)==null?void 0:h.full_name)||s.email,userId:s.id,couponCode:i.trim()||void 0,skipTrial:!0}});if(f)throw f;if(m!=null&&m.url)window.open(m.url,"_blank","noopener,noreferrer"),re.success("Checkout opened in a new tab");else throw new Error("No checkout URL returned")}catch(m){console.error("Checkout error:",m),re.error(m.message||"Failed to start checkout. Please try again.")}finally{n(!1),a(null)}},c=["Unlimited access to all marketing templates","Complete Academy training library","AI-powered tools and resources","Community forums and support","Exclusive member events and workshops","Deal pipeline & scorecard tracking","Listing exchange access","Social media content library"],d=["Everything in Individual plan, plus:","Unlimited agent seats","Brokerage admin dashboard","Team performance analytics","Custom branding options","Priority support","Agent onboarding tools","Brokerage-wide announcements"];return e.jsx(Vs,{children:e.jsxs("div",{className:"container max-w-6xl py-8 px-4",children:[e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("h1",{className:"text-3xl font-bold mb-2",children:"Upgrade Your Membership"}),e.jsx("p",{className:"text-muted-foreground text-lg",children:"Choose the plan that's right for you and unlock the full power of LevelUp"})]}),e.jsxs("div",{className:"max-w-md mx-auto mb-8",children:[e.jsx(ee,{htmlFor:"coupon",className:"text-sm font-medium",children:"Have a discount code?"}),e.jsx(pe,{id:"coupon",placeholder:"Enter discount code",value:i,onChange:u=>l(u.target.value),className:"mt-1"})]}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-6 mb-8 max-w-4xl mx-auto",children:[e.jsxs(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(Gn,{children:"Perfect for solo agents ready to level up"})]}),e.jsxs(Ie,{className:"space-y-6",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("span",{className:"text-4xl font-bold text-primary",children:"$39"}),e.jsx("span",{className:"text-muted-foreground",children:"/month"})]}),e.jsx("ul",{className:"space-y-2",children:c.map((u,h)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(ca,{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(Nn,{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(ji,{className:"h-7 w-7 text-purple-600"})}),e.jsx(Et,{className:"text-xl",children:"Brokerage"}),e.jsx(Gn,{children:"Unlimited agents — everything in Individual, plus brokerage tools"})]}),e.jsxs(Ie,{className:"space-y-6",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("span",{className:"text-4xl font-bold text-purple-600",children:"$499"}),e.jsx("span",{className:"text-muted-foreground",children:"/month"})]}),e.jsx("ul",{className:"space-y-2",children:d.map((u,h)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(ca,{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(ji,{className:"h-4 w-4 mr-2"}),"Get Started"]})]})]})]}),e.jsx(je,{className:"bg-muted/50",children:e.jsxs(Ie,{className:"py-6",children:[e.jsx("p",{className:"text-center font-medium mb-4",children:"Questions? We're here to help!"}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center",children:[e.jsxs("a",{href:"tel:1-866-527-8668",className:"flex items-center justify-center gap-2 text-primary hover:underline",children:[e.jsx(Da,{className:"h-4 w-4"}),e.jsx("span",{children:"1-866-527-8668"})]}),e.jsxs("a",{href:"mailto:support@relevelup.com",className:"flex items-center justify-center gap-2 text-primary hover:underline",children:[e.jsx(mn,{className:"h-4 w-4"}),e.jsx("span",{children:"support@relevelup.com"})]})]})]})})]})})},v$s=()=>{const{user:s,loading:t,isBrokerageManager:n,brokerageId:r}=bs(),a=Xn(),[i,l]=j.useState(""),[o,c]=j.useState(!1),[d,u]=j.useState(!1);j.useEffect(()=>{!t&&!s&&a("/auth")},[s,t,a]),j.useEffect(()=>{!t&&s&&r&&a("/profile?setup=true")},[s,t,r,a]);const h=async()=>{if(!i.trim()){re.error("Please enter a brokerage name");return}const{data:m}=await q.auth.getSession(),f=m.session;if(!s||!f){re.error("Please sign in again to create your brokerage."),a("/auth");return}c(!0);try{console.log("[SetupBrokerage] Creating brokerage…",{hasUser:!!s,hasSession:!!f,userId:s==null?void 0:s.id});const{data:g,error:x}=await q.functions.invoke("create-brokerage",{body:{name:i.trim()}});if(console.log("[SetupBrokerage] create-brokerage response",{data:g,error:x}),x)throw x;if(!(g!=null&&g.ok))throw new Error((g==null?void 0:g.error)||"Failed to create brokerage");c(!1),u(!0),re.success("Brokerage created! Setting up your account..."),setTimeout(()=>{a("/profile?setup=true")},2e3)}catch(g){console.error("Error creating brokerage:",g),re.error(g.message||"Failed to create brokerage"),c(!1)}};return t?e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):d?e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-background via-primary/5 to-secondary/10 flex items-center justify-center p-4",children:e.jsxs(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(Gn,{className:"text-lg",children:"We're assigning you as the brokerage manager and preparing your dashboard..."})]}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-center gap-2 text-muted-foreground",children:[e.jsx(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(ji,{className:"w-10 h-10 text-primary"})}),e.jsx(Et,{className:"text-2xl",children:"Set Up Your Brokerage"}),e.jsx(Gn,{className:"text-lg",children:"Create your brokerage to start managing your team"})]}),e.jsxs(Ie,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"brokerage-name",children:"Brokerage Name"}),e.jsx(pe,{id:"brokerage-name",placeholder:"Enter your brokerage name",value:i,onChange:m=>l(m.target.value),onKeyDown:m=>m.key==="Enter"&&h()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This is how your brokerage will appear to your agents"})]}),e.jsxs("div",{className:"p-4 rounded-lg bg-muted/50 space-y-3",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2",children:[e.jsx(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"})]})]})]})})},Evt=()=>{const s=Xn(),[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(Gn,{children:[t==="verifying"&&"Please wait while we verify your account...",t==="success"&&"Redirecting you to complete your profile...",t==="already_claimed"&&"This account has already been set up. Please log in to access your dashboard.",t==="error"&&r]})]}),(t==="already_claimed"||t==="error")&&e.jsx(Ie,{children:e.jsx($,{onClick:i,className:"w-full",children:"Go to Login"})})]})})},Hce="https://dashboard.relevelup.com",Tvt=()=>{const[s,t]=j.useState(!1),n=j.useMemo(()=>new URLSearchParams(window.location.search),[]),r=j.useMemo(()=>n.get("link"),[n]),a=j.useMemo(()=>n.get("type")||"recovery",[n]),i=j.useMemo(()=>{switch(a){case"claim":return{title:"Claim Your Account",cta:"Continue to Claim Account",doc:"Claim Your LevelUp Account"};case"magiclink":return{title:"Sign In to LevelUp",cta:"Continue to Sign In",doc:"Sign In to LevelUp"};case"email_change":return{title:"Confirm Your Email",cta:"Continue to Confirm Email",doc:"Confirm Your Email"};default:return{title:"Reset Your Password",cta:"Continue to Reset Password",doc:"Reset Your Password"}}},[a]),l=j.useMemo(()=>{if(!r)return!1;try{const g=new URL(r);return g.hostname.endsWith(".supabase.co")&&g.pathname.startsWith("/auth/v1/verify")}catch{return!1}},[r]);j.useEffect(()=>{document.title=i.doc},[i]);const[o,c]=j.useState(null),[d,u]=j.useState("idle"),h=j.useMemo(()=>{if(!r)return null;try{return new URL(r).searchParams.get("email")}catch{return null}},[r]),m=async()=>{var g;u("sending");try{const x=h||((g=window.prompt("Enter the email address on your LevelUp account:"))==null?void 0:g.trim());if(!x){u("idle");return}const{error:y}=await q.functions.invoke("send-password-reset",{body:{email:x,variant:a==="recovery"?"reset":"activation"}});u(y?"failed":"sent")}catch{u("failed")}},f=async()=>{if(!(!l||!r)){if(t(!0),c(null),window.location.origin!==Hce&&window.location.hostname!=="localhost"){window.location.href=`${Hce}${window.location.pathname}${window.location.search}`;return}try{const g=new URL(r),x=g.searchParams.get("token")||g.searchParams.get("token_hash"),y=g.searchParams.get("type")||(a==="claim"?"invite":a);if(x){const{error:v}=await q.auth.verifyOtp({token_hash:x,type:y});if(!v){const b=g.searchParams.get("redirect_to");let w=y==="recovery"?"/profile?reset=true":"/dashboard";if(b)try{const S=new URL(b);w=`${S.pathname}${S.search}`}catch{}window.location.replace(`${Hce}${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:a6e,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(Gn,{className:"text-gray-600 pt-2",children:o||(l?"Click the button below to continue securely.":"This link is invalid or has expired. Please request a new email from the sign-in page.")})]}),e.jsxs(Ie,{className:"space-y-4",children:[l&&!o?e.jsx($,{onClick:f,disabled:s,className:"w-full bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white font-semibold py-6 text-lg shadow-lg hover:shadow-xl",children:s?"Continuing…":i.cta}):d==="sent"?e.jsx("div",{className:"rounded-lg bg-emerald-50 border border-emerald-200 p-4 text-center text-sm text-emerald-800",children:"A fresh link is on its way — check your inbox in the next minute or two."}):e.jsxs(e.Fragment,{children:[e.jsx($,{onClick:m,disabled:d==="sending",className:"w-full bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white font-semibold py-6 text-lg shadow-lg hover:shadow-xl",children:d==="sending"?"Sending…":"Email me a fresh link"}),d==="failed"&&e.jsx("p",{className:"text-xs text-center text-red-600",children:"We couldn't send that just now. Please try again in a moment."}),e.jsx($,{variant:"outline",onClick:()=>window.location.href=`${Hce}/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."})]})]})]})})]})},Gce="https://dashboard.relevelup.com",b$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!==Gce&&window.location.hostname!=="localhost"){window.location.href=`${Gce}${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(`${Gce}/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:a6e,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(Gn,{className:"text-gray-600 pt-2",children:r?"Loading your account…":o||(t!=null&&t.brokerage_name?`${t.brokerage_name} provides LevelUp for you. Sign in below to set your password.`:"Sign in below to set your password and get started.")})]}),e.jsxs(Ie,{className:"space-y-4",children:[t&&e.jsxs("div",{className:"rounded-lg bg-gray-50 border border-gray-200 p-4 text-center",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-gray-500",children:"Your login email"}),e.jsx("p",{className:"text-base font-semibold text-[#2a4347] break-all",children:t.email})]}),t?e.jsx($,{onClick:d,disabled:i,className:"w-full bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white font-semibold py-6 text-lg shadow-lg hover:shadow-xl",children:i?"Signing you in…":"Sign me in"}):r?null:e.jsx($,{onClick:()=>window.location.href=`${Gce}/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."})]})]})]})})]})},_$s=()=>{const s=Xn(),[t]=gc(),[n,r]=j.useState(t.get("code")||""),[a,i]=j.useState(""),[l,o]=j.useState(""),[c,d]=j.useState(""),[u,h]=j.useState(!1),[m,f]=j.useState(!1),[g,x]=j.useState(!1),[y,v]=j.useState(!1),[b,w]=j.useState(null),[S,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){re.error("Invalid invite code"),x(!1);return}if(!V.is_active){re.error("This invite code is no longer active"),x(!1);return}if(V.max_uses&&V.uses_count>=V.max_uses){re.error("This invite code has reached its maximum uses"),x(!1);return}if(V.expires_at&&new Date(V.expires_at){W.preventDefault(),D(n)},U=async W=>{var V;if(W.preventDefault(),!c.trim()){re.error("Please enter your name");return}if(l.length<6){re.error("Password must be at least 6 characters");return}f(!0);try{const G="https://dashboard.relevelup.com/",{data:Y,error:X}=await q.auth.signUp({email:a.trim(),password:l,options:{emailRedirectTo:G,data:{name:c.trim()}}});if(X){X.message.includes("already registered")?re.error("This email is already registered. Please sign in instead."):re.error(X.message);return}if(Y.user){await q.rpc("add_default_signup_tag",{user_id:Y.user.id});const ae=n.toUpperCase().trim();S?await q.functions.invoke("assign-brokerage",{body:{userId:Y.user.id,brokerageId:S,inviteCode:ae}}):P?await q.functions.invoke("assign-brokerage",{body:{userId:Y.user.id,trialDays:P,inviteCode:ae}}):await q.functions.invoke("assign-brokerage",{body:{userId:Y.user.id,grandfathered:!0,inviteCode:ae}}),b&&await q.from("invite_codes").update({uses_count:((V=(await q.from("invite_codes").select("uses_count").eq("id",b).single()).data)==null?void 0:V.uses_count)+1}).eq("id",b),re.success("Account created! You can now access the dashboard."),s("/dashboard")}}catch(G){console.error("Signup error:",G),re.error("An unexpected error occurred")}finally{f(!1)}};return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(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(Gn,{children:y?E?`Create your account to join ${E}`:"Create your account to get started":"Enter your invite code to continue"})]}),e.jsx(Ie,{children:y?e.jsxs("form",{onSubmit:U,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"name",children:"Full Name"}),e.jsx(pe,{id:"name",type:"text",placeholder:"John Doe",value:c,onChange:W=>d(W.target.value),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"email",children:"Email"}),e.jsx(pe,{id:"email",type:"email",placeholder:"you@example.com",value:a,onChange:W=>i(W.target.value),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"password",children:"Password"}),e.jsxs("div",{className:"relative",children:[e.jsx(pe,{id:"password",type:u?"text":"password",placeholder:"••••••••",value:l,onChange:W=>o(W.target.value),required:!0,minLength:6}),e.jsx("button",{type:"button",className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",onClick:()=>h(!u),children:u?e.jsx($g,{className:"h-4 w-4"}):e.jsx(Ca,{className:"h-4 w-4"})})]})]}),e.jsx($,{type:"submit",className:"w-full",disabled:m,children:m?e.jsxs(e.Fragment,{children:[e.jsx(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"})]})})]})})},Yae=()=>{const{user:s,isCoach:t}=bs();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}})},w$s=()=>{const{data:s}=Yae();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}))}})},Ist=()=>{const{user:s}=bs();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}}})},j$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}}}),Lst=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||[]}}),Rst=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||[]}}),N$s=[{key:"onboarding",label:"Onboarding"},{key:"active",label:"Active"},{key:"thriving",label:"Thriving"},{key:"at_risk",label:"At Risk"},{key:"graduated",label:"Graduated"}];function k$s(){const s=Xn(),{data:t,isLoading:n}=Yae(),{data:r=[],isLoading:a}=w$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."})]})});N$s.map(l=>({...l,items:r.filter(o=>(o.pipeline_stage||"active")===l.key)}));const i=r.filter(l=>l.status==="active").length;return e.jsx(Vs,{title:"Coaching",children:e.jsxs("div",{className:"p-4 md:p-8 max-w-7xl mx-auto space-y-8",children:[e.jsxs("div",{className:"relative overflow-hidden rounded-2xl bg-gradient-to-br from-[#2a4c64] to-[#406E71] text-white p-8",children:[e.jsx("div",{className:"absolute -right-20 -top-20 h-64 w-64 rounded-full bg-white/10 blur-3xl"}),e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2 text-white/80",children:[e.jsx(Nn,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm uppercase tracking-wider font-medium",children:"Coaching Command Center"})]}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold mb-2",children:"Welcome back, Coach"}),e.jsx("p",{className:"text-white/80 mb-6",children:"Lead your agents. Track momentum. Build champions."}),e.jsxs("div",{className:"flex flex-wrap gap-6",children:[e.jsx(L7e,{icon:af,label:"Active agents",value:i}),e.jsx(L7e,{icon:Wc,label:"This month",value:"—"}),e.jsx(L7e,{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(Ie,{className:"p-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No agents assigned yet. An admin or you can invite agents to get started."})})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4",children:r.map(l=>{var o,c,d,u;return e.jsx(je,{className:"cursor-pointer hover:shadow-lg transition-all hover:-translate-y-0.5",onClick:()=>s(`/coaching/agent/${l.id}`),children:e.jsx(Ie,{className:"p-5",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsxs(Oa,{className:"h-14 w-14",children:[e.jsx(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 L7e({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 o$t({assignmentId:s}){const{user:t}=bs(),n=Wt(),[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(Ie,{className:"border-t p-3",children:e.jsxs("div",{className:"flex gap-2 items-end",children:[e.jsx(Ls,{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(Kr,{className:"h-4 w-4"})})]})})]})}var S$s=Object.defineProperty,TT=(s,t)=>S$s(s,"name",{value:t,configurable:!0}),l$t="Progress",Dst=100,[C$s,Kkr]=tp(l$t),[A$s,E$s]=C$s(l$t),T$s=j.forwardRef(TT(function(t,n){const{__scopeProgress:r,value:a=null,max:i,getValueLabel:l=c$t,...o}=t;(i||i===0)&&!MGe(i)&&console.error(d$t(`${i}`,"Progress"));const c=MGe(i)?i:Dst;a!==null&&!PGe(a,c)&&console.error(u$t(`${a}`,"Progress"));const d=PGe(a,c)?a:null,u=nse(d)?l(d,c):void 0;return e.jsx(A$s,{scope:r,value:d,max:c,children:e.jsx(Ei.div,{"aria-valuemax":c,"aria-valuemin":0,"aria-valuenow":nse(d)?d:void 0,"aria-valuetext":u,role:"progressbar","data-state":Fst(d,c),"data-value":d??void 0,"data-max":c,...o,ref:n})})},"Progress")),M$s="ProgressIndicator",P$s=j.forwardRef(TT(function(t,n){const{__scopeProgress:r,...a}=t,i=E$s(M$s,r);return e.jsx(Ei.div,{"data-state":Fst(i.value,i.max),"data-value":i.value??void 0,"data-max":i.max,...a,ref:n})},"ProgressIndicator"));function c$t(s,t){return`${Math.round(s/t*100)}%`}TT(c$t,"defaultGetValueLabel");function Fst(s,t){return s==null?"indeterminate":s===t?"complete":"loading"}TT(Fst,"getProgressState");function nse(s){return typeof s=="number"}TT(nse,"isNumber");function MGe(s){return nse(s)&&!isNaN(s)&&s>0}TT(MGe,"isValidMaxNumber");function PGe(s,t){return nse(s)&&!isNaN(s)&&s<=t&&s>=0}TT(PGe,"isValidValueNumber");function d$t(s,t){return`Invalid prop \`max\` of value \`${s}\` supplied to \`${t}\`. Only numbers greater than 0 are valid max values. Defaulting to \`${Dst}\`.`}TT(d$t,"getInvalidMaxError");function u$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 ${Dst} if no \`max\` prop is set) - \`null\` or \`undefined\` if the progress is indeterminate. Defaulting to \`null\`.`}TT(u$t,"getInvalidValueError");var h$t=T$s,I$s=P$s;const Yi=j.forwardRef(({className:s,value:t,...n},r)=>e.jsx(h$t,{ref:r,className:Pt("relative h-4 w-full overflow-hidden rounded-full bg-secondary",s),...n,children:e.jsx(I$s,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));Yi.displayName=h$t.displayName;function m$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:y}=await q.from("scorecard_transactions").select("id, sale_price, commission_amount, close_date, is_win").eq("owner_user_id",s).gte("close_date",n).lte("close_date",r);if(y)throw y;return x||[]}}),{data:i}=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,y)=>x+(Number(y.sale_price)||0),0),d=l.reduce((x,y)=>x+(Number(y.commission_amount)||0),0),u=i,h=(u==null?void 0:u.transactions_goal)||0,m=(u==null?void 0:u.volume_goal)||0,f=(u==null?void 0:u.gci_goal)||0,g=x=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(x);return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h2",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx(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(R7e,{icon:Im,label:"Transactions",value:o.toString(),goal:h,current:o,suffix:h?`/ ${h}`:""}),e.jsx(R7e,{icon:Zl,label:"Volume",value:g(c),goal:m,current:c,suffix:m?`of ${g(m)}`:""}),e.jsx(R7e,{icon:nu,label:"GCI",value:g(d),goal:f,current:d,suffix:f?`of ${g(f)}`:""})]}),o===0&&e.jsx(je,{children:e.jsxs(Ie,{className:"p-4 text-sm text-muted-foreground text-center",children:["No transactions logged for ",t," yet."]})})]})}function R7e({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(Ie,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-2",children:[e.jsx(s,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs uppercase tracking-wider",children:t})]}),e.jsx("div",{className:"text-2xl font-bold",children:n}),r>0&&e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsx(Yi,{value:l}),e.jsxs("div",{className:"flex justify-between text-xs text-muted-foreground",children:[e.jsx("span",{children:i}),e.jsxs("span",{children:[l.toFixed(0),"%"]})]})]})]})})}function f$t({assignmentId:s,canEdit:t}){const n=Wt(),[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(nh,{className:"h-5 w-5"})," Goals"]}),t&&e.jsxs($,{size:"sm",onClick:()=>{l(null),a(!0)},children:[e.jsx(dn,{className:"h-4 w-4 mr-1"})," New Goal"]})]}),o.length===0?e.jsx(je,{children:e.jsx(Ie,{className:"p-6 text-center text-muted-foreground",children:"No goals yet."})}):o.map(d=>{const u=Number(d.target_value||0),h=Number(d.current_value||0),m=u>0?Math.min(100,h/u*100):0;return e.jsx(je,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold",children:d.title}),e.jsx($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 ",en(new Date(d.due_date),"PP")]})]})},d.id)}),t&&e.jsx(L$s,{open:r,onOpenChange:a,assignmentId:s,goal:i,onSaved:c})]})}function L$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,y]=j.useState((r==null?void 0:r.due_date)||""),[v,b]=j.useState(!1);j.useState(()=>{var E,I;l((r==null?void 0:r.title)||""),c((r==null?void 0:r.description)||""),u((r==null?void 0:r.target_metric)||""),m(((E=r==null?void 0:r.target_value)==null?void 0:E.toString())||""),g(((I=r==null?void 0:r.current_value)==null?void 0:I.toString())||"0"),y((r==null?void 0:r.due_date)||"")});const w=async()=>{if(!i.trim())return;b(!0);const E={assignment_id:n,title:i,description:o||null,target_metric:d||null,target_value:h?Number(h):null,current_value:f?Number(f):0,due_date:x||null},{error:I}=r!=null&&r.id?await q.from("coaching_goals").update(E).eq("id",r.id):await q.from("coaching_goals").insert(E);if(b(!1),I)return re.error(I.message);re.success(r!=null&&r.id?"Goal updated":"Goal created"),a==null||a(),t(!1)};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsx(Bs,{children:r!=null&&r.id?"Edit Goal":"New Goal"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(pe,{placeholder:"Title",value:i,onChange:E=>l(E.target.value)}),e.jsx(Ls,{placeholder:"Description (optional)",rows:2,value:o,onChange:E=>c(E.target.value)}),e.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Metric"}),e.jsx(pe,{placeholder:"transactions",value:d,onChange:E=>u(E.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Target"}),e.jsx(pe,{type:"number",value:h,onChange:E=>m(E.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Current"}),e.jsx(pe,{type:"number",value:f,onChange:E=>g(E.target.value)})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Due date"}),e.jsx(pe,{type:"date",value:x,onChange:E=>y(E.target.value)})]})]}),e.jsxs(Sr,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx($,{onClick:w,disabled:v,children:r!=null&&r.id?"Save":"Create"})]})]})})}function p$t({assignmentId:s}){const t=Wt(),{user:n}=bs(),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:y}=await q.from("coaching_shared_files").insert({assignment_id:s,uploaded_by:n.id,file_url:g,file_name:m.name,file_size_bytes:m.size,mime_type:m.type});if(y)throw y;re.success("File uploaded"),o()}catch(g){re.error(g.message||"Upload failed")}finally{i(!1),r.current&&(r.current.value="")}}},d=async h=>{const{data:m,error:f}=await q.storage.from("coaching-files").createSignedUrl(h.file_url,60);if(f||!m)return re.error("Could not get download link");window.open(m.signedUrl,"_blank")},u=async h=>{await fo("Delete this file?")&&(await q.storage.from("coaching-files").remove([h.file_url]),await q.from("coaching_shared_files").delete().eq("id",h.id),o())};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Shared Files"}),e.jsxs($,{size:"sm",onClick:()=>{var h;return(h=r.current)==null?void 0:h.click()},disabled:a,children:[e.jsx(ni,{className:"h-4 w-4 mr-1"})," ",a?"Uploading…":"Upload"]}),e.jsx("input",{ref:r,type:"file",hidden:!0,onChange:c})]}),l.length===0?e.jsx(je,{children:e.jsx(Ie,{className:"p-6 text-center text-muted-foreground",children:"No files yet."})}):e.jsx("div",{className:"space-y-2",children:l.map(h=>e.jsx(je,{children:e.jsxs(Ie,{className:"p-3 flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-muted flex items-center justify-center",children:e.jsx(Jr,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium truncate",children:h.file_name}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[h.file_size_bytes?`${(h.file_size_bytes/1024).toFixed(0)} KB · `:"",en(new Date(h.created_at),"PP")]})]}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>d(h),children:e.jsx(xi,{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(Hn,{className:"h-4 w-4"})})]})},h.id))})]})}function R$s(){var m,f,g,x;const{id:s}=Wi(),t=Xn(),n=Wt(),{data:r,isLoading:a}=j$s(s),{data:i=[]}=Lst(s),{data:l=[]}=Rst(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(Ie,{className:"pt-0 -mt-12 pb-6",children:e.jsxs("div",{className:"flex flex-col md:flex-row gap-4 md:items-end",children:[e.jsxs(Oa,{className:"h-24 w-24 ring-4 ring-background",children:[e.jsx(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(F$s,{value:h.pipeline_stage||"active",onChange:async y=>{await q.from("coaching_assignments").update({pipeline_stage:y}).eq("id",h.id),n.invalidateQueries({queryKey:["coaching-assignment",h.id]}),n.invalidateQueries({queryKey:["coach-roster"]})}})})]})})]}),e.jsx(D$s,{assignment:h}),e.jsxs(ha,{defaultValue:"sessions",children:[e.jsxs(ma,{className:"w-full flex flex-wrap justify-start h-auto",children:[e.jsxs(Zt,{value:"sessions",children:[e.jsx(Ta,{className:"h-4 w-4 mr-2"}),"Sessions"]}),e.jsxs(Zt,{value:"actions",children:[e.jsx(Cv,{className:"h-4 w-4 mr-2"}),"Actions"]}),e.jsxs(Zt,{value:"goals",children:[e.jsx(nh,{className:"h-4 w-4 mr-2"}),"Goals"]}),e.jsxs(Zt,{value:"kpis",children:[e.jsx(Zl,{className:"h-4 w-4 mr-2"}),"KPIs"]}),e.jsxs(Zt,{value:"messages",children:[e.jsx(eo,{className:"h-4 w-4 mr-2"}),"Messages"]}),e.jsxs(Zt,{value:"files",children:[e.jsx(kv,{className:"h-4 w-4 mr-2"}),"Files"]}),e.jsxs(Zt,{value:"notes",children:[e.jsx(Jr,{className:"h-4 w-4 mr-2"}),"Private Notes"]})]}),e.jsxs(Xt,{value:"sessions",className:"space-y-4",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Sessions"}),e.jsxs($,{size:"sm",onClick:()=>c(!0),children:[e.jsx(dn,{className:"h-4 w-4 mr-1"})," New Session"]})]}),i.length===0?e.jsx(je,{children:e.jsx(Ie,{className:"p-6 text-muted-foreground text-center",children:"No sessions yet."})}):e.jsx("div",{className:"space-y-3",children:i.map(y=>e.jsx(je,{children:e.jsx(Ie,{className:"p-4",children:e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-medium",children:en(new Date(y.scheduled_at),"PPp")}),e.jsx($e,{variant:"outline",className:"capitalize",children:y.status}),y.template&&e.jsx($e,{variant:"secondary",children:y.template}),y.zoom_join_url&&e.jsx("a",{href:y.zoom_join_url,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-primary underline",children:"Join Zoom"})]}),y.agenda&&e.jsxs("p",{className:"text-sm mb-1",children:[e.jsx("span",{className:"text-muted-foreground",children:"Agent's agenda:"})," ",y.agenda]}),y.summary&&e.jsx("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap",children:y.summary}),y.private_notes&&e.jsxs("div",{className:"mt-2 p-2 rounded bg-muted/50 text-xs",children:[e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground mb-1",children:[e.jsx(pc,{className:"h-3 w-3"})," Private"]}),e.jsx("p",{className:"whitespace-pre-wrap",children:y.private_notes})]})]})})})},y.id))})]}),e.jsxs(Xt,{value:"actions",className:"space-y-4",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Action Items"}),e.jsxs($,{size:"sm",onClick:()=>u(!0),children:[e.jsx(dn,{className:"h-4 w-4 mr-1"})," Add"]})]}),l.length===0?e.jsx(je,{children:e.jsx(Ie,{className:"p-6 text-muted-foreground text-center",children:"No action items yet."})}):e.jsx("div",{className:"space-y-2",children:l.map(y=>e.jsx(je,{children:e.jsxs(Ie,{className:"p-3 flex items-center gap-3",children:[e.jsx(ai,{checked:y.status==="done",onCheckedChange:async v=>{await q.from("coaching_action_items").update({status:v?"done":"open",completed_at:v?new Date().toISOString():null}).eq("id",y.id),n.invalidateQueries({queryKey:["coaching-action-items",h.id]})}}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:y.status==="done"?"line-through text-muted-foreground":"font-medium",children:y.title}),y.description&&e.jsx("div",{className:"text-xs text-muted-foreground",children:y.description})]}),y.due_date&&e.jsx($e,{variant:"outline",children:en(new Date(y.due_date),"MMM d")}),e.jsx($e,{variant:"secondary",className:"capitalize",children:y.priority})]})},y.id))})]}),e.jsx(Xt,{value:"goals",children:e.jsx(f$t,{assignmentId:h.id,canEdit:!0})}),e.jsx(Xt,{value:"kpis",children:h.agent_id&&e.jsx(m$t,{agentUserId:h.agent_id})}),e.jsx(Xt,{value:"messages",children:e.jsx(o$t,{assignmentId:h.id})}),e.jsx(Xt,{value:"files",children:e.jsx(p$t,{assignmentId:h.id})}),e.jsx(Xt,{value:"notes",className:"space-y-4",children:e.jsx(je,{children:e.jsx(Ie,{className:"p-6 text-muted-foreground",children:"Private notes per session live under the Sessions tab. General-relationship notes coming soon."})})})]})]}),e.jsx(O$s,{open:o,onOpenChange:c,assignmentId:h.id,onSaved:()=>n.invalidateQueries({queryKey:["coaching-sessions",h.id]})}),e.jsx(z$s,{open:d,onOpenChange:u,assignmentId:h.id,onSaved:()=>n.invalidateQueries({queryKey:["coaching-action-items",h.id]})})]})}function D$s({assignment:s}){const t=Wt(),[n,r]=j.useState(s.sessions_per_month==null?"":String(s.sessions_per_month)),[a,i]=j.useState(!1),l=async()=>{i(!0);const o=n.trim()===""?null:Math.max(1,parseInt(n,10)||1),{error:c}=await q.from("coaching_assignments").update({sessions_per_month:o}).eq("id",s.id);if(i(!1),c)return re.error(c.message);re.success("Session allowance updated"),t.invalidateQueries({queryKey:["coaching-assignment",s.id]})};return e.jsx(je,{children:e.jsxs(Ie,{className:"p-4 flex flex-wrap items-end gap-3",children:[e.jsxs("div",{className:"flex-1 min-w-[220px]",children:[e.jsxs("div",{className:"font-medium flex items-center gap-2",children:[e.jsx(Ta,{className:"h-4 w-4"})," Monthly session allowance"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Leave blank to use your coach default. This agent books these on their My Coach page."})]}),e.jsx(pe,{type:"number",min:1,max:31,placeholder:"Default",value:n,onChange:o=>r(o.target.value),className:"w-28"}),e.jsxs($,{size:"sm",variant:"outline",onClick:l,disabled:a,children:[e.jsx(tl,{className:"h-4 w-4 mr-1"})," Save"]})]})})}function F$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 O$s({open:s,onOpenChange:t,assignmentId:n,onSaved:r}){const[a,i]=j.useState(()=>new Date().toISOString().slice(0,16)),[l,o]=j.useState(60),[c,d]=j.useState("weekly_1on1"),[u,h]=j.useState(""),[m,f]=j.useState(""),[g,x]=j.useState(!1),[y,v]=j.useState(!0),[b,w]=j.useState(null),[S,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 re.error((P==null?void 0:P.error)||(R==null?void 0:R.message)||"Failed to generate brief");w(P.brief||"No brief returned.")},I=async()=>{x(!0);const{data:P,error:R}=await q.from("coaching_sessions").insert({assignment_id:n,scheduled_at:new Date(a).toISOString(),duration_minutes:l,template:c,summary:u,private_notes:m,status:"completed"}).select("id").maybeSingle();if(R)return x(!1),re.error(R.message);if(re.success("Session saved"),y&&u.trim()&&(P!=null&&P.id)){const{error:D}=await q.functions.invoke("coaching-send-recap",{body:{sessionId:P.id}});D?re.error("Saved, but recap email failed: "+D.message):re.success("Recap emailed to agent")}x(!1),r==null||r(),t(!1),h(""),f(""),w(null)};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(Bs,{children:"New Session"}),e.jsxs($,{size:"sm",variant:"outline",onClick:E,disabled:S,children:[S?e.jsx(Ct,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Nn,{className:"h-4 w-4 mr-1"}),"Pre-session brief"]})]})}),e.jsxs("div",{className:"space-y-3",children:[b&&e.jsxs("div",{className:"rounded-lg border bg-gradient-to-br from-[#406E71]/5 to-[#2a4c64]/5 p-3 text-sm whitespace-pre-wrap max-h-60 overflow-y-auto",children:[e.jsxs("div",{className:"flex items-center gap-1 text-xs font-medium text-[#406E71] mb-2",children:[e.jsx(Nn,{className:"h-3 w-3"})," AI Brief"]}),b]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"When"}),e.jsx(pe,{type:"datetime-local",value:a,onChange:P=>i(P.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Duration (min)"}),e.jsx(pe,{type:"number",value:l,onChange:P=>o(Number(P.target.value))})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Template"}),e.jsxs(ms,{value:c,onValueChange:d,children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"weekly_1on1",children:"Weekly 1:1"}),e.jsx(Ge,{value:"grow",children:"GROW Model"}),e.jsx(Ge,{value:"goal_review",children:"Goal Review"}),e.jsx(Ge,{value:"breakthrough",children:"Breakthrough Session"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Summary (agent sees this)"}),e.jsx(Ls,{rows:4,value:u,onChange:P=>h(P.target.value),placeholder:"Key takeaways, wins, focus areas…"})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"text-sm font-medium flex items-center gap-1",children:[e.jsx(pc,{className:"h-3 w-3"})," Private notes (only you)"]}),e.jsx(Ls,{rows:3,value:m,onChange:P=>f(P.target.value),placeholder:"Your private observations…"})]}),e.jsxs("label",{className:"flex items-center gap-2 text-sm pt-1",children:[e.jsx(ai,{checked:y,onCheckedChange:P=>v(!!P)}),e.jsx(Kr,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Email recap to agent on save"]})]}),e.jsxs(Sr,{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 z$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 re.error(x.message);re.success("Action item added"),r==null||r(),t(!1),i(""),o(""),d("")};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsx(Bs,{children:"New Action Item"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(pe,{placeholder:"Title",value:a,onChange:x=>i(x.target.value)}),e.jsx(Ls,{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(Sr,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx($,{onClick:g,disabled:m,children:"Add"})]})]})})}function IGe({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 B$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(IGe,{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(Ie,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs(Oa,{className:"h-9 w-9",children:[e.jsx(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(IGe,{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 $$s({coachId:s,assignmentId:t}){const{user:n}=bs(),[r,a]=j.useState(null),[i,l]=j.useState(0),[o,c]=j.useState(""),[d,u]=j.useState(""),[h,m]=j.useState(!1);j.useEffect(()=>{n&&(async()=>{const{data:g}=await q.from("coaching_reviews").select("*").eq("coach_id",s).eq("agent_id",n.id).maybeSingle();g&&(a(g),l(g.rating),c(g.title||""),u(g.body||""))})()},[n,s]);const f=async()=>{if(!n)return;if(!i)return re.error("Pick a rating");m(!0);const g={coach_id:s,agent_id:n.id,assignment_id:t||null,rating:i,title:o||null,body:d||null},{error:x}=r?await q.from("coaching_reviews").update(g).eq("id",r.id):await q.from("coaching_reviews").insert(g);if(m(!1),x)return re.error(x.message);re.success("Thanks for your review!"),a({...g,id:r==null?void 0:r.id})};return e.jsx(je,{children:e.jsxs(Ie,{className:"p-5 space-y-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold",children:r?"Your review":"Leave a review"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Help other agents find a great coach."})]}),e.jsx(IGe,{value:i,size:28,onChange:l}),e.jsx(pe,{placeholder:"Title (optional)",value:o,onChange:g=>c(g.target.value)}),e.jsx(Ls,{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 Wce=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},D7e=s=>en(s,"yyyy-MM-dd"),Mvt=s=>{const[t,n]=s.split(":").map(Number),r=t>=12?"PM":"AM";return`${t%12||12}:${String(n).padStart(2,"0")} ${r}`};function U$s({assignmentId:s,upcoming:t=[]}){const n=Wt(),[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:()=>Wce({action:"context"})});j.useEffect(()=>{var ae;!r&&((ae=f==null?void 0:f.booking_types)!=null&&ae.length)&&a(f.booking_types[0].id)},[f,r]);const x=j.useMemo(()=>new Date,[]),[y,v]=j.useState(()=>Zm(new Date)),b=(f==null?void 0:f.max_advance_days)||30,w=j.useMemo(()=>Am(Mg(x),b-1),[x,b]),S=j.useMemo(()=>{const ae=Zm(y);return ae{const ae=hw(y);return ae>w?w:ae},[y,w]),E=Math.max(0,ub(A,S)+1),{data:I={},isFetching:P}=st({queryKey:["coaching-availability",r,D7e(S),E],enabled:!!r&&E>0,queryFn:async()=>(await Wce({action:"availability",booking_type_id:r,start:D7e(S),days:E})).availability||{}}),R=j.useMemo(()=>{const ae=Zm(y),le=hw(y).getDate(),ne=ae.getDay(),te=Array.from({length:ne},()=>null);for(let J=0;JObject.entries(I).filter(([,ae])=>ae.length>0),[I]),O=i?I[i]||[]:[],U=P,W=j.useMemo(()=>{const ae=[{label:"Morning",items:[]},{label:"Afternoon",items:[]},{label:"Evening",items:[]}];for(const le of O){const ne=Number(le.split(":")[0]);ne<12?ae[0].items.push(le):ne<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,Y=async()=>{if(!(!r||!i||!o)){m(!0);try{await Wce({action:"book",booking_type_id:r,date:i,time:o,agenda:d||null}),re.success("Session booked — check your Zoom link below."),c(null),u(""),n.invalidateQueries({queryKey:["coaching-booking-context",s]}),n.invalidateQueries({queryKey:["coaching-availability"]}),n.invalidateQueries({queryKey:["coaching-sessions",s]})}catch(ae){re.error(ae.message||"Could not book that session")}finally{m(!1)}}},X=async ae=>{if(await fo("Cancel this coaching session?"))try{await Wce({action:"cancel",session_id:ae}),re.success("Session cancelled"),n.invalidateQueries({queryKey:["coaching-booking-context",s]}),n.invalidateQueries({queryKey:["coaching-sessions",s]})}catch(le){re.error(le.message||"Could not cancel")}};return g?e.jsx(je,{children:e.jsxs(Ie,{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(Ie,{className:"p-4 flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-primary/10 flex items-center justify-center",children:e.jsx(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(Ie,{className:"p-4 space-y-3",children:[e.jsx("h3",{className:"font-semibold",children:"Upcoming sessions"}),t.map(ae=>e.jsxs("div",{className:"flex flex-wrap items-center gap-3 p-3 rounded-lg border",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium",children:en(new Date(ae.scheduled_at),"EEE, MMM d · p")}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[ae.duration_minutes||30," minutes"]})]}),ae.zoom_join_url&&e.jsx($,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:ae.zoom_join_url,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(ua,{className:"h-4 w-4 mr-1"})," Join"]})}),e.jsxs($,{size:"sm",variant:"ghost",onClick:()=>X(ae.id),children:[e.jsx(Nu,{className:"h-4 w-4 mr-1"})," Cancel"]})]},ae.id))]})}),e.jsx(je,{children:e.jsxs(Ie,{className:"p-4 md:p-6 space-y-5",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"mb-2 block",children:"Session type"}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:f.booking_types.map(ae=>e.jsxs("button",{onClick:()=>{a(ae.id),c(null)},className:`text-left p-3 rounded-lg border transition-colors ${r===ae.id?"border-primary bg-primary/5":"hover:bg-muted/50"}`,children:[e.jsx("div",{className:"font-medium",children:ae.name}),e.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-1 mt-1",children:[e.jsx(da,{className:"h-3 w-3"})," ",ae.duration_minutes," min"]}),ae.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:ae.description})]},ae.id))})]}),e.jsxs("div",{className:"grid gap-5 lg:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(ee,{className:"block",children:"Pick a day"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx($,{size:"icon",variant:"ghost",className:"h-7 w-7",disabled:Oae(y,x),onClick:()=>v(Ev(y,-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:en(y,"MMMM yyyy")}),e.jsx($,{size:"icon",variant:"ghost",className:"h-7 w-7",disabled:Zm(Ev(y,1))>w,onClick:()=>v(Ev(y,1)),"aria-label":"Next month",children:e.jsx(Di,{className:"h-4 w-4"})})]})]}),e.jsx("div",{className:"grid grid-cols-7 gap-1 mb-1",children:["S","M","T","W","T","F","S"].map((ae,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 ne=D7e(ae),te=(I[ne]||[]).length,ce=ae>=Mg(x)&&ae<=w&&te>0,_e=i===ne;return e.jsxs("button",{disabled:!ce,onClick:()=>{l(ne),c(null)},className:`aspect-square rounded-lg border text-sm flex flex-col items-center justify-center gap-1 transition-colors ${_e?"border-primary bg-primary text-primary-foreground":ce?"border-primary/30 bg-primary/5 hover:bg-primary/10 font-medium":"border-transparent text-muted-foreground/50 cursor-not-allowed"}`,title:ce?`${te} opening${te===1?"":"s"}`:"No openings",children:[e.jsx("span",{className:"leading-none",children:en(ae,"d")}),e.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${_e?"bg-primary-foreground":ce?"bg-primary":"bg-transparent"}`})]},ne)})}),e.jsx("div",{className:"mt-3 flex items-center gap-2 text-xs text-muted-foreground",children:P?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"h-3 w-3 animate-spin"})," Loading your coach's openings…"]}):e.jsxs(e.Fragment,{children:[e.jsx(Nn,{className:"h-3 w-3 text-primary"}),D.length===0?"No openings this month — try the next month.":`${D.length} day${D.length===1?"":"s"} with openings this month`]})})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"mb-2 block",children:i?`Available times · ${en(new Date(`${i}T12:00:00`),"EEE, MMM d")}`:"Available times"}),i?U?e.jsxs("div",{className:"text-sm text-muted-foreground flex items-center gap-2",children:[e.jsx(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:Mvt(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:[en(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(Ls,{id:"agenda",rows:3,value:d,onChange:ae=>u(ae.target.value),placeholder:"Share context so your coach can prep."})]}),e.jsxs($,{onClick:Y,disabled:h||G,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[h?e.jsx(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&&en(new Date(`${i}T12:00:00`),"MMM d")," at ",Mvt(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(Ie,{className:"p-8 text-center text-muted-foreground",children:"Your coach hasn't opened their coaching calendar yet. Check back soon."})})}function q$s(){const{user:s}=bs(),{isMember:t,pkg:n}=_C(),{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(zg,{className:"h-4 w-4 text-primary"})," Coaching prep"]}),a.length>0&&e.jsxs($e,{variant:"secondary",children:[i,"/",a.length," done"]})]}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg border border-border/60 p-3",children:[e.jsxs("div",{className:"text-sm",children:[e.jsx("div",{className:"font-medium",children:"Onboarding questionnaire"}),e.jsx("div",{className:"text-muted-foreground text-xs",children:r!=null&&r.submitted?"Submitted — your coach has it.":"Complete this before session one."})]}),e.jsx($,{asChild:!0,size:"sm",variant:r!=null&&r.submitted?"outline":"default",children:e.jsx(wr,{to:"/coaching/onboarding",children:r!=null&&r.submitted?"Review":"Start"})})]}),a.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"What we're setting up for you"}),a.map(l=>e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[l.done?e.jsx(Vr,{className:"h-4 w-4 mt-0.5 text-primary"}):e.jsx(Og,{className:"h-4 w-4 mt-0.5 text-muted-foreground/50"}),e.jsxs("span",{children:[e.jsx("span",{className:l.done?"text-muted-foreground line-through":"",children:l.title}),l.description&&e.jsx("span",{className:"block text-xs text-muted-foreground",children:l.description})]})]},l.id))]})]})]})}function V$s(){var m,f,g,x,y,v;const{user:s}=bs(),{data:t,isLoading:n,refetch:r}=Ist(),a=Wt(),i=t==null?void 0:t.id,{data:l=[]}=Lst(i),{data:o=[]}=Rst(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(Nn,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm uppercase tracking-wider",children:"Your Coach"})]}),e.jsx("h1",{className:"text-3xl font-bold",children:((g=c.coachProfile)==null?void 0:g.name)||"Your Coach"}),((x=c.coach)==null?void 0:x.headline)&&e.jsx("p",{className:"text-white/80 mt-1",children:c.coach.headline}),e.jsxs("div",{className:"flex gap-2 mt-3",children:[((y=c.coach)==null?void 0:y.is_certified)&&e.jsx($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(F7e,{icon:Cv,label:"Open action items",value:d.length}),e.jsx(F7e,{icon:nh,label:"Completed",value:u}),e.jsx(F7e,{icon:Ta,label:"Sessions",value:l.length})]}),e.jsx(q$s,{}),((v=c.coach)==null?void 0:v.id)&&e.jsx($$s,{coachId:c.coach.id,assignmentId:i}),e.jsxs(ha,{defaultValue:"book",children:[e.jsxs(ma,{className:"flex flex-wrap h-auto w-full justify-start",children:[e.jsxs(Zt,{value:"book",children:[e.jsx(bv,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Book"})]}),e.jsxs(Zt,{value:"actions",children:[e.jsx(Cv,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Actions"})]}),e.jsxs(Zt,{value:"sessions",children:[e.jsx(Ta,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Recaps"})]}),e.jsxs(Zt,{value:"goals",children:[e.jsx(nh,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Goals"})]}),e.jsxs(Zt,{value:"kpis",children:[e.jsx(Zl,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"KPIs"})]}),e.jsxs(Zt,{value:"messages",children:[e.jsx(eo,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Messages"})]}),e.jsxs(Zt,{value:"files",children:[e.jsx(kv,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Files"})]})]}),e.jsx(Xt,{value:"book",children:e.jsx(U$s,{assignmentId:i,upcoming:h})}),e.jsx(Xt,{value:"actions",className:"space-y-2",children:o.length===0?e.jsx(je,{children:e.jsx(Ie,{className:"p-6 text-center text-muted-foreground",children:"Your coach hasn't assigned any action items yet."})}):o.map(b=>e.jsx(je,{children:e.jsxs(Ie,{className:"p-3 flex items-center gap-3",children:[e.jsx(ai,{checked:b.status==="done",onCheckedChange:async w=>{await q.from("coaching_action_items").update({status:w?"done":"open",completed_at:w?new Date().toISOString():null}).eq("id",b.id),a.invalidateQueries({queryKey:["coaching-action-items",i]})}}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:b.status==="done"?"line-through text-muted-foreground":"font-medium",children:b.title}),b.description&&e.jsx("div",{className:"text-xs text-muted-foreground",children:b.description})]}),b.due_date&&e.jsx($e,{variant:"outline",children:en(new Date(b.due_date),"MMM d")}),e.jsx($e,{variant:"secondary",className:"capitalize",children:b.priority})]})},b.id))}),e.jsx(Xt,{value:"sessions",className:"space-y-3",children:l.length===0?e.jsx(je,{children:e.jsx(Ie,{className:"p-6 text-center text-muted-foreground",children:"No sessions logged yet."})}):l.map(b=>e.jsx(je,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("span",{className:"font-medium",children:en(new Date(b.scheduled_at),"PPp")}),e.jsx($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(Xt,{value:"goals",children:e.jsx(f$t,{assignmentId:i,canEdit:!1})}),e.jsx(Xt,{value:"kpis",children:s&&e.jsx(m$t,{agentUserId:s.id})}),e.jsx(Xt,{value:"messages",children:e.jsx(o$t,{assignmentId:i})}),e.jsx(Xt,{value:"files",children:e.jsx(p$t,{assignmentId:i})})]})]})})}function F7e({icon:s,label:t,value:n}){return e.jsx(je,{children:e.jsxs(Ie,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-primary/10 flex items-center justify-center",children:e.jsx(s,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold leading-none",children:n}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:t})]})]})})}const Pvt="coaching_access",O7e=s=>((s==null?void 0:s.name)||(s==null?void 0:s.email)||"?").trim().slice(0,2).toUpperCase(),z7e=s=>!!s.expires_at&&new Date(s.expires_at).getTime()<=Date.now();function H$s(){const s=Wt(),[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",Pvt).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 y=j.useMemo(()=>{const D=new Map;return h.forEach(O=>D.set(O.user_id,O)),D},[h]),v=j.useMemo(()=>new Set(f.map(D=>D.agent_id)),[f]),b=()=>{s.invalidateQueries({queryKey:["coaching-entitlements"]}),s.invalidateQueries({queryKey:["coaching-access-profiles"]}),s.invalidateQueries({queryKey:["coaching-access"]})},w=async(D,O={})=>{var V;const{data:U}=await q.auth.getUser(),{error:W}=await q.from("feature_entitlements").upsert({user_id:D,feature_key:Pvt,enabled:O.enabled??!0,expires_at:O.expires_at??null,notes:O.notes??null,tier:O.tier??null,enabled_by:((V=U==null?void 0:U.user)==null?void 0:V.id)??null,enabled_at:new Date().toISOString(),updated_at:new Date().toISOString()},{onConflict:"user_id,feature_key"});return W?(re.error(W.message),!1):(b(),!0)},S=async D=>{await w(D.id)&&re.success(`Coaching access granted to ${D.name||D.email}`),n(""),a([])},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 re.error(U.message);re.success(O?"Access enabled":"Access paused"),b()},E=async D=>{if(!await fo({title:"Revoke coaching access?",description:`${D.profile.name||D.profile.email||"This member"} will lose access to the coaching area unless they're assigned to a coach.`,confirmText:"Revoke access",destructive:!0}))return;const{error:U}=await q.from("feature_entitlements").delete().eq("id",D.entitlement.id);if(U)return re.error(U.message);re.success("Coaching access revoked"),b()},I=j.useMemo(()=>{const D=d.trim().toLowerCase(),O=h.map(U=>({entitlement:U,profile:x[U.user_id]}));return D?O.filter(({profile:U})=>`${(U==null?void 0:U.name)||""} ${(U==null?void 0:U.email)||""}`.toLowerCase().includes(D)):O},[h,x,d]),P=h.filter(D=>D.enabled&&!z7e(D)).length,R=f.filter(D=>!y.has(D.agent_id));return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3",children:[e.jsx(B7e,{icon:Rm,label:"Granted access",value:P,hint:"Standalone entitlements"}),e.jsx(B7e,{icon:Yn,label:"Coached members",value:v.size,hint:"Active coach assignments"}),e.jsx(B7e,{icon:Nn,label:"Total with access",value:new Set([...h.filter(D=>D.enabled&&!z7e(D)).map(D=>D.user_id),...v]).size,hint:"Unique members"})]}),e.jsx(je,{children:e.jsxs(Ie,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(GI,{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(Zr,{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=y.get(D.id),U=v.has(D.id);return e.jsxs("div",{className:"flex items-center gap-3 p-2.5 hover:bg-muted/40",children:[e.jsxs(Oa,{className:"h-8 w-8",children:[e.jsx(Ii,{src:D.avatar_url||void 0}),e.jsx(za,{className:"text-xs",children:O7e(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(Wd,{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(Ie,{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=z7e(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:O7e(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"}),v.has(D.user_id)&&e.jsxs($e,{variant:"outline",children:[e.jsx(Wd,{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(Cu,{className:"h-3 w-3"}),U?"Expired":"Expires"," ",new Date(D.expires_at).toLocaleDateString()]})]}),D.notes&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1 italic truncate",children:D.notes})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx(Sn,{checked:D.enabled&&!U,onCheckedChange:W=>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(pr,{className:"h-4 w-4"})})]})]},D.id)})})]})}),e.jsx(je,{children:e.jsxs(Ie,{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:O7e(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(G$s,{state:o,onClose:()=>c(null),onSave:async D=>{if(!o)return;await w(o.profile.id,D)&&(re.success("Coaching access saved"),c(null))}})]})}function B7e({icon:s,label:t,value:n,hint:r}){return e.jsx(je,{children:e.jsxs(Ie,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-primary/10 flex items-center justify-center",children:e.jsx(s,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold leading-none",children:n}),e.jsx("div",{className:"text-sm font-medium",children:t}),e.jsx("div",{className:"text-xs text-muted-foreground",children:r})]})]})})}function G$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(zs,{open:!!s,onOpenChange:g=>!g&&t(),children:e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsx(Bs,{children:s!=null&&s.entitlement?"Edit coaching access":"Grant coaching access"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"text-sm",children:[e.jsx("div",{className:"font-medium",children:(s==null?void 0:s.profile.name)||(s==null?void 0:s.profile.email)}),e.jsx("div",{className:"text-xs text-muted-foreground",children:s==null?void 0:s.profile.email})]}),e.jsxs("div",{className:"flex items-center justify-between border rounded-lg p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Access enabled"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Turn off to pause without removing the grant."})]}),e.jsx(Sn,{checked:d,onCheckedChange:u})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Expires on (optional)"}),e.jsx(pe,{type:"date",value:r,onChange:g=>a(g.target.value)}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Leave blank for ongoing access."})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Tier / plan label (optional)"}),e.jsx(pe,{value:o,onChange:g=>c(g.target.value),placeholder:"e.g. Premium, Beta, Comp"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Internal notes"}),e.jsx(Ls,{value:i,onChange:g=>l(g.target.value),rows:3,placeholder:"Why this member has access…"})]})]}),e.jsxs(Sr,{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 W$s(){const s=Wt(),[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:y}=await q.from("profiles").select("id, name, email").in("id",x),v=new Map((y||[]).map(b=>[b.id,b]));return(f||[]).map(b=>{var w,S;return{id:b.id,label:((w=v.get(b.user_id))==null?void 0:w.name)||((S=v.get(b.user_id))==null?void 0:S.email)||b.user_id}})}}),{data:l=[],isLoading:o}=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:y}=x.length?await q.from("profiles").select("id, name, email").in("id",x):{data:[]},v=new Map((y||[]).map(b=>[b.id,b]));return(f||[]).map(b=>({...b,agent:v.get(b.agent_id)}))}}),c=f=>{var g;return((g=i.find(x=>x.id===f))==null?void 0:g.label)||"—"},d=j.useMemo(()=>{const f=t.trim().toLowerCase();return l.filter(g=>{var x,y;return r!=="all"&&g.status!==r?!1:f?(((x=g.agent)==null?void 0:x.name)||"").toLowerCase().includes(f)||(((y=g.agent)==null?void 0:y.email)||"").toLowerCase().includes(f)||c(g.coach_id).toLowerCase().includes(f):!0})},[l,t,r,i]),u=()=>{s.invalidateQueries({queryKey:["admin-coaching-assignments"]}),s.invalidateQueries({queryKey:["coach-roster"]})},h=async(f,g)=>{var v,b;if(g===f.coach_id||!await fo({title:"Switch coach?",description:`${((v=f.agent)==null?void 0:v.name)||((b=f.agent)==null?void 0:b.email)} will move from ${c(f.coach_id)} to ${c(g)}. Session history stays with the assignment.`,confirmText:"Switch coach"}))return;const{error:y}=await q.from("coaching_assignments").update({coach_id:g}).eq("id",f.id);if(y)return re.error(y.message);re.success("Coach switched"),u()},m=async(f,g)=>{var y,v;if(g==="ended"&&!await fo({title:"End assignment?",description:`${((y=f.agent)==null?void 0:y.name)||((v=f.agent)==null?void 0:v.email)} will lose access to the coaching workspace unless they have standalone access.`,confirmText:"End assignment",destructive:!0}))return;const{error:x}=await q.from("coaching_assignments").update({status:g,ended_at:g==="ended"?new Date().toISOString():null}).eq("id",f.id);if(x)return re.error(x.message);re.success(g==="ended"?"Assignment ended":"Assignment reactivated"),u()};return e.jsx(je,{children:e.jsxs(Ie,{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,y;return e.jsxs("div",{className:"p-3 flex flex-col md:flex-row md:items-center gap-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-medium truncate",children:((g=f.agent)==null?void 0:g.name)||((x=f.agent)==null?void 0:x.email)||f.agent_id}),e.jsxs("div",{className:"text-xs text-muted-foreground truncate",children:[(y=f.agent)==null?void 0:y.email," · ",f.pipeline_stage||"onboarding",f.status==="ended"&&" · ended"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(uJ,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs(ms,{value:f.coach_id,onValueChange:v=>h(f,v),children:[e.jsx(us,{className:"w-full md:w-56 h-9",children:e.jsx(fs,{})}),e.jsx(hs,{children:i.map(v=>e.jsx(Ge,{value:v.id,children:v.label},v.id))})]}),f.status==="active"?e.jsxs($,{variant:"outline",size:"sm",onClick:()=>m(f,"ended"),children:[e.jsx(cV,{className:"h-4 w-4 mr-1"})," End"]}):e.jsxs($,{variant:"outline",size:"sm",onClick:()=>m(f,"active"),children:[e.jsx(Ax,{className:"h-4 w-4 mr-1"})," Reactivate"]})]})]},f.id)})})]})})}function K$s(){const s=Wt(),[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(y=>y.user_id),{data:g}=await q.from("profiles").select("id, name, email, avatar_url").in("id",f),x=new Map((g||[]).map(y=>[y.id,y]));return h.map(y=>({...y,profile:x.get(y.user_id)}))}});j.useEffect(()=>{const h=t.trim();if(h.length<2){a([]);return}const m=setTimeout(async()=>{const{data:f}=await q.from("profiles").select("id, email, name, avatar_url").or(`email.ilike.%${h}%,name.ilike.%${h}%`).limit(10);a(f||[])},250);return()=>clearTimeout(m)},[t]);const d=async h=>{const{error:m}=await q.functions.invoke("manage-user-roles",{body:{userId:h.id,role:"coach",action:"add"}});if(m)return re.error(m.message);const{error:f}=await q.from("coaches").insert({user_id:h.id});if(f&&!String(f.message).includes("duplicate"))return re.error(f.message);re.success(`${h.name||h.email} is now a coach`),n(""),a([]),s.invalidateQueries({queryKey:["admin-coaches"]})},u=async(h,m)=>{const{error:f}=await q.from("coaches").update({is_certified:m}).eq("id",h);if(f)return re.error(f.message);re.success(m?"Marked Certified":"Removed certification"),s.invalidateQueries({queryKey:["admin-coaches"]})};return e.jsxs(Vs,{title:"Coaching Admin",children:[e.jsxs("div",{className:"p-4 md:p-8 max-w-6xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(af,{className:"h-7 w-7 text-primary"}),e.jsx("h1",{className:"text-2xl font-bold",children:"LevelUp Coaching"})]}),e.jsxs(ha,{defaultValue:"coaches",className:"space-y-6",children:[e.jsxs(ma,{className:"flex-wrap h-auto",children:[e.jsx(Zt,{value:"coaches",children:"Coaches"}),e.jsx(Zt,{value:"assignments",children:"Assignments"}),e.jsx(Zt,{value:"access",children:"Coaching Access"}),e.jsx(Zt,{value:"applications",children:"Applications"}),e.jsx(Zt,{value:"settings",children:"Settings"})]}),e.jsx(Xt,{value:"assignments",className:"space-y-6",children:e.jsx(W$s,{})}),e.jsx(Xt,{value:"access",className:"space-y-6",children:e.jsx(H$s,{})}),e.jsx(Xt,{value:"applications",className:"space-y-6",children:e.jsx(X$s,{})}),e.jsx(Xt,{value:"settings",className:"space-y-6",children:e.jsx(Y$s,{})}),e.jsxs(Xt,{value:"coaches",className:"space-y-6",children:[e.jsx(je,{children:e.jsxs(Ie,{className:"p-4 space-y-3",children:[e.jsx(pe,{placeholder:"Search by user email or name…",value:t,onChange:h=>n(h.target.value)}),t.trim().length>=2&&e.jsx("div",{className:"border rounded-md divide-y max-h-72 overflow-auto",children:r.length===0?e.jsx("div",{className:"p-3 text-sm text-muted-foreground",children:"No users found"}):r.map(h=>e.jsxs("div",{className:"flex items-center justify-between p-2 hover:bg-muted/40",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium truncate",children:h.name||h.email}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:h.email})]}),e.jsxs($,{size:"sm",onClick:()=>d(h),children:[e.jsx(dn,{className:"h-4 w-4 mr-1"})," Make Coach"]})]},h.id))})]})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold mb-3",children:"Coaches"}),c?e.jsx("div",{children:"Loading…"}):o.length===0?e.jsx(je,{children:e.jsx(Ie,{className:"p-6 text-center text-muted-foreground",children:"No coaches yet. Search for a user above to promote them."})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:o.map(h=>{var m,f,g;return e.jsx(je,{children:e.jsxs(Ie,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium",children:((m=h.profile)==null?void 0:m.name)||((f=h.profile)==null?void 0:f.email)||h.user_id}),e.jsx("div",{className:"text-xs text-muted-foreground",children:(g=h.profile)==null?void 0:g.email}),e.jsxs("div",{className:"flex gap-2 mt-2 flex-wrap",children:[h.is_certified&&e.jsxs($e,{className:"bg-yellow-500/15 text-yellow-700 border-yellow-300/40",children:[e.jsx(Nn,{className:"h-3 w-3 mr-1"}),"Certified"]}),h.accepting_clients&&e.jsx($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(Sn,{checked:h.is_certified,onCheckedChange:x=>u(h.id,x)})]})]})},h.id)})})]})]})]})]}),e.jsx(Z$s,{coachId:i,onClose:()=>l(null)})]})}function Y$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 re.error("Enter a value between 0 and 5000 bps (0–50%)");r(!0);const{error:d}=await q.from("settings").upsert({key:"coaching_platform_fee_bps",value:String(c)});if(r(!1),d)return re.error(d.message);re.success("Platform fee updated")};if(!a)return null;const o=(parseInt(s,10)/100).toFixed(2);return e.jsx(je,{children:e.jsxs(Ie,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ew,{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=Wt();j.useEffect(()=>{if(!s){r(""),i([]);return}},[s]),j.useEffect(()=>{const u=n.trim();if(u.length<2){i([]);return}o(!0);const h=setTimeout(async()=>{const{data:m}=await q.from("profiles").select("id, name, email").or(`email.ilike.%${u}%,name.ilike.%${u}%`).limit(15);i(m||[]),o(!1)},250);return()=>clearTimeout(h)},[n]);const d=async u=>{const{error:h}=await q.from("coaching_assignments").insert({coach_id:s,agent_id:u,status:"active",source:"admin",pipeline_stage:"onboarding"});if(h)return re.error(h.message);re.success("Agent assigned"),c.invalidateQueries({queryKey:["coach-roster"]}),t()};return e.jsx(zs,{open:!!s,onOpenChange:u=>!u&&t(),children:e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Assign Agent"})}),e.jsx(pe,{placeholder:"Search agents by name or email…",value:n,onChange:u=>r(u.target.value),autoFocus:!0}),e.jsx("div",{className:"space-y-1 max-h-72 overflow-auto border rounded-md",children:n.trim().length<2?e.jsx("div",{className:"p-3 text-sm text-muted-foreground",children:"Type at least 2 characters to search…"}):l?e.jsx("div",{className:"p-3 text-sm text-muted-foreground",children:"Searching…"}):a.length===0?e.jsx("div",{className:"p-3 text-sm text-muted-foreground",children:"No agents found"}):a.map(u=>e.jsxs("button",{onClick:()=>d(u.id),className:"w-full text-left p-2 hover:bg-muted",children:[e.jsx("div",{className:"font-medium",children:u.name||u.email}),e.jsx("div",{className:"text-xs text-muted-foreground",children:u.email})]},u.id))}),e.jsx(Sr,{children:e.jsx($,{variant:"outline",onClick:t,children:"Close"})})]})})}function X$s(){const s=Wt(),[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 re.error(m.message);re.success(`Marked ${h}`),s.invalidateQueries({queryKey:["coach-applications"]}),s.invalidateQueries({queryKey:["coach-applications-pending-count"]}),a(null)},d=u=>u==="approved"?e.jsxs($e,{className:"bg-emerald-500/15 text-emerald-700 border-emerald-300/40",children:[e.jsx(ca,{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(pr,{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(da,{className:"h-3 w-3 mr-1"}),"Pending"]});return e.jsxs(je,{children:[e.jsxs(Ie,{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(Uz,{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(mn,{className:"h-3 w-3"}),u.email]}),u.brokerage&&e.jsxs("span",{children:["· ",u.brokerage]}),u.years_experience&&e.jsxs("span",{children:["· ",u.years_experience," yrs"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[d(u.status),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(u.created_at).toLocaleDateString()})]})]})},u.id))})]}),e.jsx(zs,{open:!!r,onOpenChange:u=>!u&&a(null),children:e.jsx(Os,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:r&&e.jsxs(e.Fragment,{children:[e.jsx(Us,{children:e.jsxs(Bs,{className:"flex items-center gap-3",children:[r.full_name,d(r.status)]})}),e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(_$,{icon:mn,label:"Email",value:r.email,link:`mailto:${r.email}`}),r.phone&&e.jsx(_$,{icon:Da,label:"Phone",value:r.phone,link:`tel:${r.phone}`}),r.brokerage&&e.jsx(_$,{label:"Brokerage",value:r.brokerage}),r.years_experience&&e.jsx(_$,{label:"Years",value:r.years_experience}),r.website_url&&e.jsx(_$,{icon:Fr,label:"Website",value:r.website_url,link:r.website_url}),r.linkedin_url&&e.jsx(_$,{icon:Fr,label:"LinkedIn",value:r.linkedin_url,link:r.linkedin_url})]}),r.specialties&&e.jsx($7e,{label:"Specialties",children:r.specialties}),e.jsx($7e,{label:"Why they want to coach",children:r.why_coach}),r.results_story&&e.jsx($7e,{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(Ls,{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(Sr,{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(pr,{className:"h-4 w-4 mr-1"})," Reject"]}),r.status!=="pending"&&e.jsxs($,{variant:"outline",onClick:()=>c(r.id,"pending"),children:[e.jsx(da,{className:"h-4 w-4 mr-1"})," Move to pending"]}),r.status!=="approved"&&e.jsxs($,{onClick:()=>c(r.id,"approved"),className:"bg-emerald-600 hover:bg-emerald-700",children:[e.jsx(ca,{className:"h-4 w-4 mr-1"})," Approve"]})]})]})})})]})}function _$({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 $7e({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 Q$s(){const s=Xn(),{data:t}=Yae(),n=Wt(),[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:y}=await q.functions.invoke("coach-stripe-status");return y}}),{data:h=[]}=st({queryKey:["coach-packages",t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{const{data:y}=await q.from("coaching_packages").select("*").eq("coach_id",t.id).order("sort_order");return y||[]}});j.useEffect(()=>{const y=new URLSearchParams(window.location.search);(y.get("onboarded")||y.get("refresh"))&&u()},[u]);const m=async()=>{var w,S;a(!0);const{data:y,error:v}=await q.functions.invoke("coach-stripe-connect");a(!1);let b=y==null?void 0:y.error;if(!b&&v)try{const A=await((S=(w=v==null?void 0:v.context)==null?void 0:w.json)==null?void 0:S.call(w));b=(A==null?void 0:A.error)||v.message}catch{b=v.message}if(b)return re.error(b,{duration:1e4});y!=null&&y.url&&(window.location.href=y.url)},f=d||{},g=!!(t!=null&&t.use_platform_stripe),x=g||f.connected&&f.charges_enabled;return e.jsx(Vs,{title:"Coaching · Billing",children:e.jsxs("div",{className:"max-w-3xl mx-auto p-4 md:p-8 space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>s("/coaching"),children:e.jsx(Va,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-2xl font-bold",children:"Billing & Packages"})]}),e.jsx(je,{children:e.jsxs(Ie,{className:"p-6 space-y-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx(Nv,{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(ll,{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(Fr,{className:"h-4 w-4 ml-1"})]})]})}),e.jsx(je,{children:e.jsxs(Ie,{className:"p-6 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Packages"}),e.jsxs($,{size:"sm",onClick:()=>{c(null),l(!0)},disabled:!x,children:[e.jsx(dn,{className:"h-4 w-4 mr-1"})," New Package"]})]}),!x&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Connect Stripe before creating packages."}),h.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No packages yet."}):e.jsx("div",{className:"space-y-2",children:h.map(y=>e.jsxs("div",{className:"flex items-center gap-3 p-3 border rounded-lg",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium flex items-center gap-2",children:[y.name,y.is_active&&y.accepting_clients===!1&&e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full bg-amber-100 text-amber-800 font-semibold",children:"Booked full"})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:["$",(y.price_cents/100).toFixed(0)," / ",y.billing_interval,!y.is_active&&" · Inactive"]})]}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>{c(y),l(!0)},children:e.jsx(pi,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:async()=>{await fo("Delete this package?")&&(await q.from("coaching_packages").delete().eq("id",y.id),n.invalidateQueries({queryKey:["coach-packages",t==null?void 0:t.id]}))},children:e.jsx(Hn,{className:"h-4 w-4"})})]},y.id))})]})}),e.jsx(J$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 J$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,y]=j.useState(!0),[v,b]=j.useState(!1);j.useEffect(()=>{s&&(l((r==null?void 0:r.name)||""),c((r==null?void 0:r.description)||""),u(r?(r.price_cents/100).toString():""),m((r==null?void 0:r.billing_interval)||"month"),g((r==null?void 0:r.is_active)??!0),y((r==null?void 0:r.accepting_clients)??!0))},[s,r]);const w=async()=>{if(!i.trim()||!d)return re.error("Name and price required");b(!0);const S={coach_id:n,name:i,description:o||null,price_cents:Math.round(Number(d)*100),billing_interval:h,is_active:f,accepting_clients:x},{error: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 re.error(A.message);re.success("Saved"),a==null||a(),t(!1)};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsx(Bs,{children:r!=null&&r.id?"Edit Package":"New Package"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(pe,{placeholder:"Name (e.g. Accelerator)",value:i,onChange:S=>l(S.target.value)}),e.jsx(Ls,{rows:3,placeholder:"What's included",value:o,onChange:S=>c(S.target.value)}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Price (USD)"}),e.jsx(pe,{type:"number",value:d,onChange:S=>u(S.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Interval"}),e.jsxs(ms,{value:h,onValueChange:m,children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"month",children:"Monthly"}),e.jsx(Ge,{value:"year",children:"Yearly"}),e.jsx(Ge,{value:"one_time",children:"One-time"})]})]})]})]}),e.jsxs("div",{className:"space-y-2 pt-1",children:[e.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[e.jsx("input",{type:"checkbox",checked:f,onChange:S=>g(S.target.checked)}),"Active (visible to agents)"]}),e.jsxs("label",{className:"flex items-start gap-2 text-sm",children:[e.jsx("input",{type:"checkbox",className:"mt-0.5",checked:x,onChange:S=>y(S.target.checked)}),e.jsxs("span",{children:[e.jsx("span",{className:"font-medium",children:"Accepting new clients"}),e.jsx("span",{className:"block text-xs text-muted-foreground",children:"Uncheck if you're booked full — visitors will still see the package but can't sign up."})]})]})]})]}),e.jsxs(Sr,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx($,{onClick:w,disabled:v,children:r!=null&&r.id?"Save":"Create"})]})]})})}function Ivt({kind:s,value:t,onChange:n}){const r=j.useRef(null),[a,i]=j.useState(!1),[l,o]=j.useState(!1),[c,d]=j.useState(null),u=j.useRef(null),h=j.useRef(null),m=j.useRef(null),f=j.useRef([]),[g,x]=j.useState(!1),y=s==="photo"?"image/*":"video/*",v=s==="photo"?10*1024*1024:200*1024*1024,b=async(P,R)=>{var G;const{data:D}=await q.auth.getUser(),O=(G=D.user)==null?void 0:G.id;if(!O)return re.error("Not signed in");if(P.size>v)return re.error(`File too large. Max ${s==="photo"?"10MB":"200MB"}.`);i(!0);const U=`${O}/${s}-${Date.now()}.${R}`,{error:W}=await q.storage.from("coach-media").upload(U,P,{upsert:!0,contentType:P.type||(s==="photo"?"image/jpeg":"video/webm")});if(W)return i(!1),re.error(W.message);const{data:V}=await q.storage.from("coach-media").createSignedUrl(U,60*60*24*365*10);i(!1),V!=null&&V.signedUrl&&(n(V.signedUrl),re.success("Uploaded"),d(null))},w=async P=>{const R=P.name.split(".").pop()||(s==="photo"?"jpg":"webm");await b(P,R)},S=async()=>{try{const P=await navigator.mediaDevices.getUserMedia({video:!0,audio:!0});h.current=P,x(!0),setTimeout(()=>{u.current&&(u.current.srcObject=P,u.current.play())},50);const R=new MediaRecorder(P,{mimeType:"video/webm"});f.current=[],R.ondataavailable=D=>D.data.size>0&&f.current.push(D.data),R.onstop=()=>{const D=new Blob(f.current,{type:"video/webm"});d(D),P.getTracks().forEach(O=>O.stop())},m.current=R,R.start(),o(!0)}catch(P){re.error(P.message||"Could not access camera")}},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:y,className:"hidden",onChange:P=>{var D;const R=(D=P.target.files)==null?void 0:D[0];R&&w(R),P.target.value=""}}),e.jsxs($,{type:"button",variant:"outline",size:"sm",disabled:a,onClick:()=>{var P;return(P=r.current)==null?void 0:P.click()},children:[a?e.jsx(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(Sx,{className:"h-4 w-4 mr-1"})," Record intro"]}),t&&e.jsxs($,{type:"button",variant:"ghost",size:"sm",onClick:()=>n(""),children:[e.jsx(Hn,{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(j_,{className:"h-4 w-4 mr-1"})," Stop"]}),!c&&!l&&e.jsxs($,{type:"button",size:"sm",onClick:()=>{var P;return(P=m.current)==null?void 0:P.start()},children:[e.jsx(ua,{className:"h-4 w-4 mr-1"})," Start"]}),c&&e.jsxs(e.Fragment,{children:[e.jsxs($,{type:"button",size:"sm",onClick:I,disabled:a,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[a?e.jsx(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 g$t(){const{user:s}=bs(),t=Wt(),n=st({queryKey:["booking-settings",s==null?void 0:s.id],queryFn:async()=>{const{data:y,error:v}=await q.from("agent_booking_settings").select("*").eq("user_id",s.id).maybeSingle();if(v)throw v;return y},enabled:!!s}),r=st({queryKey:["booking-types",s==null?void 0:s.id],queryFn:async()=>{const{data:y,error:v}=await q.from("agent_booking_types").select("*").eq("user_id",s.id).order("sort_order");if(v)throw v;return y},enabled:!!s}),a=st({queryKey:["availability-slots",s==null?void 0:s.id],queryFn:async()=>{const{data:y,error:v}=await q.from("agent_availability_slots").select("*").eq("user_id",s.id).order("day_of_week").order("start_time");if(v)throw v;return y},enabled:!!s}),i=st({queryKey:["blocked-dates",s==null?void 0:s.id],queryFn:async()=>{const{data:y,error:v}=await q.from("agent_blocked_dates").select("*").eq("user_id",s.id).order("blocked_date");if(v)throw v;return y},enabled:!!s}),l=st({queryKey:["bookings",s==null?void 0:s.id],queryFn:async()=>{const{data:y,error:v}=await q.from("bookings").select("*, booking_type:agent_booking_types(*)").eq("agent_user_id",s.id).order("booking_date",{ascending:!1});if(v)throw v;return y},enabled:!!s}),o=mt({mutationFn:async()=>{const{data:y,error:v}=await q.from("agent_booking_settings").insert({user_id:s.id,slug:""}).select().single();if(v)throw v;const b=[{name:"Listing Consultation",description:"Get a comprehensive market analysis and listing strategy for your home",duration_minutes:60,color:"#10B981",icon:"Home",sort_order:0},{name:"Buyer Consultation",description:"Discuss your home search criteria, budget, and buying process",duration_minutes:45,color:"#3B82F6",icon:"Search",sort_order:1},{name:"Home Valuation",description:"Find out what your home is worth in today's market",duration_minutes:30,color:"#F59E0B",icon:"DollarSign",sort_order:2},{name:"General Meeting",description:"Coffee chat, check-in, or quick real estate question",duration_minutes:30,color:"#8B5CF6",icon:"Coffee",sort_order:3}],{error:w}=await q.from("agent_booking_types").insert(b.map(E=>({...E,user_id:s.id})));if(w)throw w;const S=[1,2,3,4,5].map(E=>({user_id:s.id,day_of_week:E,start_time:"09:00",end_time:"17:00"})),{error:A}=await q.from("agent_availability_slots").insert(S);if(A)throw A;return y},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-settings"]}),t.invalidateQueries({queryKey:["booking-types"]}),t.invalidateQueries({queryKey:["availability-slots"]}),re.success("Scheduler set up successfully!")},onError:y=>re.error(y.message)}),c=mt({mutationFn:async y=>{const{error:v}=await q.from("agent_booking_settings").update(y).eq("user_id",s.id);if(v)throw v},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-settings"]}),re.success("Settings updated")},onError:y=>re.error(y.message)}),d=mt({mutationFn:async y=>{const v={...y,user_id:s.id};if(y.id){const{error:b}=await q.from("agent_booking_types").update(v).eq("id",y.id);if(b)throw b}else{const{error:b}=await q.from("agent_booking_types").insert(v);if(b)throw b}},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-types"]}),re.success("Booking type saved")},onError:y=>re.error(y.message)}),u=mt({mutationFn:async y=>{const{error:v}=await q.from("agent_booking_types").delete().eq("id",y);if(v)throw v},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-types"]}),re.success("Booking type deleted")},onError:y=>re.error(y.message)}),h=mt({mutationFn:async y=>{const v={...y,user_id:s.id};if(y.id){const{error:b}=await q.from("agent_availability_slots").update(v).eq("id",y.id);if(b)throw b}else{const{error:b}=await q.from("agent_availability_slots").insert(v);if(b)throw b}},onSuccess:()=>{t.invalidateQueries({queryKey:["availability-slots"]})},onError:y=>re.error(y.message)}),m=mt({mutationFn:async y=>{const{error:v}=await q.from("agent_availability_slots").delete().eq("id",y);if(v)throw v},onSuccess:()=>{t.invalidateQueries({queryKey:["availability-slots"]})},onError:y=>re.error(y.message)}),f=mt({mutationFn:async y=>{const{blocked_date:v,end_date:b,reason:w}=y,S=D=>{const[O,U,W]=D.split("-").map(Number);return new Date(O,U-1,W)},A=D=>`${D.getFullYear()}-${String(D.getMonth()+1).padStart(2,"0")}-${String(D.getDate()).padStart(2,"0")}`,E=S(v),I=b?S(b):E;if(I366)throw new Error("Range too large (max 1 year)");const{error:R}=await q.from("agent_blocked_dates").upsert(P,{onConflict:"user_id,blocked_date",ignoreDuplicates:!0});if(R)throw R;return P.length},onSuccess:y=>{t.invalidateQueries({queryKey:["blocked-dates"]}),re.success(y&&y>1?`${y} dates blocked`:"Date blocked")},onError:y=>re.error(y.message)}),g=mt({mutationFn:async y=>{const{error:v}=await q.from("agent_blocked_dates").delete().eq("id",y);if(v)throw v},onSuccess:()=>{t.invalidateQueries({queryKey:["blocked-dates"]})},onError:y=>re.error(y.message)}),x=mt({mutationFn:async({id:y,reason:v})=>{const{error:b}=await q.from("bookings").update({status:"cancelled",cancelled_at:new Date().toISOString(),cancel_reason:v}).eq("id",y);if(b)throw b;await q.functions.invoke("agent-booking",{body:{action:"cancel",booking_id:y}}).catch(w=>console.error("Google calendar cleanup failed:",w))},onSuccess:()=>{t.invalidateQueries({queryKey:["bookings"]}),re.success("Booking cancelled")},onError:y=>re.error(y.message)});return{settings:n.data,bookingTypes:r.data??[],availability:a.data??[],blockedDates:i.data??[],bookings:l.data??[],isLoading:n.isLoading,initializeSettings:o,updateSettings:c,upsertBookingType:d,deleteBookingType:u,upsertAvailability:h,deleteAvailability:m,addBlockedDate:f,removeBlockedDate:g,cancelBooking:x}}const Lvt=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];function x$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=Lvt.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(da,{className:"h-5 w-5"}),"Weekly Availability"]}),e.jsx(Gn,{children:"Set your available hours for each day"})]}),e.jsx(Ie,{className:"space-y-2",children:Lvt.map((h,m)=>{const f=d[m];return e.jsxs("div",{className:"flex items-start gap-3 py-2 border-b last:border-0",children:[e.jsx("div",{className:"w-24 pt-1",children:e.jsx("p",{className:"text-sm font-medium",children:h})}),e.jsxs("div",{className:"flex-1 space-y-1",children:[f.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-1",children:"Unavailable"}):f.map(g=>{var x,y;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pe,{type:"time",className:"w-28 h-8 text-sm",defaultValue:(x=g.start_time)==null?void 0:x.slice(0,5),onBlur:v=>t({id:g.id,start_time:v.target.value})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"to"}),e.jsx(pe,{type:"time",className:"w-28 h-8 text-sm",defaultValue:(y=g.end_time)==null?void 0:y.slice(0,5),onBlur:v=>t({id:g.id,end_time:v.target.value})}),e.jsx(Sn,{checked:g.is_active,onCheckedChange:v=>t({id:g.id,is_active:v})}),e.jsx($,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>n(g.id),children:e.jsx(Hn,{className:"h-3.5 w-3.5 text-muted-foreground"})})]},g.id)}),r===m?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pe,{type:"time",className:"w-28 h-8 text-sm",value:i,onChange:g=>l(g.target.value)}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"to"}),e.jsx(pe,{type:"time",className:"w-28 h-8 text-sm",value:o,onChange:g=>c(g.target.value)}),e.jsx($,{size:"sm",className:"h-8",onClick:u,children:"Add"}),e.jsx($,{variant:"ghost",size:"sm",className:"h-8",onClick:()=>a(null),children:"Cancel"})]}):e.jsxs($,{variant:"ghost",size:"sm",className:"h-7 text-xs text-muted-foreground",onClick:()=>a(m),children:[e.jsx(dn,{className:"h-3 w-3 mr-1"})," Add hours"]})]})]},h)})})]})}function Rvt(s){const[t,n,r]=s.split("-").map(Number);return en(new Date(t,n-1,r),"MMM d, yyyy")}function eUs(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 y$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(kq,{className:"h-5 w-5"}),"Blocked Dates"]}),e.jsx(Gn,{children:"Block a single day or a full date range (vacations, holidays, etc.)"})]}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>a(!0),children:[e.jsx(dn,{className:"h-4 w-4 mr-1"})," Block Dates"]})]}),e.jsxs(Ie,{children:[r&&e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-3 p-3 rounded-lg border bg-muted/30",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pe,{type:"date",value:i,onChange:m=>l(m.target.value),className:"w-40"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"to"}),e.jsx(pe,{type:"date",value:o,min:i||void 0,onChange:m=>c(m.target.value),className:"w-40",placeholder:"Optional"})]}),e.jsx(pe,{placeholder:"Reason (optional)",value:d,onChange:m=>u(m.target.value),className:"flex-1 min-w-[180px]"}),e.jsx($,{size:"sm",onClick:h,children:"Add"}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>a(!1),children:"Cancel"})]}),s.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No blocked dates"}):e.jsx("div",{className:"flex flex-wrap gap-2",children:eUs(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:[Rvt(m.start),m.end!==m.start&&` – ${Rvt(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(pr,{className:"h-3.5 w-3.5"})})]},m.ids[0]))})]})]})}function tUs(){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}=g$t(),[f,g]=j.useState("1-on-1 Coaching Session"),[x,y]=j.useState(45),v=j.useMemo(()=>t.filter(w=>w.is_coaching_only),[t]);if(a)return e.jsx(je,{children:e.jsxs(Ie,{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(Cu,{className:"h-5 w-5"})," Coaching calendar"]}),e.jsx(Gn,{children:"Set up your scheduler once, then open availability for the members assigned to you."})]}),e.jsx(Ie,{children:e.jsxs($,{onClick:()=>i.mutate(),disabled:i.isPending,children:[i.isPending&&e.jsx(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"),y(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(ua,{className:"h-5 w-5"})," Coaching session types"]}),e.jsx(Gn,{children:"Only assigned members can book these. They stay hidden from your public booking page."})]}),e.jsxs(Ie,{className:"space-y-3",children:[v.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No coaching session type yet — add one below so members can book you."}):v.map(w=>e.jsxs("div",{className:"flex flex-wrap items-center gap-3 rounded-lg border p-3",children:[e.jsx(pe,{className:"h-9 max-w-[240px]",defaultValue:w.name,onBlur:S=>S.target.value!==w.name&&o.mutate({id:w.id,name:S.target.value})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pe,{type:"number",min:10,max:240,step:5,className:"h-9 w-20",defaultValue:w.duration_minutes,onBlur:S=>o.mutate({id:w.id,duration_minutes:parseInt(S.target.value)||30})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"min"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sn,{checked:w.is_active,onCheckedChange:S=>o.mutate({id:w.id,is_active:S})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:w.is_active?"Bookable":"Paused"})]}),e.jsx($e,{variant:"secondary",children:"Coaching only"}),e.jsx($,{variant:"ghost",size:"sm",className:"ml-auto h-8 w-8 p-0",onClick:async()=>{await fo({title:"Delete session type?",description:`"${w.name}" will no longer be bookable.`,confirmText:"Delete",destructive:!0})&&c.mutate(w.id)},children:e.jsx(Hn,{className:"h-3.5 w-3.5 text-muted-foreground"})})]},w.id)),e.jsxs("div",{className:"flex flex-wrap items-end gap-2 pt-2 border-t",children:[e.jsxs("div",{className:"flex-1 min-w-[200px]",children:[e.jsx(ee,{className:"text-xs",children:"New session type"}),e.jsx(pe,{value:f,onChange:w=>g(w.target.value),className:"h-9"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Minutes"}),e.jsx(pe,{type:"number",min:10,max:240,step:5,className:"h-9 w-24",value:x,onChange:w=>y(parseInt(w.target.value)||30)})]}),e.jsxs($,{onClick:b,disabled:o.isPending,children:[e.jsx(dn,{className:"h-4 w-4 mr-1"})," Add"]})]})]})]}),e.jsx(x$t,{slots:n,onSave:w=>d.mutate(w),onDelete:w=>u.mutate(w)}),e.jsx(y$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(Gn,{children:"Applies to coaching bookings on your calendar."})]}),e.jsxs(Ie,{className:"grid gap-4 sm:grid-cols-3",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Buffer between sessions (min)"}),e.jsx(pe,{type:"number",min:0,max:120,step:5,className:"h-9",defaultValue:s.buffer_minutes,onBlur:w=>l.mutate({buffer_minutes:parseInt(w.target.value)||0})})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Minimum notice (hours)"}),e.jsx(pe,{type:"number",min:0,max:168,className:"h-9",defaultValue:s.min_notice_hours,onBlur:w=>l.mutate({min_notice_hours:parseInt(w.target.value)||0})})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Bookable up to (days out)"}),e.jsx(pe,{type:"number",min:1,max:365,className:"h-9",defaultValue:s.max_advance_days,onBlur:w=>l.mutate({max_advance_days:parseInt(w.target.value)||30})})]})]})]})]})}async function AZ(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 v$t(s=!0,t="coach"){const n=Wt(),r=st({queryKey:["google-calendar-connection",t],enabled:s,queryFn:async()=>await AZ(t,{action:"status"})}),a=()=>n.invalidateQueries({queryKey:["google-calendar-connection",t]}),i=mt({mutationFn:async()=>{const d=await AZ(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:()=>AZ(t,{action:"disconnect"}),onSuccess:a}),o=mt({mutationFn:d=>AZ(t,{action:"settings",...d}),onSuccess:a}),c=mt({mutationFn:()=>AZ(t,{action:"refresh_calendars"}),onSuccess:a});return{status:r,connect:i,disconnect:l,updateSettings:o,refreshCalendars:c}}function b$t({scope:s="coach"}){const{status:t,connect:n,disconnect:r,updateSettings:a,refreshCalendars:i}=v$t(!0,s),l=s==="agent";j.useEffect(()=>{const d=new URLSearchParams(window.location.search),u=d.get("google_calendar");if(!u)return;u==="connected"?(re.success("Google Calendar connected"),t.refetch()):re.error(d.get("google_calendar_error")||"Google connection failed."),d.delete("google_calendar"),d.delete("google_calendar_error");const h=d.toString();window.history.replaceState({},"",window.location.pathname+(h?`?${h}`:""))},[]);const o=t.data,c=t.error;return e.jsxs(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(xb,{className:"h-5 w-5"})," Google Calendar"]}),e.jsx(Gn,{children:l?"Hide times you're already booked on Google, and push every new booking straight onto your calendar.":"Hide times you're already booked on Google, and push new coaching sessions straight onto your calendar."})]}),(o==null?void 0:o.connected)&&e.jsxs($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(Ie,{className:"space-y-4",children:[t.isLoading&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(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(ll,{className:"h-4 w-4 mt-0.5 text-destructive shrink-0"}),e.jsx("span",{children:c.message})]}),o&&!o.configured&&e.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-amber-400/50 bg-amber-50 dark:bg-amber-950/20 p-3 text-sm",children:[e.jsx(ll,{className:"h-4 w-4 mt-0.5 text-amber-600 shrink-0"}),e.jsx("span",{children:"Google Calendar isn't switched on for LevelUp yet. Once an admin finishes the one-time Google setup, you'll be able to connect right here."})]}),(o==null?void 0:o.configured)&&!o.connected&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Not connected. Your availability comes only from the hours you set in LevelUp."}),e.jsxs($,{onClick:()=>n.mutate(void 0,{onSuccess:()=>re.success("Google Calendar connected"),onError:d=>re.error(d.message)}),disabled:n.isPending,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[n.isPending?e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(xb,{className:"h-4 w-4 mr-2"}),n.isPending?"Connecting…":"Connect Google Calendar"]}),n.isError&&e.jsx("p",{className:"text-sm text-destructive",children:n.error.message})]}),(o==null?void 0:o.connected)&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3 text-sm",children:[e.jsx("div",{className:"font-medium",children:o.account_email||"Google account"}),o.connected_at&&e.jsxs("div",{className:"text-muted-foreground text-xs",children:["Connected ",new Date(o.connected_at).toLocaleDateString()]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm",children:"Two-way sync"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:l?"Block busy times and add new bookings to Google.":"Block busy times and add booked sessions to Google."})]}),e.jsx(Sn,{checked:o.sync_enabled,onCheckedChange:d=>a.mutate({sync_enabled:d},{onError:u=>re.error(u.message)})})]}),l&&e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm",children:"Invite the guest"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Send a Google invite when they leave an email address."})]}),e.jsx(Sn,{checked:o.invite_guest!==!1,onCheckedChange:d=>a.mutate({invite_guest:d},{onError:u=>re.error(u.message)})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Calendar to use"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(ms,{value:o.selected_calendar_id||"primary",onValueChange:d=>a.mutate({calendar_id:d},{onError:u=>re.error(u.message)}),children:[e.jsx(us,{className:"h-9",children:e.jsx(fs,{placeholder:"Primary calendar"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"primary",children:"Primary calendar"}),o.calendars.filter(d=>!d.primary).map(d=>e.jsx(Ge,{value:d.id,children:d.summary||d.id},d.id))]})]}),e.jsx($,{variant:"outline",size:"icon",className:"h-9 w-9 shrink-0",onClick:()=>i.mutate(void 0,{onSuccess:()=>re.success("Calendars refreshed"),onError:d=>re.error(d.message)}),disabled:i.isPending,children:e.jsx(ro,{className:`h-4 w-4 ${i.isPending?"animate-spin":""}`})})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 pt-1",children:[e.jsxs($,{variant:"outline",size:"sm",onClick:()=>n.mutate(void 0,{onSuccess:()=>re.success("Google Calendar reconnected"),onError:d=>re.error(d.message)}),disabled:n.isPending,children:[n.isPending?e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(ro,{className:"h-4 w-4 mr-2"}),"Reconnect"]}),e.jsxs($,{variant:"ghost",size:"sm",className:"text-destructive",disabled:r.isPending,onClick:async()=>{await fo({title:"Disconnect Google Calendar?",description:"Busy times will stop hiding and new sessions won't be added to Google.",confirmText:"Disconnect",destructive:!0})&&r.mutate(void 0,{onSuccess:()=>re.success("Google Calendar disconnected"),onError:u=>re.error(u.message)})},children:[e.jsx(lV,{className:"h-4 w-4 mr-2"})," Disconnect"]})]})]})]})]})}function sUs(){const s=Xn(),{data:t,isLoading:n}=Yae(),r=Wt(),[a,i]=j.useState(""),[l,o]=j.useState(""),[c,d]=j.useState(""),[u,h]=j.useState(""),[m,f]=j.useState(""),[g,x]=j.useState(!1),[y,v]=j.useState([]),[b,w]=j.useState(""),[S,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),v(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:y,default_sessions_per_month:S}).eq("id",t.id);if(I(!1),U)return re.error(U.message);re.success("Profile saved"),r.invalidateQueries({queryKey:["my-coach-profile"]})},R=()=>{const U=b.trim();if(U){if(y.includes(U))return w("");v([...y,U]),w("")}};if(n)return e.jsx(Vs,{title:"Coach Settings",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!t)return e.jsx(Vs,{title:"Coach Settings",children:e.jsx("div",{className:"max-w-2xl mx-auto p-8 text-center text-muted-foreground",children:"You don't have a coach profile yet."})});const D=t,O=D.slug?`${window.location.origin}/coaches/${D.slug}`:null;return e.jsx(Vs,{title:"Coach Settings",children:e.jsxs("div",{className:"max-w-3xl mx-auto p-4 md:p-8 space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>s("/coaching"),children:e.jsx(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(Fr,{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(Ie,{className:"p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border bg-muted/30",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:"Accepting new clients"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"When off, you're hidden from the public directory."})]}),e.jsx(Sn,{checked:g,onCheckedChange:x})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Public URL slug"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:"/coaches/"}),e.jsx(pe,{value:a,onChange:U=>i(U.target.value.toLowerCase().replace(/[^a-z0-9-]/g,"")),placeholder:"your-name"})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Headline"}),e.jsx(pe,{value:l,onChange:U=>o(U.target.value),placeholder:"e.g. Helping new agents close their first 10 deals",maxLength:140})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Bio"}),e.jsx(Ls,{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(Ivt,{kind:"photo",value:u,onChange:h})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Intro video"}),e.jsx(Ivt,{kind:"video",value:m,onChange:f})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Specialties"}),e.jsx("div",{className:"flex flex-wrap gap-2 mb-2",children:y.map(U=>e.jsxs($e,{variant:"secondary",className:"gap-1",children:[U,e.jsx("button",{onClick:()=>v(y.filter(W=>W!==U)),children:e.jsx(pr,{className:"h-3 w-3"})})]},U))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{value:b,onChange:U=>w(U.target.value),placeholder:"Add a specialty…",onKeyDown:U=>{U.key==="Enter"&&(U.preventDefault(),R())}}),e.jsx($,{type:"button",variant:"outline",onClick:R,children:e.jsx(dn,{className:"h-4 w-4"})})]})]})]})}),e.jsx(je,{children:e.jsxs(Ie,{className:"p-6 space-y-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Coaching calendar"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Open availability right here — assigned members book you from their ",e.jsx("strong",{children:"My Coach → Book"})," tab. These session types never show on your public booking page."]})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-end gap-4",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(ee,{children:"Sessions each agent can book per month"}),e.jsx(pe,{type:"number",min:1,max:31,value:S,onChange:U=>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(b$t,{}),e.jsx(tUs,{}),e.jsx(je,{children:e.jsx(Ie,{className:"p-6",children:e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Packages & Stripe"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Manage your monetized packages on the Billing page."})]}),e.jsx($,{variant:"outline",onClick:()=>s("/coaching/billing"),children:"Go to Billing"})]})})}),e.jsx(nUs,{coachId:D.id})]})})}function nUs({coachId:s}){const[t,n]=j.useState("");Wt();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 re.error("Email required");const{error:d}=await q.from("coaching_invites").insert({coach_id:s,email:c});if(d)return re.error(d.message);n(""),re.success("Invite created"),a()},l=c=>{const d=`${window.location.origin}/auth?coach_invite=${c}`;navigator.clipboard.writeText(d),re.success("Link copied")},o=async c=>{await fo("Revoke this invite?")&&(await q.from("coaching_invites").delete().eq("id",c),a())};return e.jsx(je,{children:e.jsxs(Ie,{className:"p-6 space-y-3",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx(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(dn,{className:"h-4 w-4 mr-1"})," Create"]})]}),e.jsxs("div",{className:"space-y-2",children:[r.map(c=>e.jsxs("div",{className:"flex items-center gap-2 p-3 border rounded-lg",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium truncate",children:c.email}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[c.status," · expires ",new Date(c.expires_at).toLocaleDateString()]})]}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>l(c.token),children:e.jsx(Ha,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>o(c.id),children:e.jsx(Hn,{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 rUs="google_calendar";function aUs(){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:rUs,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 Kce=[{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 iUs(){const s=Xn(),t=Wt(),{data:n,isLoading:r}=Yae(),[a,i]=j.useState("pending"),[l,o]=j.useState(""),[c,d]=j.useState(null),[u,h]=j.useState(!1),[m,f]=j.useState(""),[g,x]=j.useState(!1),[y,v]=j.useState(""),{data:b=[],isLoading:w}=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 Kce)D[O.value]=0;for(const O of b)D[O.status]=(D[O.status]||0)+1;return D},[b]),E=async(D,O)=>{const{error:U}=await q.from("coaching_waitlist").update(O).eq("id",D);if(U)return re.error(U.message);t.invalidateQueries({queryKey:["coaching-waitlist",n==null?void 0:n.id]}),(c==null?void 0:c.id)===D&&d(W=>({...W,...O}))},I=async D=>{if(!await fo("Remove this person from the waitlist?"))return;const{error:O}=await q.from("coaching_waitlist").delete().eq("id",D);if(O)return re.error(O.message);re.success("Removed"),t.invalidateQueries({queryKey:["coaching-waitlist",n==null?void 0:n.id]}),d(null)},P=async()=>{if(!c)return;const{data:D,error:O}=await q.functions.invoke("coaching-waitlist-invite",{body:{waitlistId:c.id,message:m}});if(O||D!=null&&D.error)return re.error((D==null?void 0:D.error)||(O==null?void 0:O.message)||"Could not send invite");re.success(`Invite sent to ${c.name}`),h(!1),f(""),t.invalidateQueries({queryKey:["coaching-waitlist",n==null?void 0:n.id]})},R=async()=>{if(!n)return;const{data:D,error:O}=await q.functions.invoke("coaching-waitlist-invite",{body:{coachId:n.id,notifyAll:!0,message:y}});if(O||D!=null&&D.error)return re.error((D==null?void 0:D.error)||(O==null?void 0:O.message)||"Could not notify");re.success(`Notified ${(D==null?void 0:D.count)||0} agents`),x(!1),v(""),t.invalidateQueries({queryKey:["coaching-waitlist",n==null?void 0:n.id]})};return r?e.jsx(Vs,{title:"Waitlist",children:e.jsx("div",{className:"p-8",children:"Loading…"})}):n?e.jsxs(Vs,{title:"Coaching Waitlist",children:[e.jsxs("div",{className:"p-4 md:p-8 max-w-7xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[e.jsxs("div",{children:[e.jsxs($,{variant:"ghost",size:"sm",className:"mb-2 -ml-2",onClick:()=>s("/coaching"),children:[e.jsx(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(zg,{className:"h-6 w-6 text-[#406E71]"}),"Waitlist"]}),e.jsx("p",{className:"text-muted-foreground text-sm mt-1",children:"Agents waiting for a spot to open up with you."})]}),e.jsxs($,{variant:"outline",onClick:()=>x(!0),disabled:!A.pending,title:A.pending?"":"No pending applicants",children:[e.jsx(Vz,{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,")"]}),Kce.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(Ie,{className:"p-10 text-center text-muted-foreground",children:"No entries here yet."})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:S.map(D=>{const O=Kce.find(U=>U.value===D.status);return e.jsx(je,{className:"cursor-pointer hover:shadow-md transition-shadow",onClick:()=>d(D),children:e.jsxs(Ie,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-semibold truncate",children:D.name}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:D.email}),D.brokerage&&e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:D.brokerage})]}),e.jsx($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(zs,{open:!!c,onOpenChange:D=>!D&&d(null),children:e.jsx(Os,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:c&&e.jsxs(e.Fragment,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:c.name}),e.jsxs(Pr,{children:["Joined ",hu(new Date(c.created_at),{addSuffix:!0})]})]}),e.jsxs("div",{className:"space-y-3 text-sm",children:[e.jsx(EZ,{label:"Email",value:c.email}),e.jsx(EZ,{label:"Phone",value:c.phone}),e.jsx(EZ,{label:"Brokerage",value:c.brokerage}),e.jsx(EZ,{label:"Years",value:c.years_in_business}),e.jsx(EZ,{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:Kce.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(Ls,{rows:3,defaultValue:c.coach_notes||"",onBlur:D=>{D.target.value!==(c.coach_notes||"")&&E(c.id,{coach_notes:D.target.value})}})]})]}),e.jsxs(Sr,{className:"flex-wrap gap-2",children:[e.jsxs($,{variant:"outline",className:"text-destructive",onClick:()=>I(c.id),children:[e.jsx(Hn,{className:"h-4 w-4 mr-1"})," Remove"]}),e.jsx($,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:`mailto:${c.email}`,children:[e.jsx(mn,{className:"h-4 w-4 mr-1"})," Email directly"]})}),e.jsxs($,{className:"bg-[#406E71] hover:bg-[#2a4c64]",onClick:()=>{f(""),h(!0)},children:[e.jsx(Kr,{className:"h-4 w-4 mr-1"})," Invite to subscribe"]})]})]})})}),e.jsx(zs,{open:u,onOpenChange:h,children:e.jsxs(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Invite to subscribe"}),e.jsxs(Pr,{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(Ls,{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(Sr,{children:[e.jsx($,{variant:"outline",onClick:()=>h(!1),children:"Cancel"}),e.jsxs($,{className:"bg-[#406E71] hover:bg-[#2a4c64]",onClick:P,children:[e.jsx(Kr,{className:"h-4 w-4 mr-1"})," Send invite"]})]})]})}),e.jsx(zs,{open:g,onOpenChange:x,children:e.jsxs(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Notify all pending applicants"}),e.jsx(Pr,{children:"Send everyone with status “Pending” an email letting them know spots are opening up. They'll each be marked “Invited”."})]}),e.jsx(Ls,{rows:4,placeholder:"Good news — I just opened up new coaching spots…",value:y,onChange:D=>v(D.target.value)}),e.jsxs(Sr,{children:[e.jsx($,{variant:"outline",onClick:()=>x(!1),children:"Cancel"}),e.jsxs($,{className:"bg-[#406E71] hover:bg-[#2a4c64]",onClick:R,children:[e.jsx(Vz,{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 EZ({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 oUs(){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(Nn,{className:"h-3.5 w-3.5 text-yellow-300"}),"LevelUp Certified Coaches"]}),e.jsxs("h1",{className:"text-5xl md:text-7xl font-bold tracking-tight leading-[1.05]",children:["Coaching that ",e.jsx("span",{className:"bg-gradient-to-r from-yellow-300 to-yellow-100 bg-clip-text text-transparent",children:"moves the needle."})]}),e.jsx("p",{className:"text-white/75 mt-6 max-w-2xl mx-auto text-lg leading-relaxed",children:"Hand-picked real-estate coaches ready to help you hit your next breakthrough — from lead gen to listings to luxury."}),e.jsxs("div",{className:"flex flex-wrap justify-center gap-6 mt-10 text-sm text-white/70",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(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(wr,{to:`/coaches/${n.slug||n.id}`,className:"group",children:e.jsx("article",{className:"relative h-full rounded-2xl bg-[#1c3447] overflow-hidden transition-all duration-300 hover:-translate-y-1 hover:shadow-[0_24px_60px_-20px_rgba(42,76,100,0.5)]",children:e.jsxs("div",{className:"relative aspect-[3/4] w-full overflow-hidden",children:[a?e.jsx("img",{src:a,alt:r,className:"absolute inset-0 h-full w-full object-cover object-top group-hover:scale-105 transition-transform duration-700"}):e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-gradient-to-br from-[#2a4c64] to-[#406E71] text-white text-6xl font-bold",children:r.charAt(0)}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-[#0d1f2d] via-[#0d1f2d]/70 to-transparent"}),e.jsxs("div",{className:"absolute top-3 left-3 right-3 flex items-start justify-between gap-2",children:[n.is_certified?e.jsxs("div",{className:"inline-flex items-center gap-1 px-2.5 py-1 rounded-full bg-gradient-to-r from-yellow-400 to-yellow-300 text-[#2a4c64] text-[11px] font-semibold shadow-md",children:[e.jsx(Nn,{className:"h-3 w-3"})," Certified"]}):e.jsx("span",{}),e.jsxs("div",{className:`inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-[11px] font-medium backdrop-blur-md ${n.accepting_clients?"bg-emerald-500/90 text-white":"bg-white/85 text-[#2a4c64]"}`,children:[e.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${n.accepting_clients?"bg-white":"bg-amber-500"}`}),n.accepting_clients?"Accepting":"Waitlist"]})]}),e.jsxs("div",{className:"absolute inset-x-0 bottom-0 p-5 text-white",children:[e.jsx("h3",{className:"text-xl font-bold leading-tight drop-shadow-sm",children:r}),n.headline&&e.jsx("p",{className:"text-sm text-yellow-200/90 font-medium mt-1 line-clamp-1",children:n.headline}),n.bio&&e.jsx("p",{className:"text-[13px] text-white/80 mt-2 line-clamp-2 leading-relaxed",children:n.bio}),n.specialties&&n.specialties.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-3",children:n.specialties.slice(0,2).map(o=>e.jsx("span",{className:"text-[10px] px-2 py-0.5 rounded-full bg-white/15 backdrop-blur-sm text-white border border-white/20",children:o},o))}),e.jsxs("div",{className:"flex items-center justify-between mt-4 pt-3 border-t border-white/15",children:[e.jsx("span",{className:"text-sm font-semibold text-white",children:"View profile"}),e.jsx("span",{className:"inline-flex items-center justify-center h-8 w-8 rounded-full bg-white/15 backdrop-blur-sm text-white group-hover:bg-yellow-300 group-hover:text-[#1c3447] transition-colors",children:e.jsx(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(Nn,{className:"h-3.5 w-3.5 text-yellow-300"})," Coach Applications Open"]}),e.jsxs("h2",{className:"text-3xl md:text-4xl font-bold leading-tight",children:["Are you the kind of agent ",e.jsx("span",{className:"text-yellow-300",children:"other agents need?"})]}),e.jsx("p",{className:"text-white/80 mt-4 max-w-xl leading-relaxed",children:"LevelUp Coaches are the top 1% — top producers, proven mentors, and category leaders making a measurable difference in agents' businesses. If that's you, we want to meet you."}),e.jsxs("div",{className:"mt-6 flex flex-wrap gap-3 text-sm text-white/70",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(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(wr,{to:"/coaches/apply",className:"inline-flex items-center gap-2 bg-yellow-300 text-[#1c3447] hover:bg-yellow-200 font-bold px-7 py-4 rounded-xl shadow-lg shadow-yellow-300/20 transition-all hover:-translate-y-0.5",children:["Apply to coach ",e.jsx(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 lUs=z2({name:vl().trim().min(1,"Name required").max(120),email:vl().trim().email("Invalid email").max(255),phone:vl().trim().max(40).optional().or(yx("")),brokerage:vl().trim().max(160).optional().or(yx("")),years_in_business:vl().max(40).optional().or(yx("")),biggest_challenge:vl().trim().max(1e3).optional().or(yx("")),preferred_package:vl().max(120).optional().or(yx("")),message:vl().trim().max(1500).optional().or(yx(""))});function cUs({open:s,onOpenChange:t,coachId:n,coachName:r,packages:a=[]}){const{user:i}=bs(),[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=lUs.safeParse(c);if(!m.success){re.error(((g=m.error.issues[0])==null?void 0:g.message)||"Please check your entries");return}o(!0);const{error:f}=await q.from("coaching_waitlist").insert({coach_id:n,agent_user_id:(i==null?void 0:i.id)||null,name:c.name.trim(),email:c.email.trim().toLowerCase(),phone:c.phone||null,brokerage:c.brokerage||null,years_in_business:c.years_in_business||null,biggest_challenge:c.biggest_challenge||null,preferred_package:c.preferred_package||null,message:c.message||null,status:"pending"});if(o(!1),f){re.error(f.message||"Could not join waitlist");return}re.success(`You're on the waitlist${r?` for ${r}`:""}. We'll be in touch when a spot opens.`),t(!1),d({...c,biggest_challenge:"",message:""})};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{children:["Join the waitlist",r?` — ${r}`:""]}),e.jsx(Pr,{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(Ls,{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(Ls,{rows:2,value:c.message,onChange:m=>u("message",m.target.value)})]})]}),e.jsxs(Sr,{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 dUs(){var x;const{slug:s}=Wi(),t=Xn(),{user:n}=bs(),[r,a]=j.useState(null),[i,l]=j.useState(!1),{data:o,isLoading:c}=st({queryKey:["coach-public",s],enabled:!!s,queryFn:async()=>{const y=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(s||""),v=q.from("coaches").select("*"),{data:b}=y?await v.eq("id",s).maybeSingle():await v.eq("slug",s).maybeSingle();if(!b)return null;const[{data:w},{data:S}]=await Promise.all([q.from("profiles").select("id, name, avatar_url").eq("id",b.user_id).maybeSingle(),q.from("coaching_packages").select("*").eq("coach_id",b.id).eq("is_active",!0).order("sort_order")]);return{coach:b,profile:w,packages:S||[]}}}),d=async y=>{if(!n){re.error("Please sign in to subscribe"),t(`/auth?redirect=/coaches/${s}`);return}a(y);const{data:v,error:b}=await q.functions.invoke("create-coaching-checkout",{body:{packageId:y}});if(a(null),b||v!=null&&v.error){re.error((v==null?void 0:v.error)||(b==null?void 0:b.message)||"Checkout failed");return}v!=null&&v.url&&(window.location.href=v.url)};if(c)return e.jsx("div",{className:"p-12 text-center",children:"Loading…"});if(!(o!=null&&o.coach))return e.jsx("div",{className:"p-12 text-center",children:"Coach not found."});const{coach:u,profile:h,packages:m}=o,f=u,g=(y,v)=>{const b=(y/100).toLocaleString("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0});return v==="one_time"?b:`${b} / ${v}`};return e.jsxs("div",{className:"min-h-screen bg-background",children:[e.jsx("div",{className:"bg-gradient-to-br from-[#2a4c64] to-[#406E71] text-white",children:e.jsxs("div",{className:"max-w-5xl mx-auto px-4 py-12 md:py-20",children:[e.jsxs($,{variant:"ghost",size:"sm",className:"text-white/80 hover:text-white hover:bg-white/10 mb-6",onClick:()=>t("/coaches"),children:[e.jsx(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(Nn,{className:"h-3 w-3"})," LevelUp Certified"]}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold",children:(h==null?void 0:h.name)||"Coach"}),f.headline&&e.jsx("p",{className:"text-white/80 text-lg mt-2",children:f.headline}),((x=f.specialties)==null?void 0:x.length)>0&&e.jsx("div",{className:"flex flex-wrap gap-2 mt-4",children:f.specialties.map(y=>e.jsx($e,{className:"bg-white/15 text-white border-white/20",children:y},y))})]})]})]})}),e.jsxs("div",{className:"max-w-5xl mx-auto px-4 py-12 grid grid-cols-1 md:grid-cols-3 gap-8",children:[e.jsxs("div",{className:"md:col-span-2 space-y-6",children:[f.intro_video_url&&e.jsx("div",{className:"aspect-video rounded-xl overflow-hidden bg-black",children:e.jsx("video",{src:f.intro_video_url,controls:!0,className:"w-full h-full"})}),f.bio&&e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-semibold mb-3",children:"About"}),e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap leading-relaxed",children:f.bio})]}),e.jsx(B$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(Ie,{className:"p-6 text-sm text-muted-foreground text-center",children:"No packages available yet."})}):m.map(y=>{const v=y.accepting_clients===!1;return e.jsx(je,{className:`border-2 transition-colors ${v?"border-amber-200 bg-amber-50/30":"hover:border-[#406E71]"}`,children:e.jsxs(Ie,{className:"p-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("h3",{className:"font-semibold text-lg",children:y.name}),v&&e.jsx("span",{className:"text-[10px] uppercase tracking-wider font-bold px-2 py-1 rounded-full bg-amber-500 text-white shrink-0",children:"Booked Full"})]}),y.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:y.description}),e.jsx("div",{className:"text-2xl font-bold mt-3",children:g(y.price_cents,y.billing_interval)}),v?e.jsxs("div",{className:"mt-4 space-y-2",children:[e.jsx("div",{className:"rounded-md bg-amber-100 border border-amber-200 text-amber-900 px-3 py-2.5 text-sm text-center",children:"Currently not accepting new clients."}),e.jsxs($,{variant:"outline",className:"w-full",onClick:()=>l(!0),children:[e.jsx(zg,{className:"h-4 w-4 mr-1"})," Join Waitlist"]})]}):e.jsxs($,{className:"w-full mt-4 bg-[#406E71] hover:bg-[#2a4c64]",onClick:()=>d(y.id),disabled:r===y.id,children:[r===y.id?"Loading…":"Get Started",e.jsx(ca,{className:"h-4 w-4 ml-1"})]})]})},y.id)}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"Secure checkout powered by Stripe."}),e.jsxs($,{variant:"ghost",size:"sm",className:"w-full text-muted-foreground",onClick:()=>l(!0),children:[e.jsx(zg,{className:"h-4 w-4 mr-1"})," Join the waitlist instead"]})]})]}),e.jsx(cUs,{open:i,onOpenChange:l,coachId:f.id,coachName:h==null?void 0:h.name,packages:m.map(y=>({id:y.id,name:y.name}))})]})}const uUs=z2({full_name:vl().trim().min(2,"Please enter your full name").max(100),email:vl().trim().email("Enter a valid email").max(255),phone:vl().trim().max(40).optional().or(yx("")),brokerage:vl().trim().max(150).optional().or(yx("")),years_experience:vl().trim().max(40).optional().or(yx("")),specialties:vl().trim().max(500).optional().or(yx("")),why_coach:vl().trim().min(20,"Tell us a bit more — at least 20 characters").max(2e3),results_story:vl().trim().max(2e3).optional().or(yx("")),website_url:vl().trim().max(300).optional().or(yx("")),linkedin_url:vl().trim().max(300).optional().or(yx(""))});function hUs(){const s=Xn(),[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=uUs.safeParse(i);if(!u.success){const f=(m=Object.values(u.error.flatten().fieldErrors)[0])==null?void 0:m[0];return re.error(f||"Please check the form and try again")}n(!0);const{error:h}=await q.from("coach_applications").insert(u.data);if(n(!1),h)return re.error(h.message||"Could not submit application");a(!0),window.scrollTo({top:0,behavior:"smooth"})};return r?e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-[#1c3447] via-[#2a4c64] to-[#406E71] text-white flex items-center justify-center p-6",children:e.jsxs("div",{className:"max-w-xl text-center",children:[e.jsx("div",{className:"inline-flex items-center justify-center h-20 w-20 rounded-full bg-gradient-to-br from-yellow-400 to-yellow-300 text-[#1c3447] mb-6 shadow-2xl",children:e.jsx(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(wr,{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(Nn,{className:"h-3.5 w-3.5 text-yellow-300"}),"Coach Application — By Invitation & Application Only"]}),e.jsx("h1",{className:"text-4xl md:text-6xl font-bold tracking-tight leading-[1.05] max-w-3xl",children:"Join the most respected coaching program in real estate."}),e.jsx("p",{className:"text-white/80 mt-6 max-w-2xl text-lg leading-relaxed",children:"LevelUp Coaches don't just teach — they transform careers. We hand-pick top-producing agents and proven mentors who are ready to multiply their impact, build a recurring revenue stream, and help thousands of agents finally break through."}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-4 mt-12",children:[e.jsxs("div",{className:"rounded-2xl bg-white/5 backdrop-blur-sm border border-white/10 p-5",children:[e.jsx(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(t5,{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(t5,{label:"Email *",children:e.jsx(pe,{type:"email",value:i.email,onChange:d=>o("email",d.target.value),required:!0,maxLength:255})}),e.jsx(t5,{label:"Phone",children:e.jsx(pe,{value:i.phone,onChange:d=>o("phone",d.target.value),maxLength:40})}),e.jsx(t5,{label:"Current brokerage",children:e.jsx(pe,{value:i.brokerage,onChange:d=>o("brokerage",d.target.value),maxLength:150})}),e.jsx(t5,{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(t5,{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(t5,{label:"Website",children:e.jsx(pe,{value:i.website_url,onChange:d=>o("website_url",d.target.value),placeholder:"https://",maxLength:300})}),e.jsx(t5,{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(t5,{label:"Why do you want to coach with LevelUp? *",children:e.jsx(Ls,{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(t5,{label:"Tell us about results you've created — for yourself or other agents.",children:e.jsx(Ls,{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 t5({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 Ost="/assets/testimonial-avatar-1-BsCQFauB.jpg",zst="/assets/testimonial-avatar-2-B6VPVc2t.jpg",Bst="/assets/testimonial-avatar-3-GuEFwYUE.jpg",$st="/assets/testimonial-avatar-4-98iKMtkB.jpg",Ust="/assets/testimonial-avatar-5-ZsZfyxMX.jpg",mUs=[Ost,zst,Bst,$st,Ust],fUs=[{key:"dashboard",label:"Agent Command Center",caption:"Your entire day — smart queue, calendar and pipeline in one view.",src:Kae},{key:"crm",label:"CRM & Contact Hub",caption:"Contacts, tags, follow-ups and deal history, always one click away.",src:e6e},{key:"pipeline",label:"Deal Pipeline",caption:"Every active deal with tasks, forms and commission tracking built in.",src:t6e},{key:"staging",label:"Staging Studio",caption:"AI photo staging — MLS-ready before/afters in minutes.",src:s6e},{key:"coaching",label:"Coaching",caption:"Book live coaching sessions with Google Meet created automatically.",src:n6e},{key:"marketing",label:"Marketing Studio",caption:"Templates, social posts, reels and print — all branded to you.",src:r6e}];function pUs({slot:s}){return e.jsxs("figure",{className:"rounded-2xl overflow-hidden border border-white/10 bg-white/5 backdrop-blur-sm shadow-2xl",children:[e.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-2 border-b border-white/10",children:[e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-red-400/80"}),e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-amber-400/80"}),e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-green-400/80"}),e.jsx("span",{className:"ml-3 text-[11px] rounded px-2 py-0.5 bg-white/10 text-white/70",children:"dashboard.relevelup.com"})]}),s.src?e.jsx("img",{src:s.src,alt:`LevelUp ${s.label} screenshot`,className:"w-full h-auto block",loading:"lazy"}):e.jsxs("div",{className:"w-full aspect-[16/10] flex flex-col items-center justify-center gap-3 bg-white/5",children:[e.jsx(Nn,{className:"h-8 w-8 text-white/40"}),e.jsx("p",{className:"text-sm font-medium text-white/60",children:s.label})]}),e.jsxs("figcaption",{className:"px-4 py-3 text-sm text-white/80",children:[e.jsx("span",{className:"font-semibold text-white",children:s.label})," — ",s.caption]})]})}const gUs=z2({name:vl().trim().min(2,"Name must be at least 2 characters").max(100),email:vl().trim().email("Please enter a valid email address").max(255),phone:vl().trim().min(10,"Please enter a valid phone number").max(20).optional().or(yx("")),brokerage:vl().trim().max(200).optional().or(yx(""))}),xUs=[{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:Ta,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:Jr,title:"Resource Kits",description:"Downloadable toolkits with scripts, checklists, guides, and everything you need to close more deals."},{icon:ul,title:"Social Swag",description:"Fresh social media content and designs updated regularly to help you stand out online."}],yUs=[{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:nh,items:["Custom lead websites","Open House Guest Book","RSVP pages","Resource landing pages","Listing Revival™","FSBO Breakthrough","Attract system"]},{category:"CRM & Deals",icon:Cv,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:ey,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:ji,items:["Manager dashboard","Team analytics","Agent onboarding","Office form libraries","Listing Exchange","Brand kits","Recruiting pipeline"]}],vUs=[{icon:Yn,title:"Contact Management",description:"Organize your sphere into relationship tiers—Top 25, Past Clients, Referral Partners, and more."},{icon:Nn,title:"Smart TouchPlans",description:"Automated action plans that tell you exactly who to contact and how, based on relationship type."},{icon:Da,title:"One-Tap Actions",description:"Call, text, or email contacts directly with pre-written scripts tailored to each relationship."},{icon:Fg,title:"Birthday Alerts",description:"Never miss an important date—get reminders for birthdays and home anniversaries."},{icon:ci,title:"Pop-by Map",description:"See all your contacts on a map and plan efficient pop-by routes in your area."},{icon: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:eg,title:"Daily Action Cards",description:"Wake up to a prioritized list of exactly who to reach out to today."}],bUs=[{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."}],Yce="bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]",_Us=()=>{const s=Xn(),[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=gUs.safeParse(r);if(!u.success){const f={};u.error.issues.forEach(g=>{g.path[0]&&(f[g.path[0]]=g.message)}),l(f);return}n(!0);try{const f=typeof window<"u"&&localStorage.getItem("levelup_referral_code")||void 0,{data:g,error:x}=await q.functions.invoke("create-trial-signup",{body:{name:r.name.trim(),email:r.email.trim().toLowerCase(),phone:((h=r.phone)==null?void 0:h.trim())||void 0,brokerage:((m=r.brokerage)==null?void 0:m.trim())||void 0,referral_code:f}});if(x){console.error("Trial signup error:",x),re.error(x.message||"Something went wrong. Please try again.");return}if(g!=null&&g.error){re.error(g.error);return}re.success("🎉 Welcome aboard! Check your email to claim your account."),typeof window<"u"&&window.oaiq&&window.oaiq("measure","trial_started",{type:"plan_enrollment"}),typeof window<"u"&&window.fbq&&window.fbq("track","Lead",{content_name:"Trial Signup",value:0,currency:"USD"}),s("/trial/success")}catch(f){console.error("Trial signup error:",f),re.error("Something went wrong. Please try again.")}finally{n(!1)}},c=()=>{var d;(d=document.getElementById("trial-form"))==null||d.scrollIntoView({behavior:"smooth",block:"center"})};return e.jsxs(e.Fragment,{children:[e.jsxs(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:qEe,alt:"LevelUp",className:"h-8 md:h-10"})}),e.jsxs("div",{className:"flex items-center gap-2 md:gap-4",children:[e.jsx($,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>{var d;return(d=document.getElementById("features"))==null?void 0:d.scrollIntoView({behavior:"smooth"})},children:"Features"}),e.jsx($,{onClick:()=>s("/auth"),className:"bg-white text-[#4a6b6d] hover:bg-gray-100 font-medium shadow-md",children:"Sign In"})]})]})}),e.jsxs("section",{className:"relative overflow-hidden bg-[#0f2530]",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-b from-[#122c3a] via-[#16384a] to-[#0f2530]"}),e.jsx("div",{className:"absolute -top-40 left-1/2 -translate-x-1/2 h-[560px] w-[900px] rounded-full bg-[#4aa8a0]/25 blur-[140px] animate-[hero-glow_7s_ease-in-out_infinite]"}),e.jsx("div",{className:"absolute top-1/3 -left-40 h-[420px] w-[420px] rounded-full bg-[#2a6f8a]/20 blur-[120px]"}),e.jsx("div",{className:"absolute top-1/4 -right-40 h-[420px] w-[420px] rounded-full bg-[#c9a84c]/10 blur-[120px]"}),e.jsx("div",{className:"absolute inset-0 opacity-[0.12] bg-[linear-gradient(to_right,rgba(255,255,255,0.5)_1px,transparent_1px),linear-gradient(to_bottom,rgba(255,255,255,0.5)_1px,transparent_1px)] bg-[size:56px_56px] [mask-image:radial-gradient(ellipse_75%_65%_at_50%_35%,black,transparent)]"}),e.jsx("div",{className:"absolute inset-x-0 bottom-0 h-40 bg-gradient-to-t from-[#0f2530] to-transparent"}),e.jsx("div",{className:"container mx-auto px-4 relative",children:e.jsxs("div",{className:"grid lg:grid-cols-2 gap-12 items-center pt-28 md:pt-36 pb-20 md:pb-28",children:[e.jsxs("div",{className:"space-y-8 text-center lg:text-left",children:[e.jsx("div",{className:"flex justify-center lg:justify-start animate-fade-in",children:e.jsxs("span",{className:"inline-flex items-center gap-2 rounded-full border border-white/15 bg-white/5 backdrop-blur-sm px-4 py-1.5 text-xs md:text-sm font-semibold tracking-wide text-white/85 shadow-lg",children:[e.jsx(Nn,{className:"h-3.5 w-3.5 text-[#7fd4cc]"}),"7-Day Free Trial • No Credit Card Required"]})}),e.jsxs("h1",{className:"text-4xl sm:text-5xl md:text-6xl font-sans font-bold tracking-tight text-white leading-[1.05] animate-fade-in",children:["Take LevelUp for a"," ",e.jsx("span",{className:"bg-gradient-to-r from-[#8fe0d6] via-[#5cc0b6] to-[#e6c878] bg-clip-text text-transparent italic",children:"Free Test Drive"})]}),e.jsx("p",{className:"text-base md:text-xl text-white/65 max-w-xl mx-auto lg:mx-0 leading-relaxed animate-fade-in",children:"Weekly coaching, a smart CRM, done-for-you marketing and AI tools — everything a modern agent runs on, in one login."}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center lg:justify-start animate-fade-in",children:[e.jsxs("div",{className:"flex items-center gap-2 text-white/80",children:[e.jsx(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:mUs.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(eg,{className:"h-4 w-4 text-[#7fd4cc]"})," Set up in 2 minutes"]})]})]}),e.jsxs("div",{id:"trial-form",className:"lg:pl-8 relative",children:[e.jsx("div",{className:"absolute -inset-6 rounded-[32px] bg-[#4aa8a0]/20 blur-2xl","aria-hidden":!0}),e.jsx(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(Ie,{className:"p-8",children:[e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("div",{className:"inline-flex items-center justify-center w-16 h-16 rounded-full bg-[#4a6b6d] mb-4",children:e.jsx(qg,{className:"h-8 w-8 text-white"})}),e.jsx("h2",{className:"text-2xl font-bold text-foreground font-sans",children:"Start Your Free Trial"}),e.jsx("p",{className:"text-muted-foreground mt-2",children:"Get instant access • No credit card needed"})]}),e.jsxs("form",{onSubmit:o,className:"space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"name",children:"Full Name *"}),e.jsx(pe,{id:"name",type:"text",placeholder:"John Smith",value:r.name,onChange:d=>a({...r,name:d.target.value}),required:!0}),i.name&&e.jsx("p",{className:"text-sm text-destructive",children:i.name})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"email",children:"Email Address *"}),e.jsx(pe,{id:"email",type:"email",placeholder:"john@example.com",value:r.email,onChange:d=>a({...r,email:d.target.value}),required:!0}),i.email&&e.jsx("p",{className:"text-sm text-destructive",children:i.email})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"phone",children:"Phone Number"}),e.jsx(pe,{id:"phone",type:"tel",placeholder:"(555) 123-4567",value:r.phone,onChange:d=>a({...r,phone:d.target.value})}),i.phone&&e.jsx("p",{className:"text-sm text-destructive",children:i.phone})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"brokerage",children:"Brokerage Name"}),e.jsx(pe,{id:"brokerage",type:"text",placeholder:"Your brokerage or team name",value:r.brokerage,onChange:d=>a({...r,brokerage:d.target.value})}),i.brokerage&&e.jsx("p",{className:"text-sm text-destructive",children:i.brokerage})]}),e.jsx($,{type:"submit",className:"w-full h-12 text-lg font-semibold bg-[#4a6b6d] hover:bg-[#3d5a5c]",disabled:t,children:t?e.jsxs(e.Fragment,{children:[e.jsx(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 ${Yce}`})}),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:fUs.map(d=>e.jsx(pUs,{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(M4,{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:xUs.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(Ie,{children:e.jsx("p",{className:"text-muted-foreground leading-relaxed",children:d.description})})]},u))}),e.jsxs("div",{className:"mt-14 max-w-6xl mx-auto rounded-3xl bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] p-8 md:p-12 relative overflow-hidden shadow-2xl",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:`absolute inset-0 ${Yce}`})}),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:yUs.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(ca,{className:"h-3.5 w-3.5 text-emerald-300 shrink-0"}),u]},u))})]},d.category))}),e.jsxs("p",{className:"text-center text-white/50 text-sm mt-10 flex items-center justify-center gap-2",children:[e.jsx(Nn,{className:"h-4 w-4"}),"New tools added every month — membership keeps getting more valuable."]})]})]})]})}),e.jsxs("section",{className:"py-20 bg-gradient-to-br from-[#4a6b6d] to-[#3d5a5c] relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:`absolute inset-0 ${Yce}`})}),e.jsxs("div",{className:"container mx-auto px-4 relative",children:[e.jsxs("div",{className:"text-center max-w-3xl mx-auto mb-16",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-4 py-2 rounded-full bg-white/10 text-white text-sm font-medium mb-6",children:[e.jsx(Nn,{className:"w-4 h-4"}),"Included with Your Trial"]}),e.jsxs("h2",{className:"text-3xl mb-6 text-white font-sans font-bold md:text-6xl",children:["Meet ",e.jsx("span",{className:"italic",children:"Agent OS"})]}),e.jsx("p",{className:"text-lg text-white/80",children:"Your relationship-first operating system. Never forget a follow-up, track every touchpoint, and turn your sphere into a referral machine."})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 max-w-6xl mx-auto",children:vUs.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(Ie,{children:e.jsx("p",{className:"text-white/70 text-sm leading-relaxed",children:d.description})})]},u))})]})]}),e.jsx("section",{className:"py-20 bg-background",children:e.jsxs("div",{className:"container mx-auto px-4",children:[e.jsxs("div",{className:"text-center mb-16",children:[e.jsx("h2",{className:"text-3xl md:text-4xl font-bold mb-4 font-sans",children:"Loved by Top Producers"}),e.jsx("p",{className:"text-lg text-muted-foreground",children:"See what agents are saying about LevelUp"})]}),e.jsx("div",{className:"grid md:grid-cols-3 gap-8 max-w-5xl mx-auto",children:bUs.map((d,u)=>e.jsx(je,{className:"border hover:shadow-lg transition-shadow",children:e.jsxs(Ie,{className:"p-6",children:[e.jsx("div",{className:"flex gap-1 mb-4",children:[1,2,3,4,5].map(h=>e.jsx(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(eg,{className:"h-6 w-6 text-[#4a6b6d]"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:"Fast Setup"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Start in 2 minutes"})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-[#4a6b6d]/10 flex items-center justify-center",children:e.jsx(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 ${Yce}`})}),e.jsxs(Ie,{className:"p-12 text-center relative",children:[e.jsx("h2",{className:"text-3xl md:text-4xl font-bold text-white mb-4 font-sans",children:"Ready to Level Up Your Business?"}),e.jsx("p",{className:"text-xl text-white/80 mb-8 max-w-2xl mx-auto",children:"Join thousands of successful agents. Start your free 7-day trial today."}),e.jsxs($,{onClick:c,size:"lg",className:"h-14 px-8 text-lg font-semibold bg-white text-[#1e3a4c] hover:bg-white/90 shadow-2xl transition-all hover:scale-105 rounded-full",children:["Start Your Free Trial Now",e.jsx(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:SG,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."})]})})})]})]})},wUs=()=>{const s=Xn();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:qEe,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(Ie,{className:"p-8 md:p-12 text-center",children:[e.jsxs("div",{className:"relative inline-block mb-8",children:[e.jsx("div",{className:"w-24 h-24 rounded-full bg-gradient-to-br from-[#4a6b6d] to-[#3d5a5c] flex items-center justify-center",children:e.jsx(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(Cx,{className:"h-5 w-5 text-white"})})]}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold text-foreground mb-4 font-sans",children:"You're In! 🎉"}),e.jsx("p",{className:"text-xl text-muted-foreground mb-8",children:"Your 7-day LevelUp adventure starts now!"}),e.jsxs("div",{className:"bg-[#4a6b6d]/10 rounded-xl p-6 mb-8",children:[e.jsxs("div",{className:"flex items-center justify-center gap-3 mb-4",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-[#4a6b6d]/20 flex items-center justify-center",children:e.jsx(mn,{className:"h-6 w-6 text-[#4a6b6d]"})}),e.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"Check Your Inbox"})]}),e.jsx("p",{className:"text-muted-foreground",children:"We just sent you a magic link to claim your account and set up your password. Click the link in your email to get started!"})]}),e.jsxs("div",{className:"text-left space-y-3 mb-8",children:[e.jsx("p",{className:"text-sm text-muted-foreground font-medium uppercase tracking-wide",children:"What happens next:"}),e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-[#4a6b6d] flex items-center justify-center flex-shrink-0 mt-0.5",children:e.jsx("span",{className:"text-xs font-bold text-white",children:"1"})}),e.jsx("p",{className:"text-foreground",children:"Check your email for the welcome message"})]}),e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-[#4a6b6d] flex items-center justify-center flex-shrink-0 mt-0.5",children:e.jsx("span",{className:"text-xs font-bold text-white",children:"2"})}),e.jsx("p",{className:"text-foreground",children:'Click "Claim Your Account" to set your password'})]}),e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-[#4a6b6d] flex items-center justify-center flex-shrink-0 mt-0.5",children:e.jsx("span",{className:"text-xs font-bold text-white",children:"3"})}),e.jsx("p",{className:"text-foreground",children:"Start exploring all the features!"})]})]}),e.jsxs("p",{className:"text-sm text-muted-foreground mb-6",children:["Didn't receive the email? Check your spam folder or"," ",e.jsx("button",{onClick:()=>s("/trial"),className:"text-[#4a6b6d] hover:underline font-medium",children:"try again"})]}),e.jsxs($,{onClick:()=>s("/auth"),className:"bg-[#4a6b6d] hover:bg-[#3d5a5c]",children:["Go to Sign In",e.jsx(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:SG,alt:"LevelUp",className:"h-8"}),e.jsxs("p",{className:"text-sm text-white/40",children:["© ",new Date().getFullYear()," LevelUp Consulting Group. All rights reserved."]})]})})})]})]})},jUs="https://us06web.zoom.us/meeting/register/7Ybq3ZIkRn2_RLkkv_uY8A",Zce="ld-open-house-invite-dismissed";function _$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(`${Zce}-${s}`))return;let o=null;const c=d=>{d.clientY<=0&&!localStorage.getItem(`${Zce}-${s}`)&&a(!0)};return o=setTimeout(()=>{localStorage.getItem(`${Zce}-${s}`)||a(!0)},n),document.addEventListener("mouseleave",c),()=>{o&&clearTimeout(o),document.removeEventListener("mouseleave",c)}},[s,n]);const i=()=>{a(!1),localStorage.setItem(`${Zce}-${s}`,"1")};return e.jsx(zs,{open:r,onOpenChange:l=>!l&&i(),children:e.jsx(Os,{className:"laborday-theme max-w-md border-0 p-0 overflow-hidden bg-transparent",overlayClassName:"bg-black/70 backdrop-blur-sm",children:e.jsxs("div",{className:"relative text-white",style:{background:"linear-gradient(150deg, hsl(var(--ld-navy)) 0%, hsl(var(--ld-navy-deep)) 100%)"},children:[e.jsx("div",{className:"h-2 w-full",style:{background:"repeating-linear-gradient(90deg, hsl(var(--ld-red)) 0px, hsl(var(--ld-red)) 24px, hsl(var(--ld-cream)) 24px, hsl(var(--ld-cream)) 48px, hsl(var(--ld-navy)) 48px, hsl(var(--ld-navy)) 72px)"}}),e.jsx("button",{onClick:i,className:"absolute right-3 top-5 rounded-full p-1.5 text-white/70 hover:bg-white/10 hover:text-white transition-colors","aria-label":"Close",children:e.jsx(pr,{className:"h-4 w-4"})}),e.jsxs("div",{className:"p-6 pt-8 text-center",children:[e.jsx("div",{className:"mx-auto mb-4 flex h-14 w-14 items-center justify-center rounded-full bg-white/10 ring-1 ring-white/20",children:e.jsx(ua,{className:"h-6 w-6 ld-gold-text"})}),e.jsxs(Us,{children:[e.jsx(Bs,{className:"text-xl font-bold leading-tight text-white",children:t}),e.jsxs(Pr,{className:"text-white/80 mt-3 text-sm leading-relaxed",children:["Join us for our next"," ",e.jsx("span",{className:"font-semibold ld-gold-text",children:"LevelUp Live Open House"})," ","and get an inside look at our agent growth platform."]})]}),e.jsxs("div",{className:"mt-5 inline-flex items-center gap-2 rounded-full bg-white/10 px-4 py-2 text-sm font-medium text-white ring-1 ring-white/15",children:[e.jsx(Ta,{className:"h-4 w-4 ld-gold-text"}),"Every Friday at 1:00 PM ET"]}),e.jsxs("div",{className:"mt-6 flex flex-col gap-3",children:[e.jsx($,{asChild:!0,size:"lg",className:"w-full bg-accent text-accent-foreground hover:bg-accent/90 font-bold",children:e.jsxs("a",{href:jUs,target:"_blank",rel:"noreferrer",className:"gap-2",children:["Register for the Open House",e.jsx(Fr,{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 w$t=Date.UTC(2026,8,12,3,59,59),U7e="Friday, September 11 at 11:59 PM ET",q7e=300,Xce=39*12,NUs=[{key:"dashboard",label:"Agent Command Center",caption:"Your entire day — smart queue, calendar and pipeline in one view.",src:Kae},{key:"crm",label:"CRM & Contact Hub",caption:"Contacts, tags, follow-ups and deal history, always one click away.",src:e6e},{key:"pipeline",label:"Deal Pipeline",caption:"Every active deal with tasks, forms and commission tracking built in.",src:t6e},{key:"staging",label:"Staging Studio",caption:"AI photo staging — MLS-ready before/afters in minutes.",src:s6e},{key:"coaching",label:"Coaching",caption:"Book live coaching sessions with Google Meet created automatically.",src:n6e},{key:"marketing",label:"Marketing Studio",caption:"Templates, social posts, reels and print — all branded to you.",src:r6e}],kUs=[{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."}],SUs="https://www.google.com/search?q=levelup+consulting+group#lrd=0x8842f50045c4bd33:0xc9b99b5330a91b3f,1,,,,",j$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:a7,title:"Full CRM & Contact Hub",desc:"Contacts, tags, smart follow-ups, lead ponds and team assignments — your database finally organized.",value:600},{icon:vb,title:"Deal Pipeline",desc:"Track every transaction from offer to closing with tasks, forms and commission math built in.",value:480},{icon:Sx,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:dl,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:c_,title:"Forms & E-Signature",desc:"Upload any PDF, map fields, send for signature — done from one place.",value:300},{icon:ua,title:"Weekly Reels & Video Tools",desc:"Personalized Instagram scripts delivered every Monday, plus screen recording and virtual backgrounds.",value:468},{icon:eo,title:"Reviews Engine",desc:"Collect Google and video reviews with a single link — your reputation on autopilot.",value:240},{icon:Nn,title:"ChatGPT App + 30 AI Tools",desc:"Your entire business controllable from ChatGPT — create contacts, open houses, marketing assets and more.",value:500},{icon:Ta,title:"My Calendar & Booking",desc:"Agent-first calendar with time zones, Google Calendar sync and self-serve booking links.",value:144}],Dvt=j$t.reduce((s,t)=>s+t.value,0),CUs=[{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 N$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 Fvt({dark:s=!1}){const{d:t,h:n,m:r,sec:a,expired:i}=N$t(w$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 Ovt(){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 AUs({slot:s,dark:t=!0}){return e.jsxs("figure",{className:`ld-shot overflow-hidden border ${t?"ld-glass":"bg-card border-border"}`,children:[e.jsxs("div",{className:`flex items-center gap-1.5 px-3 py-2 border-b ${t?"border-white/10":"border-border"}`,children:[e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-red-400/80"}),e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-amber-400/80"}),e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-green-400/80"}),e.jsx("span",{className:`ml-3 text-[11px] rounded px-2 py-0.5 ${t?"bg-white/10 text-white/70":"bg-muted text-muted-foreground"}`,children:"dashboard.relevelup.com"})]}),s.src?e.jsx("img",{src:s.src,alt:`LevelUp ${s.label} screenshot`,className:"w-full h-auto block",loading:"lazy"}):e.jsxs("div",{className:`w-full aspect-[16/10] flex flex-col items-center justify-center gap-3 ${t?"bg-white/5":"bg-muted"}`,children:[e.jsx(Nn,{className:`h-8 w-8 ${t?"text-white/40":"text-muted-foreground/50"}`}),e.jsx("p",{className:`text-sm font-medium ${t?"text-white/60":"text-muted-foreground"}`,children:s.label}),e.jsx("p",{className:`text-xs px-6 text-center ${t?"text-white/40":"text-muted-foreground/70"}`,children:"Screenshot placeholder"})]}),e.jsxs("figcaption",{className:`px-4 py-3 text-sm ${t?"text-white/80":"text-muted-foreground"}`,children:[e.jsx("span",{className:`font-semibold ${t?"text-white":"text-foreground"}`,children:s.label})," — ",s.caption]})]})}function EUs(){const{expired:s}=N$t(w$t),[t,n]=j.useState(""),[r,a]=j.useState(""),[i,l]=j.useState(!1),[o,c]=j.useState(0),d=j.useMemo(()=>[Ost,zst,Bst,$st,Ust],[]),u=Xce-q7e,h=async()=>{if(!r.trim()||!r.includes("@")){re.error("Enter your email to claim the offer.");return}l(!0);try{const{data:m,error:f}=await q.functions.invoke("create-checkout",{body:{tier:"individual_annual",email:r.trim(),name:t.trim()||void 0,skipTrial:!0}});if(f){const g=f instanceof kae?await f.context.text():f.message;throw new Error(g||"Checkout failed to start")}if(m!=null&&m.url){window.location.href=m.url;return}throw new Error("No checkout URL returned")}catch(m){console.error("Labor Day checkout error:",m),re.error(m.message||"Could not start checkout. Please try again."),l(!1)}};return e.jsxs("div",{className:"laborday-theme min-h-screen bg-background",children:[e.jsxs(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 ${U7e}.`}),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:["$",Xce]})]})]}),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:SG,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 ",U7e]})]}),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 ($",Xce,"/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(Fvt,{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(pc,{className:"h-3 w-3"})," Secure Stripe checkout · Manage or cancel anytime from your profile"]})]}),e.jsxs("p",{className:"mt-6 text-white/70 text-sm",children:["Trusted by ",e.jsx("span",{className:"font-bold text-white",children:"3,000+ agents"})," to run and grow their business"]})]})]})]}),e.jsx("section",{className:"py-20 md:py-28 px-6",children:e.jsxs("div",{className:"max-w-6xl mx-auto",children:[e.jsxs("div",{className:"text-center mb-14",children:[e.jsx("span",{className:"text-sm font-semibold tracking-[0.15em] uppercase text-primary",children:"Everything included"}),e.jsx("h2",{className:"text-3xl md:text-5xl font-bold mt-4 tracking-tight",children:"One membership. The entire platform."}),e.jsxs("p",{className:"text-muted-foreground mt-4 max-w-2xl mx-auto",children:["This isn't a teaser tier. You get every tool LevelUp members use daily — worth $",Dvt.toLocaleString(),"/year at market rates."]})]}),e.jsxs("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 gap-5",children:[j$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:["$",Dvt.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:NUs.map(m=>e.jsx(AUs,{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(Ovt,{}),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:kUs.map(m=>e.jsxs("blockquote",{className:"bg-card border rounded-2xl p-5 flex flex-col gap-3",children:[e.jsx(Ovt,{}),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:SUs,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(pr,{className:"h-4 w-4 mt-0.5 shrink-0"})," $",Xce," per year"]}),e.jsxs("li",{className:"flex gap-2",children:[e.jsx(pr,{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(ca,{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:["$",q7e]}),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(ca,{className:"h-4 w-4 mt-0.5 shrink-0 text-accent"})," $",q7e," per year — save $",u," vs monthly"]}),e.jsxs("li",{className:"flex gap-2",children:[e.jsx(Fq,{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(ca,{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:CUs.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(Fvt,{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(pc,{className:"h-3 w-3"})," Secure Stripe checkout · Ends ",U7e]}),e.jsxs("p",{className:"text-white/50 text-sm mt-10",children:["© ",new Date().getFullYear()," LevelUp Consulting Group"]})]})]}),e.jsx(_$t,{pageKey:"individual-labor-day-2026",headline:"Not ready to join the LevelUp family yet?"})]})}const k$t=Date.UTC(2026,8,12,3,59,59),V7e="Friday, September 11 at 11:59 PM ET",oQ=399,o3e=499,zvt=(o3e-oQ)*12,TUs=[{key:"dashboard",label:"Agent Command Center",caption:"Every agent's day — smart queue, calendar and pipeline in one view.",src:Kae},{key:"crm",label:"CRM & Contact Hub",caption:"Contacts, tags, follow-ups and deal history for every agent.",src:e6e},{key:"pipeline",label:"Deal Pipeline",caption:"Every transaction with tasks, forms and commission tracking built in.",src:t6e},{key:"staging",label:"Staging Studio",caption:"AI photo staging — MLS-ready before/afters in minutes.",src:s6e},{key:"coaching",label:"Coaching",caption:"Live coaching sessions your agents book themselves.",src:n6e},{key:"marketing",label:"Marketing Studio",caption:"Templates, social posts, reels and print — all branded.",src:r6e}],MUs=[{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."}],PUs="https://www.google.com/search?q=levelup+consulting+group#lrd=0x8842f50045c4bd33:0xc9b99b5330a91b3f,1,,,,",IUs=[{icon:bb,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:a7,title:"Full CRM & Contact Hub",desc:"Contacts, tags, smart follow-ups, lead ponds and team assignments — every agent's database finally organized."},{icon:vb,title:"Deal Pipeline",desc:"Transactions from offer to closing with tasks, forms and commission math built in."},{icon:Sx,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:dl,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:c_,title:"Forms & E-Signature",desc:"Upload any PDF, map fields, send for signature — done from one place."},{icon:ua,title:"Weekly Reels & Video Tools",desc:"Personalized Instagram scripts every Monday, plus screen recording and virtual backgrounds."}],LUs=[{icon:ji,title:"Your Own Brokerage Hub",desc:"Brand profiles, announcements and resources pushed to every agent from one place."},{icon:c_,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."}],RUs=[{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 S$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 Bvt({dark:s=!1}){const{d:t,h:n,m:r,sec:a,expired:i}=S$t(k$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 $vt(){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 DUs({slot:s,dark:t=!0}){return e.jsxs("figure",{className:`ld-shot overflow-hidden border ${t?"ld-glass":"bg-card border-border"}`,children:[e.jsxs("div",{className:`flex items-center gap-1.5 px-3 py-2 border-b ${t?"border-white/10":"border-border"}`,children:[e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-red-400/80"}),e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-amber-400/80"}),e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-green-400/80"}),e.jsx("span",{className:`ml-3 text-[11px] rounded px-2 py-0.5 ${t?"bg-white/10 text-white/70":"bg-muted text-muted-foreground"}`,children:"dashboard.relevelup.com"})]}),s.src?e.jsx("img",{src:s.src,alt:`LevelUp ${s.label} screenshot`,className:"w-full h-auto block",loading:"lazy"}):e.jsxs("div",{className:`w-full aspect-[16/10] flex flex-col items-center justify-center gap-3 ${t?"bg-white/5":"bg-muted"}`,children:[e.jsx(Nn,{className:`h-8 w-8 ${t?"text-white/40":"text-muted-foreground/50"}`}),e.jsx("p",{className:`text-sm font-medium ${t?"text-white/60":"text-muted-foreground"}`,children:s.label})]}),e.jsxs("figcaption",{className:`px-4 py-3 text-sm ${t?"text-white/80":"text-muted-foreground"}`,children:[e.jsx("span",{className:`font-semibold ${t?"text-white":"text-foreground"}`,children:s.label})," — ",s.caption]})]})}function FUs(){const{expired:s}=S$t(k$t),[t,n]=j.useState(""),[r,a]=j.useState(""),[i,l]=j.useState(!1),[o,c]=j.useState(0),d=j.useMemo(()=>[Ost,zst,Bst,$st,Ust],[]),u=async()=>{if(!r.trim()||!r.includes("@")){re.error("Enter your email to claim the offer.");return}l(!0);try{const{data:h,error:m}=await q.functions.invoke("create-checkout",{body:{tier:"brokerage_labor_day",email:r.trim(),name:t.trim()||void 0,skipTrial:!0}});if(m){const f=m instanceof kae?await m.context.text():m.message;throw new Error(f||"Checkout failed to start")}if(h!=null&&h.url){window.location.href=h.url;return}throw new Error("No checkout URL returned")}catch(h){console.error("Brokerage Labor Day checkout error:",h),re.error(h.message||"Could not start checkout. Please try again."),l(!1)}};return e.jsxs("div",{className:"laborday-theme min-h-screen bg-background",children:[e.jsxs(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 ${V7e}.`}),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:["$",oQ,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:["$",o3e]})]})]}),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:SG,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 ",V7e]})]}),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(Bvt,{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(pc,{className:"h-3 w-3"})," Secure Stripe checkout · Set up your brokerage right after payment"]})]}),e.jsxs("p",{className:"mt-6 text-white/70 text-sm",children:["Trusted by ",e.jsx("span",{className:"font-bold text-white",children:"3,000+ agents"})," and the brokerages they work for"]})]})]})]}),e.jsx("section",{className:"py-20 md:py-28 px-6",children:e.jsxs("div",{className:"max-w-6xl mx-auto",children:[e.jsxs("div",{className:"text-center mb-14",children:[e.jsx("span",{className:"text-sm font-semibold tracking-[0.15em] uppercase text-primary",children:"What your agents get"}),e.jsx("h2",{className:"text-3xl md:text-5xl font-bold mt-4 tracking-tight",children:"A full membership for every agent. No per-seat fees."}),e.jsx("p",{className:"text-muted-foreground mt-4 max-w-2xl mx-auto",children:"Individually, this membership costs $39/month per agent. As a brokerage partner, every agent gets it — all included in one flat rate."})]}),e.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 gap-5",children:IUs.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:LUs.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:TUs.map(h=>e.jsx(DUs,{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($vt,{}),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:MUs.map(h=>e.jsxs("blockquote",{className:"bg-card border rounded-2xl p-5 flex flex-col gap-3",children:[e.jsx($vt,{}),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: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:"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 $",oQ,"."]})]}),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:["$",o3e]}),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(pr,{className:"h-4 w-4 mt-0.5 shrink-0"})," $",(o3e*12).toLocaleString()," per year"]}),e.jsxs("li",{className:"flex gap-2",children:[e.jsx(pr,{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(ca,{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 $",zvt.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:["$",oQ]}),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(ca,{className:"h-4 w-4 mt-0.5 shrink-0 text-accent"})," $",(oQ*12).toLocaleString()," per year — save $",zvt.toLocaleString()," vs standard"]}),e.jsxs("li",{className:"flex gap-2",children:[e.jsx(Fq,{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(ca,{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:RUs.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(Bvt,{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(pc,{className:"h-3 w-3"})," Secure Stripe checkout · Ends ",V7e]}),e.jsxs("p",{className:"text-white/50 text-sm mt-10",children:["© ",new Date().getFullYear()," LevelUp Consulting Group"]})]})]}),e.jsx(_$t,{pageKey:"brokerage-labor-day-2026",headline:"Not ready to partner with LevelUp yet?"})]})}const OUs=["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"],zUs=["Everything in Individual, plus:","Unlimited agent seats","Brokerage admin dashboard","Team performance analytics","Agent onboarding tools","Priority support"],BUs=()=>{const{user:s,loading:t}=bs(),n=Xn(),[r]=gc(),a=r.get("plan"),i=a==="individual"?"individual_agent":a==="brokerage"?"brokerage_over_25":a,[l,o]=j.useState(!1),[c,d]=j.useState(null),[u,h]=j.useState(""),m=x=>{const y=`/upgrade?plan=${x}`;n(`/auth?next=${encodeURIComponent(y)}`)},f=async x=>{var y;if(!(s!=null&&s.email)){m(x);return}o(!0),d(x);try{const{data:v,error:b}=await q.functions.invoke("create-checkout",{body:{tier:x,email:s.email,name:((y=s.user_metadata)==null?void 0:y.full_name)||s.email,userId:s.id,couponCode:u.trim()||void 0,skipTrial:!0}});if(b)throw b;if(v!=null&&v.url)window.location.href=v.url;else throw new Error("No checkout URL returned")}catch(v){console.error("Checkout error:",v),re.error(v.message||"Failed to start checkout. Please try again."),o(!1),d(null)}},g=(x,y,v,b,w,S,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(Ie,{className:"p-6 text-center space-y-4",children:[e.jsx("div",{className:`mx-auto h-12 w-12 rounded-full flex items-center justify-center ${A?"bg-primary/10":"bg-amber-500/10"}`,children:S}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-xl",children:y}),e.jsxs("p",{className:`text-3xl font-bold mt-1 ${A?"text-primary":"text-amber-600"}`,children:[v,e.jsx("span",{className:"text-sm font-normal text-muted-foreground",children:"/mo"})]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:b})]}),e.jsx("ul",{className:"text-sm space-y-1.5 text-left text-muted-foreground",children:w.map(E=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx(ca,{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(Nn,{className:"h-4 w-4 mr-2"}),"Upgrade to ",y]}):e.jsxs(e.Fragment,{children:[e.jsx(KI,{className:"h-4 w-4 mr-2"}),"Sign in & upgrade to ",y]})})]})]});return e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-[#f4f7fa] to-white",children:e.jsxs("div",{className:"container max-w-5xl py-10 px-4",children:[e.jsxs("div",{className:"text-center mb-10",children:[e.jsx("img",{src:a6e,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",OUs,e.jsx(Yn,{className:"h-6 w-6 text-primary"}),!0),g("brokerage_over_25","Brokerage","$499","For teams and brokerages",zUs,e.jsx(ji,{className:"h-6 w-6 text-amber-600"}),!1)]}),e.jsxs("div",{className:"mt-10 bg-white/70 border rounded-xl p-5 max-w-2xl mx-auto space-y-3",children:[e.jsx("p",{className:"text-sm font-medium text-center",children:"Questions before you upgrade? We're happy to help:"}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 justify-center",children:[e.jsxs("a",{href:"tel:1-866-527-8668",className:"flex items-center justify-center gap-2 text-primary hover:underline text-sm",children:[e.jsx(Da,{className:"h-4 w-4"}),e.jsx("span",{children:"1-866-527-8668"})]}),e.jsxs("a",{href:"mailto:support@relevelup.com",className:"flex items-center justify-center gap-2 text-primary hover:underline text-sm",children:[e.jsx(mn,{className:"h-4 w-4"}),e.jsx("span",{children:"support@relevelup.com"})]})]})]}),e.jsx("p",{className:"text-center text-xs text-muted-foreground mt-8",children:"Secure checkout powered by Stripe. Your existing account, listings, and settings are preserved."})]})})},$Us=z2({viewerName:vl().min(1,"Name is required").max(100,"Name must be less than 100 characters"),viewerEmail:vl().email("Please enter a valid email").max(255,"Email must be less than 255 characters"),viewerPhone:vl().max(20,"Phone must be less than 20 characters").optional(),message:vl().min(1,"Message is required").max(1e3,"Message must be less than 1000 characters")});function UUs({shareToken:s,agentName:t,hasContact:n}){const[r,a]=j.useState(!1),[i,l]=j.useState(!1),[o,c]=j.useState(null),d=bLe({resolver:_Le($Us),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(Ie,{className:"py-8 text-center",children:[e.jsx("div",{className:"inline-flex items-center justify-center w-16 h-16 rounded-full bg-primary/20 mb-4",children:e.jsx(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(Gn,{children:n?`Have a question or want to connect? Send ${t||"them"} a message.`:`Interested? Share your info and ${t||"your agent"} will be in touch.`})]}),e.jsx(Ie,{children:e.jsx(kLe,{...d,children:e.jsxs("form",{onSubmit:d.handleSubmit(u),className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsx(jg,{control:d.control,name:"viewerName",render:({field:h})=>e.jsxs(Up,{children:[e.jsx(qp,{children:"Your Name *"}),e.jsx(Vp,{children:e.jsx(pe,{placeholder:"John Smith",...h})}),e.jsx(f_,{})]})}),e.jsx(jg,{control:d.control,name:"viewerEmail",render:({field:h})=>e.jsxs(Up,{children:[e.jsx(qp,{children:"Email *"}),e.jsx(Vp,{children:e.jsx(pe,{type:"email",placeholder:"john@example.com",...h})}),e.jsx(f_,{})]})})]}),!n&&e.jsx(jg,{control:d.control,name:"viewerPhone",render:({field:h})=>e.jsxs(Up,{children:[e.jsx(qp,{children:"Phone (optional)"}),e.jsx(Vp,{children:e.jsx(pe,{type:"tel",placeholder:"(555) 123-4567",...h})}),e.jsx(f_,{})]})}),e.jsx(jg,{control:d.control,name:"message",render:({field:h})=>e.jsxs(Up,{children:[e.jsx(qp,{children:"Message *"}),e.jsx(Vp,{children:e.jsx(Ls,{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(f_,{})]})}),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(Kr,{className:"h-4 w-4"}),"Send Message"]})})]})})})]})}const qUs=()=>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(AE,{className:"absolute bottom-[20%] right-[10%] w-12 h-12 text-blue-600/15 rotate-12"})]}),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-red-500/5 via-transparent to-blue-500/5"}),e.jsxs("div",{className:"absolute top-[10%] left-[15%] w-32 h-32",children:[e.jsx("div",{className:"absolute inset-0 rounded-full border-2 border-red-400/20 animate-ping",style:{animationDuration:"3s"}}),e.jsx(Nn,{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-8 h-8 text-red-400/40"})]}),e.jsxs("div",{className:"absolute top-[5%] right-[20%] w-24 h-24",children:[e.jsx("div",{className:"absolute inset-0 rounded-full border-2 border-blue-400/20 animate-ping",style:{animationDuration:"4s",animationDelay:"1s"}}),e.jsx(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(Nn,{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-5 h-5 text-amber-400/40"})]}),e.jsx(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(AE,{className:"absolute top-[8%] left-[5%] w-10 h-10 text-red-500/20 rotate-12"})]}),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-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(qS,{className:"w-20 h-20 text-pink-400 rotate-12"})}),e.jsx("div",{className:"absolute top-[2%] right-[8%] opacity-15",children:e.jsx(qS,{className:"w-16 h-16 text-rose-400 -rotate-12"})}),e.jsx("div",{className:"absolute bottom-[15%] left-[8%] opacity-15",children:e.jsx(qS,{className:"w-14 h-14 text-purple-400 rotate-45"})}),e.jsx("div",{className:"absolute bottom-[20%] right-[5%] opacity-20",children:e.jsx(qS,{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"})]}),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-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"}})]}),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-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(qS,{className:"absolute top-[20%] left-[32%] w-7 h-7 text-purple-400/30"}),e.jsx(qS,{className:"absolute top-[12%] right-[28%] w-6 h-6 text-pink-400/30"}),e.jsx(Eq,{className:"absolute top-[18%] left-[52%] w-5 h-5 text-sky-400/35"})]}),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-orange-900/12 via-purple-900/8 to-slate-900/12"}),e.jsx(Bz,{className:"absolute top-[5%] left-[10%] w-16 h-16 text-orange-400/25"}),e.jsx(Bz,{className:"absolute top-[10%] right-[12%] w-12 h-12 text-purple-400/20 animate-pulse"}),e.jsxs("div",{className:"absolute bottom-[18%] left-[8%]",children:[e.jsx("div",{className:"w-14 h-12 rounded-full bg-orange-500/20"}),e.jsx("div",{className:"absolute -top-2 left-1/2 -translate-x-1/2 w-2 h-4 bg-green-600/25 rounded-t-full"})]}),e.jsxs("div",{className:"absolute bottom-[22%] right-[12%]",children:[e.jsx("div",{className:"w-12 h-10 rounded-full bg-orange-400/15"}),e.jsx("div",{className:"absolute -top-1.5 left-1/2 -translate-x-1/2 w-1.5 h-3 bg-green-600/20 rounded-t-full"})]}),e.jsx("div",{className:"absolute top-[15%] left-[40%] opacity-20",children:e.jsx("svg",{viewBox:"0 0 24 12",className:"w-10 h-5 text-slate-800 fill-current",children:e.jsx("path",{d:"M12 6c-2-4-6-6-12-6 4 2 6 4 6 6s-2 4-6 6c6 0 10-2 12-6zm0 0c2-4 6-6 12-6-4 2-6 4-6 6s2 4 6 6c-6 0-10-2-12-6z"})})}),e.jsx(Nn,{className:"absolute top-[8%] left-[55%] w-6 h-6 text-purple-400/35 animate-pulse"}),e.jsx(Nn,{className:"absolute bottom-[28%] right-[25%] w-5 h-5 text-orange-400/30 animate-pulse",style:{animationDelay:"0.5s"}})]}),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-red-900/8 via-green-900/5 to-emerald-900/8"}),e.jsx(eL,{className:"absolute bottom-[8%] left-[5%] w-20 h-20 text-green-600/18"}),e.jsx(eL,{className:"absolute bottom-[12%] right-[8%] w-16 h-16 text-emerald-600/15"}),e.jsx(eL,{className:"absolute bottom-[10%] left-[28%] w-12 h-12 text-green-500/12"}),e.jsx(Xj,{className:"absolute top-[5%] left-[15%] w-10 h-10 text-sky-300/30 animate-pulse"}),e.jsx(Xj,{className:"absolute top-[10%] right-[20%] w-8 h-8 text-blue-300/25 animate-pulse",style:{animationDelay:"0.3s"}}),e.jsx(Xj,{className:"absolute top-[18%] left-[45%] w-6 h-6 text-sky-200/25 animate-pulse",style:{animationDelay:"0.6s"}}),e.jsx(Xj,{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"})]}),XUs=()=>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(Nn,{className:"absolute top-[3%] left-[50%] w-10 h-10 text-yellow-400/40"}),e.jsx(Cx,{className:"absolute bottom-[18%] left-[10%] w-12 h-12 text-purple-400/18 rotate-12"}),e.jsx(Cx,{className:"absolute bottom-[20%] right-[12%] w-10 h-10 text-amber-400/15 -rotate-12"})]}),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.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(Nn,{className:"absolute top-[5%] left-[20%] w-7 h-7 text-blue-400/35"}),e.jsx(Nn,{className:"absolute top-[10%] right-[18%] w-6 h-6 text-sky-400/30"})]}),JUs=()=>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(gE,{className:"absolute top-[5%] left-[10%] w-16 h-16 text-green-500/25"}),e.jsx(gE,{className:"absolute top-[8%] right-[12%] w-12 h-12 text-emerald-500/20"}),e.jsx(gE,{className:"absolute bottom-[18%] left-[12%] w-14 h-14 text-green-400/22"}),e.jsx(gE,{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"})]})]})]}),eqs=()=>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(AE,{className:"absolute top-[8%] left-[60%] w-10 h-10 text-indigo-400/18"})]}),tqs=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-amber-900/6 via-rose-900/6 to-purple-900/6"}),e.jsx(Fg,{className:"absolute bottom-[10%] left-[50%] -translate-x-1/2 w-20 h-20 text-amber-400/18"}),e.jsxs("div",{className:"absolute top-[5%] left-[15%]",children:[e.jsx("div",{className:"w-12 h-14 rounded-full bg-rose-400/25"}),e.jsx("div",{className:"w-0.5 h-10 bg-rose-400/18 mx-auto"})]}),e.jsxs("div",{className:"absolute top-[3%] left-[25%]",children:[e.jsx("div",{className:"w-10 h-12 rounded-full bg-sky-400/25"}),e.jsx("div",{className:"w-0.5 h-12 bg-sky-400/18 mx-auto"})]}),e.jsxs("div",{className:"absolute top-[8%] right-[18%]",children:[e.jsx("div",{className:"w-11 h-13 rounded-full bg-purple-400/25"}),e.jsx("div",{className:"w-0.5 h-9 bg-purple-400/18 mx-auto"})]}),e.jsxs("div",{className:"absolute top-[5%] right-[10%]",children:[e.jsx("div",{className:"w-10 h-12 rounded-full bg-amber-400/25"}),e.jsx("div",{className:"w-0.5 h-11 bg-amber-400/18 mx-auto"})]}),e.jsx("div",{className:"absolute top-[20%] left-[35%] w-3 h-3 bg-pink-400/35 rounded-full"}),e.jsx("div",{className:"absolute top-[18%] right-[40%] w-2.5 h-2.5 bg-emerald-400/35 rounded-full"}),e.jsx("div",{className:"absolute top-[25%] left-[55%] w-2 h-2 bg-amber-400/35 rounded-full"}),e.jsx("div",{className:"absolute top-[22%] right-[30%] w-2.5 h-2.5 bg-sky-400/35 rounded-full"}),e.jsx(Cx,{className:"absolute top-[8%] left-[45%] w-10 h-10 text-purple-400/22 rotate-12"}),e.jsx(ul,{className:"absolute bottom-[18%] right-[15%] w-12 h-12 text-rose-400/18"})]}),sqs=()=>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"})]}),nqs=()=>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(ek,{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(ek,{className:"absolute top-[15%] left-[18%] w-10 h-10 text-yellow-400/30"}),e.jsx(Nn,{className:"absolute top-[10%] left-[42%] w-7 h-7 text-amber-400/35"}),e.jsx(ek,{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"})]}),rqs=()=>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(w_,{className:"absolute top-[12%] right-[18%] w-10 h-10 text-amber-400/25"}),e.jsx(w_,{className:"absolute bottom-[22%] left-[22%] w-8 h-8 text-yellow-400/22"}),e.jsx(Jo,{className:"absolute top-[18%] left-[40%] w-6 h-6 text-rose-400/22 fill-rose-400/12"}),e.jsx(Jo,{className:"absolute top-[22%] right-[35%] w-5 h-5 text-teal-400/20 fill-teal-400/10"}),e.jsx(Nn,{className:"absolute top-[5%] left-[55%] w-8 h-8 text-teal-400/30"}),e.jsx(Cx,{className:"absolute bottom-[20%] left-[48%] w-10 h-10 text-cyan-400/18 rotate-12"})]}),aqs=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-emerald-900/10 via-teal-900/6 to-cyan-900/10"}),e.jsx(Cx,{className:"absolute top-[5%] left-[12%] w-14 h-14 text-emerald-400/25 rotate-12"}),e.jsx(Cx,{className:"absolute top-[8%] right-[10%] w-12 h-12 text-teal-400/22 -rotate-12"}),e.jsx(w_,{className:"absolute bottom-[18%] left-[18%] w-12 h-12 text-amber-400/25"}),e.jsx(va,{className:"absolute bottom-[15%] right-[12%] w-14 h-14 text-teal-500/18"}),e.jsx(Nn,{className:"absolute top-[15%] left-[42%] w-10 h-10 text-emerald-400/35"}),e.jsx(Nn,{className:"absolute top-[20%] right-[32%] w-7 h-7 text-cyan-400/30"}),e.jsx("div",{className:"absolute top-[25%] left-[55%] w-3 h-3 bg-amber-400/30 rounded-full"}),e.jsx("div",{className:"absolute top-[22%] right-[42%] w-2.5 h-2.5 bg-teal-400/30 rounded-full"}),e.jsx("div",{className:"absolute top-[28%] left-[35%] w-2 h-2 bg-emerald-400/30 rounded-full"})]}),iqs=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-amber-900/10 via-yellow-900/6 to-orange-900/10"}),e.jsx(w_,{className:"absolute bottom-[12%] left-[50%] -translate-x-1/2 w-24 h-24 text-amber-400/25 rotate-45"}),e.jsx(w_,{className:"absolute top-[10%] left-[12%] w-10 h-10 text-yellow-400/30"}),e.jsx(w_,{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(Cx,{className:"absolute bottom-[22%] right-[18%] w-12 h-12 text-orange-400/18 rotate-12"}),e.jsx(Nn,{className:"absolute top-[5%] right-[35%] w-8 h-8 text-yellow-400/35"}),e.jsx(ei,{className:"absolute top-[18%] left-[28%] w-6 h-6 text-amber-400/25 fill-amber-400/15"})]}),oqs=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-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(w_,{className:"absolute top-[10%] right-[12%] w-10 h-10 text-amber-400/28"}),e.jsx(Jo,{className:"absolute top-[8%] left-[18%] w-8 h-8 text-rose-400/25 fill-rose-400/15"}),e.jsx(Nn,{className:"absolute top-[12%] left-[45%] w-8 h-8 text-teal-400/30"}),e.jsx(i2,{className:"absolute top-[15%] right-[28%] w-10 h-10 text-emerald-400/20"})]}),Uvt=()=>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"})]}),lqs=()=>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"})]}),cqs=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(i2,{className:"absolute top-5 left-[10%] w-4 h-4 text-blue-400/50 animate-pulse"}),e.jsx(Nn,{className:"absolute top-10 right-[15%] w-3 h-3 text-amber-400/50 animate-pulse delay-100"}),e.jsx(va,{className:"absolute top-8 left-[38%] w-3 h-3 text-teal-300/40 animate-pulse delay-200"})]}),dqs=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(T4,{className:"absolute top-5 left-[12%] w-4 h-4 text-amber-500/50 animate-pulse"}),e.jsx(qq,{className:"absolute top-10 right-[15%] w-3 h-3 text-rose-400/50 animate-pulse delay-100"}),e.jsx(T4,{className:"absolute top-8 left-[40%] w-3 h-3 text-amber-400/40 animate-pulse delay-200"})]}),TZ=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(Nn,{className:"absolute top-5 left-[10%] w-4 h-4 text-emerald-400/50 animate-pulse"}),e.jsx(Cx,{className:"absolute top-10 right-[12%] w-5 h-5 text-amber-400/50 animate-pulse delay-150"}),e.jsx(Nn,{className:"absolute top-8 left-[45%] w-3 h-3 text-sky-400/40 animate-pulse delay-300"})]}),qvt=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(va,{className:"absolute top-6 left-[12%] w-4 h-4 text-teal-400/40 animate-pulse"}),e.jsx(Nn,{className:"absolute top-10 right-[15%] w-3 h-3 text-emerald-400/50 animate-pulse delay-100"}),e.jsx(va,{className:"absolute top-4 right-[40%] w-3 h-3 text-cyan-400/30 animate-pulse delay-200"})]}),LGe=[{id:"default",name:"Classic",description:"Clean, professional look for any occasion",icon:e.jsx(Nn,{className:"h-5 w-5"}),category:"general",headerText:()=>"Video Message",subText:"A personal video just for you",gradientClasses:"from-background to-muted/30",accentColor:"primary"},{id:"thank_you",name:"Thank You",description:"Express your gratitude",icon:e.jsx(Jo,{className:"h-5 w-5"}),category:"general",headerText:s=>s?`Thank You, ${s}!`:"Thank You!",subText:"Your support means the world to me",gradientClasses:"from-rose-50/70 via-pink-50/50 to-red-50/40 dark:from-rose-950/30 dark:via-pink-950/20 dark:to-red-950/20",accentColor:"rose",decorativeElement:e.jsx(lqs,{})},{id:"thinking_of_you",name:"Thinking of You",description:"Let them know they're on your mind",icon:e.jsx(fJ,{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(TZ,{})},{id:"check_in",name:"Check-in",description:"Touch base with your contacts",icon:e.jsx(T4,{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(dqs,{})},{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(TZ,{})},{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(Uvt,{})},{id:"welcome_neighborhood",name:"Welcome to the Neighborhood",description:"Greet new neighbors",icon:e.jsx(ci,{className:"h-5 w-5"}),category:"general",headerText:s=>s?`Welcome to the Neighborhood, ${s}!`:"Welcome to the Neighborhood!",subText:"So excited to have you as our new neighbor",gradientClasses:"from-teal-50/70 via-cyan-50/50 to-sky-50/40 dark:from-teal-950/30 dark:via-cyan-950/20 dark:to-sky-950/20",accentColor:"teal",decorativeElement:e.jsx(qvt,{})},{id:"just_because",name:"Just Because",description:"No reason needed to connect",icon:e.jsx(qq,{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(TZ,{})},{id:"birthday",name:"Birthday",description:"Celebrate their special day",icon:e.jsx(Fg,{className:"h-5 w-5"}),category:"holidays",headerText:s=>s?`Happy Birthday, ${s}!`:"Happy Birthday!",subText:"Wishing you an amazing year ahead",gradientClasses:"from-amber-50/80 via-rose-50/60 to-purple-50/40 dark:from-amber-950/30 dark:via-rose-950/20 dark:to-purple-950/20",accentColor:"amber",decorativeElement:e.jsx(tqs,{})},{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(sqs,{})},{id:"groundhog_day",name:"Groundhog Day",description:"A fun seasonal greeting",icon:e.jsx(ek,{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(nqs,{})},{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(XUs,{})},{id:"easter",name:"Easter",description:"Celebrate the spring season",icon:e.jsx(Eq,{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(WUs,{})},{id:"mothers_day",name:"Mother's Day",description:"Celebrate the amazing moms",icon:e.jsx(qS,{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(HUs,{})},{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(GUs,{})},{id:"memorial_day",name:"Memorial Day",description:"Honor those who served",icon:e.jsx(AE,{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(qUs,{})},{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(VUs,{})},{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(eqs,{})},{id:"halloween",name:"Halloween",description:"Spooky seasonal greetings",icon:e.jsx(Bz,{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(KUs,{})},{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(eL,{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(YUs,{})},{id:"hanukkah",name:"Hanukkah",description:"Celebrate the Festival of Lights",icon:e.jsx(Nn,{className:"h-5 w-5"}),category:"holidays",headerText:s=>s?`Happy Hanukkah, ${s}!`:"Happy Hanukkah!",subText:"Wishing you eight nights of light and joy",gradientClasses:"from-blue-50/70 via-indigo-50/50 to-sky-50/40 dark:from-blue-950/30 dark:via-indigo-950/20 dark:to-sky-950/20",accentColor:"blue",decorativeElement:e.jsx(QUs,{})},{id:"st_patricks_day",name:"St. Patrick's Day",description:"Celebrate the luck of the Irish",icon:e.jsx(gE,{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(JUs,{})},{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(rqs,{})},{id:"under_contract",name:"Under Contract",description:"Celebrate this exciting milestone",icon:e.jsx(Cx,{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(aqs,{})},{id:"just_listed",name:"Just Listed",description:"Announce a new listing",icon:e.jsx(Ta,{className:"h-5 w-5"}),category:"transactional",headerText:s=>s?`Exciting News, ${s}!`:"Just Listed!",subText:"A new property is now on the market",gradientClasses:"from-blue-50/70 via-indigo-50/50 to-violet-50/40 dark:from-blue-950/30 dark:via-indigo-950/20 dark:to-violet-950/20",accentColor:"blue",decorativeElement:e.jsx(qvt,{})},{id:"just_sold",name:"Just Sold",description:"Celebrate a successful sale",icon:e.jsx(nu,{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(TZ,{})},{id:"price_reduction",name:"Price Reduction",description:"Notify about a price change",icon:e.jsx(sC,{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(i2,{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(cqs,{})},{id:"closing_day",name:"Closing Day",description:"Celebrate their closing day",icon:e.jsx(w_,{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(iqs,{})},{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(oqs,{})},{id:"offer_accepted",name:"Offer Accepted",description:"Celebrate their accepted offer",icon:e.jsx(qy,{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(TZ,{})},{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(Uvt,{})}],uqs=[{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 hqs(s){return LGe.filter(t=>t.category===s)}function _V(s){return LGe.find(t=>t.id===s)||LGe[0]}function Vvt(){const{shareToken:s,recipientToken:t}=Wi(),[n,r]=j.useState(null),[a,i]=j.useState(null),[l,o]=j.useState(null),[c,d]=j.useState(!0),[u,h]=j.useState(null),[m,f]=j.useState(!0),g=j.useRef(null),x=j.useRef(0),y=j.useRef(0),v=(()=>{const U=new URLSearchParams(window.location.search);return t||U.get("rt")||null})(),b=j.useCallback((U,W=!1)=>{if(!v||U<=0)return;const V=Math.max(1,Math.round(U));if(V<=y.current)return;const Y=`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/track-video-share?t=${encodeURIComponent(v)}&e=watch&ws=${V}`;W&&navigator.sendBeacon?navigator.sendBeacon(Y):fetch(Y,{method:"GET",keepalive:W}).catch(()=>{}),y.current=Math.max(y.current,V)},[v]);j.useEffect(()=>{var ae;if(!m||!(n!=null&&n.playback_url)||!v)return;let U=!1;const W=()=>{x.current>0&&b(x.current,!0)},V=()=>{document.visibilityState==="hidden"&&W()},G=()=>{W()},Y=()=>{var ne;if(U||!g.current||!((ne=window.playerjs)!=null&&ne.Player))return;const 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)Y();else if(X)X.addEventListener("load",Y,{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=Y,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,v,b]),j.useEffect(()=>{x.current=0,y.current=0},[v,s]),j.useEffect(()=>{const U=()=>{['[id*="lc_text_widget"]','[class*="lc-text-widget"]','[id*="chat-widget"]','[class*="chat-widget"]','iframe[src*="widgets.leadconnectorhq"]','iframe[src*="msgsndr"]',"[data-chat-widget]"].forEach(Y=>{document.querySelectorAll(Y).forEach(X=>{X.style.display="none"})})};U();const W=[setTimeout(U,500),setTimeout(U,1500),setTimeout(U,3e3)],V=new MutationObserver(U);return V.observe(document.body,{childList:!0,subtree:!0}),()=>{W.forEach(clearTimeout),V.disconnect()}},[]),j.useEffect(()=>{(async()=>{if(!s){h("Invalid share link"),d(!1);return}const{data:W,error:V}=await q.from("agent_videos").select("id, title, playback_url, thumbnail_url, preview_url, duration_seconds, share_token, owner_user_id, contact_id, page_template, recipient_name").eq("share_token",s).eq("is_deleted",!1).single();if(V||!W){h("Video not found or has been removed"),d(!1);return}r(W);try{await q.rpc("log_video_view",{p_video_id:W.id,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null})}catch(G){console.warn("Failed to log video view:",G)}if(W.owner_user_id){const{data:G}=await q.from("profiles").select("id, name, email, phone").eq("id",W.owner_user_id).single();if(G){i(G);try{const{data:Y}=await q.storage.from("avatars").list(`${W.owner_user_id}`);if(Y&&Y.length>0){const{data:X}=q.storage.from("avatars").getPublicUrl(`${W.owner_user_id}/${Y[0].name}`);o(X.publicUrl)}}catch{}}}d(!1)})()},[s]);const w=U=>{if(!U)return"0:00";const W=Math.floor(U/60),V=U%60;return`${W}:${V.toString().padStart(2,"0")}`},S=U=>U.includes("iframe.mediadelivery.net/play/")?U.replace("/play/","/embed/")+"?autoplay=true&responsive=true":U,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=_V((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(Ie,{className:"py-12 text-center",children:[e.jsx(ua,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"Video Not Found"}),e.jsx("p",{className:"text-muted-foreground",children:u||"This video is no longer available."})]})})});const O=E.id!=="default";return e.jsxs(e.Fragment,{children:[e.jsxs(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(mn,{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(ua,{className:"h-16 w-16 text-primary/50"})}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/30 group-hover:bg-black/40 transition-colors",children:e.jsx("div",{className:"w-20 h-20 rounded-full bg-white/90 flex items-center justify-center shadow-lg transform group-hover:scale-105 transition-transform",children:e.jsx(zu,{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(zu,{className:"h-5 w-5"}),"Watch Video"]})}),e.jsx(UUs,{shareToken:s,agentName:(a==null?void 0:a.name)||null,hasContact:!!n.contact_id})]})]})]})}function mqs(){return j.useEffect(()=>(document.body.classList.add("video-landing-page"),()=>{document.body.classList.remove("video-landing-page")}),[]),e.jsx(ket,{})}function fqs(){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 pqs=[{key:"residential",title:"Residential",tagline:"Homes, condos, land & luxury",path:"/mission-control/listings/new/residential",icon:va,points:["Standard listing details","Listing Exchange & referrals","Single-property site & marketing"]},{key:"commercial",title:"Commercial",tagline:"Investment, office, retail, industrial & land",path:"/mission-control/listings/new/commercial",icon:ji,points:["Pitch Mode to win the assignment","Institutional-grade microsite","Gated OM & investor tracking"],featured:!0}];function gqs(){const s=Xn(),{search:t}=mu();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:pqs.map(n=>{const r=n.icon;return e.jsxs("button",{onClick:()=>s(`${n.path}${t}`),className:`group relative overflow-hidden rounded-2xl border p-7 text-left transition-all hover:-translate-y-0.5 hover:shadow-xl ${n.featured?"border-primary/40 bg-gradient-to-br from-primary/[0.07] to-transparent":"bg-card"}`,children:[n.featured&&e.jsxs("span",{className:"absolute right-5 top-5 inline-flex items-center gap-1 rounded-full border border-primary/30 bg-primary/10 px-2.5 py-1 text-[10px] font-semibold uppercase tracking-wider text-primary",children:[e.jsx(Nn,{className:"h-3 w-3"})," Commercial Launch"]}),e.jsx("div",{className:"mb-5 flex h-12 w-12 items-center justify-center rounded-xl border bg-background",children:e.jsx(r,{className:"h-6 w-6"})}),e.jsx("h2",{className:"text-xl font-semibold",children:n.title}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:n.tagline}),e.jsx("ul",{className:"mt-5 space-y-2 text-sm text-muted-foreground",children:n.points.map(a=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"mt-[7px] h-1 w-1 shrink-0 rounded-full bg-foreground/40"}),a]},a))}),e.jsxs("span",{className:"mt-6 inline-flex items-center gap-1 text-sm font-medium text-primary",children:["Continue ",e.jsx(Qa,{className:"h-4 w-4 transition-transform group-hover:translate-x-0.5"})]})]},n.key)})})]})})}const C$t=()=>{const{user:s}=bs();return st({queryKey:["managed-agent-ids",s==null?void 0:s.id],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("team_members").select("team_id").eq("user_id",s.id).eq("role","team_leader");if(n)throw n;const r=(t||[]).map(l=>l.team_id).filter(Boolean);if(!r.length)return[s.id];const{data:a,error:i}=await q.from("team_members").select("user_id").in("team_id",r);if(i)throw i;return Array.from(new Set([s.id,...(a||[]).map(l=>l.user_id).filter(Boolean)]))},enabled:!!s,staleTime:5*60*1e3})},A$t=s=>{const{user:t}=bs(),{data:n}=C$t();return!t||!s?!1:t.id===s?!0:(n||[]).includes(s)},E$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$t=s=>{const{user:t,brokerageId:n}=bs();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=>Vst(qst(o)))}})};function qst(s){return s&&Array.isArray(s.commercial)&&(s.commercial=s.commercial[0]??null),s}function Vst(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 Hst=()=>{const{user:s}=bs(),{data:t,isLoading:n}=C$t(),r=t&&t.length?t:s?[s.id]:[];return st({queryKey:["my-listings",s==null?void 0:s.id,r.slice().sort().join(",")],queryFn:async()=>{if(!s)return[];const{data:a,error:i}=await q.from("listings").select(` *, photos:listing_photos(*), commercial:commercial_listing_details(*) `).in("agent_id",r).order("created_at",{ascending:!1});if(i)throw i;return a.map(l=>Vst(qst(l)))},enabled:!!s&&!n})},Zae=s=>{const{user:t}=bs();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}),Vst(qst(n))},enabled:!!s})},M$t=()=>{const s=Wt(),{user:t}=bs();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"]})}})},xqs=()=>{const s=Wt();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"]})}})},P$t=()=>{const s=Wt();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]})}})},I$t=()=>{const s=Wt();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"]})}})},L$t=()=>{const s=Wt();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"]})}})},R$t=()=>{const s=Wt();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"]})}})},D$t=()=>{const s=Wt();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"]})}})},F$t=()=>{const s=Wt();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"]})}})},yqs=()=>{const{user:s}=bs();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})},O$t=()=>{const s=Wt(),{user:t}=bs();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"]})}})},z$t=s=>{const{user:t}=bs();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})},vqs=()=>{const s=Wt(),{user:t}=bs();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"]})}})},bqs=s=>{const{user:t}=bs();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})},_qs=()=>{const{user:s}=bs();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}})},wqs=()=>{const{user:s}=bs();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})},jqs=()=>{const s=Wt(),{user:t}=bs();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"]})}})},Nqs=()=>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}}}),kqs=()=>{const{user:s,brokerageId:t}=bs();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})},H7e=q,gp=s=>s===""||s==null?null:Number(String(s).replace(/[^0-9.\-]/g,"")),Sqs={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 Hvt({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(pr,{className:"h-4 w-4"})})]},i)),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:()=>r([...n,""]),children:[e.jsx(dn,{className:"mr-1.5 h-3.5 w-3.5"})," Add"]})]})}function G7e({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(pr,{className:"h-4 w-4"})})]},l)),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:()=>a([...r,{}]),children:[e.jsx(dn,{className:"mr-1.5 h-3.5 w-3.5"})," Add row"]})]})}const Cqs=[{key:"radius_1",label:"1 mile"},{key:"radius_3",label:"3 miles"},{key:"radius_5",label:"5 miles"}],Aqs=[{key:"population",label:"Population"},{key:"households",label:"Households"},{key:"avg_income",label:"Avg income"},{key:"daytime_pop",label:"Daytime pop."}];function Gvt(){const{listingId:s}=Wi(),t=Xn(),{user:n,loading:r}=bs(),a=!!s,{data:i,isLoading:l}=Zae(s||""),{data:o}=P7t(s);M$t();const c=P$t(),d=I7t(),u=L7t(),[h,m]=j.useState(null),[f,g]=j.useState(Sqs),[x,y]=j.useState([""]),[v,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,Y]=j.useState([]),X=!a||!!(n!=null&&n.id)&&(i==null?void 0:i.agent_id)===n.id;j.useEffect(()=>{!a||r||l||!i||X||(re.error("Only the listing agent can edit this commercial listing"),t(`/mission-control/listings/${i.id}/commercial`,{replace:!0}))},[r,i,a,X,l,t]);const ae=ue=>{if(!(ue!=null&&ue.length))return;const ve=Array.from(ue);V(Ee=>[...Ee,...ve]),Y(Ee=>[...Ee,...ve.map(Se=>URL.createObjectURL(Se))])},le=ue=>{URL.revokeObjectURL(G[ue]),V(ve=>ve.filter((Ee,Se)=>Se!==ue)),Y(ve=>ve.filter((Ee,Se)=>Se!==ue))},ne=async ue=>{if(!W.length)return;const{count:ve}=await H7e.from("listing_photos").select("id",{count:"exact",head:!0}).eq("listing_id",ue),Ee=ve??0;for(let Se=0;Seg(Ee=>({...Ee,[ue]:ve}));j.useEffect(()=>{!a||!i||(m(i.lifecycle_stage==="pitch"?"pitch":"assignment"),g(ue=>({...ue,property_address:i.property_address??"",city:i.city??"",state:i.state??"",description:i.description??"",year_built:i.year_built?String(i.year_built):"",is_public:!!i.is_public,allow_sharing:i.allow_sharing??!0,share_with_brokerage:i.share_with_brokerage??!1,open_to_referrals:i.open_to_referrals??!0,open_to_social_promotion:i.open_to_social_promotion??!0,show_on_lead_site:i.show_on_lead_site??!0,site_only:!i.is_public&&(i.show_on_lead_site??!1)&&!i.allow_sharing})))},[a,i]),j.useEffect(()=>{var ue;o&&(g(ve=>({...ve,submarket:o.submarket??"",opportunity_title:o.opportunity_title??"",deal_type:o.deal_type??"sale",commercial_type:o.commercial_type??"office",asking_price:o.asking_price!=null?String(o.asking_price):"",lease_rate:o.lease_rate!=null?String(o.lease_rate):"",lease_rate_unit:o.lease_rate_unit??"sf_year",lease_type:o.lease_type??"",building_sf:o.building_sf!=null?String(o.building_sf):"",available_sf:o.available_sf!=null?String(o.available_sf):"",lot_acres:o.lot_acres!=null?String(o.lot_acres):"",units:o.units!=null?String(o.units):"",floors:o.floors!=null?String(o.floors):"",parking_spaces:o.parking_spaces!=null?String(o.parking_spaces):"",zoning:o.zoning??"",occupancy_pct:o.occupancy_pct!=null?String(o.occupancy_pct):"",tenancy:o.tenancy??"",noi:o.noi!=null?String(o.noi):"",cap_rate:o.cap_rate!=null?String(o.cap_rate):"",gross_income:o.gross_income!=null?String(o.gross_income):"",operating_expenses:o.operating_expenses!=null?String(o.operating_expenses):"",broker_coop_pct:o.broker_coop_pct!=null?String(o.broker_coop_pct):"",call_for_offers_at:o.call_for_offers_at?o.call_for_offers_at.slice(0,10):"",is_confidential:!!o.is_confidential,hide_address:!!o.hide_address,requires_nda:!!o.requires_nda,om_gate_mode:o.om_gate_mode??"email",opportunity_zone:!!o.opportunity_zone})),y((ue=o.investment_highlights)!=null&&ue.length?o.investment_highlights:[""]),b(o.property_highlights??[]),S((o.spaces??[]).map(ve=>({...ve,sf:(ve==null?void 0:ve.sf)!=null?String(ve.sf):""}))),E((o.tenants??[]).map(ve=>({...ve,sf:(ve==null?void 0:ve.sf)!=null?String(ve.sf):""}))),P(o.traffic_counts??[]),D(o.demographics??{}))},[o]);const J=f.deal_type==="lease"||f.deal_type==="sale_or_lease",ce=f.deal_type!=="lease",_e=j.useMemo(()=>({deal_type:f.deal_type,commercial_type:f.commercial_type,opportunity_title:f.opportunity_title||null,submarket:f.submarket||null,asking_price:gp(f.asking_price),lease_rate:gp(f.lease_rate),lease_rate_unit:f.lease_rate_unit,lease_type:f.lease_type||null,building_sf:gp(f.building_sf),available_sf:gp(f.available_sf),lot_acres:gp(f.lot_acres),units:gp(f.units),floors:gp(f.floors),parking_spaces:gp(f.parking_spaces),zoning:f.zoning||null,occupancy_pct:gp(f.occupancy_pct),tenancy:f.tenancy||null,noi:gp(f.noi),cap_rate:gp(f.cap_rate),gross_income:gp(f.gross_income),operating_expenses:gp(f.operating_expenses),broker_coop_pct:gp(f.broker_coop_pct),call_for_offers_at:f.call_for_offers_at?new Date(f.call_for_offers_at).toISOString():null,is_confidential:f.is_confidential,hide_address:f.hide_address,requires_nda:f.requires_nda,om_gate_mode:f.om_gate_mode,opportunity_zone:f.opportunity_zone,investment_highlights:x.map(ue=>ue.trim()).filter(Boolean),spaces:w.filter(ue=>Object.values(ue).some(ve=>String(ve??"").trim())),tenants:A.filter(ue=>Object.values(ue).some(ve=>String(ve??"").trim())),traffic_counts:I.filter(ue=>String(ue.road??"").trim()||String(ue.count??"").trim()),demographics:Object.fromEntries(Object.entries(R).filter(([,ue])=>Object.values(ue??{}).some(ve=>String(ve??"").trim()))),property_highlights:v.map(ue=>ue.trim()).filter(Boolean),price_per_sf:gp(f.asking_price)&&gp(f.building_sf)?Math.round(gp(f.asking_price)/gp(f.building_sf)*100)/100:null,price_per_unit:gp(f.asking_price)&&gp(f.units)?Math.round(gp(f.asking_price)/gp(f.units)):null}),[f,x,v,w,A,I,R]),he=async()=>{if(a&&!X){re.error("Only the listing agent can edit this commercial listing");return}if(!f.city||!f.state){re.error("City and state are required");return}if(!a&&!h){re.error("Choose whether you already have the assignment");return}U(!0);try{let ue=s;const ve={property_address:f.property_address||null,city:f.city,state:f.state,neighborhood:f.submarket||null,price:gp(f.asking_price)??0,property_type:"commercial",description:f.description||null,year_built:gp(f.year_built),square_footage:gp(f.building_sf)},Ee=h==="pitch",Se=Ee?{is_public:!1,allow_sharing:!1,share_with_brokerage:!1,open_to_referrals:!1,open_to_social_promotion:!1,show_on_lead_site:!1}:{is_public:f.site_only?!1:f.is_public,allow_sharing:f.site_only?!1:f.allow_sharing,share_with_brokerage:f.site_only?!1:f.share_with_brokerage,open_to_referrals:f.open_to_referrals,open_to_social_promotion:f.site_only?!1:f.open_to_social_promotion,show_on_lead_site:f.site_only?!0:f.show_on_lead_site},Le=!Ee&&(Se.is_public||Se.show_on_lead_site||Se.allow_sharing)?"active":"coming_soon";if(a&&ue)await c.mutateAsync({id:ue,...ve,...Se,...Le==="active"?{status:"active"}:{}});else{const Fe=await H7e.from("listings").insert({...ve,...Se,agent_id:n.id,listing_class:"commercial",lifecycle_stage:Ee?"pitch":"won",status:Le}).select().single();if(Fe.error)throw Fe.error;ue=Fe.data.id,Ee&&await u.mutateAsync({listingId:ue,values:{launch_plan:M7t}})}await d.mutateAsync({listingId:ue,values:_e}),await ne(ue),re.success(a?"Commercial listing updated":"Commercial listing created"),t(`/mission-control/listings/${ue}/commercial`)}catch(ue){console.error(ue),re.error(ue.message||"Could not save listing")}finally{U(!1)}};return a&&(r||l||!i||!X)?e.jsx("div",{className:"flex min-h-[50vh] items-center justify-center",children:e.jsx(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(nh,{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(ji,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight md:text-3xl",children:a?"Edit commercial listing":h==="pitch"?"New pitch":"New commercial listing"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:h==="pitch"?"Private until you win it — never shown in the Exchange or on the public web.":"Only the fields that matter for this deal type are required."})]})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{className:"text-base",children:"The opportunity"}),e.jsx(Gn,{children:"How this deal is positioned to the market."})]}),e.jsxs(Ie,{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Deal type"}),e.jsxs(ms,{value:f.deal_type,onValueChange:ue=>te("deal_type",ue),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:Object.entries(AL).map(([ue,ve])=>e.jsx(Ge,{value:ue,children:ve},ue))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Property type"}),e.jsxs(ms,{value:f.commercial_type,onValueChange:ue=>te("commercial_type",ue),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:Object.entries(i6).map(([ue,ve])=>e.jsx(Ge,{value:ue,children:ve},ue))})]})]}),e.jsxs("div",{className:"space-y-2 md:col-span-2",children:[e.jsxs(ee,{children:["Opportunity name ",e.jsx("span",{className:"text-muted-foreground",children:"(optional)"})]}),e.jsx(pe,{value:f.opportunity_title,placeholder:"e.g. Gateway Logistics Center",onChange:ue=>te("opportunity_title",ue.target.value)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Used instead of the street address on confidential offerings."})]}),e.jsxs("div",{className:"space-y-2 md:col-span-2",children:[e.jsx(ee,{children:"Property story"}),e.jsx(Ls,{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(Ie,{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2 md:col-span-2",children:[e.jsx(ee,{children:"Street address"}),e.jsx(pe,{value:f.property_address,onChange:ue=>te("property_address",ue.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"City *"}),e.jsx(pe,{value:f.city,onChange:ue=>te("city",ue.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"State *"}),e.jsx(pe,{value:f.state,maxLength:2,onChange:ue=>te("state",ue.target.value.toUpperCase())})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Submarket"}),e.jsx(pe,{value:f.submarket,placeholder:"e.g. North Loop",onChange:ue=>te("submarket",ue.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Zoning"}),e.jsx(pe,{value:f.zoning,onChange:ue=>te("zoning",ue.target.value)})]})]})]}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-base",children:"Pricing"})}),e.jsxs(Ie,{className:"grid gap-4 md:grid-cols-2",children:[ce&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Asking price"}),e.jsx(pe,{value:f.asking_price,placeholder:"4750000",onChange:ue=>te("asking_price",ue.target.value)})]}),J&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Lease rate"}),e.jsx(pe,{value:f.lease_rate,placeholder:"24.50",onChange:ue=>te("lease_rate",ue.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Rate basis"}),e.jsxs(ms,{value:f.lease_rate_unit,onValueChange:ue=>te("lease_rate_unit",ue),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"sf_year",children:"Per SF / year"}),e.jsx(Ge,{value:"sf_month",children:"Per SF / month"}),e.jsx(Ge,{value:"month",children:"Per month"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Lease structure"}),e.jsxs(ms,{value:f.lease_type||"none",onValueChange:ue=>te("lease_type",ue==="none"?"":ue),children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Select"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"none",children:"Not specified"}),uDs.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(Ie,{className:"grid gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Building SF"}),e.jsx(pe,{value:f.building_sf,onChange:ue=>te("building_sf",ue.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Available SF"}),e.jsx(pe,{value:f.available_sf,onChange:ue=>te("available_sf",ue.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Lot acres"}),e.jsx(pe,{value:f.lot_acres,onChange:ue=>te("lot_acres",ue.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Units"}),e.jsx(pe,{value:f.units,onChange:ue=>te("units",ue.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Floors"}),e.jsx(pe,{value:f.floors,onChange:ue=>te("floors",ue.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Parking spaces"}),e.jsx(pe,{value:f.parking_spaces,onChange:ue=>te("parking_spaces",ue.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Year built"}),e.jsx(pe,{value:f.year_built,onChange:ue=>te("year_built",ue.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Tenancy"}),e.jsxs(ms,{value:f.tenancy||"none",onValueChange:ue=>te("tenancy",ue==="none"?"":ue),children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Select"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"none",children:"Not specified"}),e.jsx(Ge,{value:"single",children:"Single tenant"}),e.jsx(Ge,{value:"multi",children:"Multi-tenant"}),e.jsx(Ge,{value:"vacant",children:"Vacant"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Occupancy (%)"}),e.jsx(pe,{value:f.occupancy_pct,onChange:ue=>te("occupancy_pct",ue.target.value)})]})]})]}),e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{className:"text-base",children:"Investment metrics"}),e.jsx(Gn,{children:"Only what you enter is shown on the microsite."})]}),e.jsxs(Ie,{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"NOI"}),e.jsx(pe,{value:f.noi,onChange:ue=>te("noi",ue.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Cap rate (%)"}),e.jsx(pe,{value:f.cap_rate,onChange:ue=>te("cap_rate",ue.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Gross income"}),e.jsx(pe,{value:f.gross_income,onChange:ue=>te("gross_income",ue.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Operating expenses"}),e.jsx(pe,{value:f.operating_expenses,onChange:ue=>te("operating_expenses",ue.target.value)})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3 md:col-span-2",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Opportunity Zone"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Highlight qualified OZ tax treatment."})]}),e.jsx(Sn,{checked:f.opportunity_zone,onCheckedChange:ue=>te("opportunity_zone",ue)})]})]})]}),e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{className:"text-base",children:"Highlights"}),e.jsx(Gn,{children:"3–6 reasons this opportunity matters. These headline the microsite."})]}),e.jsxs(Ie,{className:"space-y-6",children:[e.jsx(Hvt,{label:"Investment highlights",placeholder:"e.g. 12-year NNN lease to investment-grade tenant",items:x,onChange:y}),e.jsx(Hvt,{label:"Property highlights",placeholder:"e.g. 32' clear height, 14 dock doors",items:v,onChange:b})]})]}),e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{className:"text-base",children:"Spaces, tenants & market data"}),e.jsx(Gn,{children:"Everything here is optional — the microsite only renders the sections you fill in."})]}),e.jsxs(Ie,{className:"space-y-8",children:[e.jsx(G7e,{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(G7e,{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(G7e,{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."})]}),Cqs.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}),Aqs.map(ve=>{var Ee;return e.jsxs("div",{className:"min-w-[120px] flex-1 space-y-1",children:[e.jsx(ee,{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:ve.label}),e.jsx(pe,{value:((Ee=R[ue.key])==null?void 0:Ee[ve.key])??"",onChange:Se=>D({...R,[ue.key]:{...R[ue.key]??{},[ve.key]:Se.target.value}})})]},ve.key)})]},ue.key))]})]})]}),e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{className:"text-base",children:"Photography"}),e.jsx(Gn,{children:"Cinematic exterior, aerial and interior imagery drives the microsite hero and gallery."})]}),e.jsxs(Ie,{className:"space-y-3",children:[e.jsxs("label",{className:"flex cursor-pointer items-center justify-center rounded-lg border border-dashed px-4 py-8 text-sm text-muted-foreground hover:bg-muted/40",children:[e.jsx(dn,{className:"mr-2 h-4 w-4"}),"Add photos",e.jsx("input",{type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:ue=>ae(ue.target.files)})]}),G.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid grid-cols-3 gap-2 sm:grid-cols-4",children:G.map((ue,ve)=>e.jsxs("div",{className:"group relative aspect-[4/3] overflow-hidden rounded-md border",children:[e.jsx("img",{src:ue,alt:`Commercial photo ${ve+1}`,className:"h-full w-full object-cover"}),e.jsx("button",{type:"button",onClick:()=>le(ve),className:"absolute right-1 top-1 rounded-full bg-background/90 p-1 opacity-0 transition group-hover:opacity-100","aria-label":"Remove photo",children:e.jsx(pr,{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(Gn,{children:"Choose where this opportunity appears. You control the Listing Exchange, your own website, and the public commercial marketplace independently."})]}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"My website only"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Hide from the Listing Exchange, other agents and the public marketplace."})]}),e.jsx(Sn,{checked:f.site_only,onCheckedChange:ue=>g(ve=>({...ve,site_only:ue,is_public:ue?!1:ve.is_public,show_on_lead_site:ue?!0:ve.show_on_lead_site,share_with_brokerage:ue?!1:ve.share_with_brokerage}))})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Publish publicly"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Go live on commercial.relevelup.com to capture leads."})]}),e.jsx(Sn,{checked:f.is_public,disabled:f.site_only,onCheckedChange:ue=>te("is_public",ue)})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Show on my website"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Feature it on your own lead site."})]}),e.jsx(Sn,{checked:f.show_on_lead_site,onCheckedChange:ue=>te("show_on_lead_site",ue)})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Allow sharing"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Other LevelUp agents can share it from the Exchange."})]}),e.jsx(Sn,{checked:f.allow_sharing,disabled:f.site_only,onCheckedChange:ue=>te("allow_sharing",ue)})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Share with my brokerage"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Visible to agents inside your brokerage."})]}),e.jsx(Sn,{checked:f.share_with_brokerage,disabled:f.site_only,onCheckedChange:ue=>te("share_with_brokerage",ue)})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Open to referrals"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Accept tenant / buyer referrals from other agents."})]}),e.jsx(Sn,{checked:f.open_to_referrals,onCheckedChange:ue=>te("open_to_referrals",ue)})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Social promotion"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Other agents may promote it on social media."})]}),e.jsx(Sn,{checked:f.open_to_social_promotion,disabled:f.site_only,onCheckedChange:ue=>te("open_to_social_promotion",ue)})]})]})]}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-base",children:"Confidentiality & document gating"})}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Confidential offering"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Teaser presentation, no address, search engines blocked."})]}),e.jsx(Sn,{checked:f.is_confidential,onCheckedChange:ue=>te("is_confidential",ue)})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Hide street address"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show city / submarket only."})]}),e.jsx(Sn,{checked:f.hide_address,onCheckedChange:ue=>te("hide_address",ue)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Offering Memorandum access"}),e.jsxs(ms,{value:f.om_gate_mode,onValueChange:ue=>te("om_gate_mode",ue),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"open",children:"Open download"}),e.jsx(Ge,{value:"email",children:"Require name, email & company"}),e.jsx(Ge,{value:"nda",children:"Require confidentiality acknowledgement"})]})]})]})]})]})]})]}),e.jsx("div",{className:"fixed inset-x-0 bottom-0 border-t bg-background/95 backdrop-blur",children:e.jsxs("div",{className:"mx-auto flex max-w-4xl items-center justify-between gap-3 px-4 py-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:h==="pitch"?"Saved privately — nothing publishes until you win.":"Not published until you launch."}),e.jsxs($,{onClick:he,disabled:O,children:[O&&e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}),a?"Save changes":"Create & continue"]})]})})]})}function i6e(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 B$t(){const{user:s}=bs(),t=Wt();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 $$t(){const s=Wt();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 Eqs(){const s=Wt();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 Tqs(){const s=Wt();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 Gst(s){const{data:t,error:n}=await q.storage.from("listing-documents").createSignedUrl(s,3600);if(n)throw n;return t.signedUrl}function Mqs(){for(var s=arguments.length,t=new Array(s),n=0;nr=>{t.forEach(a=>a(r))},t)}const o6e=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function oK(s){const t=Object.prototype.toString.call(s);return t==="[object Window]"||t==="[object global]"}function Wst(s){return"nodeType"in s}function Uw(s){var t,n;return s?oK(s)?s:Wst(s)&&(t=(n=s.ownerDocument)==null?void 0:n.defaultView)!=null?t:window:window}function Kst(s){const{Document:t}=Uw(s);return s instanceof t}function Xae(s){return oK(s)?!1:s instanceof Uw(s).HTMLElement}function U$t(s){return s instanceof Uw(s).SVGElement}function lK(s){return s?oK(s)?s.document:Wst(s)?Kst(s)?s:Xae(s)||U$t(s)?s.ownerDocument:document:document:document}const Y4=o6e?j.useLayoutEffect:j.useEffect;function Yst(s){const t=j.useRef(s);return Y4(()=>{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 rse(s,t){t===void 0&&(t=[s]);const n=j.useRef(s);return Y4(()=>{n.current!==s&&(n.current=s)},t),n}function Qae(s,t){const n=j.useRef();return j.useMemo(()=>{const r=s(n.current);return n.current=r,r},[...t])}function VEe(s){const t=Yst(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 RGe(s){const t=j.useRef();return j.useEffect(()=>{t.current=s},[s]),t.current}let W7e={};function Jae(s,t){return j.useMemo(()=>{if(t)return t;const n=W7e[s]==null?0:W7e[s]+1;return W7e[s]=n,s+"-"+n},[s,t])}function q$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 wV=q$t(1),ase=q$t(-1);function Iqs(s){return"clientX"in s&&"clientY"in s}function Zst(s){if(!s)return!1;const{KeyboardEvent:t}=Uw(s.target);return t&&s instanceof t}function Lqs(s){if(!s)return!1;const{TouchEvent:t}=Uw(s.target);return t&&s instanceof t}function DGe(s){if(Lqs(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 Iqs(s)?{x:s.clientX,y:s.clientY}:null}const PL=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[PL.Translate.toString(s),PL.Scale.toString(s)].join(" ")}},Transition:{toString(s){let{property:t,duration:n,easing:r}=s;return t+" "+n+"ms "+r}}}),Wvt="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function Rqs(s){return s.matches(Wvt)?s:s.querySelector(Wvt)}const Dqs={display:"none"};function Fqs(s){let{id:t,value:n}=s;return Gt.createElement("div",{id:t,style:Dqs},n)}function Oqs(s){let{id:t,announcement:n,ariaLiveType:r="assertive"}=s;const a={position:"fixed",top:0,left:0,width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(100%)",whiteSpace:"nowrap"};return Gt.createElement("div",{id:t,style:a,role:"status","aria-live":r,"aria-atomic":!0},n)}function zqs(){const[s,t]=j.useState("");return{announce:j.useCallback(r=>{r!=null&&t(r)},[]),announcement:s}}const V$t=j.createContext(null);function Bqs(s){const t=j.useContext(V$t);j.useEffect(()=>{if(!t)throw new Error("useDndMonitor must be used within a children of ");return t(s)},[s,t])}function $qs(){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 Uqs={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. `},qqs={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 Vqs(s){let{announcements:t=qqs,container:n,hiddenTextDescribedById:r,screenReaderInstructions:a=Uqs}=s;const{announce:i,announcement:l}=zqs(),o=Jae("DndLiveRegion"),[c,d]=j.useState(!1);if(j.useEffect(()=>{d(!0)},[]),Bqs(j.useMemo(()=>({onDragStart(h){let{active:m}=h;i(t.onDragStart({active:m}))},onDragMove(h){let{active:m,over:f}=h;t.onDragMove&&i(t.onDragMove({active:m,over:f}))},onDragOver(h){let{active:m,over:f}=h;i(t.onDragOver({active:m,over:f}))},onDragEnd(h){let{active:m,over:f}=h;i(t.onDragEnd({active:m,over:f}))},onDragCancel(h){let{active:m,over:f}=h;i(t.onDragCancel({active:m,over:f}))}}),[i,t])),!c)return null;const u=Gt.createElement(Gt.Fragment,null,Gt.createElement(Fqs,{id:r,value:a.draggable}),Gt.createElement(Oqs,{id:o,announcement:l}));return n?vv.createPortal(u,n):u}var g0;(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"})(g0||(g0={}));function HEe(){}function EG(s,t){return j.useMemo(()=>({sensor:s,options:t??{}}),[s,t])}function l6e(){for(var s=arguments.length,t=new Array(s),n=0;n[...t].filter(r=>r!=null),[...t])}const fC=Object.freeze({x:0,y:0});function H$t(s,t){return Math.sqrt(Math.pow(s.x-t.x,2)+Math.pow(s.y-t.y,2))}function G$t(s,t){let{data:{value:n}}=s,{data:{value:r}}=t;return n-r}function Hqs(s,t){let{data:{value:n}}=s,{data:{value:r}}=t;return r-n}function Kvt(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 W$t(s,t){if(!s||s.length===0)return null;const[n]=s;return n[t]}function Yvt(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 c6e=s=>{let{collisionRect:t,droppableRects:n,droppableContainers:r}=s;const a=Yvt(t,t.left,t.top),i=[];for(const l of r){const{id:o}=l,c=n.get(o);if(c){const d=H$t(Yvt(c),a);i.push({id:o,data:{droppableContainer:l,value:d}})}}return i.sort(G$t)},Gqs=s=>{let{collisionRect:t,droppableRects:n,droppableContainers:r}=s;const a=Kvt(t),i=[];for(const l of r){const{id:o}=l,c=n.get(o);if(c){const d=Kvt(c),u=a.reduce((m,f,g)=>m+H$t(d[g],f),0),h=Number((u/4).toFixed(4));i.push({id:o,data:{droppableContainer:l,value:h}})}}return i.sort(G$t)};function Wqs(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=Wqs(o,t);c>0&&a.push({id:l,data:{droppableContainer:i,value:c}})}}return a.sort(Hqs)};function Yqs(s,t,n){return{...s,scaleX:t&&n?t.width/n.width:1,scaleY:t&&n?t.height/n.height:1}}function K$t(s,t){return s&&t?{x:s.left-t.left,y:s.top-t.top}:fC}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 Xqs=Zqs(1);function Qqs(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 Jqs(s,t,n){const r=Qqs(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 eVs={ignoreTransform:!1};function cK(s,t){t===void 0&&(t=eVs);let n=s.getBoundingClientRect();if(t.ignoreTransform){const{transform:d,transformOrigin:u}=Uw(s).getComputedStyle(s);d&&(n=Jqs(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 Zvt(s){return cK(s,{ignoreTransform:!0})}function tVs(s){const t=s.innerWidth,n=s.innerHeight;return{top:0,left:0,right:t,bottom:n,width:t,height:n}}function sVs(s,t){return t===void 0&&(t=Uw(s).getComputedStyle(s)),t.position==="fixed"}function nVs(s,t){t===void 0&&(t=Uw(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 d6e(s,t){const n=[];function r(a){if(t!=null&&n.length>=t||!a)return n;if(Kst(a)&&a.scrollingElement!=null&&!n.includes(a.scrollingElement))return n.push(a.scrollingElement),n;if(!Xae(a)||U$t(a)||n.includes(a))return n;const i=Uw(s).getComputedStyle(a);return a!==s&&nVs(a,i)&&n.push(a),sVs(a,i)?n:r(a.parentNode)}return s?r(s):n}function Y$t(s){const[t]=d6e(s,1);return t??null}function K7e(s){return!o6e||!s?null:oK(s)?s:Wst(s)?Kst(s)||s===lK(s).scrollingElement?window:Xae(s)?s:null:null}function Z$t(s){return oK(s)?s.scrollX:s.scrollLeft}function X$t(s){return oK(s)?s.scrollY:s.scrollTop}function FGe(s){return{x:Z$t(s),y:X$t(s)}}var uv;(function(s){s[s.Forward=1]="Forward",s[s.Backward=-1]="Backward"})(uv||(uv={}));function Q$t(s){return!o6e||!s?!1:s===document.scrollingElement}function J$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 rVs={x:.2,y:.2};function aVs(s,t,n,r,a){let{top:i,left:l,right:o,bottom:c}=n;r===void 0&&(r=10),a===void 0&&(a=rVs);const{isTop:d,isBottom:u,isLeft:h,isRight:m}=J$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=uv.Backward,g.y=r*Math.abs((t.top+x.height-i)/x.height)):!u&&c>=t.bottom-x.height&&(f.y=uv.Forward,g.y=r*Math.abs((t.bottom-x.height-c)/x.height)),!m&&o>=t.right-x.width?(f.x=uv.Forward,g.x=r*Math.abs((t.right-x.width-o)/x.width)):!h&&l<=t.left+x.width&&(f.x=uv.Backward,g.x=r*Math.abs((t.left+x.width-l)/x.width)),{direction:f,speed:g}}function iVs(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 eUt(s){return s.reduce((t,n)=>wV(t,FGe(n)),fC)}function oVs(s){return s.reduce((t,n)=>t+Z$t(n),0)}function lVs(s){return s.reduce((t,n)=>t+X$t(n),0)}function cVs(s,t){if(t===void 0&&(t=cK),!s)return;const{top:n,left:r,bottom:a,right:i}=t(s);Y$t(s)&&(a<=0||i<=0||n>=window.innerHeight||r>=window.innerWidth)&&s.scrollIntoView({block:"center",inline:"center"})}const dVs=[["x",["left","right"],oVs],["y",["top","bottom"],lVs]];let Xst=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=d6e(n),a=eUt(r);this.rect={...t},this.width=t.width,this.height=t.height;for(const[i,l,o]of dVs)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 bee{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 uVs(s){const{EventTarget:t}=Uw(s);return s instanceof t?s:lK(s)}function Y7e(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 jN;(function(s){s.Click="click",s.DragStart="dragstart",s.Keydown="keydown",s.ContextMenu="contextmenu",s.Resize="resize",s.SelectionChange="selectionchange",s.VisibilityChange="visibilitychange"})(jN||(jN={}));function Xvt(s){s.preventDefault()}function hVs(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 tUt={start:[Xu.Space,Xu.Enter],cancel:[Xu.Esc],end:[Xu.Space,Xu.Enter,Xu.Tab]},mVs=(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 u6e{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 bee(lK(n)),this.windowListeners=new bee(Uw(n)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(jN.Resize,this.handleCancel),this.windowListeners.add(jN.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(jN.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:t,onStart:n}=this.props,r=t.node.current;r&&cVs(r),n(fC)}handleKeyDown(t){if(Zst(t)){const{active:n,context:r,options:a}=this.props,{keyboardCodes:i=tUt,coordinateGetter:l=mVs,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}:fC;this.referenceCoordinates||(this.referenceCoordinates=u);const h=l(t,{active:n,context:r.current,currentCoordinates:u});if(h){const m=ase(h,u),f={x:0,y:0},{scrollableAncestors:g}=r.current;for(const x of g){const y=t.code,{isTop:v,isRight:b,isLeft:w,isBottom:S,maxScroll:A,minScroll:E}=J$t(x),I=iVs(x),P={x:Math.min(y===Xu.Right?I.right-I.width/2:I.right,Math.max(y===Xu.Right?I.left:I.left+I.width/2,h.x)),y:Math.min(y===Xu.Down?I.bottom-I.height/2:I.bottom,Math.max(y===Xu.Down?I.top:I.top+I.height/2,h.y))},R=y===Xu.Right&&!b||y===Xu.Left&&!w,D=y===Xu.Down&&!S||y===Xu.Up&&!v;if(R&&P.x!==h.x){const O=x.scrollLeft+m.x,U=y===Xu.Right&&O<=A.x||y===Xu.Left&&O>=E.x;if(U&&!m.y){x.scrollTo({left:O,behavior:o});return}U?f.x=x.scrollLeft-O:f.x=y===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=y===Xu.Down&&O<=A.y||y===Xu.Up&&O>=E.y;if(U&&!m.x){x.scrollTo({top:O,behavior:o});return}U?f.y=x.scrollTop-O:f.y=y===Xu.Down?x.scrollTop-A.y:x.scrollTop-E.y,f.y&&x.scrollBy({top:-f.y,behavior:o});break}}this.handleMove(t,wV(ase(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()}}u6e.activators=[{eventName:"onKeyDown",handler:(s,t,n)=>{let{keyboardCodes:r=tUt,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 Qvt(s){return!!(s&&"distance"in s)}function Jvt(s){return!!(s&&"delay"in s)}class Qst{constructor(t,n,r){var a;r===void 0&&(r=uVs(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=lK(l),this.documentListeners=new bee(this.document),this.listeners=new bee(r),this.windowListeners=new bee(Uw(l)),this.initialCoordinates=(a=DGe(i))!=null?a:fC,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(jN.Resize,this.handleCancel),this.windowListeners.add(jN.DragStart,Xvt),this.windowListeners.add(jN.VisibilityChange,this.handleCancel),this.windowListeners.add(jN.ContextMenu,Xvt),this.documentListeners.add(jN.Keydown,this.handleKeydown),n){if(r!=null&&r({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(Jvt(n)){this.timeoutId=setTimeout(this.handleStart,n.delay),this.handlePending(n);return}if(Qvt(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(jN.Click,hVs,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(jN.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=DGe(t))!=null?n:fC,d=ase(a,c);if(!r&&o){if(Qvt(o)){if(o.tolerance!=null&&Y7e(d,o.tolerance))return this.handleCancel();if(Y7e(d,o.distance))return this.handleStart()}if(Jvt(o)&&Y7e(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 fVs={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class dK extends Qst{constructor(t){const{event:n}=t,r=lK(n.target);super(t,fVs,r)}}dK.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 pVs={move:{name:"mousemove"},end:{name:"mouseup"}};var OGe;(function(s){s[s.RightClick=2]="RightClick"})(OGe||(OGe={}));class gVs extends Qst{constructor(t){super(t,pVs,lK(t.event.target))}}gVs.activators=[{eventName:"onMouseDown",handler:(s,t)=>{let{nativeEvent:n}=s,{onActivation:r}=t;return n.button===OGe.RightClick?!1:(r==null||r({event:n}),!0)}}];const Z7e={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class xVs extends Qst{constructor(t){super(t,Z7e)}static setup(){return window.addEventListener(Z7e.move.name,t,{capture:!1,passive:!1}),function(){window.removeEventListener(Z7e.move.name,t)};function t(){}}}xVs.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 _ee;(function(s){s[s.Pointer=0]="Pointer",s[s.DraggableRect=1]="DraggableRect"})(_ee||(_ee={}));var GEe;(function(s){s[s.TreeOrder=0]="TreeOrder",s[s.ReversedTreeOrder=1]="ReversedTreeOrder"})(GEe||(GEe={}));function yVs(s){let{acceleration:t,activator:n=_ee.Pointer,canScroll:r,draggingRect:a,enabled:i,interval:l=5,order:o=GEe.TreeOrder,pointerCoordinates:c,scrollableAncestors:d,scrollableAncestorRects:u,delta:h,threshold:m}=s;const f=bVs({delta:h,disabled:!i}),[g,x]=Pqs(),y=j.useRef({x:0,y:0}),v=j.useRef({x:0,y:0}),b=j.useMemo(()=>{switch(n){case _ee.Pointer:return c?{top:c.y,bottom:c.y,left:c.x,right:c.x}:null;case _ee.DraggableRect:return a}},[n,a,c]),w=j.useRef(null),S=j.useCallback(()=>{const E=w.current;if(!E)return;const I=y.current.x*v.current.x,P=y.current.y*v.current.y;E.scrollBy(I,P)},[]),A=j.useMemo(()=>o===GEe.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}=aVs(E,P,b,t,m);for(const O of["x","y"])f[O][R[O]]||(D[O]=0,R[O]=0);if(D.x>0||D.y>0){x(),w.current=E,g(S,l),y.current=D,v.current=R;return}}y.current={x:0,y:0},v.current={x:0,y:0},x()},[t,S,r,x,i,l,JSON.stringify(b),JSON.stringify(f),g,d,A,u,JSON.stringify(m)])}const vVs={x:{[uv.Backward]:!1,[uv.Forward]:!1},y:{[uv.Backward]:!1,[uv.Forward]:!1}};function bVs(s){let{delta:t,disabled:n}=s;const r=RGe(t);return Qae(a=>{if(n||!r||!a)return vVs;const i={x:Math.sign(t.x-r.x),y:Math.sign(t.y-r.y)};return{x:{[uv.Backward]:a.x[uv.Backward]||i.x===-1,[uv.Forward]:a.x[uv.Forward]||i.x===1},y:{[uv.Backward]:a.y[uv.Backward]||i.y===-1,[uv.Forward]:a.y[uv.Forward]||i.y===1}}},[n,t,r])}function _Vs(s,t){const n=t!=null?s.get(t):void 0,r=n?n.node.current:null;return Qae(a=>{var i;return t==null?null:(i=r??a)!=null?i:null},[r,t])}function wVs(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 ise;(function(s){s[s.Always=0]="Always",s[s.BeforeDragging=1]="BeforeDragging",s[s.WhileDragging=2]="WhileDragging"})(ise||(ise={}));var zGe;(function(s){s.Optimized="optimized"})(zGe||(zGe={}));const ebt=new Map;function jVs(s,t){let{dragging:n,dependencies:r,config:a}=t;const[i,l]=j.useState(null),{frequency:o,measure:c,strategy:d}=a,u=j.useRef(s),h=y(),m=rse(h),f=j.useCallback(function(v){v===void 0&&(v=[]),!m.current&&l(b=>b===null?v:b.concat(v.filter(w=>!b.includes(w))))},[m]),g=j.useRef(null),x=Qae(v=>{if(h&&!n)return ebt;if(!v||v===ebt||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 Xst(c(S),S):null;w.rect.current=A,A&&b.set(w.id,A)}return b}return v},[s,i,n,h,c]);return j.useEffect(()=>{u.current=s},[s]),j.useEffect(()=>{h||f()},[n,h]),j.useEffect(()=>{i&&i.length>0&&l(null)},[JSON.stringify(i)]),j.useEffect(()=>{h||typeof o!="number"||g.current!==null||(g.current=setTimeout(()=>{f(),g.current=null},o))},[o,h,f,...r]),{droppableRects:x,measureDroppableContainers:f,measuringScheduled:i!=null};function y(){switch(d){case ise.Always:return!1;case ise.BeforeDragging:return n;default:return!n}}}function sUt(s,t){return Qae(n=>s?n||(typeof t=="function"?t(s):s):null,[t,s])}function NVs(s,t){return sUt(s,t)}function kVs(s){let{callback:t,disabled:n}=s;const r=Yst(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 h6e(s){let{callback:t,disabled:n}=s;const r=Yst(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 SVs(s){return new Xst(cK(s),s)}function tbt(s,t,n){t===void 0&&(t=SVs);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=kVs({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=h6e({callback:i});return Y4(()=>{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 CVs(s){const t=sUt(s);return K$t(s,t)}const sbt=[];function AVs(s){const t=j.useRef(s),n=Qae(r=>s?r&&r!==sbt&&s&&t.current&&s.parentNode===t.current.parentNode?r:d6e(s):sbt,[s]);return j.useEffect(()=>{t.current=s},[s]),n}function EVs(s){const[t,n]=j.useState(null),r=j.useRef(s),a=j.useCallback(i=>{const l=K7e(i.target);l&&n(o=>o?(o.set(l,FGe(l)),new Map(o)):null)},[]);return j.useEffect(()=>{const i=r.current;if(s!==i){l(i);const o=s.map(c=>{const d=K7e(c);return d?(d.addEventListener("scroll",a,{passive:!0}),[d,FGe(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=K7e(c);d==null||d.removeEventListener("scroll",a)})}},[a,s]),j.useMemo(()=>s.length?t?Array.from(t.values()).reduce((i,l)=>wV(i,l),fC):eUt(s):fC,[s,t])}function nbt(s,t){t===void 0&&(t=[]);const n=j.useRef(null);return j.useEffect(()=>{n.current=null},t),j.useEffect(()=>{const r=s!==fC;r&&!n.current&&(n.current=s),!r&&n.current&&(n.current=null)},[s]),n.current?ase(s,n.current):fC}function TVs(s){j.useEffect(()=>{if(!o6e)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 MVs(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 nUt(s){return j.useMemo(()=>s?tVs(s):null,[s])}const rbt=[];function PVs(s,t){t===void 0&&(t=cK);const[n]=s,r=nUt(n?Uw(n):null),[a,i]=j.useState(rbt);function l(){i(()=>s.length?s.map(c=>Q$t(c)?r:new Xst(t(c),c)):rbt)}const o=h6e({callback:l});return Y4(()=>{o==null||o.disconnect(),l(),s.forEach(c=>o==null?void 0:o.observe(c))},[s]),a}function IVs(s){if(!s)return null;if(s.children.length>1)return s;const t=s.children[0];return Xae(t)?t:s}function LVs(s){let{measure:t}=s;const[n,r]=j.useState(null),a=j.useCallback(d=>{for(const{target:u}of d)if(Xae(u)){r(h=>{const m=t(u);return h?{...h,width:m.width,height:m.height}:m});break}},[t]),i=h6e({callback:a}),l=j.useCallback(d=>{const u=IVs(d);i==null||i.disconnect(),u&&(i==null||i.observe(u)),r(u?t(u):null)},[t,i]),[o,c]=VEe(l);return j.useMemo(()=>({nodeRef:o,rect:n,setRef:c}),[n,o,c])}const RVs=[{sensor:dK,options:{}},{sensor:u6e,options:{}}],DVs={current:{}},l3e={draggable:{measure:Zvt},droppable:{measure:Zvt,strategy:ise.WhileDragging,frequency:zGe.Optimized},dragOverlay:{measure:cK}};class wee 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 FVs={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new wee,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:HEe},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:l3e,measureDroppableContainers:HEe,windowRect:null,measuringScheduled:!1},OVs={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:HEe,draggableNodes:new Map,over:null,measureDroppableContainers:HEe},m6e=j.createContext(OVs),rUt=j.createContext(FVs);function zVs(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new wee}}}function BVs(s,t){switch(t.type){case g0.DragStart:return{...s,draggable:{...s.draggable,initialCoordinates:t.initialCoordinates,active:t.active}};case g0.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 g0.DragEnd:case g0.DragCancel:return{...s,draggable:{...s.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case g0.RegisterDroppable:{const{element:n}=t,{id:r}=n,a=new wee(s.droppable.containers);return a.set(r,n),{...s,droppable:{...s.droppable,containers:a}}}case g0.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 wee(s.droppable.containers);return l.set(n,{...i,disabled:a}),{...s,droppable:{...s.droppable,containers:l}}}case g0.UnregisterDroppable:{const{id:n,key:r}=t,a=s.droppable.containers.get(n);if(!a||r!==a.key)return s;const i=new wee(s.droppable.containers);return i.delete(n),{...s,droppable:{...s.droppable,containers:i}}}default:return s}}function $Vs(s){let{disabled:t}=s;const{active:n,activatorEvent:r,draggableNodes:a}=j.useContext(m6e),i=RGe(r),l=RGe(n==null?void 0:n.id);return j.useEffect(()=>{if(!t&&!r&&i&&l!=null){if(!Zst(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=Rqs(u);if(h){h.focus();break}}})}},[r,t,a,l,i]),null}function UVs(s,t){let{transform:n,...r}=t;return s!=null&&s.length?s.reduce((a,i)=>i({transform:a,...r}),n):n}function qVs(s){return j.useMemo(()=>({draggable:{...l3e.draggable,...s==null?void 0:s.draggable},droppable:{...l3e.droppable,...s==null?void 0:s.droppable},dragOverlay:{...l3e.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 VVs(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;Y4(()=>{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=K$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=Y$t(d);m&&m.scrollBy({top:h.y,left:h.x})}},[t,l,o,r,n])}const aUt=j.createContext({...fC,scaleX:1,scaleY:1});var dP;(function(s){s[s.Uninitialized=0]="Uninitialized",s[s.Initializing=1]="Initializing",s[s.Initialized=2]="Initialized"})(dP||(dP={}));const f6e=j.memo(function(t){var n,r,a,i;let{id:l,accessibility:o,autoScroll:c=!0,children:d,sensors:u=RVs,collisionDetection:h=Kqs,measuring:m,modifiers:f,...g}=t;const x=j.useReducer(BVs,void 0,zVs),[y,v]=x,[b,w]=$qs(),[S,A]=j.useState(dP.Uninitialized),E=S===dP.Initialized,{draggable:{active:I,nodes:P,translate:R},droppable:{containers:D}}=y,O=I!=null?P.get(I):null,U=j.useRef({initial:null,translated:null}),W=j.useMemo(()=>{var ds;return I!=null?{id:I,data:(ds=O==null?void 0:O.data)!=null?ds:DVs,rect:U}:null},[I,O]),V=j.useRef(null),[G,Y]=j.useState(null),[X,ae]=j.useState(null),le=rse(g,Object.values(g)),ne=Jae("DndDescribedBy",l),te=j.useMemo(()=>D.getEnabled(),[D]),J=qVs(m),{droppableRects:ce,measureDroppableContainers:_e,measuringScheduled:he}=jVs(te,{dragging:E,dependencies:[R.x,R.y],config:J.droppable}),ue=_Vs(P,I),ve=j.useMemo(()=>X?DGe(X):null,[X]),Ee=Xs(),Se=NVs(ue,J.draggable.measure);VVs({activeNode:I!=null?P.get(I):null,config:Ee.layoutShiftCompensation,initialRect:Se,measure:J.draggable.measure});const Le=tbt(ue,J.draggable.measure,Se),Fe=tbt(ue?ue.parentElement:null),ke=j.useRef({activatorEvent:null,active:null,activeNode:ue,collisionRect:null,collisions:null,droppableRects:ce,draggableNodes:P,draggingNode:null,draggingNodeRect:null,droppableContainers:D,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),Be=D.getNodeFor((n=ke.current.over)==null?void 0:n.id),Ne=LVs({measure:J.dragOverlay.measure}),Ae=(r=Ne.nodeRef.current)!=null?r:ue,Ce=E?(a=Ne.rect)!=null?a:Le:null,Ve=!!(Ne.nodeRef.current&&Ne.rect),ze=CVs(Ve?null:Le),qe=nUt(Ae?Uw(Ae):null),dt=AVs(E?Be??ue:null),Xe=PVs(dt),at=UVs(f,{transform:{x:R.x-ze.x,y:R.y-ze.y,scaleX:1,scaleY:1},activatorEvent:X,active:W,activeNodeRect:Le,containerNodeRect:Fe,draggingNodeRect:Ce,over:ke.current.over,overlayNodeRect:Ne.rect,scrollableAncestors:dt,scrollableAncestorRects:Xe,windowRect:qe}),rt=ve?wV(ve,R):null,Ke=EVs(dt),Je=nbt(Ke),pt=nbt(Ke,[Le]),gt=wV(at,Je),ss=Ce?Xqs(Ce,at):null,Yt=W&&ss?h({active:W,collisionRect:ss,droppableRects:ce,droppableContainers:te,pointerCoordinates:rt}):null,ts=W$t(Yt,"id"),[ys,Bt]=j.useState(null),Ft=Ve?at:wV(at,pt),as=Yqs(Ft,(i=ys==null?void 0:ys.rect)!=null?i:null,Le),kt=j.useRef(null),Ks=j.useCallback((ds,Ss)=>{let{sensor:yn,options:Js}=Ss;if(V.current==null)return;const Ut=P.get(V.current);if(!Ut)return;const hn=ds.nativeEvent,hr=new yn({active:V.current,activeNode:Ut,event:hn,options:Js,context:ke,onAbort(jr){if(!P.get(jr))return;const{onDragAbort:$n}=le.current,kn={id:jr};$n==null||$n(kn),b({type:"onDragAbort",event:kn})},onPending(jr,kr,$n,kn){if(!P.get(jr))return;const{onDragPending:bn}=le.current,xs={id:jr,constraint:kr,initialCoordinates:$n,offset:kn};bn==null||bn(xs),b({type:"onDragPending",event:xs})},onStart(jr){const kr=V.current;if(kr==null)return;const $n=P.get(kr);if(!$n)return;const{onDragStart:kn}=le.current,Fn={activatorEvent:hn,active:{id:kr,data:$n.data,rect:U}};vv.unstable_batchedUpdates(()=>{kn==null||kn(Fn),A(dP.Initializing),v({type:g0.DragStart,initialCoordinates:jr,active:kr}),b({type:"onDragStart",event:Fn}),Y(kt.current),ae(hn)})},onMove(jr){v({type:g0.DragMove,coordinates:jr})},onEnd:Rs(g0.DragEnd),onCancel:Rs(g0.DragCancel)});kt.current=hr;function Rs(jr){return async function(){const{active:$n,collisions:kn,over:Fn,scrollAdjustedTranslate:bn}=ke.current;let xs=null;if($n&&bn){const{cancelDrop:Lr}=le.current;xs={activatorEvent:hn,active:$n,collisions:kn,delta:bn,over:Fn},jr===g0.DragEnd&&typeof Lr=="function"&&await Promise.resolve(Lr(xs))&&(jr=g0.DragCancel)}V.current=null,vv.unstable_batchedUpdates(()=>{v({type:jr}),A(dP.Uninitialized),Bt(null),Y(null),ae(null),kt.current=null;const Lr=jr===g0.DragEnd?"onDragEnd":"onDragCancel";if(xs){const Or=le.current[Lr];Or==null||Or(xs),b({type:Lr,event:xs})}})}}},[P]),wt=j.useCallback((ds,Ss)=>(yn,Js)=>{const Ut=yn.nativeEvent,hn=P.get(Js);if(V.current!==null||!hn||Ut.dndKit||Ut.defaultPrevented)return;const hr={active:hn};ds(yn,Ss.options,hr)===!0&&(Ut.dndKit={capturedBy:Ss.sensor},V.current=Js,Ks(yn,Ss))},[P,Ks]),gs=wVs(u,wt);TVs(u),Y4(()=>{Le&&S===dP.Initializing&&A(dP.Initialized)},[Le,S]),j.useEffect(()=>{const{onDragMove:ds}=le.current,{active:Ss,activatorEvent:yn,collisions:Js,over:Ut}=ke.current;if(!Ss||!yn)return;const hn={active:Ss,activatorEvent:yn,collisions:Js,delta:{x:gt.x,y:gt.y},over:Ut};vv.unstable_batchedUpdates(()=>{ds==null||ds(hn),b({type:"onDragMove",event:hn})})},[gt.x,gt.y]),j.useEffect(()=>{const{active:ds,activatorEvent:Ss,collisions:yn,droppableContainers:Js,scrollAdjustedTranslate:Ut}=ke.current;if(!ds||V.current==null||!Ss||!Ut)return;const{onDragOver:hn}=le.current,hr=Js.get(ts),Rs=hr&&hr.rect.current?{id:hr.id,rect:hr.rect.current,data:hr.data,disabled:hr.disabled}:null,jr={active:ds,activatorEvent:Ss,collisions:yn,delta:{x:Ut.x,y:Ut.y},over:Rs};vv.unstable_batchedUpdates(()=>{Bt(Rs),hn==null||hn(jr),b({type:"onDragOver",event:jr})})},[ts]),Y4(()=>{ke.current={activatorEvent:X,active:W,activeNode:ue,collisionRect:ss,collisions:Yt,droppableRects:ce,draggableNodes:P,draggingNode:Ae,draggingNodeRect:Ce,droppableContainers:D,over:ys,scrollableAncestors:dt,scrollAdjustedTranslate:gt},U.current={initial:Ce,translated:ss}},[W,ue,Yt,ss,P,Ae,Ce,ce,D,ys,dt,gt]),yVs({...Ee,delta:R,draggingRect:ss,pointerCoordinates:rt,scrollableAncestors:dt,scrollableAncestorRects:Xe});const ks=j.useMemo(()=>({active:W,activeNode:ue,activeNodeRect:Le,activatorEvent:X,collisions:Yt,containerNodeRect:Fe,dragOverlay:Ne,draggableNodes:P,droppableContainers:D,droppableRects:ce,over:ys,measureDroppableContainers:_e,scrollableAncestors:dt,scrollableAncestorRects:Xe,measuringConfiguration:J,measuringScheduled:he,windowRect:qe}),[W,ue,Le,X,Yt,Fe,Ne,P,D,ce,ys,_e,dt,Xe,J,he,qe]),Is=j.useMemo(()=>({activatorEvent:X,activators:gs,active:W,activeNodeRect:Le,ariaDescribedById:{draggable:ne},dispatch:v,draggableNodes:P,over:ys,measureDroppableContainers:_e}),[X,gs,W,Le,v,ne,P,ys,_e]);return Gt.createElement(V$t.Provider,{value:w},Gt.createElement(m6e.Provider,{value:Is},Gt.createElement(rUt.Provider,{value:ks},Gt.createElement(aUt.Provider,{value:as},d)),Gt.createElement($Vs,{disabled:(o==null?void 0:o.restoreFocus)===!1})),Gt.createElement(Vqs,{...o,hiddenTextDescribedById:ne}));function Xs(){const ds=(G==null?void 0:G.autoScrollEnabled)===!1,Ss=typeof c=="object"?c.enabled===!1:c===!1,yn=E&&!ds&&!Ss;return typeof c=="object"?{...c,enabled:yn}:{enabled:yn}}}),HVs=j.createContext(null),abt="button",GVs="Draggable";function WVs(s){let{id:t,data:n,disabled:r=!1,attributes:a}=s;const i=Jae(GVs),{activators:l,activatorEvent:o,active:c,activeNodeRect:d,ariaDescribedById:u,draggableNodes:h,over:m}=j.useContext(m6e),{role:f=abt,roleDescription:g="draggable",tabIndex:x=0}=a??{},y=(c==null?void 0:c.id)===t,v=j.useContext(y?aUt:HVs),[b,w]=VEe(),[S,A]=VEe(),E=MVs(l,t),I=rse(n);Y4(()=>(h.set(t,{id:t,key:i,node:b,activatorNode:S,data:I}),()=>{const R=h.get(t);R&&R.key===i&&h.delete(t)}),[h,t]);const P=j.useMemo(()=>({role:f,tabIndex:x,"aria-disabled":r,"aria-pressed":y&&f===abt?!0:void 0,"aria-roledescription":g,"aria-describedby":u.draggable}),[r,f,x,y,g,u.draggable]);return{active:c,activatorEvent:o,activeNodeRect:d,attributes:P,isDragging:y,listeners:r?void 0:E,node:b,over:m,setNodeRef:w,setActivatorNodeRef:A,transform:v}}function KVs(){return j.useContext(rUt)}const YVs="Droppable",ZVs={timeout:25};function XVs(s){let{data:t,disabled:n=!1,id:r,resizeObserverConfig:a}=s;const i=Jae(YVs),{active:l,dispatch:o,over:c,measureDroppableContainers:d}=j.useContext(m6e),u=j.useRef({disabled:n}),h=j.useRef(!1),m=j.useRef(null),f=j.useRef(null),{disabled:g,updateMeasurementsFor:x,timeout:y}={...ZVs,...a},v=rse(x??r),b=j.useCallback(()=>{if(!h.current){h.current=!0;return}f.current!=null&&clearTimeout(f.current),f.current=setTimeout(()=>{d(Array.isArray(v.current)?v.current:[v.current]),f.current=null},y)},[y]),w=h6e({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]=VEe(S),I=rse(t);return j.useEffect(()=>{!w||!A.current||(w.disconnect(),h.current=!1,w.observe(A.current))},[A,w]),j.useEffect(()=>(o({type:g0.RegisterDroppable,element:{id:r,key:i,disabled:n,node:A,rect:m,data:I}}),()=>o({type:g0.UnregisterDroppable,key:i,id:r})),[r]),j.useEffect(()=>{n!==u.current.disabled&&(o({type:g0.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 p6e(s,t,n){const r=s.slice();return r.splice(n<0?r.length+n:n,0,r.splice(t,1)[0]),r}function QVs(s,t){return s.reduce((n,r,a)=>{const i=t.get(r);return i&&(n[a]=i),n},Array(s.length))}function Qce(s){return s!==null&&s>=0}function JVs(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=tHs(n,l,a);if(l===a){const d=n[i];return d?{x:aa&&l<=i?{x:-o.width-c,y:0,...Jce}:l=i?{x:o.width+c,y:0,...Jce}:{x:0,y:0,...Jce}};function tHs(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=p6e(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}},ede={scaleX:1,scaleY:1},sHs=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,...ede}:a=l?{x:0,y:o.height+c,...ede}:{x:0,y:0,...ede}};function nHs(s,t,n){const r=s[t],a=s[t-1],i=s[t+1];return r?nr.map(E=>typeof E=="object"&&"id"in E?E.id:E),[r]),g=l!=null,x=l?f.indexOf(l.id):-1,y=d?f.indexOf(d.id):-1,v=j.useRef(f),b=!JVs(f,v.current),w=y!==-1&&x===-1||b,S=eHs(i);Y4(()=>{b&&g&&u(f)},[b,f,g,u]),j.useEffect(()=>{v.current=f},[f]);const A=j.useMemo(()=>({activeIndex:x,containerId:h,disabled:S,disableTransforms:w,items:f,overIndex:y,useDragOverlay:m,sortedRects:QVs(f,c),strategy:a}),[x,h,S.draggable,S.droppable,w,f,y,c,m,a]);return Gt.createElement(oUt.Provider,{value:A},t)}const rHs=s=>{let{id:t,items:n,activeIndex:r,overIndex:a}=s;return p6e(n,r,a).indexOf(t)},aHs=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},iHs={duration:200,easing:"ease"},lUt="transform",oHs=PL.Transition.toString({property:lUt,duration:0,easing:"linear"}),lHs={roleDescription:"sortable"};function cHs(s){let{disabled:t,index:n,node:r,rect:a}=s;const[i,l]=j.useState(null),o=j.useRef(n);return Y4(()=>{if(!t&&n!==o.current&&r.current){const c=a.current;if(c){const d=cK(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 x6e(s){let{animateLayoutChanges:t=aHs,attributes:n,disabled:r,data:a,getNewIndex:i=rHs,id:l,strategy:o,resizeObserverConfig:c,transition:d=iHs}=s;const{items:u,containerId:h,activeIndex:m,disabled:f,disableTransforms:g,sortedRects:x,overIndex:y,useDragOverlay:v,strategy:b}=j.useContext(oUt),w=dHs(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}=XVs({id:l,data:A,disabled:w.droppable,resizeObserverConfig:{updateMeasurementsFor:E,...c}}),{active:O,activatorEvent:U,activeNodeRect:W,attributes:V,setNodeRef:G,listeners:Y,isDragging:X,over:ae,setActivatorNodeRef:le,transform:ne}=WVs({id:l,data:A,attributes:{...lHs,...n},disabled:w.draggable}),te=Mqs(D,G),J=!!O,ce=J&&!g&&Qce(m)&&Qce(y),_e=!v&&X,he=_e&&ce?ne:null,ve=ce?he??(o??b)({rects:x,activeNodeRect:W,activeIndex:m,overIndex:y,index:S}):null,Ee=Qce(m)&&Qce(y)?i({id:l,items:u,activeIndex:m,overIndex:y}):S,Se=O==null?void 0:O.id,Le=j.useRef({activeId:Se,items:u,newIndex:Ee,containerId:h}),Fe=u!==Le.current.items,ke=t({active:O,containerId:h,isDragging:X,isSorting:J,id:l,index:S,items:u,newIndex:Le.current.newIndex,previousItems:Le.current.items,previousContainerId:Le.current.containerId,transition:d,wasDragging:Le.current.activeId!=null}),Be=cHs({disabled:!ke,index:S,node:P,rect:I});return j.useEffect(()=>{J&&Le.current.newIndex!==Ee&&(Le.current.newIndex=Ee),h!==Le.current.containerId&&(Le.current.containerId=h),u!==Le.current.items&&(Le.current.items=u)},[J,Ee,h,u]),j.useEffect(()=>{if(Se===Le.current.activeId)return;if(Se!=null&&Le.current.activeId==null){Le.current.activeId=Se;return}const Ae=setTimeout(()=>{Le.current.activeId=Se},50);return()=>clearTimeout(Ae)},[Se]),{active:O,activeIndex:m,attributes:V,data:A,rect:I,index:S,newIndex:Ee,items:u,isOver:R,isSorting:J,isDragging:X,listeners:Y,node:P,overIndex:y,over:ae,setNodeRef:te,setActivatorNodeRef:le,setDroppableNodeRef:D,setDraggableNodeRef:G,transform:Be??ve,transition:Ne()};function Ne(){if(Be||Fe&&Le.current.newIndex===S)return oHs;if(!(_e&&!Zst(U)||!d)&&(J||ke))return PL.Transition.toString({...d,property:lUt})}}function dHs(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 WEe(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 uHs=[Xu.Down,Xu.Right,Xu.Up,Xu.Left],cUt=(s,t)=>{let{context:{active:n,collisionRect:r,droppableRects:a,droppableContainers:i,over:l,scrollableAncestors:o}}=t;if(uHs.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 y=d6e(g).some((E,I)=>o[I]!==E),v=dUt(h,m),b=hHs(h,m),w=y||!v?{x:0,y:0}:{x:b?r.width-f.width:0,y:b?r.height-f.height:0},S={x:f.left,y:f.top};return w.x&&w.y?S:ase(S,w)}}}};function dUt(s,t){return!WEe(s)||!WEe(t)?!1:s.data.current.sortable.containerId===t.data.current.sortable.containerId}function hHs(s,t){return!WEe(s)||!WEe(t)||!dUt(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(pr,{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 uUt({photos:s,uploading:t,onUpload:n,onRemove:r,onReorder:a,onSetPrimary:i}){var h,m;const l=l6e(EG(dK,{activationConstraint:{distance:5}})),o=[...s].sort((f,g)=>(f.sort_order??0)-(g.sort_order??0)),c=((h=o.find(f=>f.is_primary))==null?void 0:h.id)??null,d=c??((m=o[0])==null?void 0:m.id),u=f=>{var E;const{active:g,over:x}=f;if(!x||g.id===x.id)return;const y=o.findIndex(I=>I.id===g.id),v=o.findIndex(I=>I.id===x.id),b=[...o],[w]=b.splice(y,1);b.splice(v,0,w);const S=c??((E=b[0])==null?void 0:E.id),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(f6e,{sensors:l,collisionDetection:c6e,onDragEnd:u,children:e.jsx(g6e,{items:o.map(f=>f.id),strategy:eie,children:e.jsxs("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-4",children:[o.map(f=>e.jsx(mHs,{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 y6e({open:s,onOpenChange:t,listingId:n,listingSlug:r,listingTitle:a,isCommercial:i=!1}){const{user:l}=bs(),[o,c]=j.useState(null),[d,u]=j.useState(!1),[h,m]=j.useState(!1);j.useEffect(()=>{(async()=>{if(!(!s||!l)){u(!0);try{const{data:v,error:b}=await q.from("listing_shares").select("id, share_token, click_count, lead_count").eq("listing_id",n).eq("sharing_agent_id",l.id).order("created_at",{ascending:!1}).limit(1).maybeSingle();if(b)throw b;if(v&&v.share_token)c(v);else if(v&&!v.share_token){const{data:w,error:S}=await q.from("listing_shares").update({share_type:"referral_link"}).eq("id",v.id).select("id, share_token, click_count, lead_count").single();if(S)throw S;c(w)}else{const{data:w,error:S}=await q.from("listing_shares").insert({listing_id:n,sharing_agent_id:l.id,share_type:"referral_link"}).select("id, share_token, click_count, lead_count").single();if(S)throw S;c(w)}}catch(v){console.error("Error creating share link:",v),re.error("Failed to generate share link")}finally{u(!1)}}})()},[s,l,n]);const f=o!=null&&o.share_token?`${i?fDs:"https://listings.relevelup.com"}/${r||n}?ref=${o.share_token}`:"",g=async()=>{try{await navigator.clipboard.writeText(f),m(!0),re.success("Link copied to clipboard!"),setTimeout(()=>m(!1),2e3)}catch{re.error("Failed to copy link")}},x=y=>{const v=encodeURIComponent(f),b=encodeURIComponent(`Check out this listing: ${a}`);switch(y){case"email":window.open(`mailto:?subject=${b}&body=${v}`);break;case"text":window.open(`sms:?body=${b}%20${v}`);break;case"facebook":window.open(`https://www.facebook.com/sharer/sharer.php?u=${v}`,"_blank");break}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(Nn,{className:"h-5 w-5 text-amber-500"}),"Share & Earn Leads"]}),e.jsx(Pr,{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(ca,{className:"h-4 w-4"}):e.jsx(Ha,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Share via"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{variant:"outline",className:"flex-1",onClick:()=>x("email"),disabled:d,children:[e.jsx(mn,{className:"h-4 w-4 mr-2"}),"Email"]}),e.jsxs($,{variant:"outline",className:"flex-1",onClick:()=>x("text"),disabled:d,children:[e.jsx(eo,{className:"h-4 w-4 mr-2"}),"Text"]}),e.jsxs($,{variant:"outline",className:"flex-1",onClick:()=>x("facebook"),disabled:d,children:[e.jsx(Qp,{className:"h-4 w-4 mr-2"}),"Facebook"]})]})]}),o&&(o.click_count>0||o.lead_count>0)&&e.jsxs("div",{className:"pt-4 border-t",children:[e.jsx(ee,{className:"mb-2 block",children:"Your Share Performance"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"bg-muted rounded-lg p-3 text-center",children:[e.jsxs("div",{className:"flex items-center justify-center gap-1 text-muted-foreground mb-1",children:[e.jsx(Ca,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs",children:"Clicks"})]}),e.jsx("p",{className:"text-2xl font-bold",children:o.click_count})]}),e.jsxs("div",{className:"bg-primary/10 rounded-lg p-3 text-center",children:[e.jsxs("div",{className:"flex items-center justify-center gap-1 text-primary mb-1",children:[e.jsx(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 fHs=Object.defineProperty,KEe=Object.getOwnPropertySymbols,hUt=Object.prototype.hasOwnProperty,mUt=Object.prototype.propertyIsEnumerable,ibt=(s,t,n)=>t in s?fHs(s,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):s[t]=n,BGe=(s,t)=>{for(var n in t||(t={}))hUt.call(t,n)&&ibt(s,n,t[n]);if(KEe)for(var n of KEe(t))mUt.call(t,n)&&ibt(s,n,t[n]);return s},$Ge=(s,t)=>{var n={};for(var r in s)hUt.call(s,r)&&t.indexOf(r)<0&&(n[r]=s[r]);if(s!=null&&KEe)for(var r of KEe(s))t.indexOf(r)<0&&mUt.call(s,r)&&(n[r]=s[r]);return n};/** * @license QR Code generator library (TypeScript) * Copyright (c) Project Nayuki. * SPDX-License-Identifier: MIT */var H7;(s=>{const t=class _u{constructor(c,d,u,h){if(this.version=c,this.errorCorrectionLevel=d,this.modules=[],this.isFunction=[],c<_u.MIN_VERSION||c>_u.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=_u.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[_u.Ecc.MEDIUM,_u.Ecc.QUARTILE,_u.Ecc.HIGH])f&&x<=_u.getNumDataCodewords(g,w)*8&&(d=w);let y=[];for(const w of c){n(w.mode.modeBits,4,y),n(w.numChars,w.mode.numCharCountBits(g),y);for(const S of w.getData())y.push(S)}a(y.length==x);const v=_u.getNumDataCodewords(g,d)*8;a(y.length<=v),n(0,Math.min(4,v-y.length),y),n(0,(8-y.length%8)%8,y),a(y.length%8==0);for(let w=236;y.lengthb[S>>>3]|=w<<7-(S&7)),new _u(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(_u.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)*_u.PENALTY_N3),f=this.modules[m][y],g=1);c+=this.finderPenaltyTerminateAndCount(f,g,x)*_u.PENALTY_N3}for(let m=0;m5&&c++):(this.finderPenaltyAddHistory(g,x),f||(c+=this.finderPenaltyCountPatterns(x)*_u.PENALTY_N3),f=this.modules[y][m],g=1);c+=this.finderPenaltyTerminateAndCount(f,g,x)*_u.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*_u.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.length_u.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(_u.getNumRawDataModules(c)/8)-_u.ECC_CODEWORDS_PER_BLOCK[d.ordinal][c]*_u.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]^=_u.reedSolomonMultiply(f,m))}return u}static reedSolomonMultiply(c,d){if(c>>>8||d>>>8)throw new RangeError("Byte out of range");let u=0;for(let h=7;h>=0;h--)u=u<<1^(u>>>7)*285,u^=(d>>>h&1)*c;return a(u>>>8==0),u}finderPenaltyCountPatterns(c){const d=c[1];a(d<=this.size*3);const u=d>0&&c[2]==d&&c[3]==d*3&&c[4]==d&&c[5]==d;return(u&&c[0]>=d*4&&c[6]>=d?1:0)+(u&&c[6]>=d*4&&c[0]>=d?1:0)}finderPenaltyTerminateAndCount(c,d,u){return c&&(this.finderPenaltyAddHistory(d,u),d=0),d+=this.size,this.finderPenaltyAddHistory(d,u),this.finderPenaltyCountPatterns(u)}finderPenaltyAddHistory(c,d){d[0]==0&&(c+=this.size),d.pop(),d.unshift(c)}};t.MIN_VERSION=1,t.MAX_VERSION=40,t.PENALTY_N1=3,t.PENALTY_N2=3,t.PENALTY_N3=40,t.PENALTY_N4=10,t.ECC_CODEWORDS_PER_BLOCK=[[-1,7,10,15,20,26,18,20,24,30,18,20,24,26,30,22,24,28,30,28,28,28,28,30,30,26,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,10,16,26,18,24,16,18,22,22,26,30,22,22,24,24,28,28,26,26,26,26,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28],[-1,13,22,18,26,18,24,18,22,20,24,28,26,24,20,30,24,28,28,26,30,28,30,30,30,30,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,17,28,22,16,22,28,26,26,24,28,24,28,22,24,24,30,28,28,26,28,30,24,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30]],t.NUM_ERROR_CORRECTION_BLOCKS=[[-1,1,1,1,1,1,2,2,2,2,4,4,4,4,4,6,6,6,6,7,8,8,9,9,10,12,12,12,13,14,15,16,17,18,19,19,20,21,22,24,25],[-1,1,1,1,2,2,4,4,4,5,5,5,8,9,9,10,10,11,13,14,16,17,17,18,20,21,23,25,26,28,29,31,33,35,37,38,40,43,45,47,49],[-1,1,1,2,2,4,4,6,6,8,8,8,10,12,16,12,17,16,18,21,20,23,23,25,27,29,34,34,35,38,40,43,45,48,51,53,56,59,62,65,68],[-1,1,1,2,4,4,4,5,6,8,8,11,11,16,16,18,16,19,21,25,25,25,34,30,32,35,37,40,42,45,48,51,54,57,60,63,66,70,74,77,81]],s.QrCode=t;function n(o,c,d){if(c<0||c>31||o>>>c)throw new RangeError("Value out of range");for(let u=c-1;u>=0;u--)d.push(o>>>u&1)}function r(o,c){return(o>>>c&1)!=0}function a(o){if(!o)throw new Error("Assertion error")}const i=class dx{constructor(c,d,u){if(this.mode=c,this.numChars=d,this.bitData=u,d<0)throw new RangeError("Invalid argument");this.bitData=u.slice()}static makeBytes(c){let d=[];for(const u of c)n(u,8,d);return new dx(dx.Mode.BYTE,c.length,d)}static makeNumeric(c){if(!dx.isNumeric(c))throw new RangeError("String contains non-numeric characters");let d=[];for(let u=0;u=1<{(t=>{const n=class{constructor(a,i){this.ordinal=a,this.formatBits=i}};n.LOW=new n(0,1),n.MEDIUM=new n(1,0),n.QUARTILE=new n(2,3),n.HIGH=new n(3,2),t.Ecc=n})(s.QrCode||(s.QrCode={}))})(H7||(H7={}));(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={}))})(H7||(H7={}));var ZU=H7;/** * @license qrcode.react * Copyright (c) Paul O'Shannessy * SPDX-License-Identifier: ISC */var pHs={L:ZU.QrCode.Ecc.LOW,M:ZU.QrCode.Ecc.MEDIUM,Q:ZU.QrCode.Ecc.QUARTILE,H:ZU.QrCode.Ecc.HIGH},fUt=128,pUt="L",gUt="#FFFFFF",xUt="#000000",yUt=!1,vUt=1,gHs=4,xHs=0,yHs=.1;function bUt(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 _Ut(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 vHs(s,t,n,r){if(r==null)return null;const a=s.length+n*2,i=Math.floor(t*yHs),l=a/t,o=(r.width||i)*l,c=(r.height||i)*l,d=r.x==null?s.length/2-o/2:r.x*l,u=r.y==null?s.length/2-c/2:r.y*l,h=r.opacity==null?1:r.opacity;let m=null;if(r.excavate){let g=Math.floor(d),x=Math.floor(u),y=Math.ceil(o+d-g),v=Math.ceil(c+u-x);m={x:g,y:x,w:y,h:v}}const f=r.crossOrigin;return{x:d,y:u,h:c,w:o,excavation:m,opacity:h,crossOrigin:f}}function bHs(s,t){return t!=null?Math.max(Math.floor(t),0):s?gHs:xHs}function wUt({value:s,level:t,minVersion:n,includeMargin:r,marginSize:a,imageSettings:i,size:l,boostLevel:o}){let c=Gt.useMemo(()=>{const g=(Array.isArray(s)?s:[s]).reduce((x,y)=>(x.push(...ZU.QrSegment.makeSegments(y)),x),[]);return ZU.QrCode.encodeSegments(g,pHs[t],n,void 0,void 0,o)},[s,t,n,o]);const{cells:d,margin:u,numCells:h,calculatedImageSettings:m}=Gt.useMemo(()=>{let f=c.getModules();const g=bHs(r,a),x=f.length+g*2,y=vHs(f,l,g,i);return{cells:f,margin:g,numCells:x,calculatedImageSettings:y}},[c,l,i,r,a]);return{qrcode:c,margin:u,cells:d,numCells:h,calculatedImageSettings:m}}var _Hs=function(){try{new Path2D().addPath(new Path2D)}catch{return!1}return!0}(),jUt=Gt.forwardRef(function(t,n){const r=t,{value:a,size:i=fUt,level:l=pUt,bgColor:o=gUt,fgColor:c=xUt,includeMargin:d=yUt,minVersion:u=vUt,boostLevel:h,marginSize:m,imageSettings:f}=r,x=$Ge(r,["value","size","level","bgColor","fgColor","includeMargin","minVersion","boostLevel","marginSize","imageSettings"]),{style:y}=x,v=$Ge(x,["style"]),b=f==null?void 0:f.src,w=Gt.useRef(null),S=Gt.useRef(null),A=Gt.useCallback(V=>{w.current=V,typeof n=="function"?n(V):n&&(n.current=V)},[n]),[E,I]=Gt.useState(!1),{margin:P,cells:R,numCells:D,calculatedImageSettings:O}=wUt({value:a,level:l,minVersion:u,boostLevel:h,includeMargin:d,marginSize:m,imageSettings:f,size:i});Gt.useEffect(()=>{if(w.current!=null){const V=w.current,G=V.getContext("2d");if(!G)return;let Y=R;const X=S.current,ae=O!=null&&X!==null&&X.complete&&X.naturalHeight!==0&&X.naturalWidth!==0;ae&&O.excavation!=null&&(Y=_Ut(R,O.excavation));const le=window.devicePixelRatio||1;V.height=V.width=i*le;const ne=i/D*le;G.scale(ne,ne),G.fillStyle=o,G.fillRect(0,0,D,D),G.fillStyle=c,_Hs?G.fill(new Path2D(bUt(Y,P))):R.forEach(function(te,J){te.forEach(function(ce,_e){ce&&G.fillRect(_e+P,J+P,1,1)})}),O&&(G.globalAlpha=O.opacity),ae&&G.drawImage(X,O.x+P,O.y+P,O.w,O.h)}}),Gt.useEffect(()=>{I(!1)},[b]);const U=BGe({height:i,width:i},y);let W=null;return b!=null&&(W=Gt.createElement("img",{src:b,key:b,style:{display:"none"},onLoad:()=>{I(!0)},ref:S,crossOrigin:O==null?void 0:O.crossOrigin})),Gt.createElement(Gt.Fragment,null,Gt.createElement("canvas",BGe({style:U,height:i,width:i,ref:A,role:"img"},v)),W)});jUt.displayName="QRCodeCanvas";var uk=Gt.forwardRef(function(t,n){const r=t,{value:a,size:i=fUt,level:l=pUt,bgColor:o=gUt,fgColor:c=xUt,includeMargin:d=yUt,minVersion:u=vUt,boostLevel:h,title:m,marginSize:f,imageSettings:g}=r,x=$Ge(r,["value","size","level","bgColor","fgColor","includeMargin","minVersion","boostLevel","title","marginSize","imageSettings"]),{margin:y,cells:v,numCells:b,calculatedImageSettings:w}=wUt({value:a,level:l,minVersion:u,boostLevel:h,includeMargin:d,marginSize:f,imageSettings:g,size:i});let S=v,A=null;g!=null&&w!=null&&(w.excavation!=null&&(S=_Ut(v,w.excavation)),A=Gt.createElement("image",{href:g.src,height:w.h,width:w.w,x:w.x+y,y:w.y+y,preserveAspectRatio:"none",opacity:w.opacity,crossOrigin:w.crossOrigin}));const E=bUt(S,y);return Gt.createElement("svg",BGe({height:i,width:i,viewBox:`0 0 ${b} ${b}`,ref:n,role:"img"},x),!!m&&Gt.createElement("title",null,m),Gt.createElement("path",{fill:o,d:`M0,0 h${b}v${b}H0z`,shapeRendering:"crispEdges"}),Gt.createElement("path",{fill:c,d:E,shapeRendering:"crispEdges"}),A)});uk.displayName="QRCodeSVG";function NUt({open:s,onOpenChange:t,url:n,title:r,fileBase:a}){const i=j.useRef(null),o=`${(h=>h.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||"listing")(a||r||"listing")}-qr`,c=()=>{var m;const h=(m=i.current)==null?void 0:m.querySelector("svg");return h?new XMLSerializer().serializeToString(h):null},d=()=>{const h=c();if(!h)return;const m=new Blob([h],{type:"image/svg+xml;charset=utf-8"}),f=document.createElement("a");f.href=URL.createObjectURL(m),f.download=`${o}.svg`,f.click(),URL.revokeObjectURL(f.href)},u=(h=1024)=>{const m=c();if(!m)return;const f=new Image,g=new Blob([m],{type:"image/svg+xml;charset=utf-8"}),x=URL.createObjectURL(g);f.onload=()=>{const y=document.createElement("canvas");y.width=h,y.height=h;const v=y.getContext("2d");v&&(v.fillStyle="#ffffff",v.fillRect(0,0,h,h),v.drawImage(f,0,0,h,h),URL.revokeObjectURL(x),y.toBlob(b=>{if(!b)return;const w=document.createElement("a");w.href=URL.createObjectURL(b),w.download=`${o}.png`,w.click(),URL.revokeObjectURL(w.href)},"image/png"))},f.src=x};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Listing QR Code"}),e.jsx(Pr,{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(uk,{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(xi,{className:"h-4 w-4"}),"PNG"]}),e.jsxs($,{variant:"outline",onClick:d,className:"gap-2",children:[e.jsx(xi,{className:"h-4 w-4"}),"SVG"]}),e.jsxs($,{variant:"outline",onClick:async()=>{await navigator.clipboard.writeText(n),re.success("Link copied")},className:"gap-2",children:[e.jsx(Ha,{className:"h-4 w-4"}),"Copy link"]})]})]})})}var wHs=Object.defineProperty,kUt=(s,t)=>wHs(s,"name",{value:t,configurable:!0}),obt="horizontal",jHs=["horizontal","vertical"],NHs=j.forwardRef(kUt(function(t,n){const{decorative:r,orientation:a=obt,...i}=t,l=SUt(a)?a:obt,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 SUt(s){return jHs.includes(s)}kUt(SUt,"isValidOrientation");var CUt=NHs;const Vc=j.forwardRef(({className:s,orientation:t="horizontal",decorative:n=!0,...r},a)=>e.jsx(CUt,{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=CUt.displayName;const qw=()=>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}}),AUt=()=>{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 y=0;y{const{data:g,error:x}=await q.from("innercircle_contact_tags").select("id, contact_id, relationship_type_id, relationship_type:relationship_types(*)").in("contact_id",f);if(x)throw x;return g??[]})),Promise.all(c(o).map(async f=>{const{data:g,error:x}=await q.from("lead_sources").select("id, name").in("id",f);if(x)throw x;return g??[]}))]),h=new Map;d.flat().forEach(f=>{const g=h.get(f.contact_id)??[];g.push(f),h.set(f.contact_id,g)});const m=new Map(u.flat().map(f=>[f.id,f]));return i.map(f=>({...f,lead_source_ref:f.lead_source_id?m.get(f.lead_source_id)??null:null,tags:h.get(f.id)??[]}))},enabled:!!t,staleTime:10*60*1e3})},kHs=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}),EUt=()=>{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})},v6e=()=>{const s=Wt(),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"})}})},Jst=()=>{const s=Wt();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"})}})},TUt=()=>{const s=Wt();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"})}})},MUt=()=>{const s=Wt();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"})}})},SHs=()=>{const s=Wt();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"]})}})},tie=()=>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}}),CHs=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}}),AHs=()=>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}}),EHs=()=>{const s=Wt(),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"})}})},THs=()=>{const s=Wt(),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"})}})},MHs=()=>{const s=Wt();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"})}})},PHs=()=>{const s=Wt();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"})}})},IHs=()=>{const s=Wt();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"})}})},LHs=()=>{const s=Wt();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"})}})},RHs=()=>{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})},DHs=()=>{const s=Wt(),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"})}})},uK=(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})},PUt=()=>{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})},FHs=(s=90)=>{const{data:t}=R_(),{data:n}=PUt();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=Wt(),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{}}})},IUt="agentos_weekly_touch_goal",lbt=20,LUt=()=>{if(typeof window>"u")return lbt;const s=localStorage.getItem(IUt);if(s){const t=parseInt(s,10);if(!isNaN(t)&&t>0)return t}return lbt},OHs=s=>{localStorage.setItem(IUt,s.toString())},_6e=()=>{const{data:s}=uK(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=LUt();return{actionsThisWeek:r,weeklyGoal:i,streak:a,progress:Math.min(r/i*100,100)}},zHs=()=>{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})},BHs=()=>{const s=Wt();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`})}})},ent=()=>{const s=Sa(),{data:t}=zHs(),{data:n}=uK(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 y=new Date(x.cycle_start_date),b=Math.floor((i.getTime()-y.getTime())/(30.44*24*60*60*1e3))%12+1,w=x.plan.items.find(S=>S.month_number===b);if(w&&w.action_type){const S=`${x.contact_id}-${w.action_type_id}`;if(!c.has(S)){const{data: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,y)=>x.contact.first_name.localeCompare(y.contact.first_name)),m=(u-1)%Math.max(1,h.length);return[...h.slice(m),...h.slice(0,m)].slice(0,d)},enabled:!!s&&!!t})};function $Hs(){const{user:s}=bs(),{limitFor:t,isRestricted:n}=_C(),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 UHs({onSelect:s}){const{user:t}=bs(),[n,r]=j.useState("root"),[a,i]=j.useState(null),{data:l=[],isLoading:o}=st({queryKey:["agent-email-template-categories"],queryFn:async()=>{const{data:v,error:b}=await q.from("email_template_categories").select("*").order("sort_order");if(b)throw b;return v}}),{data:c=[],isLoading:d}=st({queryKey:["agent-email-templates",a],enabled:n==="category"&&!!a,queryFn:async()=>{const{data:v,error:b}=await q.from("agent_email_templates").select("*").eq("is_active",!0).eq("category_id",a).order("sort_order");if(b)throw b;return v}}),{data:u=[],isLoading:h}=st({queryKey:["picker-campaign-templates",t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{const{data:v,error:b}=await q.from("campaign_templates").select("id,name,subject,body_html,is_shared,user_id,updated_at").or(`user_id.eq.${t.id},is_shared.eq.true`).order("updated_at",{ascending:!1});if(b)throw b;return v}}),m=u.filter(v=>v.user_id===(t==null?void 0:t.id)&&!v.is_shared),f=u.filter(v=>v.is_shared),g=l.find(v=>v.id===a);if(o)return e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(Ct,{className:"h-5 w-5 animate-spin text-muted-foreground"})});const x=v=>{s({title:v.name,subject:v.subject,body:v.body_html})};if(n==="root")return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground px-1 mb-1.5",children:"Your templates"}),e.jsxs("button",{onClick:()=>r("my"),className:"w-full flex items-center justify-between p-2.5 rounded-lg border hover:bg-accent transition-colors text-left",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"h-8 w-8 rounded-md bg-primary/10 text-primary flex items-center justify-center",children:e.jsx(sl,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:"My Saved Templates"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[m.length," template",m.length===1?"":"s"," you've created"]})]})]}),e.jsx(Di,{className:"h-4 w-4 text-muted-foreground shrink-0"})]}),e.jsxs("button",{onClick:()=>r("shared"),className:"w-full flex items-center justify-between p-2.5 rounded-lg border hover:bg-accent transition-colors text-left",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"h-8 w-8 rounded-md bg-blue-500/10 text-blue-600 dark:text-blue-400 flex items-center justify-center",children:e.jsx(dl,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:"Shared Library"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[f.length," team template",f.length===1?"":"s"]})]})]}),e.jsx(Di,{className:"h-4 w-4 text-muted-foreground shrink-0"})]})]}),l.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground px-1 mb-1.5",children:"Quick scripts by category"}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto space-y-1 pr-1",children:l.map(v=>e.jsxs("button",{onClick:()=>{i(v.id),r("category")},className:"w-full flex items-center justify-between p-2.5 rounded-lg border hover:bg-accent transition-colors text-left",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"text-lg",children:v.icon}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:v.name}),v.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1",children:v.description})]})]}),e.jsx(Di,{className:"h-4 w-4 text-muted-foreground shrink-0"})]},v.id))})]})]});const y=e.jsxs("button",{onClick:()=>{r("root"),i(null)},className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(kd,{className:"h-3.5 w-3.5"}),"Back"]});return n==="my"?e.jsxs("div",{className:"space-y-2",children:[y,e.jsxs("p",{className:"text-xs font-medium flex items-center gap-1.5",children:[e.jsx(sl,{className:"h-3.5 w-3.5"})," My Saved Templates"]}),h?e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(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(Nn,{className:"h-6 w-6 text-muted-foreground mx-auto"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"You haven't created any templates yet."}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Create beautiful templates in ",e.jsx("span",{className:"font-medium",children:"Email Templates"})," in the sidebar — they'll appear here."]})]}):e.jsx(uo,{className:"max-h-[280px]",children:e.jsx("div",{className:"space-y-1",children:m.map(v=>e.jsxs("button",{onClick:()=>x(v),className:"w-full p-2.5 rounded-lg border hover:bg-accent transition-colors text-left",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:v.name}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:v.subject||"(no subject)"})]},v.id))})})]}):n==="shared"?e.jsxs("div",{className:"space-y-2",children:[y,e.jsxs("p",{className:"text-xs font-medium flex items-center gap-1.5",children:[e.jsx(dl,{className:"h-3.5 w-3.5"})," Shared Library"]}),h?e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(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(uo,{className:"max-h-[280px]",children:e.jsx("div",{className:"space-y-1",children:f.map(v=>e.jsxs("button",{onClick:()=>x(v),className:"w-full p-2.5 rounded-lg border hover:bg-accent transition-colors text-left",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:v.name}),e.jsx($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:v.subject||"(no subject)"})]},v.id))})})]}):e.jsxs("div",{className:"space-y-2",children:[y,e.jsxs("p",{className:"text-xs font-medium flex items-center gap-1.5",children:[e.jsx("span",{children:g==null?void 0:g.icon})," ",g==null?void 0:g.name]}),d?e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(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(uo,{className:"max-h-[280px]",children:e.jsx("div",{className:"space-y-1",children:c.map(v=>e.jsxs("button",{onClick:()=>s(v),className:"w-full p-2.5 rounded-lg border hover:bg-accent transition-colors text-left",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"font-medium text-sm",children:v.title}),v.tone&&e.jsx($e,{variant:"secondary",className:"text-[10px] shrink-0",children:v.tone})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:v.subject})]},v.id))})})]})}function l6(){var a;const{user:s}=bs(),{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 sie(){const{user:s}=bs();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 w6e({open:s,onOpenChange:t,hasPending:n,pendingEmails:r}){const a=Xn();return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("div",{className:"h-9 w-9 rounded-full bg-amber-500/10 text-amber-600 flex items-center justify-center",children:e.jsx(ll,{className:"h-5 w-5"})}),e.jsx(Bs,{children:"Verify your sending email first"})]}),e.jsx(Pr,{className:"pt-2",children:`Before you can send emails through Amazon, your "from" address needs to be verified so inboxes trust it and it doesn't land in spam.`})]}),n&&r&&r.length>0?e.jsxs("div",{className:"rounded-lg border bg-amber-500/5 p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium text-amber-700",children:[e.jsx(da,{className:"h-4 w-4"})," Waiting for you to click Amazon's link"]}),r.map(i=>e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(mn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:i})]},i)),e.jsx("p",{className:"text-xs text-muted-foreground pt-1",children:"Check that inbox (and your spam folder) for an email from Amazon Web Services and click the verification link."})]}):e.jsx("div",{className:"rounded-lg border bg-muted/40 p-3 text-sm text-muted-foreground",children:"It only takes a minute — add your email address on the Integrations page, then click the verification link Amazon sends you."}),e.jsxs(Sr,{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(Fr,{className:"h-4 w-4 mr-1"}),n?"Manage senders":"Verify my email"]})]})]})})}function j6e(){const{user:s}=bs(),t=Wt(),{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"]}),re.success("Connect page created!")},onError:d=>{var u;(u=d.message)!=null&&u.includes("duplicate")?re.error("That slug is already taken. Try another."):re.error("Failed to create page")}}),i=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"]}),re.success("Page updated!")},onError:()=>re.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 RUt({value:s,onChange:t,userId:n,placeholder:r}){const[a,i]=j.useState(!1),[l,o]=j.useState([]),[c,d]=j.useState(!1),[u,h]=j.useState(0),m=j.useRef(null),f=j.useRef(null);j.useEffect(()=>{const x=y=>{m.current&&!m.current.contains(y.target)&&i(!1)};return document.addEventListener("mousedown",x),()=>document.removeEventListener("mousedown",x)},[]),j.useEffect(()=>{f.current&&clearTimeout(f.current);const x=s.trim();if(!n||x.length<1||x.includes("@")&&x.indexOf("@")>0&&/\S+@\S+\.\S+/.test(x)){o([]);return}return f.current=setTimeout(async()=>{d(!0);const y=`%${x}%`,v=q,{data:b,error:w}=await v.from("innercircle_contacts").select("id, first_name, last_name, email").eq("owner_user_id",n).not("email","is",null).or(`first_name.ilike.${y},last_name.ilike.${y},email.ilike.${y}`).order("first_name",{ascending:!0}).limit(8);d(!1),!w&&b&&(o(b),h(0),i(b.length>0))},180),()=>{f.current&&clearTimeout(f.current)}},[s,n]);const g=x=>{x.email&&(t(x.email),i(!1))};return e.jsxs("div",{ref:m,className:"relative",children:[e.jsx(pe,{id:"gmail-to",value:s,onChange:x=>t(x.target.value),onFocus:()=>l.length>0&&i(!0),onKeyDown:x=>{!a||l.length===0||(x.key==="ArrowDown"?(x.preventDefault(),h(y=>Math.min(y+1,l.length-1))):x.key==="ArrowUp"?(x.preventDefault(),h(y=>Math.max(y-1,0))):x.key==="Enter"?(x.preventDefault(),g(l[u])):x.key==="Escape"&&i(!1))},placeholder:r||"Start typing a name or email...",autoComplete:"off"}),a&&e.jsx("div",{className:"absolute z-50 mt-1 w-full rounded-md border bg-popover shadow-lg max-h-72 overflow-y-auto",children:c&&l.length===0?e.jsxs("div",{className:"px-3 py-2 text-sm text-muted-foreground flex items-center gap-2",children:[e.jsx(Ct,{className:"h-3 w-3 animate-spin"})," Searching..."]}):l.map((x,y)=>{const v=[x.first_name,x.last_name].filter(Boolean).join(" ")||"(No name)";return e.jsxs("button",{type:"button",onMouseEnter:()=>h(y),onClick:()=>g(x),className:`w-full flex items-center gap-2 px-3 py-2 text-left text-sm border-b last:border-b-0 ${y===u?"bg-accent":"bg-popover"}`,children:[e.jsx(sl,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-medium truncate",children:v}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:x.email})]})]},x.id)})})]})}function qHs(){const{user:s}=bs(),{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 VHs(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 HHs(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 X7e=25*1024*1024,cbt=Math.floor(6.5*1024*1024),GHs=750*1024,eN=50,WHs=["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 tde(s){return s<1024?s+" B":s<1024*1024?(s/1024).toFixed(1)+" KB":(s/(1024*1024)).toFixed(1)+" MB"}function KHs(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 YHs(s){if(!s)return"";const t=s.trim();return t.split(/\s+/)[0]||t}function hj(s,t){const n=YHs(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 kk({open:s,onOpenChange:t,contact:n,bulkContacts:r,defaultSubject:a="",defaultBody:i="",gmailEmail:l,onSendComplete:o,sendSource:c,logTouchpoint:d=!0}){const{user:u}=bs(),h=Wt(),{isReady:m,settings:f}=l6(),{data:g}=sie(),[x,y]=j.useState(!1),{intakePage:v}=j6e(),b=v?`https://contacts.relevelup.com/${v.slug}`:null,w=!!r&&r.length>0,S=$Hs(),A=m,E=w?r:n?[n]:[],I=E[0],P=w?Math.ceil(E.length/eN):1,R=w&&E.length>eN,[D,O]=j.useState((I==null?void 0:I.email)||""),[U,W]=j.useState(a),[V,G]=j.useState(i),[Y,X]=j.useState(!1),[ae,le]=j.useState(!1),[ne,te]=j.useState([]),J=j.useRef(new Map),[ce,_e]=j.useState(a),[he,ue]=j.useState(i),[ve,Ee]=j.useState(!1),[Se,Le]=j.useState("composing"),[Fe,ke]=j.useState(0),[Be,Ne]=j.useState(0),[Ae,Ce]=j.useState(0),[Ve,ze]=j.useState(0),qe=j.useRef(!1),dt=j.useRef(0),[Xe,at]=j.useState(!0),{signatureHtml:rt,hasSignature:Ke}=qHs(),[Je,pt]=j.useState(!0),[gt,ss]=j.useState(null),Yt=Qn=>{let Cr=5381;for(let Un=0;Un>>0;return Cr.toString(36)},ts=w?`bulk-${E.length}-${Yt(E.map(Qn=>Qn.id||Qn.email||"").join("|"))}`:(I==null?void 0:I.id)||"adhoc",ys=Yt(`${a||""}::${(i||"").slice(0,400)}`),Bt=`levelup:email-draft:${ts}:${ys}`,[Ft,as]=j.useState(!1),kt=j.useRef(!1),Ks=()=>{try{localStorage.removeItem(Bt)}catch{}as(!1)};j.useEffect(()=>{s&&pt(Ke)},[s,Ke]),j.useEffect(()=>{if(s){const Qn=/<[a-z][\s\S]*>/i.test(i),Cr=Qn?HHs(i):i;Xs.current=Qn?{plain:Cr,html:i}:null,O((I==null?void 0:I.email)||""),_e(a),ue(Cr),W(hj(a,I||{first_name:""})),G(hj(Cr,I||{first_name:""})),le(!a&&!i),Ee(!1),Js(Un=>Un+1),te([]),J.current=new Map,Le("composing"),ke(0),Ne(0),Ce(0),ze(0),qe.current=!1,dt.current=0,ss(null);try{const Un=localStorage.getItem(Bt);if(Un){const dr=JSON.parse(Un),Pa=(dr==null?void 0:dr.savedAt)&&Date.now()-dr.savedAt<14*24*60*60*1e3,ii=(dr==null?void 0:dr.rawSubject)||(dr==null?void 0:dr.rawBody)||(dr==null?void 0:dr.html);Pa&&ii&&(dr.to&&O(dr.to),_e(dr.rawSubject||""),ue(dr.rawBody||""),W(hj(dr.rawSubject||"",I||{first_name:""})),G(hj(dr.rawBody||"",I||{first_name:""})),dr.html&&(Xs.current={plain:dr.rawBody||"",html:dr.html}),le(!1),Js($i=>$i+1),as(!0))}}catch{}kt.current=!0}else kt.current=!1},[s,I,a,i]),j.useEffect(()=>{if(!s||!kt.current||Se!=="composing")return;const Qn=Xs.current,Cr={to:D,rawSubject:ce,rawBody:he,html:Qn&&he===Qn.plain?Qn.html:null,savedAt:Date.now()},Un=()=>{try{if(!ce&&!he)return;localStorage.setItem(Bt,JSON.stringify({...Cr,savedAt:Date.now(),html:Xs.current&&he===Xs.current.plain?Xs.current.html:null}))}catch{}},dr=setTimeout(Un,600);return window.addEventListener("blur",Un),document.addEventListener("visibilitychange",Un),()=>{clearTimeout(dr),window.removeEventListener("blur",Un),document.removeEventListener("visibilitychange",Un)}},[s,D,ce,he,Se,Bt]);const wt=async Qn=>{const Cr=Qn.target.files;if(!Cr)return;const Un=ne.reduce((ii,$i)=>ii+$i.size,0),dr=[];let Pa=Un;for(const ii of Array.from(Cr)){if(!WHs.includes(ii.type)){re.error(`${ii.name}: Unsupported file type`);continue}if(Pa+ii.size>X7e){re.error(`Total attachments exceed ${tde(X7e)} limit`);break}try{const $i=await KHs(ii);dr.push({name:ii.name,type:ii.type,size:ii.size,data:$i}),Pa+=ii.size}catch{re.error(`Failed to read ${ii.name}`)}}te(ii=>[...ii,...dr]),Qn.target.value=""},gs=Qn=>{const Cr=ne[Qn];Cr&&J.current.delete(`${Cr.name}::${Cr.size}`),te(Un=>Un.filter((dr,Pa)=>Pa!==Qn))},ks=async()=>{if(ne.length===0||!u)return{inline:[],paths:[]};const Qn=[],Cr=[];for(const Un of ne){const dr=`${Un.name}::${Un.size}`,Pa=J.current.get(dr);if(Pa){Cr.push(Pa);continue}if(Un.size<=GHs){Qn.push(Un);continue}const ii=Un.name.replace(/[^a-zA-Z0-9._-]/g,"_"),$i=`${u.id}/${Date.now()}-${ii}`,Rn=atob(Un.data),xa=new Uint8Array(Rn.length);for(let ho=0;ho{if(!/<[a-z][\s\S]*>/i.test(Qn)||typeof window>"u")return Qn;const Cr=Qn.replace(/<\s*(br|\/p|\/div|\/li|\/h[1-6]|\/tr)\s*[^>]*>/gi,` `).replace(/<\s*li\b[^>]*>/gi,"• ").replace(/<\s*(p|div|h[1-6]|tr)\b[^>]*>/gi,""),Un=document.createElement("div");return Un.innerHTML=Cr,(Un.textContent||Un.innerText||"").replace(/\u00a0/g," ").replace(/\n{3,}/g,` `).trim()},Xs=j.useRef(null),ds=Xs.current&&he===Xs.current.plain?Xs.current.html:null,Ss=j.useRef(null),[yn,Js]=j.useState(0),Ut=()=>{const Qn=Ss.current,Cr=Xs.current;!Qn||!Cr||(Xs.current={plain:Cr.plain,html:Qn.innerHTML})},hn=Qn=>{const Cr=/<[a-z][\s\S]*>/i.test(Qn.body),Un=Cr?Is(Qn.body):Qn.body;Xs.current=Cr?{plain:Un,html:Qn.body}:null,_e(Qn.subject),ue(Un),W(hj(Qn.subject,I||{first_name:""})),G(hj(Un,I||{first_name:""})),le(!1),Js(dr=>dr+1)},hr=Qn=>{let Cr=Qn.replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+|mailto:[^\s)]+)\)/g,(Un,dr,Pa)=>`${dr}`);return Cr=Cr.replace(/(^|[\s(])((?:https?:\/\/|www\.)[^\s<)]+)/g,(Un,dr,Pa)=>{const ii=Pa.startsWith("http")?Pa:`https://${Pa}`;return`${dr}${Pa}`}),Cr},Rs=Qn=>/<\s*(p|div|span|table|tr|td|img|br|h[1-6]|a|body|html|section|article|ul|ol|li)\b/i.test(Qn)?Qn:Qn.split(/\n\n+/).map(Cr=>`

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

`).join(""),jr=(Qn,Cr)=>{const Un="https://relzejiswnotikjgvjhz.supabase.co/functions/v1/bulk-email-track";let dr=Qn.replace(/]*?)href=(["'])(.*?)\2([^>]*)>/gi,(ii,$i,Rn,xa,Ya)=>{if(!xa||/^(mailto:|tel:|#)/i.test(xa)||xa.includes("/bulk-email-track")||xa.includes("/ses-campaign-track"))return ii;const ho=`${Un}?s=${Cr}&t=click&u=${encodeURIComponent(xa)}`;return``});const Pa=``;return/<\/body>/i.test(dr)?dr=dr.replace(/<\/body>/i,`${Pa}`):dr=`${dr}${Pa}`,dr},kr=async Qn=>{if(!(Qn!=null&&Qn.email))return re.error("Please enter a recipient email"),!1;const Cr=Qn||{first_name:""},Un=hj(ce,Cr),dr=Xs.current,Pa=dr&&he===dr.plain,ii=hj(Pa?dr.html:he,Cr);let $i=Pa?ii:Rs(ii);Je&&rt&&($i=VHs($i,hj(rt,Cr)));const Rn=u&&Qn.id?crypto.randomUUID():null;Rn&&($i=jr($i,Rn));try{if(u&&Qn.email){const ho=new Date(Date.now()-6e5).toISOString(),{data:Tc}=await q.from("bulk_email_sends").select("id").eq("user_id",u.id).eq("contact_email",Qn.email).eq("subject",Un).gte("sent_at",ho).limit(1);if(Tc&&Tc.length>0)return console.log(`Skipping duplicate send to ${Qn.email} (same subject within 10 min)`),re.info(`Skipped ${Qn.first_name||Qn.email} — already sent this in the last 10 min`),!0}const{inline:xa,paths:Ya}=await ks();if(A){const ho=(f==null?void 0:f.display_name)||"ReLevelUp",Tc=`${ho.toLowerCase().replace(/[^a-z]/g,".")}@send.relevelup.com`,zd=`${ho} <${Tc}>`;let Nl=Ya[0];if(!Nl&&xa.length>0&&u){const Xr=xa[0],Eo=Xr.name.replace(/[^a-zA-Z0-9._-]/g,"_"),Th=`${u.id}/${Date.now()}-${Eo}`,ah=atob(Xr.data),ao=new Uint8Array(ah.length);for(let xc=0;xc({name:zd,type:Nl,data:Ho})),attachment_paths:Ya,skip_signature:!0}});if(Tc)throw Tc;if(!(ho!=null&&ho.success))throw new Error((ho==null?void 0:ho.error)||"Failed to send")}if(u&&Qn.id&&Rn&&(await q.from("bulk_email_sends").insert({id:Rn,user_id:u.id,contact_id:Qn.id,contact_email:Qn.email,subject:Un,source:c||(A?"ses_bulk":"sphere_gaps")}),d))try{await q.from("contact_touch_logs").insert({owner_user_id:u.id,contact_id:Qn.id,action_type_id:"9a88a47c-cb2a-4401-a2b5-111a76b19f9d",notes:`Mass Email: ${Un}`,completed_at:new Date().toISOString()})}catch(ho){console.warn("touch log insert failed",ho)}return!0}catch(xa){return console.error("Send error:",xa),re.error("Failed to send to "+Qn.first_name+": "+(xa instanceof Error?xa.message:"Unknown error")),!1}},$n=()=>{const Qn=Fe*eN;return E.slice(Qn,Qn+eN)},kn=async(Qn=0,Cr=Xe)=>{if(!U||!V){re.error("Please fill in subject and message");return}X(!0),Le("sending");let Un=Math.max(0,Math.min(Qn,E.length)),dr=!1;for(;UnYa+1):Ce(Ya=>Ya+1),Rn<$i-1&&await new Promise(Ya=>setTimeout(Ya,150))}if(h.invalidateQueries({queryKey:["bulk-email-sends"]}),h.invalidateQueries({queryKey:["contact-touch-logs"]}),h.invalidateQueries({queryKey:["contacts-last-touch"]}),dr||qe.current||Un>=E.length)break;if(!Cr){X(!1),Le("batch_complete");return}if(ze(0),await new Promise(Rn=>setTimeout(Rn,1500)),qe.current){dr=!0;break}}X(!1),!dr&&!qe.current&&Ks(),Le(dr||qe.current?"batch_complete":"all_done")},Fn=async()=>{var Cr;if(!U||!V){re.error("Please fill in subject and message");return}const Qn=w?(r==null?void 0:r.length)||0:1;if(S.wouldExceed(Qn)){re.error(`Your package includes ${(Cr=S.limit)==null?void 0:Cr.toLocaleString()} emails per month. You have ${S.remaining.toLocaleString()} left — request an upgrade for unlimited sending.`);return}if(A&&g&&!g.hasVerifiedSes&&!g.hasGmail){y(!0);return}if(!w){const Un=I||{id:"",first_name:"",last_name:"",email:D.trim()};if(!Un.email){re.error("Please enter a recipient email");return}X(!0);try{await kr(Un)&&(h.invalidateQueries({queryKey:["bulk-email-sends"]}),Ks(),re.success("Email sent successfully!"),t(!1),o==null||o())}finally{X(!1)}return}qe.current=!1,dt.current=0,await kn(0)},bn=async()=>{qe.current=!1,ze(0),await kn(dt.current,!1)},xs=async()=>{qe.current=!1,at(!0),ze(0),await kn(dt.current,!0)},Lr=()=>{if(Y){qe.current=!0;return}t(!1),o==null||o()},Or=Fe*eN;Math.min(Or+eN,E.length);const la=w&&E.length>0?Math.round((Be+Ae)/E.length*100):0;return e.jsxs(zs,{open:s,onOpenChange:Lr,children:[e.jsxs(Os,{className:"sm:max-w-[600px] max-h-[90vh] overflow-y-auto",onPointerDownOutside:Qn=>{(ce||he)&&Qn.preventDefault()},onInteractOutside:Qn=>{(ce||he)&&Qn.preventDefault()},onEscapeKeyDown:Qn=>{(ce||he)&&Qn.preventDefault()},children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(mn,{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&&Se==="composing"&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Composing email for ",e.jsxs("span",{className:"font-medium",children:[E.length," contacts"]}),". You'll review each personalized email before sending."]})]}),Ft&&Se==="composing"&&e.jsxs("div",{className:"flex items-center justify-between gap-2 rounded-lg border border-primary/30 bg-primary/5 px-3 py-2 text-xs",children:[e.jsx("span",{children:"We brought back the email you were writing."}),e.jsx($,{type:"button",variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:()=>{Ks(),_e(""),ue(""),W(""),G(""),Xs.current=null,Js(Qn=>Qn+1)},children:"Start fresh"})]}),Se==="sending"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx(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:[Ve," of ",$n().length," in this batch"]}),Xe&&P>1&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Auto-continuing through all ",P," batches — keep this window open."]})]}),e.jsx(Yi,{value:Ve/Math.max($n().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:()=>{qe.current=!0},children:"Stop Sending"})]}),Se==="batch_complete"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx(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:Lr,children:"Done for Now"}),e.jsxs($,{className:"flex-1 gap-2",onClick:xs,children:[e.jsx(Kr,{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(eN,Math.max(E.length-(Be+Ae),0))," contacts"]})]}),Se==="all_done"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx(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:Lr,children:"Close"})]}),Se==="composing"&&e.jsxs("div",{className:"space-y-4",children:[ae?e.jsxs("div",{className:"border rounded-lg p-3 bg-muted/30 max-h-[50vh] overflow-y-auto",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("p",{className:"text-sm font-medium flex items-center gap-1.5",children:[e.jsx(Jr,{className:"h-4 w-4"})," Choose a Template"]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>le(!1),className:"h-7 px-2 text-xs",children:[e.jsx(pr,{className:"h-3 w-3 mr-1"})," Write from scratch"]})]}),e.jsx(UHs,{onSelect:hn})]}):e.jsxs($,{variant:"outline",size:"sm",className:"gap-2",onClick:()=>le(!0),children:[e.jsx(Jr,{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(RUt,{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:Qn=>{W(Qn.target.value),_e(Qn.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(Qn=>Qn+"{{first_name}}"),ue(Qn=>Qn+"{{first_name}}")},children:"{{first_name}}"}),e.jsx($e,{variant:"outline",className:"text-[10px] cursor-pointer hover:bg-accent",onClick:()=>{G(Qn=>Qn+"{{last_name}}"),ue(Qn=>Qn+"{{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 Qn=` When you get a sec, can you share your latest contact info with me? It only takes about a minute: ${b} `;G(Cr=>Cr+Qn),ue(Cr=>Cr+Qn)},title:"Insert your Connect Page link",children:"+ Connect Page"})]})]}),ds&&!ve?e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"overflow-hidden rounded-xl border bg-background",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 border-b bg-muted/40 px-3 py-2",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx($,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0 font-bold",onMouseDown:Qn=>Qn.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:Qn=>Qn.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:Qn=>Qn.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:Qn=>Qn.preventDefault(),onClick:()=>{const Qn=window.prompt("Link address (https://...)");Qn&&document.execCommand("createLink",!1,Qn)},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:Ss,contentEditable:!0,suppressContentEditableWarning:!0,onInput:Ut,onBlur:Ut,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:ds}},yn)]}),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 Qn=document.getElementById("gmail-body"),Cr=Qn?V.slice(Qn.selectionStart,Qn.selectionEnd):"",Un=window.prompt("Link text (what the reader sees)",Cr||"Click here");if(!Un)return;let dr=window.prompt("Link address (https://...)","https://");if(!dr)return;dr=dr.trim(),/^(https?:\/\/|mailto:)/i.test(dr)||(dr=`https://${dr}`);const Pa=`[${Un}](${dr})`,ii=Qn?Qn.selectionStart:V.length,$i=Qn?Qn.selectionEnd:V.length,Rn=V.slice(0,ii)+Pa+V.slice($i);G(Rn),ue(Rn)},children:"Insert link"}),e.jsx("span",{className:"text-[11px] text-muted-foreground",children:"Web addresses you type become clickable automatically"})]}),e.jsx(Ls,{id:"gmail-body",value:V,onChange:Qn=>{G(Qn.target.value),ue(Qn.target.value)},placeholder:"Write your message...",rows:10,className:"resize-y"})]}),w&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Use ","{{first_name}}",", ","{{last_name}}"," to personalize. You'll preview each recipient's email in the next step."]}),e.jsxs("div",{className:"flex items-center justify-between rounded-md border bg-muted/30 px-3 py-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-medium",children:"Include my email signature"}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:Ke?"Your saved signature is added to the bottom of this email.":"Add a signature in Profile settings to use this."})]}),e.jsx(Sn,{checked:Je&&Ke,onCheckedChange:pt,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 Qn;return(Qn=document.getElementById("gmail-attachments"))==null?void 0:Qn.click()},disabled:Y,children:[e.jsx(ZI,{className:"h-4 w-4"}),"Attach Files"]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["PDF, images, Word, Excel (max ",tde(X7e)," 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:wt})]}),ne.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:ne.map((Qn,Cr)=>e.jsxs($e,{variant:"secondary",className:"gap-1.5 pl-2 pr-1 py-1",children:[e.jsx(ZI,{className:"h-3 w-3"}),e.jsx("span",{className:"max-w-[140px] truncate text-xs",children:Qn.name}),e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["(",tde(Qn.size),")"]}),e.jsx("button",{type:"button",onClick:()=>gs(Cr),className:"ml-0.5 rounded-full p-0.5 hover:bg-muted",children:e.jsx(pr,{className:"h-3 w-3"})})]},Cr))}),A&&ne.some(Qn=>Qn.size>cbt)&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Files over ",tde(cbt)," 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:()=>{ss(E[0]||null),Le("reviewing")},disabled:!U||!V,className:"gap-2",children:["Review Emails",e.jsx(Qa,{className:"h-4 w-4"})]}):e.jsxs($,{onClick:Fn,disabled:Y||!U||!V||!D.trim(),className:"gap-2",children:[Y?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Kr,{className:"h-4 w-4"}),Y?"Sending...":"Send Email"]})]})]}),Se==="reviewing"&&w&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-xs text-primary bg-primary/10 rounded-md px-2.5 py-1.5",children:["✉️ Click any recipient below to preview the ",e.jsx("span",{className:"font-semibold",children:"exact personalized email"})," they will receive."]}),R&&e.jsxs("div",{className:"rounded-md border border-amber-500/30 bg-amber-500/5 px-2.5 py-2 space-y-2",children:[e.jsxs("p",{className:"text-xs text-amber-600",children:["📦 ",E.length," contacts will be sent in ",P," batches of up to ",eN,"."]}),e.jsxs("label",{className:"flex items-start gap-2 text-xs cursor-pointer",children:[e.jsx("input",{type:"checkbox",className:"mt-0.5 accent-current",checked:Xe,onChange:Qn=>at(Qn.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(Qn=>e.jsxs("div",{className:`text-sm px-2 py-1 rounded cursor-pointer transition-colors ${(gt==null?void 0:gt.id)===Qn.id?"bg-primary/10 text-primary font-medium":"text-muted-foreground hover:bg-accent hover:text-foreground"}`,onClick:()=>ss(Qn),children:[Qn.first_name," ",Qn.last_name," — ",Qn.email]},Qn.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(mn,{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:"})," ",hj(ce,gt)]})]}),e.jsx(Vc,{}),ds?e.jsx("div",{className:"rounded-lg border bg-background max-h-72 overflow-y-auto [&_img]:max-w-full",dangerouslySetInnerHTML:{__html:hj(ds,gt)}}):e.jsx("div",{className:"text-sm whitespace-pre-wrap bg-background rounded p-2.5 max-h-40 overflow-y-auto border",children:hj(he,gt)})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsxs($,{variant:"outline",onClick:()=>{Le("composing"),ss(null)},children:[e.jsx(Va,{className:"h-4 w-4 mr-1"}),"Back to Edit"]}),e.jsxs($,{onClick:Fn,disabled:Y,className:"gap-2",children:[Y?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Kr,{className:"h-4 w-4"}),R?`Send First ${eN}`:`Send to ${E.length}`]})]})]})]}),e.jsx(w6e,{open:x,onOpenChange:y,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 XHs={single_family:"Single Family Home",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury Home",commercial:"Commercial",other:"Property"};function DUt({open:s,onOpenChange:t,listing:n}){const{user:r}=bs(),{data:a=[],isLoading:i}=R_(),{data:l=[]}=qw(),[o,c]=j.useState(""),[d,u]=j.useState("all"),[h,m]=j.useState(new Set),[f,g]=j.useState(!1),[x,y]=j.useState(null);j.useEffect(()=>{s||(c(""),u("all"),m(new Set),g(!1))},[s]),j.useEffect(()=>{!s||!r||(async()=>{const{data:P}=await q.from("gmail_integrations").select("gmail_email").eq("user_id",r.id).maybeSingle();y((P==null?void 0:P.gmail_email)||null)})()},[s,r]);const v=j.useMemo(()=>a.filter(P=>P.email),[a]),b=j.useMemo(()=>{let P=v;if(d!=="all"&&(P=P.filter(R=>{var D;return(D=R.tags)==null?void 0:D.some(O=>O.relationship_type_id===d)})),o.trim()){const R=o.toLowerCase();P=P.filter(D=>`${D.first_name||""} ${D.last_name||""}`.toLowerCase().includes(R)||(D.email||"").toLowerCase().includes(R))}return P},[v,o,d]),w=()=>{h.size===b.length?m(new Set):m(new Set(b.map(P=>P.id)))},S=P=>{const R=new Set(h);R.has(P)?R.delete(P):R.add(P),m(R)},A=j.useMemo(()=>v.filter(P=>h.has(P.id)).map(P=>({id:P.id,first_name:P.first_name||"there",last_name:P.last_name,email:P.email})),[v,h]),{defaultSubject:E,defaultBody:I}=j.useMemo(()=>{var te,J,ce,_e;const P=n.property_address||`${n.city}, ${n.state}`,R=ZHs(n.price),D=XHs[n.property_type]||"home",O=n.bedrooms?`${n.bedrooms} bed`:"",U=n.bathrooms?`${n.bathrooms} bath`:"",W=n.square_footage?`${n.square_footage.toLocaleString()} sqft`:"",V=[O,U,W].filter(Boolean).join(" • "),G=`https://listings.relevelup.com/${n.slug||n.id}`,Y=((J=(te=n.photos)==null?void 0:te.find(he=>he.is_primary))==null?void 0:J.photo_url)||((_e=(ce=n.photos)==null?void 0:ce[0])==null?void 0:_e.photo_url)||"",ae={active:"Just Listed",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"}[n.status]||"New Listing",le=`${ae}: ${P} — ${R}`,ne=`

Hi {{first_name}},

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

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

${R}

${P}

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

${V?`

${V} • ${D}

`:""} View Photos & Details →

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

Talk soon,

`;return{defaultSubject:le,defaultBody:ne}},[n]);return f?e.jsx(kk,{open:f,onOpenChange:P=>{g(P),P||t(!1)},bulkContacts:A,defaultSubject:E,defaultBody:I,gmailEmail:x}):e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-[640px] max-h-[90vh] flex flex-col",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(Nn,{className:"h-5 w-5 text-amber-500"}),"Email this listing to your sphere"]}),e.jsx(Pr,{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(Zr,{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(uo,{className:"flex-1 -mx-6 px-6",children:i?e.jsxs("div",{className:"flex items-center justify-center py-12 text-muted-foreground",children:[e.jsx(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:v.length===0?"No contacts with email addresses yet.":"No contacts match your search."}):e.jsx("div",{className:"space-y-1 py-2",children:b.map(P=>e.jsxs("label",{className:"flex items-center gap-3 p-2 rounded-md hover:bg-muted/50 cursor-pointer",children:[e.jsx(ai,{checked:h.has(P.id),onCheckedChange:()=>S(P.id)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:"text-sm font-medium truncate",children:[P.first_name," ",P.last_name]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:P.email})]}),P.tags&&P.tags.length>0&&e.jsx("div",{className:"flex gap-1 flex-wrap justify-end max-w-[40%]",children:P.tags.slice(0,2).map(R=>{var D;return e.jsx($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(mn,{className:"h-4 w-4"}),"Compose Email (",h.size,")"]})]})]})]})})}const QHs="#2a4c64",JHs="#B8965A";function N6e(){const{user:s}=bs();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(v=>v.is_active)||o[0]||{},d=a.data||{},u=i.data||{};let h=null;if(l.brokerage_id){const{data:v}=await q.from("brokerage_brand_profiles").select("primary_color, accent_color, logo_url, lock_colors, lock_logo").eq("brokerage_id",l.brokerage_id).maybeSingle();h=v||null}const m=!!(h!=null&&h.lock_colors),f=(...v)=>v.map(b=>typeof b=="string"&&b.trim()?b.trim():null).find(Boolean)||null,g=m?f(h==null?void 0:h.primary_color,u.brand_color,c.brand_color):f(u.brand_color,h==null?void 0:h.primary_color,c.brand_color),x=m?f(h==null?void 0:h.accent_color,u.accent_color,c.accent_color):f(u.accent_color,h==null?void 0:h.accent_color,c.accent_color);let y=l.brokerage_name||d.brokerage_display_name||c.brokerage_legal_name||null;if(!y&&l.brokerage_id){const{data:v}=await q.from("brokerages").select("name").eq("id",l.brokerage_id).maybeSingle();y=(v==null?void 0:v.name)||null}return{name:l.name||s.email||"Your Name",headshotUrl:u.headshot_url||l.avatar_url||null,brokerageName:y,brokerageLogoUrl:(h!=null&&h.lock_logo?h==null?void 0:h.logo_url:u.logo_url)||u.logo_url||d.brokerage_logo_url||d.team_logo_url||c.team_logo_url||(h==null?void 0:h.logo_url)||null,licenseNumber:u.license_number||c.agent_license_number||null,licenseState:u.license_state||c.license_state||null,phone:l.phone||null,email:d.display_email||l.email||s.email||null,website:u.website_url||l.website_url||null,brandColor:g||QHs,accentColor:x||JHs,tagline:u.tagline||d.positioning_statement||l.title||d.title||null}}})}const dbt=[{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"}],eGs=[{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"}],YEe=s=>{switch(s){case"price_improvement":return"price_improvement";case"under_contract":return"under_contract";case"sold":return"sold";default:return"just_listed"}},tGs=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)}`},sde=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),ubt=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}),hbt=(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)},lQ=(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()}…`},sGs=(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},rGs=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}},_M=(s,t)=>{const{r:n,g:r,b:a}=rGs(s);return`rgba(${n},${r},${a},${t})`};function tnt({listingId:s,open:t,onOpenChange:n,initialStatus:r}){var _e,he;const a=Xn(),{data:i}=Zae(s||""),{data:l}=N6e(),[o,c]=j.useState(null),[d,u]=j.useState({base:null,accent:null}),[h,m]=j.useState(!1),[f,g]=j.useState(!1),[x,y]=j.useState(null),[v,b]=j.useState(null),[w,S]=j.useState(r||"just_listed"),[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,ve)=>ue.is_primary&&!ve.is_primary?-1:!ue.is_primary&&ve.is_primary?1:(ue.sort_order??0)-(ve.sort_order??0)),[i==null?void 0:i.photos]),U=j.useMemo(()=>({key:"brand",label:"My Brand Kit",base:d.base||(l==null?void 0:l.brandColor)||"#2a4c64",accent:d.accent||(l==null?void 0:l.accentColor)||"#B8965A"}),[d.base,d.accent,l==null?void 0:l.brandColor,l==null?void 0:l.accentColor]),W=j.useMemo(()=>[U,...eGs],[U]),V=W.find(ue=>ue.key===A)||U,G=((_e=dbt.find(ue=>ue.key===w))==null?void 0:_e.ribbon)||"JUST LISTED",Y=v||((he=O[0])==null?void 0:he.photo_url)||null,X=tGs((o==null?void 0:o.phone)||(l==null?void 0:l.phone)),ae=[i!=null&&i.bedrooms?`${i.bedrooms} BD`:null,i!=null&&i.bathrooms?`${i.bathrooms} BA`:null,i!=null&&i.square_footage?`${i.square_footage.toLocaleString()} SF`:null].filter(Boolean);j.useEffect(()=>{var ve;if(!t)return;S(r||YEe(i==null?void 0:i.status));const ue=((ve=O[0])==null?void 0:ve.photo_url)||null;b(Ee=>Ee||ue)},[t,i==null?void 0:i.id,O.length]),j.useEffect(()=>{t||(y(null),b(null),D(!1),u({base:null,accent:null}))},[t]),j.useEffect(()=>{let ue=!1;if(!(!t||!(i!=null&&i.agent_id)))return(async()=>{var Ae,Ce,Ve,ze;const[ve,Ee,Se]=await Promise.all([q.from("profiles").select("name, phone, phone_e164, avatar_url, brokerage:brokerages!profiles_brokerage_id_fkey(name)").eq("id",i.agent_id).maybeSingle(),q.from("agent_brand_profiles").select("brand_color, accent_color").eq("user_id",i.agent_id).maybeSingle(),q.from("lead_sites").select("brand_color, accent_color, is_active, created_at").eq("agent_id",i.agent_id).order("created_at",{ascending:!0}).limit(5)]);if(ue)return;const Le=ve.data;c({name:(Le==null?void 0:Le.name)||((Ae=i.agent)==null?void 0:Ae.name)||"Agent",phone:(Le==null?void 0:Le.phone)||(Le==null?void 0:Le.phone_e164)||null,avatar_url:(Le==null?void 0:Le.avatar_url)||null,brokerage:((Ce=Le==null?void 0:Le.brokerage)==null?void 0:Ce.name)||((ze=(Ve=i.agent)==null?void 0:Ve.brokerage)==null?void 0:ze.name)||null});const Fe=Ee.data||null,ke=Se.data||[],Be=ke.find(qe=>qe.is_active)||ke[0]||{},Ne=qe=>typeof qe=="string"&&qe.trim()?qe.trim():null;u({base:Ne(Fe==null?void 0:Fe.brand_color)||Ne(Be.brand_color),accent:Ne(Fe==null?void 0:Fe.accent_color)||Ne(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(", "),ve=ae.join(" · "),Ee=sde(i.price),Se=X?`call or text ${X}`:"send me a message",Le=(i.city||"").replace(/[^a-zA-Z]/g,""),Fe={just_listed:`✨ JUST LISTED in ${ue||"town"}!`,price_improvement:`📉 PRICE IMPROVEMENT in ${ue||"town"}!`,under_contract:`🤝 UNDER CONTRACT in ${ue||"town"}!`,sold:`🎉 JUST SOLD in ${ue||"town"}!`,open_house:`🚪 OPEN HOUSE in ${ue||"town"}!`},ke={just_listed:`Want a private tour? ${Se}.`,price_improvement:`This one won't last at the new number — ${Se}.`,under_contract:`Looking for something similar? ${Se}.`,sold:`Thinking about making a move? ${Se}.`,open_house:`Stop by or ${Se} for details.`},Be={just_listed:"#JustListed",price_improvement:"#PriceImprovement",under_contract:"#UnderContract",sold:"#JustSold",open_house:"#OpenHouse"},Ne=[Fe[w],i.property_address||"",[ve,Ee].filter(Boolean).join(" · "),i.description?i.description.split(/\n+/)[0].slice(0,180):"",ke[w],[Be[w],Le?`#${Le}RealEstate`:"","#RealEstate","#DreamHome"].filter(Boolean).join(" ")].filter(Boolean);P(Ne.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",ve=(o==null?void 0:o.brokerage)||(l==null?void 0:l.brokerageName)||null;m(!0);try{const Ee=document.createElement("canvas");Ee.width=1080,Ee.height=1080;const Se=Ee.getContext("2d");if(!Se)throw new Error("Canvas unavailable");if(Se.fillStyle=V.base,Se.fillRect(0,0,1080,1080),Y)try{const ze=await ubt(Y);hbt(Se,ze,0,0,1080,1080)}catch{}const Le=Se.createLinearGradient(0,0,0,1080);Le.addColorStop(0,_M(V.base,.6)),Le.addColorStop(.34,_M(V.base,.18)),Le.addColorStop(.62,_M(V.base,.5)),Le.addColorStop(1,_M(V.base,.98)),Se.fillStyle=Le,Se.fillRect(0,0,1080,1080),Se.fillStyle=V.accent,Se.fillRect(56,62,72,3),Se.font="600 22px Arial, sans-serif",nGs(Se,G,146,72,8),(w==="sold"||w==="under_contract")&&(Se.save(),Se.fillStyle=_M(V.accent,.92),Se.fillRect(0,430,1080,96),Se.fillStyle=V.base,Se.font="700 46px Arial, sans-serif",Se.textAlign="center",Se.textBaseline="middle",Se.fillText(w==="sold"?"SOLD":"UNDER CONTRACT",540,479),Se.restore(),Se.textAlign="left"),Se.save(),Se.shadowColor="rgba(0,0,0,0.55)",Se.shadowBlur=24,Se.shadowOffsetY=4,Se.fillStyle="#F8FAFC",Se.font="600 64px Georgia, serif",Se.textBaseline="top";const Fe=sGs(Se,i.property_address||`${i.city||""}, ${i.state||""}`.trim(),952,2);let ke=Fe.length>1?590:654;Fe.forEach(ze=>{Se.fillText(ze,64,ke),ke+=70}),Se.restore();const Be=[i.city,i.state].filter(Boolean).join(", ")+(i.neighborhood?` · ${i.neighborhood}`:"");Se.fillStyle="rgba(248,250,252,0.9)",Se.font="600 26px Arial, sans-serif",Se.fillText(lQ(Se,Be.toUpperCase(),952),64,ke+8),Se.fillStyle=V.accent,Se.font="700 56px Arial, sans-serif";const Ne=w==="sold"?`SOLD · ${sde(i.price)}`:w==="price_improvement"?`NOW ${sde(i.price)}`:sde(i.price);Se.fillText(Ne,64,ke+58),ae.length>0&&(Se.fillStyle="rgba(248,250,252,0.86)",Se.font="600 22px Arial, sans-serif",Se.fillText(lQ(Se,ae.join(" · "),400),620,ke+78));const Ae=Se.createLinearGradient(0,880,0,1080);Ae.addColorStop(0,_M(V.base,.96)),Ae.addColorStop(1,V.base),Se.fillStyle=Ae,Se.fillRect(0,880,1080,200),Se.fillStyle=V.accent,Se.fillRect(0,880,1080,3),Se.save(),Se.beginPath(),Se.arc(124,980,60,0,Math.PI*2),Se.closePath(),Se.fillStyle=_M(V.accent,.18),Se.fill(),Se.lineWidth=6,Se.strokeStyle=V.accent,Se.stroke(),Se.clip();const Ce=(o==null?void 0:o.avatar_url)||(l==null?void 0:l.headshotUrl)||null;let Ve=!1;if(Ce)try{const ze=await ubt(Ce);hbt(Se,ze,64,920,120,120),Ve=!0}catch{Ve=!1}Ve||(Se.fillStyle=V.accent,Se.font="700 48px Arial, sans-serif",Se.textAlign="center",Se.textBaseline="middle",Se.fillText(ue.charAt(0).toUpperCase(),124,982)),Se.restore(),Se.textAlign="left",Se.textBaseline="alphabetic",Se.fillStyle="#F8FAFC",Se.font="600 38px Georgia, serif",Se.fillText(lQ(Se,ue,X?430:820),212,970),ve&&(Se.fillStyle=V.accent,Se.font="600 20px Arial, sans-serif",Se.fillText(lQ(Se,ve.toUpperCase(),X?430:820),212,1008)),X&&(Se.textAlign="right",Se.fillStyle=_M(V.accent,.9),Se.font="600 16px Arial, sans-serif",Se.fillText("CALL · TEXT",1016,958),Se.fillStyle="#F8FAFC",Se.font="600 38px Arial, sans-serif",Se.fillText(X,1016,1008)),y(Ee.toDataURL("image/png"))}catch(Ee){console.error("Generate graphic error",Ee),re.error("Could not generate graphic")}finally{m(!1)}},[i,o,l,V,Y,G,w,ae,X]);j.useEffect(()=>{if(!t||!i)return;const ue=setTimeout(()=>{le()},300);return()=>clearTimeout(ue)},[t,i==null?void 0:i.id,o==null?void 0:o.name,v,w,A,l==null?void 0:l.brandColor]);const ne=async ue=>(await fetch(ue)).blob(),te=async()=>{if(!x)return;const ue=document.createElement("a");ue.href=x,ue.download=`${w}-${(i==null?void 0:i.slug)||(i==null?void 0:i.id)||"graphic"}.png`,ue.click(),re.success("Downloaded!")},J=async()=>{try{await navigator.clipboard.writeText(I),re.success("Caption copied")}catch{re.error("Copy not supported in this browser")}},ce=async()=>{var ue;if(x){g(!0);try{const{data:ve}=await q.auth.getUser(),Ee=(ue=ve.user)==null?void 0:ue.id;if(!Ee)throw new Error("Not signed in");const Se=await ne(x),Le=`listing-social/${Ee}/${crypto.randomUUID()}.png`,{error:Fe}=await q.storage.from("agent-uploads").upload(Le,Se,{contentType:"image/png",upsert:!0});if(Fe)throw Fe;const{data:ke}=q.storage.from("agent-uploads").getPublicUrl(Le);sessionStorage.setItem("social-studio-seed",JSON.stringify({mediaUrl:ke.publicUrl,mediaType:"image",caption:I,source:"listing",sourceRef:i==null?void 0:i.id})),n(!1),a("/social-studio"),re.success("Draft ready in Social Studio")}catch(ve){console.error("Push to Social Studio failed",ve),re.error("Could not send to Social Studio")}finally{g(!1)}}};return e.jsx(zs,{open:t,onOpenChange:n,children:e.jsx(Os,{className:"!max-w-[900px] !w-[calc(100vw-2rem)] !p-0 !gap-0 !block overflow-hidden",style:{maxHeight:"calc(100vh - 2rem)"},children:e.jsxs("div",{className:"flex flex-col",style:{maxHeight:"calc(100vh - 2rem)"},children:[e.jsxs(Us,{className:"px-5 pt-5 pb-3 shrink-0",children:[e.jsxs(Bs,{className:"flex items-center gap-2 pr-8",children:[e.jsx(Nn,{className:"h-5 w-5 text-amber-500 shrink-0"}),e.jsx("span",{className:"truncate",children:"Share this listing"})]}),e.jsx(Pr,{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:dbt.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 ${v===ue.photo_url?"border-amber-500 ring-2 ring-amber-500/30":"border-transparent hover:border-muted-foreground/40"}`,children:e.jsx("img",{src:ue.photo_url,alt:"",className:"h-full w-full object-cover"})},ue.id))})]})]}),e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Post text"}),e.jsxs($,{type:"button",variant:"ghost",size:"sm",className:"h-7 gap-1.5 text-xs",onClick:J,children:[e.jsx(Ha,{className:"h-3.5 w-3.5"})," Copy"]})]}),e.jsx(Ls,{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(xi,{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(qg,{className:"h-3.5 w-3.5"}),"Push to Social Studio"]})]})]})})})}function aGs({listing:s,canEdit:t}){const n=Xn(),{data:r,isLoading:a}=pDs(s.id),i=L7t(),l=R7t(),[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(M7t),[h,m]=j.useState("");j.useEffect(()=>{r&&(c({owner_name:r.owner_name??"",owner_company:r.owner_company??"",owner_email:r.owner_email??"",owner_phone:r.owner_phone??"",decision_maker_notes:r.decision_maker_notes??"",pitch_date:r.pitch_date?String(r.pitch_date).slice(0,10):"",positioning:r.positioning??"",pricing_strategy:r.pricing_strategy??"",pitch_notes:r.pitch_notes??"",competitors:r.competitors??""}),Array.isArray(r.launch_plan)&&r.launch_plan.length&&u(r.launch_plan))},[r]);const f=r!=null&&r.preview_token?`${window.location.origin}/commercial-pitch/${r.preview_token}`:null,g=async()=>{await i.mutateAsync({listingId:s.id,values:{...o,pitch_date:o.pitch_date||null,launch_plan:d.filter(v=>{var b;return(b=v.label)==null?void 0:b.trim()})}}),re.success("Pitch saved")},x=async()=>{await l.mutateAsync({listingId:s.id,stage:"won"}),re.success("Assignment won — welcome to Launch"),n(`/mission-control/listings/${s.id}/commercial`)},y=async()=>{await l.mutateAsync({listingId:s.id,stage:"lost",lostReason:h}),re("Marked as lost opportunity"),n("/mission-control/listings")};return a?e.jsx("div",{className:"flex justify-center py-20",children:e.jsx(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(Gn,{children:"Who actually signs the listing agreement."})]}),e.jsxs(Ie,{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Owner name"}),e.jsx(pe,{value:o.owner_name,onChange:v=>c({...o,owner_name:v.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Entity / company"}),e.jsx(pe,{value:o.owner_company,onChange:v=>c({...o,owner_company:v.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Email"}),e.jsx(pe,{type:"email",value:o.owner_email,onChange:v=>c({...o,owner_email:v.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Phone"}),e.jsx(pe,{value:o.owner_phone,onChange:v=>c({...o,owner_phone:v.target.value})})]}),e.jsxs("div",{className:"space-y-2 md:col-span-2",children:[e.jsx(ee,{children:"Decision-maker intel"}),e.jsx(Ls,{rows:3,value:o.decision_maker_notes,onChange:v=>c({...o,decision_maker_notes:v.target.value}),placeholder:"Motivations, timing, partners, tax position, who influences the decision…"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Pitch date"}),e.jsx(pe,{type:"date",value:o.pitch_date,onChange:v=>c({...o,pitch_date:v.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Competing brokers"}),e.jsx(pe,{value:o.competitors,onChange:v=>c({...o,competitors:v.target.value})})]})]})]}),e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{className:"text-base",children:"Positioning & pricing strategy"}),e.jsx(Gn,{children:"The argument you're making for how this asset goes to market."})]}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Proposed positioning"}),e.jsx(Ls,{rows:4,value:o.positioning,onChange:v=>c({...o,positioning:v.target.value}),placeholder:"Buyer profile, story, comparable trades, why this asset wins attention…"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Pricing strategy"}),e.jsx(Ls,{rows:4,value:o.pricing_strategy,onChange:v=>c({...o,pricing_strategy:v.target.value}),placeholder:"Recommended ask, cap-rate rationale, call-for-offers timing…"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Private pitch notes"}),e.jsx(Ls,{rows:3,value:o.pitch_notes,onChange:v=>c({...o,pitch_notes:v.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(Gn,{children:"Shown on the owner-facing preview — this is what they buy."})]}),e.jsxs(Ie,{className:"space-y-3",children:[d.map((v,b)=>e.jsxs("div",{className:"rounded-lg border p-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{value:v.label,placeholder:"Milestone",onChange:w=>u(d.map((S,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(pr,{className:"h-4 w-4"})})]}),e.jsx(Ls,{className:"mt-2",rows:2,value:v.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(dn,{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(Gn,{children:"A private, seller-facing page showing exactly what happens the day they hire you."})]}),e.jsx(Ie,{className:"space-y-3",children:f?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex items-center gap-2 rounded-lg border bg-background px-3 py-2",children:e.jsx("span",{className:"truncate text-xs text-muted-foreground",children:f})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{variant:"outline",size:"sm",className:"flex-1",onClick:()=>{navigator.clipboard.writeText(f),re.success("Link copied")},children:[e.jsx(Ha,{className:"mr-1.5 h-3.5 w-3.5"})," Copy"]}),e.jsxs($,{size:"sm",className:"flex-1",onClick:()=>window.open(f,"_blank"),children:[e.jsx(Fr,{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(Ie,{className:"space-y-3",children:[e.jsxs(fc,{children:[e.jsx(Tg,{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(Tg,{asChild:!0,children:e.jsxs($,{variant:"outline",className:"w-full",children:[e.jsx(Nu,{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:v=>m(v.target.value)}),e.jsxs(rc,{children:[e.jsx(oc,{children:"Cancel"}),e.jsx(Yl,{onClick:y,children:"Mark lost"})]})]})]})]})]})]})]}),e.jsx("div",{className:"sticky bottom-4 flex justify-end",children:e.jsxs($,{onClick:g,disabled:i.isPending,size:"lg",className:"shadow-lg",children:[i.isPending?e.jsx(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(Gn,{children:"Only the listing agent can view or update pitch strategy and owner information."})]})})}function iGs({listingId:s}){const{data:t=[],isLoading:n}=i6e(s),r=B$t(),a=$$t(),i=Eqs(),l=j.useRef(null),[o,c]=j.useState("om"),[d,u]=j.useState("email"),h=async f=>{if(f!=null&&f.length)try{for(const g of Array.from(f))await r.mutateAsync({listingId:s,file:g,docKind:o,gateLevel:d});re.success("Document uploaded")}catch(g){re.error(g.message||"Upload failed")}finally{l.current&&(l.current.value="")}},m=async f=>{try{window.open(await Gst(f),"_blank")}catch{re.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(Gn,{children:"Offering memorandum, financials and diligence files. Everything is stored privately and released through expiring secure links only."})]}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-muted-foreground",children:"Document type"}),e.jsxs(ms,{value:o,onValueChange:f=>c(f),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:Object.entries(JHe).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(Vyt).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(Jr,{className:"mx-auto mb-3 h-7 w-7 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No documents yet. Upload the OM to activate gated requests."})]}):e.jsx("div",{className:"divide-y rounded-xl border",children:t.map(f=>e.jsxs("div",{className:"flex flex-wrap items-center gap-3 p-4",children:[e.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-lg border bg-muted/40",children:e.jsx(Jr,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:f.title||f.file_name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(f.file_size/1024/1024).toFixed(2)," MB · ",f.download_count??0," downloads"]})]}),e.jsx($e,{variant:"secondary",children:JHe[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(xi,{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(pc,{className:"mr-2 h-3.5 w-3.5"}),e.jsx(fs,{})]}),e.jsx(hs,{children:Object.entries(Vyt).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(Hn,{className:"h-4 w-4"})})]},f.id))})]})]})})}const oGs={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 lGs({listingId:s}){const{data:t=[],isLoading:n}=Ztt(s),{data:r=[]}=Ytt(s),a=j.useMemo(()=>{const o={};for(const c of r)c.lead_id&&(o[c.lead_id]=(o[c.lead_id]??0)+(Gyt[c.event_type]??1));return o},[r]),i=j.useMemo(()=>[...t].map(o=>({...o,score:(a[o.id]??0)+(Gyt[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(Gn,{children:"Ranked by document access, tour requests and repeat engagement."})]}),e.jsx(Ie,{className:"grid gap-3 md:grid-cols-2",children:l.slice(0,6).map(o=>{const c=Wyt(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||eGe[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(mn,{className:"mr-1.5 h-3.5 w-3.5"})," Email"]})}),o.phone&&e.jsx($,{asChild:!0,size:"sm",variant:"ghost",children:e.jsxs("a",{href:`tel:${o.phone}`,children:[e.jsx(Da,{className:"mr-1.5 h-3.5 w-3.5"})," Call"]})})]})]},o.id)})})]}),e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{className:"text-base",children:"Investors & inquiries"}),e.jsx(Gn,{children:"Every prospect is written into your LevelUp CRM automatically."})]}),e.jsx(Ie,{children:i.length===0?e.jsxs("div",{className:"rounded-xl border border-dashed py-14 text-center",children:[e.jsx(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=Wyt(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:eGe[o.investor_role]??o.investor_role}),e.jsx($e,{variant:"outline",children:oGs[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 cGs={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 dGs({listing:s}){const{data:t=[],isLoading:n}=Ytt(s.id),{data:r=[]}=Ztt(s.id),[a,i]=j.useState(""),[l,o]=j.useState(""),[c,d]=j.useState(!1),u=async f=>{d(!0);try{const{data:g,error:x}=await q.functions.invoke("commercial-seller-report",{body:{action:f?"send":"generate",listingId:s.id,days:7,narrative:l||null,recipients:a.split(/[,\s]+/).map(y=>y.trim()).filter(Boolean)}});if(x)throw x;if(g!=null&&g.error)throw new Error(g.error);re.success(f?"Activity report sent to your owner":"Weekly report generated")}catch(g){re.error(g.message||"Could not build the report")}finally{d(!1)}},h=j.useMemo(()=>{const f=y=>{const v=Array.isArray(y)?y:[y];return t.filter(b=>v.includes(b.event_type)).length},g=new Set(t.map(y=>y.session_id).filter(Boolean)),x=new Map;return t.forEach(y=>y.session_id&&x.set(y.session_id,(x.get(y.session_id)??0)+1)),{views:f("page_view")||s.view_count||0,unique:g.size,repeat:[...x.values()].filter(y=>y>3).length,omRequests:f(["om_request","om_download"]),downloads:f(["doc_download","om_download"]),tours:f("tour_request"),inquiries:r.length,shares:s.share_count??0}},[t,r,s]),m=[{label:"Microsite views",value:h.views,icon:Ca},{label:"Unique visitors",value:h.unique,icon:Yn},{label:"Repeat visitors",value:h.repeat,icon:rf},{label:"OM requests",value:h.omRequests,icon:vJ},{label:"Document downloads",value:h.downloads,icon:xi},{label:"Tour requests",value:h.tours,icon:rf},{label:"Total inquiries",value:h.inquiries,icon:Yn},{label:"Shares",value:h.shares,icon:Fd}];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(Gn,{children:"Last 7 days of activity, packaged as a branded report the owner can read in their inbox."})]}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Owner email(s)"}),e.jsx(pe,{placeholder:"owner@example.com, asset.manager@example.com",value:a,onChange:f=>i(f.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Broker note (optional)"}),e.jsx(Ls,{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(mn,{className:"mr-2 h-4 w-4"}),"Send report"]}),e.jsx($,{variant:"outline",onClick:()=>u(!1),disabled:c,children:"Save without sending"})]})]})]}),e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{className:"text-base",children:"Owner activity report"}),e.jsx(Gn,{children:"Everything below is what your owner sees in the weekly activity report — proof the asset is being worked."})]}),e.jsx(Ie,{children:n?e.jsx("div",{className:"flex justify-center py-10",children:e.jsx(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:cGs[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 uGs({listing:s,details:t,publicUrl:n}){var g,x;const r=Xn(),[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:rL(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((y,v)=>e.jsx("button",{onClick:()=>c(v),className:`h-16 w-24 shrink-0 overflow-hidden rounded-lg border-2 ${v===o?"border-primary":"border-transparent"}`,children:e.jsx("img",{src:y.photo_url,alt:"",className:"h-full w-full object-cover"})},y.id??v))}),e.jsxs("div",{className:"mt-6 flex flex-wrap items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"mb-2 flex flex-wrap items-center gap-2",children:[e.jsxs($e,{variant:"outline",className:"border-primary/30 bg-primary/10 text-primary",children:[e.jsx(ji,{className:"mr-1 h-3 w-3"})," Commercial"]}),(t==null?void 0:t.deal_type)&&e.jsx($e,{variant:"secondary",children:AL[t.deal_type]}),(t==null?void 0:t.commercial_type)&&e.jsx($e,{variant:"secondary",children:i6[t.commercial_type]}),(t==null?void 0:t.is_confidential)&&e.jsxs($e,{variant:"outline",children:[e.jsx(pc,{className:"mr-1 h-3 w-3"})," Confidential"]})]}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight md:text-3xl",children:rL(s,t)}),e.jsxs("p",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(ci,{className:"h-4 w-4"})," ",qae(s,t)]}),e.jsx("p",{className:"mt-2 text-2xl font-semibold",children:kG(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(Fr,{className:"mr-2 h-4 w-4"})," View microsite"]}),s.allow_sharing&&e.jsxs($,{onClick:()=>i(!0),children:[e.jsx(Fd,{className:"mr-2 h-4 w-4"})," Share link"]})]})]}),e.jsx("div",{className:"mt-6",children:e.jsx(F7t,{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(Ie,{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(Ie,{className:"space-y-2",children:u.map((y,v)=>e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(Nn,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),e.jsx("span",{children:y})]},v))})]}),h.length>0&&e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-base",children:"Available spaces"})}),e.jsx(Ie,{className:"space-y-2 text-sm",children:h.map((y,v)=>e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 border-b pb-2 last:border-0",children:[e.jsx("span",{className:"font-medium",children:y.suite||`Space ${v+1}`}),e.jsx("span",{className:"text-muted-foreground",children:[yE(y.sf),y.rate,y.use,y.availability].filter(Boolean).join(" · ")})]},v))})]}),m.length>0&&e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-base",children:"Tenant roster"})}),e.jsx(Ie,{className:"space-y-2 text-sm",children:m.map((y,v)=>e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 border-b pb-2 last:border-0",children:[e.jsx("span",{className:"font-medium",children:y.name||`Tenant ${v+1}`}),e.jsx("span",{className:"text-muted-foreground",children:[yE(y.sf),y.rent,y.lease_expiry].filter(Boolean).join(" · ")})]},v))})]})]}),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(Ie,{className:"space-y-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:(f==null?void 0:f.name)||"LevelUp Member"}),((x=f==null?void 0:f.brokerage)==null?void 0:x.name)&&e.jsx("p",{className:"text-muted-foreground",children:f.brokerage.name})]}),(f==null?void 0:f.email)&&e.jsxs($,{variant:"outline",className:"w-full",onClick:()=>window.open(`mailto:${f.email}`),children:[e.jsx(mn,{className:"mr-2 h-4 w-4"})," Email agent"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Only the listing agent can update this listing."})]})]}),s.open_to_referrals&&e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-base",children:"Open to referrals"})}),e.jsx(Ie,{className:"text-sm text-muted-foreground",children:"The listing agent welcomes buyer or tenant referrals on this opportunity."})]})]})]})]}),e.jsx(y6e,{open:a,onOpenChange:i,listingId:s.id,listingSlug:s.slug??null,listingTitle:rL(s,t),isCommercial:!0})]})}function hGs(){const{listingId:s=""}=Wi(),t=Xn(),{user:n}=bs(),[r,a]=gc(),{data:i,isLoading:l}=Zae(s),{data:o}=P7t(s),{data:c=[]}=i6e(s),{data:d=[]}=Ytt(s),{data:u=[]}=Ztt(s),h=I7t(),m=R7t(),f=gDs(),g=L$t(),x=R$t(),y=D$t(),v=F$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 mDs(o,{photoCount:((J=i==null?void 0:i.photos)==null?void 0:J.length)??0,hasOm:c.some(ce=>ce.doc_kind==="om"),isPublic:!!(i!=null&&i.is_public)})},[o,i,c]),Y=async J=>{var ce;if(!(!J||!i)){w(!0);try{for(const _e of Array.from(J)){const he=_e.name.split(".").pop(),ue=`${n==null?void 0:n.id}/${i.id}/${Date.now()}-${Math.random().toString(36).slice(2)}.${he}`,{error:ve}=await q.storage.from("listing-photos").upload(ue,_e);if(ve)throw ve;const{data:{publicUrl:Ee}}=q.storage.from("listing-photos").getPublicUrl(ue);await g.mutateAsync({listingId:i.id,photoUrl:Ee,isPrimary:!((ce=i.photos)!=null&&ce.length)})}re.success("Photos uploaded")}catch(_e){re.error(_e.message||"Upload failed")}finally{w(!1)}}};if(l)return e.jsx(Vs,{title:"Commercial Launch",children:e.jsx("div",{className:"flex min-h-[50vh] items-center justify-center",children:e.jsx(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=l7e.findIndex(J=>J.key===ae),ne=rL(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(ji,{className:"mr-1 h-3 w-3"})," Commercial Launch"]}),(o==null?void 0:o.deal_type)&&e.jsx($e,{variant:"secondary",children:AL[o.deal_type]}),(o==null?void 0:o.commercial_type)&&e.jsx($e,{variant:"secondary",children:i6[o.commercial_type]}),X&&e.jsxs($e,{className:"bg-amber-500/15 text-amber-600 hover:bg-amber-500/15",children:[e.jsx(nh,{className:"mr-1 h-3 w-3"})," Pitch — private"]}),(o==null?void 0:o.is_confidential)&&e.jsxs($e,{variant:"outline",children:[e.jsx(pc,{className:"mr-1 h-3 w-3"})," Confidential"]})]}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight md:text-3xl",children:ne}),e.jsx("p",{className:"text-muted-foreground",children:qae(i,o)}),e.jsx("p",{className:"mt-2 text-xl font-semibold",children:kG(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(pc,{className:"mr-1 h-3 w-3"})," View only — listing agent controls updates"]}),te&&e.jsxs($,{variant:"outline",onClick:()=>t(`/mission-control/listings/${i.id}/commercial/edit`),children:[e.jsx(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(Fr,{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(Fr,{className:"mr-2 h-4 w-4"})," View microsite"]})]})]}),!X&&e.jsx("div",{className:"mt-6 flex flex-wrap items-center gap-2",children:l7e.filter(J=>J.key!=="pitch").map((J,ce)=>{const _e=l7e.findIndex(ve=>ve.key===J.key),he=_e===le,ue=_ete&&m.mutate({listingId:i.id,stage:J.key}),className:`flex items-center gap-2 rounded-full border px-3.5 py-1.5 text-xs font-medium transition-colors ${he?"border-primary bg-primary text-primary-foreground":ue?"border-primary/30 bg-primary/10 text-primary":"text-muted-foreground hover:bg-muted"} ${te?"":"cursor-default"}`,children:[ue&&e.jsx(ca,{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(aGs,{listing:i,canEdit:te}):e.jsxs(ha,{value:te||["overview","marketing"].includes(U)?U:"overview",onValueChange:W,children:[e.jsxs(ma,{className:"mb-6 flex w-full flex-wrap justify-start",children:[e.jsx(Zt,{value:"overview",children:"Overview"}),e.jsx(Zt,{value:"marketing",children:"Marketing"}),te&&e.jsx(Zt,{value:"investors",children:"Investors & Leads"}),te&&e.jsx(Zt,{value:"reporting",children:"Reporting"}),te&&e.jsx(Zt,{value:"documents",children:"Documents"}),te&&e.jsx(Zt,{value:"settings",children:"Settings"})]}),e.jsxs(Xt,{value:"overview",className:"space-y-6",children:[e.jsx(F7t,{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(Gn,{children:"Everything an institutional-quality launch needs."})]}),e.jsxs("span",{className:"text-2xl font-semibold tabular-nums",children:[G.score,"%"]})]}),e.jsx(Yi,{value:G.score,className:"mt-3"})]}),e.jsx(Ie,{className:"space-y-2",children:Z4e.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(ca,{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(Ie,{className:"grid gap-2",children:[e.jsxs($,{variant:"outline",className:"justify-start",onClick:()=>A(!0),children:[e.jsx(Fd,{className:"mr-2 h-4 w-4"})," Share link"]}),e.jsxs($,{variant:"outline",className:"justify-start",onClick:()=>I(!0),children:[e.jsx(Jp,{className:"mr-2 h-4 w-4"})," Signage QR code"]}),te&&e.jsxs($,{variant:"outline",className:"justify-start",onClick:()=>R(!0),children:[e.jsx(mn,{className:"mr-2 h-4 w-4"})," Email brokers & investors"]}),te&&e.jsxs($,{variant:"outline",className:"justify-start",onClick:()=>O(!0),children:[e.jsx(Nn,{className:"mr-2 h-4 w-4"})," Generate social post"]}),te&&e.jsxs($,{variant:"outline",className:"justify-start",onClick:()=>W("documents"),children:[e.jsx(pc,{className:"mr-2 h-4 w-4"})," Manage gated OM"]})]})]}),(o==null?void 0:o.call_for_offers_at)&&e.jsxs(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(Ie,{children:e.jsxs("p",{className:"flex items-center gap-2 text-lg font-semibold",children:[e.jsx(Cu,{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(Ie,{className:"space-y-2",children:[d.slice(0,6).map(J=>e.jsxs("div",{className:"flex items-center justify-between gap-2 text-sm",children:[e.jsx("span",{className:"truncate capitalize",children:J.event_type.replace(/_/g," ")}),e.jsx("span",{className:"shrink-0 text-xs text-muted-foreground",children:new Date(J.created_at).toLocaleDateString(void 0,{month:"short",day:"numeric"})})]},J.id)),d.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No activity yet."}),e.jsxs("p",{className:"pt-2 text-xs text-muted-foreground",children:[u.length," inquiries captured"]})]})]})]})]})]}),e.jsxs(Xt,{value:"marketing",className:"space-y-6",children:[e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{className:"text-base",children:"Photography"}),e.jsx(Gn,{children:"The first image becomes the cinematic microsite hero."})]}),e.jsx(Ie,{children:te?e.jsx(uUt,{photos:i.photos??[],uploading:b,onUpload:Y,onRemove:J=>x.mutate({photoId:J,listingId:i.id}),onReorder:J=>y.mutate({photos:J.map(ce=>({id:ce.id,sort_order:ce.sort_order,is_primary:ce.is_primary}))}),onSetPrimary:J=>v.mutate({photoId:J,listingId:i.id})}):e.jsxs("div",{className:"grid grid-cols-2 gap-3 md:grid-cols-4",children:[(i.photos??[]).map(J=>e.jsx("img",{src:J.photo_url,alt:ne,className:"aspect-[4/3] w-full rounded-lg object-cover",loading:"lazy"},J.id)),!(i.photos??[]).length&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No photos yet."})]})})]}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-4",children:[{icon:dl,title:"Property microsite",body:"Institutional-grade public page with gated OM.",action:()=>window.open(V,"_blank"),cta:"Preview"},{icon:Jp,title:"Signage QR",body:"On-site sign that routes to the microsite.",action:()=>I(!0),cta:"Create"},...te?[{icon:mn,title:"Broker & investor email",body:"Send to targeted segments of your database.",action:()=>R(!0),cta:"Compose"},{icon:Nn,title:"Social & LinkedIn",body:"Branded launch graphics and copy.",action:()=>O(!0),cta:"Generate"}]:[]].map(J=>e.jsxs(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(Gn,{className:"text-xs",children:J.body})]}),e.jsx(Ie,{className:"mt-auto",children:e.jsx($,{size:"sm",variant:"outline",className:"w-full",onClick:J.action,children:J.cta})})]},J.title))})]}),te&&e.jsx(Xt,{value:"investors",children:e.jsx(lGs,{listingId:i.id})}),te&&e.jsx(Xt,{value:"reporting",children:e.jsx(dGs,{listing:i})}),te&&e.jsx(Xt,{value:"documents",children:e.jsx(iGs,{listingId:i.id})}),te&&e.jsx(Xt,{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(Gn,{children:"Control who can see this offering."})]}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Publish public microsite"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Makes the commercial microsite live at a shareable URL."})]}),e.jsx(Sn,{checked:!!i.is_public,onCheckedChange:J=>{f.mutate({listingId:i.id,values:{is_public:J,allow_sharing:J?!0:i.allow_sharing}}),J&&ae==="won"&&m.mutate({listingId:i.id,stage:"launched"})}})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Share inside my brokerage"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Visible to agents in your brokerage on the Exchange."})]}),e.jsx(Sn,{checked:!!i.share_with_brokerage,onCheckedChange:J=>f.mutate({listingId:i.id,values:{share_with_brokerage:J}})})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Confidential offering"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Teaser mode, address hidden, search engines blocked."})]}),e.jsx(Sn,{checked:!!(o!=null&&o.is_confidential),onCheckedChange:J=>h.mutate({listingId:i.id,values:{is_confidential:J}})})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Hide street address"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show city / submarket only."})]}),e.jsx(Sn,{checked:!!(o!=null&&o.hide_address),onCheckedChange:J=>h.mutate({listingId:i.id,values:{hide_address:J}})})]}),V&&e.jsxs("div",{className:"flex items-center gap-2 rounded-lg border bg-muted/40 px-3 py-2",children:[e.jsx("span",{className:"truncate text-xs text-muted-foreground",children:V}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>{navigator.clipboard.writeText(V),re.success("Copied")},children:e.jsx(Ha,{className:"h-3.5 w-3.5"})})]})]})]})})]})}),e.jsx(y6e,{open:S,onOpenChange:A,listingId:i.id,listingSlug:i.slug,listingTitle:ne,isCommercial:!0}),e.jsx(NUt,{open:E,onOpenChange:I,url:V,title:ne,fileBase:i.slug||i.id}),e.jsx(DUt,{open:P,onOpenChange:R,listing:i}),e.jsx(tnt,{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(uGs,{listing:i,details:o,publicUrl:V})}function mGs(){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:y}=await q.functions.invoke("commercial-pitch-preview",{body:{token:s}});if(y)throw y;if(x!=null&&x.error)throw new Error(x.error);return x},enabled:!!s});if(n)return e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-[#0b0f14]",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-2 border-white/20 border-t-white/70"})});if(r||!(t!=null&&t.listing))return e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-[#0b0f14] px-6 text-center text-white/60",children:"This preview link is no longer active."});const{listing:a,details:i,pitch:l}=t,o=a.agent,c=(f=(m=a.photos)==null?void 0:m[0])==null?void 0:f.photo_url,d=Xtt(i).slice(0,4),u=l.launch_plan??[],h=[{icon:dl,label:"Dedicated property microsite",detail:"An institutional-grade page built for this asset alone."},{icon:Jr,label:"Offering Memorandum & teaser",detail:"Gated, tracked and released only to qualified prospects."},{icon:mn,label:"Targeted broker & investor email",detail:"Direct outreach to buyers, brokers and 1031 capital."},{icon:Jp,label:"Signage, QR & social distribution",detail:"On-site and digital presence working together."},{icon: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 — ",rL(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:rL(a,i)}),e.jsxs("p",{className:"mt-4 flex items-center gap-2 text-sm uppercase tracking-[0.2em] text-white/55",children:[e.jsx(ci,{className:"h-4 w-4"})," ",qae(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:AL[(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:i6[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:kG(i,a.price)})]})]})]}),u.length>0&&e.jsx("section",{className:"border-t border-white/10",children:e.jsxs("div",{className:"mx-auto max-w-6xl px-6 py-20 md:px-10",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.24em] text-white/40",children:"The plan"}),e.jsx("h2",{className:"mt-3 font-serif text-3xl md:text-4xl",children:"What happens the day you hire us"}),e.jsx("div",{className:"mt-12 space-y-8",children:u.map((x,y)=>e.jsxs("div",{className:"flex gap-6 border-t border-white/10 pt-6",children:[e.jsx("span",{className:"font-serif text-2xl text-white/25 tabular-nums",children:String(y+1).padStart(2,"0")}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-medium",children:x.label}),x.detail&&e.jsx("p",{className:"mt-1.5 text-white/60",children:x.detail})]})]},y))})]})}),e.jsx("section",{className:"border-t border-white/10",children:e.jsxs("div",{className:"mx-auto max-w-6xl px-6 py-20 md:px-10",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.24em] text-white/40",children:"Distribution"}),e.jsx("h2",{className:"mt-3 font-serif text-3xl md:text-4xl",children:"Where your property shows up"}),e.jsx("div",{className:"mt-12 grid gap-4 md:grid-cols-3",children:h.map(x=>e.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/[0.03] p-7",children:[e.jsx(x.icon,{className:"mb-4 h-5 w-5 text-white/70"}),e.jsx("p",{className:"font-medium",children:x.label}),e.jsx("p",{className:"mt-1.5 text-sm text-white/55",children:x.detail})]},x.label))})]})}),o&&e.jsx("section",{className:"border-t border-white/10 bg-white/[0.02]",children:e.jsxs("div",{className:"mx-auto flex max-w-6xl flex-col items-start gap-6 px-6 py-16 md:flex-row md:items-center md:justify-between md:px-10",children:[e.jsxs("div",{className:"flex items-center gap-5",children:[o.avatar_url&&e.jsx("img",{src:o.avatar_url,alt:o.name,className:"h-20 w-20 rounded-full object-cover ring-1 ring-white/15"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-[0.22em] text-white/40",children:"Prepared by"}),e.jsx("p",{className:"mt-2 font-serif text-2xl",children:o.name}),e.jsx("p",{className:"text-sm text-white/55",children:((g=o.brokerage)==null?void 0:g.name)||o.brokerage_name})]})]}),e.jsxs("div",{className:"flex gap-3 text-sm text-white/70",children:[o.email&&e.jsx("a",{className:"rounded-full border border-white/20 px-5 py-2 hover:bg-white/10",href:`mailto:${o.email}`,children:"Email"}),o.phone&&e.jsx("a",{className:"rounded-full border border-white/20 px-5 py-2 hover:bg-white/10",href:`tel:${o.phone}`,children:"Call"})]})]})}),e.jsx("footer",{className:"py-10 text-center text-xs text-white/35",children:"Confidential — prepared exclusively for the property owner."})]})}const fGs={office_exclusive:"Office Exclusive",coming_soon:"Coming Soon",pre_market:"Pre-Market",active:"Active"},pGs=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s||0);function gGs(){var J;const[s]=gc(),t=s.get("r"),n=s.get("m"),[r,a]=j.useState(null),[i,l]=j.useState(null),[o,c]=j.useState(!0),[d,u]=j.useState(0),[h,m]=j.useState(!1),[f,g]=j.useState(""),[x,y]=j.useState(""),[v,b]=j.useState(""),[w,S]=j.useState(""),[A,E]=j.useState("tour"),[I,P]=j.useState(!1),[R,D]=j.useState(!1),O=async()=>{if(!f.trim()||!x.trim()){re.error("Please enter your name and email");return}P(!0);try{const _e=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/private-listing-lead",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({r:t,m:n,name:f.trim(),email:x.trim(),phone:v.trim()||null,message:w.trim()||null,intent:A})}),he=await _e.json();if(!_e.ok||!(he!=null&&he.success))throw new Error((he==null?void 0:he.error)||"Could not send");D(!0),re.success("Sent! The agent will be in touch shortly.")}catch(ce){re.error((ce==null?void 0:ce.message)||"Could not send")}finally{P(!1)}};if(j.useEffect(()=>{if(!t||!n){l("Invalid link"),c(!1);return}const ce=`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/private-listing-view?r=${encodeURIComponent(t)}&m=${encodeURIComponent(n)}`;fetch(ce).then(_e=>_e.json()).then(_e=>{_e.error?l("This private listing link is no longer valid."):a({listing:_e.listing,agent:_e.agent})}).catch(()=>l("Unable to load listing.")).finally(()=>c(!1))},[t,n]),o)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-slate-50",children:e.jsx("div",{className:"text-slate-500",children:"Loading…"})});if(i||!r)return e.jsxs(e.Fragment,{children:[e.jsx(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(pc,{className:"h-10 w-10 text-slate-400 mx-auto mb-3"}),e.jsx("h1",{className:"text-xl font-semibold text-slate-900",children:"Private listing unavailable"}),e.jsx("p",{className:"text-slate-600 mt-2",children:i||"This link has expired or was not shared with you."})]})})]});const{listing:U,agent:W}=r,V=(J=U.photos)!=null&&J.length?U.photos:[],G=V[0],Y=fGs[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}`),ne=encodeURIComponent(`Hi ${X}, I'd love to learn more about ${U.address}, ${U.city}. Thanks!`),te=W!=null&&W.booking_slug?`https://dashboard.relevelup.com/book/${W.booking_slug}`:null;return e.jsxs(e.Fragment,{children:[e.jsxs(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(pc,{className:"h-3.5 w-3.5"}),e.jsxs("span",{className:"font-medium tracking-wide uppercase",children:["Private listing · Shared by ",X]})]}),e.jsxs("div",{className:"relative",children:[G?e.jsx("button",{type:"button",className:"block w-full",onClick:()=>{u(0),m(!0)},children:e.jsx("img",{src:G,alt:U.address,className:"w-full h-[42vh] md:h-[60vh] object-cover"})}):e.jsx("div",{className:"w-full h-[42vh] md:h-[60vh] bg-slate-200 flex items-center justify-center text-slate-400",children:"No photos available"}),e.jsx("div",{className:"absolute top-4 left-4",children:e.jsx($e,{className:"bg-indigo-600 text-white border-0 text-xs px-2.5 py-1 shadow",children:Y})}),V.length>1&&e.jsxs("div",{className:"absolute bottom-4 right-4 bg-black/60 text-white text-xs px-2.5 py-1 rounded-full",children:[V.length," photos"]})]}),e.jsxs("div",{className:"max-w-5xl mx-auto px-4 sm:px-6 -mt-10 relative z-10",children:[e.jsx(je,{className:"shadow-xl border-slate-200",children:e.jsxs(Ie,{className:"p-6 sm:p-8",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl sm:text-3xl font-bold text-slate-900",children:U.address}),e.jsxs("p",{className:"text-slate-600 mt-1 flex items-center gap-1.5",children:[e.jsx(ci,{className:"h-4 w-4"}),U.city,", ",U.state," ",U.zip]})]}),e.jsx("div",{className:"text-right",children:e.jsx("p",{className:"text-3xl sm:text-4xl font-bold text-indigo-600",children:pGs(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(r2,{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(A0,{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(j_,{className:"h-5 w-5 mx-auto text-slate-500 mb-1"}),e.jsx("p",{className:"text-lg font-semibold text-slate-900",children:U.sqft.toLocaleString()}),e.jsx("p",{className:"text-xs text-slate-500",children:"Sq Ft"})]}):null]}),U.description&&e.jsxs("div",{className:"mt-8",children:[e.jsx("h2",{className:"text-lg font-semibold text-slate-900 mb-2",children:"About this property"}),e.jsx("p",{className:"text-slate-700 leading-relaxed whitespace-pre-line",children:U.description})]}),V.length>1&&e.jsxs("div",{className:"mt-8",children:[e.jsx("h2",{className:"text-lg font-semibold text-slate-900 mb-3",children:"Photos"}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:V.slice(0,9).map((ce,_e)=>e.jsx("button",{type:"button",onClick:()=>{u(_e),m(!0)},className:"aspect-[4/3] overflow-hidden rounded-lg bg-slate-100",children:e.jsx("img",{src:ce,alt:"",className:"w-full h-full object-cover hover:scale-105 transition"})},_e))})]})]})}),e.jsxs(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(Ie,{className:"p-6 sm:p-8",children:R?e.jsxs("div",{className:"flex flex-col items-center text-center py-6",children:[e.jsx(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=>y(ce.target.value),placeholder:"you@email.com",maxLength:255})]})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"pl-phone",children:"Phone (optional)"}),e.jsx(pe,{id:"pl-phone",value:v,onChange:ce=>b(ce.target.value),placeholder:"(555) 555-5555",maxLength:40})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"pl-msg",children:"Message (optional)"}),e.jsx(Ls,{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(Ie,{className:"p-6 sm:p-8",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row items-center sm:items-start gap-5",children:[W!=null&&W.avatar_url?e.jsx("img",{src:W.avatar_url,alt:X,className:"h-20 w-20 rounded-full object-cover ring-2 ring-indigo-100"}):e.jsx("div",{className:"h-20 w-20 rounded-full bg-indigo-100 flex items-center justify-center text-indigo-600 text-2xl font-bold",children:X.charAt(0)}),e.jsxs("div",{className:"flex-1 text-center sm:text-left",children:[e.jsx("p",{className:"text-xs uppercase tracking-wider text-slate-500",children:"Shared by"}),e.jsx("h3",{className:"text-xl font-bold text-slate-900",children:X}),(W==null?void 0:W.brokerage_name)&&e.jsx("p",{className:"text-slate-600 text-sm",children:W.brokerage_name}),e.jsx("p",{className:"text-slate-600 text-sm mt-2",children:"Want a private tour or more info? Reach out — I'm happy to help."})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-2 mt-6",children:[ae&&e.jsx($,{asChild:!0,className:"bg-indigo-600 hover:bg-indigo-700",children:e.jsxs("a",{href:`mailto:${ae}?subject=${le}&body=${ne}`,children:[e.jsx(mn,{className:"h-4 w-4 mr-1.5"}),"Email"]})}),(W==null?void 0:W.phone)&&e.jsx($,{asChild:!0,variant:"outline",children:e.jsxs("a",{href:`tel:${W.phone}`,children:[e.jsx(Da,{className:"h-4 w-4 mr-1.5"}),W.phone]})}),te&&e.jsx($,{asChild:!0,variant:"outline",children:e.jsxs("a",{href:te,target:"_blank",rel:"noreferrer",children:[e.jsx(Cu,{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(pr,{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 xGs(){var i;const{slug:s}=Wi(),{data:t,isLoading:n,error:r}=$7t(s);if(j.useEffect(()=>(document.body.classList.add("agent-card-page"),()=>{document.body.classList.remove("agent-card-page")}),[]),j.useEffect(()=>{t!=null&&t.id&&ju(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(Jtt,{card:t})]})}const yGs="https://images.unsplash.com/photo-1507525428034-b723cf961d3e?w=1600&q=80",vGs="https://images.unsplash.com/photo-1616486338812-3dadae4b4ace?w=1600&q=80",bGs="https://images.unsplash.com/photo-1500534314209-a25ddb2bd429?w=1600&q=80",_Gs="https://images.unsplash.com/photo-1600585154340-be6161a56a0c?w=1600&q=80",wGs="https://images.unsplash.com/photo-1519741497674-611481863552?w=1600&q=80",jGs="https://images.unsplash.com/photo-1494526585095-c41746248156?w=1600&q=80",c3e={"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:jGs},"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:yGs},"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:vGs},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:bGs},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:_Gs},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:wGs}},NGs=["#111111","#2f7a7d","#c9a84c","#d84a7a","#3b6fa0","#9b72cf","#e85d3a","#4a6741"];function FUt(s){return s&&s in c3e?c3e[s]:c3e["minimal-mono"]}function kGs(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 OUt({slugOverride:s}={}){var ks;const{slug:t}=Wi(),n=s||t,[r]=gc(),a=r.get("t"),[i,l]=j.useState(!0),[o,c]=j.useState(null),[d,u]=j.useState(null),h=j.useRef(null),m=j.useRef(null),[f,g]=j.useState(null),[x,y]=j.useState(null),[v,b]=j.useState(!1),[w,S]=j.useState(!1),[A,E]=j.useState(0),[I,P]=j.useState(!1),[R,D]=j.useState(""),[O,U]=j.useState(""),[W,V]=j.useState(""),[G,Y]=j.useState(""),[X,ae]=j.useState(""),[le,ne]=j.useState(""),[te,J]=j.useState(""),[ce,_e]=j.useState(""),[he,ue]=j.useState(""),[ve,Ee]=j.useState(""),[Se,Le]=j.useState(""),[Fe,ke]=j.useState(""),[Be,Ne]=j.useState(""),[Ae,Ce]=j.useState([]),[Ve,ze]=j.useState([]),[qe,dt]=j.useState(""),[Xe,at]=j.useState(""),[rt,Ke]=j.useState(""),[Je,pt]=j.useState([]);j.useEffect(()=>{gt()},[n,a]);const gt=async()=>{if(!n)return;l(!0);const{data:Is,error:Xs}=await q.from("contact_intake_pages").select("*").eq("slug",n).eq("is_active",!0).maybeSingle();if(Xs||!Is){P(!0),l(!1);return}u(Is),m.current=Is;const{data:ds}=await q.from("profiles").select("name, avatar_url, title, phone, email, brokerage_id").eq("id",Is.user_id).single();if(ds){let Ss;if(ds.brokerage_id){const{data:Ut}=await q.from("brokerages").select("name").eq("id",ds.brokerage_id).single();Ss=(Ut==null?void 0:Ut.name)||void 0}let yn=ds.avatar_url||null;if(!yn){const{data:Ut}=q.storage.from("avatars").getPublicUrl(`${Is.user_id}/avatar.jpg`);Ut!=null&&Ut.publicUrl&&(yn=`${Ut.publicUrl}?t=${Date.now()}`)}const Js={...ds,avatar_url:yn,brokerage_name:Ss};c(Js),h.current=Js}if(a)try{console.log("[ConnectPage] Resolving token:",a,"for page:",Is.id);const{data:Ss,error:yn}=await q.functions.invoke("process-intake-submissions",{body:{action:"resolve_token",token:a,page_id:Is.id}});if(console.log("[ConnectPage] Resolve result:",{resolved:Ss,resolveErr:yn}),!yn&&(Ss!=null&&Ss.contact_id)){y(Ss.contact_id);const Js=Ss.contact;Js&&(g(Js),D(Js.first_name||""),U(Js.last_name||""),V(Js.email||""),Y(Js.phone||""),ae(Js.address||""),ne(Js.city||""),J(Js.state||""),_e(Js.zip||""),ue(Js.birthday||""),Ee(Js.home_anniversary||""))}}catch(Ss){console.error("Failed to resolve token:",Ss)}l(!1)},ss=async()=>{var Is,Xs;if(!R.trim()){re.error("Please enter your first name");return}if(!n){re.error("Invalid page. Please refresh.");return}S(!0);try{let ds=(Is=m.current)==null?void 0:Is.id,Ss=(Xs=m.current)==null?void 0:Xs.user_id;if(!ds||!Ss){const{data:Ut}=await q.from("contact_intake_pages").select("id, user_id").eq("slug",n).eq("is_active",!0).maybeSingle();if(!Ut){re.error("This page is no longer active. Please contact the agent directly."),S(!1);return}ds=Ut.id,Ss=Ut.user_id}const yn={intake_page_id:ds,agent_user_id:Ss,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:he||null,home_anniversary:ve||null,real_estate_interest:Se||null,message:Fe.trim()||null,life_events:{spouse_name:Be.trim()||null,kids:Ae.filter(Ut=>Ut.name.trim()),pets:Ve.filter(Ut=>Ut.name.trim()),favorite_spots:qe.trim()||null,dream_neighborhood:Xe.trim()||null,wedding_anniversary:rt||null},referrals:Je.filter(Ut=>Ut.name.trim()&&Ut.contact.trim())},{error:Js}=await q.from("contact_intake_submissions").insert(yn);if(console.log("[ConnectPage] Insert result:",{error:Js}),Js)throw Js;a&&await q.from("contact_intake_tokens").update({used_at:new Date().toISOString()}).eq("token",a);try{const Ut=[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:Ss,contactName:Ut,contactEmail:W.trim()||null,contactPhone:G.trim()||null,slug:n})})}catch(Ut){console.warn("Connect page notification failed (non-blocking):",Ut)}b(!0)}catch(ds){console.error(ds),re.error("Something went wrong. Please try again.")}finally{S(!1)}};if(i)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 via-white to-blue-50",children:e.jsx(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(v)return e.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 via-white to-blue-50 p-4",children:[e.jsx(Dl,{children:e.jsxs("title",{children:["Thank You | ",o==null?void 0:o.name]})}),e.jsxs(Br.div,{initial:{opacity:0,scale:.9},animate:{opacity:1,scale:1},className:"max-w-md w-full text-center space-y-6 p-8",children:[e.jsx(Br.div,{initial:{scale:0},animate:{scale:1},transition:{type:"spring",delay:.2},className:"mx-auto w-20 h-20 rounded-full bg-emerald-100 flex items-center justify-center",children:e.jsx(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 Yt=!!a&&!!f,ts=(d==null?void 0:d.show_little_things)??!0,ys=[{title:Yt?"Confirm Your Info":"Let's Get Connected",fields:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"First Name *"}),e.jsx("input",{type:"text",value:R,onChange:Is=>D(Is.target.value),placeholder:"Jane",className:"connect-input",required:!0})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Last Name"}),e.jsx("input",{type:"text",value:O,onChange:Is=>U(Is.target.value),placeholder:"Smith",className:"connect-input"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Email"}),e.jsx("input",{type:"email",value:W,onChange:Is=>V(Is.target.value),placeholder:"jane@email.com",className:"connect-input"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Phone"}),e.jsx("input",{type:"tel",value:G,onChange:Is=>Y(Is.target.value),placeholder:"(555) 123-4567",className:"connect-input"})]})]})},{title:"A Little More About You",fields:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Street Address"}),e.jsx("input",{type:"text",value:X,onChange:Is=>ae(Is.target.value),placeholder:"123 Main St",className:"connect-input"})]}),e.jsxs("div",{className:"grid grid-cols-5 gap-3",children:[e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"City"}),e.jsx("input",{type:"text",value:le,onChange:Is=>ne(Is.target.value),placeholder:"Austin",className:"connect-input"})]}),e.jsxs("div",{className:"col-span-1",children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"State"}),e.jsx("input",{type:"text",value:te,onChange:Is=>J(Is.target.value),placeholder:"TX",maxLength:2,className:"connect-input"})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Zip"}),e.jsx("input",{type:"text",value:ce,onChange:Is=>_e(Is.target.value),placeholder:"78701",className:"connect-input"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Birthday"}),e.jsx("input",{type:"date",value:he,onChange:Is=>ue(Is.target.value),className:"connect-input"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Home Anniversary"}),e.jsx("input",{type:"date",value:ve,onChange:Is=>Ee(Is.target.value),className:"connect-input"})]})]})]})},...ts?[{title:"The Little Things",subtitle:"Optional — helps me remember what matters to you.",fields:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Spouse / partner's name"}),e.jsx("input",{type:"text",value:Be,onChange:Is=>Ne(Is.target.value),placeholder:"Alex",className:"connect-input"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Wedding anniversary"}),e.jsx("input",{type:"date",value:rt,onChange:Is=>Ke(Is.target.value),className:"connect-input"})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[e.jsx("label",{className:"block text-sm font-medium",style:{color:"var(--c-text-muted)"},children:"Kids"}),e.jsxs("button",{type:"button",onClick:()=>Ce(Is=>[...Is,{name:"",age:""}]),className:"text-xs inline-flex items-center gap-1",style:{color:"var(--c-accent)"},children:[e.jsx(dn,{className:"h-3 w-3"})," Add"]})]}),e.jsxs("div",{className:"space-y-2",children:[Ae.length===0&&e.jsx("p",{className:"text-xs",style:{color:"var(--c-text-muted)"},children:"None to add? Skip this."}),Ae.map((Is,Xs)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("input",{type:"text",value:Is.name,onChange:ds=>Ce(Ss=>Ss.map((yn,Js)=>Js===Xs?{...yn,name:ds.target.value}:yn)),placeholder:"Child's name",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),e.jsx("input",{type:"text",value:Is.age,onChange:ds=>Ce(Ss=>Ss.map((yn,Js)=>Js===Xs?{...yn,age:ds.target.value}:yn)),placeholder:"Age",className:"connect-input shrink-0",style:{width:"5rem"}}),e.jsx("button",{type:"button",onClick:()=>Ce(ds=>ds.filter((Ss,yn)=>yn!==Xs)),className:"p-2 rounded-md hover:bg-black/5 shrink-0","aria-label":"Remove",children:e.jsx(pr,{className:"h-3.5 w-3.5",style:{color:"var(--c-text-muted)"}})})]},Xs))]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[e.jsx("label",{className:"block text-sm font-medium",style:{color:"var(--c-text-muted)"},children:"Pets"}),e.jsxs("button",{type:"button",onClick:()=>ze(Is=>[...Is,{name:"",kind:""}]),className:"text-xs inline-flex items-center gap-1",style:{color:"var(--c-accent)"},children:[e.jsx(dn,{className:"h-3 w-3"})," Add"]})]}),e.jsxs("div",{className:"space-y-2",children:[Ve.length===0&&e.jsx("p",{className:"text-xs",style:{color:"var(--c-text-muted)"},children:"None to add? Skip this."}),Ve.map((Is,Xs)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("input",{type:"text",value:Is.name,onChange:ds=>ze(Ss=>Ss.map((yn,Js)=>Js===Xs?{...yn,name:ds.target.value}:yn)),placeholder:"Pet's name",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),e.jsx("input",{type:"text",value:Is.kind,onChange:ds=>ze(Ss=>Ss.map((yn,Js)=>Js===Xs?{...yn,kind:ds.target.value}:yn)),placeholder:"Dog, cat…",className:"connect-input shrink-0",style:{width:"7rem"}}),e.jsx("button",{type:"button",onClick:()=>ze(ds=>ds.filter((Ss,yn)=>yn!==Xs)),className:"p-2 rounded-md hover:bg-black/5 shrink-0","aria-label":"Remove",children:e.jsx(pr,{className:"h-3.5 w-3.5",style:{color:"var(--c-text-muted)"}})})]},Xs))]})]}),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:qe,onChange:Is=>dt(Is.target.value),placeholder:"That coffee shop on Main, Town Lake…",className:"connect-input"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Dream neighborhood"}),e.jsx("input",{type:"text",value:Xe,onChange:Is=>at(Is.target.value),placeholder:"Where you'd love to live someday",className:"connect-input"})]}),e.jsxs("div",{className:"rounded-xl p-4",style:{background:"color-mix(in srgb, var(--c-accent) 8%, transparent)"},children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",style:{color:"var(--c-text)"},children:"Know someone who'd love an agent like me?"}),e.jsx("p",{className:"text-xs",style:{color:"var(--c-text-muted)"},children:"Refer a friend — up to 3."})]}),Je.length<3&&e.jsxs("button",{type:"button",onClick:()=>pt(Is=>[...Is,{name:"",contact:""}]),className:"text-xs inline-flex items-center gap-1 px-2 py-1 rounded-md",style:{background:"var(--c-accent)",color:"var(--c-accent-text)"},children:[e.jsx(dn,{className:"h-3 w-3"})," Add"]})]}),e.jsx("div",{className:"space-y-2",children:Je.map((Is,Xs)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("input",{type:"text",value:Is.name,onChange:ds=>pt(Ss=>Ss.map((yn,Js)=>Js===Xs?{...yn,name:ds.target.value}:yn)),placeholder:"Their name",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),e.jsx("input",{type:"text",value:Is.contact,onChange:ds=>pt(Ss=>Ss.map((yn,Js)=>Js===Xs?{...yn,contact:ds.target.value}:yn)),placeholder:"Phone or email",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),e.jsx("button",{type:"button",onClick:()=>pt(ds=>ds.filter((Ss,yn)=>yn!==Xs)),className:"p-2 rounded-md hover:bg-black/5","aria-label":"Remove",children:e.jsx(pr,{className:"h-3.5 w-3.5",style:{color:"var(--c-text-muted)"}})})]},Xs))})]})]})}]:[],{title:"One Last Thing",fields:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-slate-600 mb-3",children:["Are you thinking about making a move anytime soon? ",e.jsx("span",{className:"text-slate-400 font-normal",children:"(totally optional)"})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3",children:[{value:"buying",label:"🏠 Buying",desc:"Looking for a home"},{value:"selling",label:"📋 Selling",desc:"Thinking of selling"},{value:"both",label:"🔄 Both",desc:"Buy & sell"},{value:"not_now",label:"😊 Not right now",desc:"Just staying connected"}].map(Is=>e.jsxs("button",{type:"button",onClick:()=>Le(Se===Is.value?"":Is.value),className:`p-3.5 rounded-xl border-2 text-left transition-all ${Se===Is.value?"border-blue-500 bg-blue-50 shadow-sm":"border-slate-200 bg-white hover:border-slate-300"}`,children:[e.jsx("span",{className:"block text-sm font-medium text-slate-800",children:Is.label}),e.jsx("span",{className:"block text-xs text-slate-500 mt-0.5",children:Is.desc})]},Is.value))})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:["Anything else you'd like to share? ",e.jsx("span",{className:"text-slate-400 font-normal",children:"(optional)"})]}),e.jsx("textarea",{value:Fe,onChange:Is=>ke(Is.target.value),placeholder:"Feel free to drop a note...",rows:3,className:"connect-input resize-none"})]})]})}],Bt=ys.length,Ft=FUt(d==null?void 0:d.theme),as=kGs(Ft,(d==null?void 0:d.accent_color)||null),kt=(d==null?void 0:d.cover_image_url)||Ft.defaultCover,Ks=(d==null?void 0:d.headline)||"Let's stay connected",wt=(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:as,children:[e.jsxs(Dl,{children:[e.jsxs("title",{children:["Connect with ",(o==null?void 0:o.name)||"Agent"]}),e.jsx("meta",{name:"description",content:`${Ks} — ${(o==null?void 0:o.name)||"your agent"}`}),kt&&e.jsx("meta",{property:"og:image",content:kt}),e.jsx("meta",{property:"og:title",content:`Connect with ${(o==null?void 0:o.name)||"me"}`}),e.jsx("meta",{property:"og:description",content:Ks}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"})]}),e.jsx("style",{children:` .connect-shell { font-family: var(--c-body-font); color: var(--c-text); } .connect-shell h1, .connect-shell h2 { font-family: var(--c-heading-font); } .connect-input { width: 100%; padding: 0.75rem 1rem; border-radius: 0.75rem; border: 1px solid var(--c-border); background: var(--c-surface); color: var(--c-text); font-family: var(--c-body-font); font-size: 0.95rem; transition: border-color 150ms, box-shadow 150ms; } .connect-input::placeholder { color: var(--c-text-muted); opacity: 0.7; } .connect-input:focus { outline: none; border-color: var(--c-accent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--c-accent) 25%, transparent); } `}),e.jsxs("div",{className:"relative w-full overflow-hidden",style:{height:"clamp(200px, 30vh, 320px)"},children:[e.jsx(Br.img,{src:kt,alt:"",initial:{scale:1.08},animate:{scale:1},transition:{duration:1.4,ease:"easeOut"},className:"absolute inset-0 w-full h-full object-cover"}),e.jsx("div",{className:"absolute inset-0",style:{background:"linear-gradient(180deg, rgba(0,0,0,0) 20%, rgba(0,0,0,0.55) 100%)"}}),e.jsxs("div",{className:"absolute inset-x-0 bottom-0 p-6 pb-16 text-center",children:[e.jsx(Br.h1,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{delay:.15,duration:.6},style:{color:"#fff",fontFamily:Ft.headingFont,fontWeight:500,letterSpacing:"-0.01em"},className:"text-3xl sm:text-4xl leading-tight",children:Ks}),wt&&e.jsx(Br.p,{initial:{opacity:0},animate:{opacity:.9},transition:{delay:.35,duration:.6},style:{color:"#fff"},className:"text-sm mt-2",children:wt})]})]}),e.jsxs("div",{className:"max-w-lg mx-auto px-4 pb-12 -mt-12 relative",children:[e.jsxs(Br.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{delay:.25},className:"text-center mb-6",children:[o!=null&&o.avatar_url?e.jsx("img",{src:o.avatar_url,alt:o.name,className:"w-24 h-24 rounded-full object-cover mx-auto shadow-xl",style:{border:"4px solid var(--c-surface)"}}):e.jsx("div",{className:"w-24 h-24 rounded-full mx-auto flex items-center justify-center shadow-xl",style:{background:Ft.accent,color:Ft.accentText,border:"4px solid var(--c-surface)"},children:e.jsx("span",{className:"text-3xl font-bold",children:((ks=o==null?void 0:o.name)==null?void 0:ks.charAt(0))||"?"})}),(o==null?void 0:o.title)&&e.jsx("p",{className:"text-sm mt-3",style:{color:"var(--c-text-muted)"},children:o.title}),((o==null?void 0:o.phone)||(o==null?void 0:o.email))&&e.jsxs("div",{className:"flex items-center justify-center gap-2 mt-3",children:[(o==null?void 0:o.phone)&&e.jsx("a",{href:`tel:${o.phone}`,className:"flex items-center justify-center w-10 h-10 rounded-full transition-opacity hover:opacity-80",style:{background:"color-mix(in srgb, var(--c-accent) 12%, transparent)",color:"var(--c-accent)"},"aria-label":"Call agent",children:e.jsx(Da,{className:"h-4 w-4"})}),(o==null?void 0:o.email)&&e.jsx("a",{href:`mailto:${o.email}`,className:"flex items-center justify-center w-10 h-10 rounded-full transition-opacity hover:opacity-80",style:{background:"color-mix(in srgb, var(--c-accent) 12%, transparent)",color:"var(--c-accent)"},"aria-label":"Email agent",children:e.jsx(mn,{className:"h-4 w-4"})})]})]}),e.jsx(Br.p,{initial:{opacity:0},animate:{opacity:1},transition:{delay:.35},className:"text-center mb-6 px-2 leading-relaxed text-sm",style:{color:"var(--c-text-muted)"},children:(d==null?void 0:d.welcome_message)||"I'd love to stay in touch — just a few quick details."}),e.jsx("div",{className:"flex gap-1.5 mb-6 px-2",children:Array.from({length:Bt}).map((Is,Xs)=>e.jsx("div",{className:"h-1 flex-1 rounded-full transition-all duration-500",style:{background:Xs<=A?"var(--c-accent)":"color-mix(in srgb, var(--c-text) 12%, transparent)"}},Xs))}),e.jsxs(Br.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{delay:.4},className:"rounded-2xl p-6 sm:p-8",style:{background:"var(--c-surface)",border:"1px solid var(--c-border)",boxShadow:gs?"0 20px 40px -20px rgba(0,0,0,0.5)":"0 20px 40px -20px rgba(0,0,0,0.15)"},children:[e.jsx(aK,{mode:"wait",children:e.jsxs(Br.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:-20},transition:{duration:.25},children:[e.jsxs("div",{className:"mb-6",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Nn,{className:"h-4 w-4",style:{color:"var(--c-accent)"}}),e.jsx("h2",{className:"text-lg font-semibold",style:{color:"var(--c-text)"},children:ys[A].title})]}),ys[A].subtitle&&e.jsx("p",{className:"text-xs mt-1 ml-6",style:{color:"var(--c-text-muted)"},children:ys[A].subtitle})]}),ys[A].fields]},A)}),e.jsxs("div",{className:"flex justify-between mt-8",children:[A>0?e.jsx("button",{type:"button",onClick:()=>E(Is=>Is-1),className:"px-5 py-2.5 text-sm font-medium transition-opacity hover:opacity-70",style:{color:"var(--c-text-muted)"},children:"Back"}):e.jsx("div",{}),A{if(A===0&&!R.trim()){re.error("Please enter your first name");return}E(Is=>Is+1)},className:"px-6 py-2.5 text-sm font-medium rounded-xl transition-transform hover:scale-[1.02] shadow-sm",style:{background:"var(--c-accent)",color:"var(--c-accent-text)"},children:"Continue"}):e.jsx("button",{type:"button",onClick:()=>ss(),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(Is=>Is+1),className:"text-xs transition-opacity hover:opacity-80",style:{color:"var(--c-text-muted)"},children:"Skip this step"})})]}),e.jsx("div",{className:"text-center mt-8",children:e.jsxs("div",{className:"flex items-center justify-center gap-1 text-xs",style:{color:"var(--c-text-muted)"},children:[e.jsx(Jo,{className:"h-3 w-3"}),e.jsx("span",{children:"Powered by ReLevelUp"})]})})]})]})}const hK=()=>({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 MZ({banners:s,autoPlayInterval:t=5e3,className:n}){const[r,a]=j.useState(0),[i,l]=j.useState(!1),{trackEngagement:o}=hK(),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 SGs=["reserved","scheduled_for_charge","paid","payment_failed","completed"],TG=s=>!!s&&(s.access_override||SGs.includes(s.status)),Sg=(s,t="usd")=>new Intl.NumberFormat("en-US",{style:"currency",currency:t.toUpperCase(),maximumFractionDigits:s%100===0?0:2}).format(s/100),ose=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`},UGe=(s,t="usd",n)=>`One-time payment: ${Sg(s,t)} for the ${ose(n)}`,snt=[{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}],lse=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:[]}},CGs=(s,t)=>!s.hidden.includes(t),mbt=(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,k6e=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||[]}}),nnt=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}}),BUt=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}}),rnt=()=>{const{user:s}=bs();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||[]}})},ant=s=>{const{data:t=[],...n}=rnt();return{...n,data:s&&t.find(r=>r.program_id===s)||null}},AGs=()=>{const{user:s}=bs(),t=Wt();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=>re.error(n.message||"Could not save your answers")})},$Ut=s=>{const{user:t}=bs();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}})},EGs=()=>{const s=Wt();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"]})}})},TGs=(s,t)=>{const{user:n}=bs(),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}}})},MGs=s=>{const{user:t}=bs(),n=Wt();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=>re.error(r.message||"Could not update progress")})},PGs=s=>{const{user:t}=bs(),n=Wt();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:()=>{re.success("Video logged — nice work"),n.invalidateQueries({queryKey:["program-workspace"]})},onError:r=>re.error(r.message||"Could not log the video")})},IGs=s=>{const{user:t}=bs(),n=Wt();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:()=>{re.success("Weekly check-in saved"),n.invalidateQueries({queryKey:["program-workspace"]})},onError:r=>re.error(r.message||"Could not save your check-in")})},LGs=s=>{const{user:t}=bs(),n=Wt();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=>re.error(r.message||"Could not update your RSVP")})},RGs=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||[]}}),DGs=s=>{const t=Wt();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:()=>{re.success("Discount code saved"),t.invalidateQueries({queryKey:["program-discount-codes"]})},onError:n=>{var r;return re.error((r=n.message)!=null&&r.includes("duplicate")?"That code already exists for this program":n.message||"Could not save the code")}})},FGs=()=>{const s=Wt();return mt({mutationFn:async t=>{const{error:n}=await q.from("program_discount_codes").delete().eq("id",t);if(n)throw n},onSuccess:()=>{re.success("Discount code deleted"),s.invalidateQueries({queryKey:["program-discount-codes"]})},onError:t=>re.error(t.message||"Could not delete the code")})},OGs=()=>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}}),zGs=()=>mt({mutationFn:async s=>{const{error:t}=await q.rpc("program_clear_discount",{_enrollment_id:s});if(t)throw t}}),BGs=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||[]}}),$Gs=s=>{const t=Wt();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:()=>{re.success("Session saved"),t.invalidateQueries({queryKey:["admin-program-events"]}),t.invalidateQueries({queryKey:["program-workspace"]})},onError:n=>re.error(n.message||"Could not save the session")})},UGs=()=>{const s=Wt();return mt({mutationFn:async t=>{const{error:n}=await q.from("program_events").delete().eq("id",t);if(n)throw n},onSuccess:()=>{re.success("Session removed"),s.invalidateQueries({queryKey:["admin-program-events"]}),s.invalidateQueries({queryKey:["program-workspace"]})},onError:t=>re.error(t.message||"Could not remove the session")})},qGs=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||[]}}}),VGs=s=>{const t=Wt();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:()=>{re.success("Video saved"),t.invalidateQueries({queryKey:["admin-program-lessons"]}),t.invalidateQueries({queryKey:["program-workspace"]})},onError:n=>re.error(n.message||"Could not save the video")})},HGs=()=>{const s=Wt();return mt({mutationFn:async t=>{const{error:n}=await q.from("program_lessons").delete().eq("id",t);if(n)throw n},onSuccess:()=>{re.success("Video removed"),s.invalidateQueries({queryKey:["admin-program-lessons"]}),s.invalidateQueries({queryKey:["program-workspace"]})},onError:t=>re.error(t.message||"Could not remove the video")})},UUt=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},jee=s=>!!s&&/\.(mp4|webm|mov|m4v)(\?|$)/i.test(s),qUt=[{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"}],mK="event-images",nie=s=>{if(s.file_path){const{data:t}=q.storage.from(mK).getPublicUrl(s.file_path);return t.publicUrl}return s.url||null},Nee=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(mK).download(s.file_path);if(r||!n){const c=nie(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)},VUt=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||[]}}),GGs=s=>{const t=Wt();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:()=>{re.success("Resource saved"),t.invalidateQueries({queryKey:["admin-program-resources"]}),t.invalidateQueries({queryKey:["program-workspace"]})},onError:n=>re.error(n.message||"Could not save the resource")})},WGs=()=>{const s=Wt();return mt({mutationFn:async t=>{t.file_path&&await q.storage.from(mK).remove([t.file_path]);const{error:n}=await q.from("program_resources").delete().eq("id",t.id);if(n)throw n},onSuccess:()=>{re.success("Resource removed"),s.invalidateQueries({queryKey:["admin-program-resources"]}),s.invalidateQueries({queryKey:["program-workspace"]})},onError:t=>re.error(t.message||"Could not remove the resource")})},KGs=(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||[]}}),YGs=(s,t)=>{const n=Wt(),{user:r}=bs();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:()=>{re.success("Personal resource saved"),n.invalidateQueries({queryKey:["admin-program-member-resources"]}),n.invalidateQueries({queryKey:["program-workspace"]})},onError:a=>re.error(a.message||"Could not save the resource")})},ZGs=()=>{const s=Wt();return mt({mutationFn:async t=>{t.file_path&&await q.storage.from(mK).remove([t.file_path]);const{error:n}=await q.from("program_member_resources").delete().eq("id",t.id);if(n)throw n},onSuccess:()=>{re.success("Personal resource removed"),s.invalidateQueries({queryKey:["admin-program-member-resources"]}),s.invalidateQueries({queryKey:["program-workspace"]})},onError:t=>re.error(t.message||"Could not remove the resource")})},XGs=s=>{const{user:t}=bs();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}})},QGs=s=>{const t=Wt(),{user:n}=bs();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=>{re.success(r?"You're on the list — we'll email you when enrollment opens.":"Removed from the notify list"),t.invalidateQueries({queryKey:["program-interest"]}),t.invalidateQueries({queryKey:["admin-program-interest"]})},onError:r=>re.error(r.message||"Could not update your notify preference")})},JGs=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}})}}),eWs=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)},tWs=()=>{const{data:s=[]}=zUt(),{data:t=[]}=rnt(),n=new Set(t.filter(TG).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=eWs(a.kickoff_at),l=i===null?null:i>1?`Kicks off in ${i} days`:i===1?"Kicks off tomorrow":i===0?"Kicks off today":"In progress";return e.jsxs("div",{className:"flex flex-col gap-4 rounded-2xl border border-primary/30 bg-gradient-to-r from-primary/12 via-primary/5 to-background p-5 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"flex h-12 w-12 shrink-0 items-center justify-center rounded-xl bg-primary/15",children:e.jsx(qg,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("h3",{className:"text-lg font-semibold leading-tight",children:a.name}),l&&e.jsx($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(wr,{to:`/programs/${a.slug}/workspace`,children:["Open program dashboard",e.jsx(Qa,{className:"ml-1.5 h-4 w-4"})]})})]},a.id)})})},sWs={url:"/exp-agent-advantage.webp"};function nWs({className:s}){const{isMember:t,program:n,packageName:r}=_C();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:sWs.url,alt:"eXp Agent Advantage — powered by LevelUp",className:"h-14 w-auto object-contain dark:invert dark:brightness-95 sm:h-16"})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center justify-center gap-2 sm:justify-start",children:[e.jsx(Nn,{className:"h-4 w-4 text-primary","aria-hidden":"true"}),e.jsx("span",{className:"text-xs font-semibold uppercase tracking-wider text-primary",children:"Partnership Benefit"})]}),e.jsx("h2",{className:"mt-1 text-lg font-semibold text-foreground sm:text-xl",children:"Welcome to your eXp Agent Advantage dashboard"}),e.jsxs("p",{className:"mt-1 max-w-2xl text-sm text-muted-foreground",children:["You are enrolled in the ",r||"eXp"," partnership. Everything below is included with your membership — coaching, tools, and resources built exclusively for eXp Luxury agents."]})]})]})]})}function rWs({className:s}){var E,I,P;const{user:t}=bs(),{isMember:n,program:r,pkg:a,packageName:i}=_C(),l=j.useMemo(()=>!n||!(a!=null&&a.includes_coaching)?!1:((r==null?void 0:r.name)||"").toLowerCase().includes("exp"),[n,a,r]),{data:o}=Ist(),c=o==null?void 0:o.id,{data:d=[]}=Lst(c),{data:u=[]}=Rst(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,y=d.filter(R=>R.status!=="cancelled"&&new Date(R.scheduled_at).getTime()>Date.now()).sort((R,D)=>new Date(R.scheduled_at).getTime()-new Date(D.scheduled_at).getTime())[0],v=u.filter(R=>R.status!=="done"),b=u.length-v.length,w=(h==null?void 0:h.items)||[],S=w.filter(R=>R.done).length,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(Nn,{className:"h-4 w-4","aria-hidden":"true"}),e.jsx("span",{className:"text-xs font-semibold uppercase tracking-[0.18em]",children:i?`${i} Coaching`:"Included Coaching"})]}),e.jsx("h2",{className:"mt-1 text-2xl font-bold leading-tight",children:m}),e.jsx("p",{className:"mt-1 max-w-xl text-sm text-white/80",children:g||"1:1 accountability coaching included with your eXp Agent Advantage membership."})]}),e.jsxs("div",{className:"flex flex-col gap-2 md:items-end",children:[e.jsx($,{asChild:!0,className:"bg-white text-[#2a4c64] hover:bg-white/90",children:e.jsxs(wr,{to:"/my-coach",children:[e.jsx(bv,{className:"mr-2 h-4 w-4"})," Book a session"]})}),e.jsx($,{asChild:!0,variant:"outline",className:"border-white/40 bg-white/10 text-white hover:bg-white/20 hover:text-white",children:e.jsxs(wr,{to:"/my-coach",children:[e.jsx(eo,{className:"mr-2 h-4 w-4"})," Message coach"]})})]})]})]}),e.jsxs("div",{className:"grid gap-4 p-5 md:grid-cols-3",children:[e.jsxs("div",{className:"rounded-xl border border-border/60 bg-muted/30 p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:[e.jsx(ua,{className:"h-3.5 w-3.5"})," Next session"]}),y?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"mt-2 text-lg font-semibold text-foreground",children:en(new Date(y.scheduled_at),"EEE, MMM d")}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[en(new Date(y.scheduled_at),"h:mm a"),y.title?` · ${y.title}`:""]}),y.meeting_url&&e.jsx($,{asChild:!0,size:"sm",variant:"outline",className:"mt-3",children:e.jsx("a",{href:y.meeting_url,target:"_blank",rel:"noreferrer",children:"Join meeting"})})]}):e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"mt-2 text-sm text-muted-foreground",children:["Nothing on the calendar yet — grab a time with ",m.split(" ")[0],"."]}),e.jsx($,{asChild:!0,size:"sm",className:"mt-3",children:e.jsx(wr,{to:"/my-coach",children:"Schedule now"})})]})]}),e.jsxs("div",{className:"rounded-xl border border-border/60 bg-muted/30 p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:[e.jsx(Cv,{className:"h-3.5 w-3.5"})," Action items"]}),e.jsxs("div",{className:"mt-2 flex items-baseline gap-2",children:[e.jsx("span",{className:"text-2xl font-bold text-foreground",children:v.length}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"open"}),b>0&&e.jsxs($e,{variant:"secondary",className:"ml-auto",children:[b," done"]})]}),e.jsxs("ul",{className:"mt-2 space-y-1",children:[v.slice(0,3).map(R=>e.jsxs("li",{className:"flex items-start gap-2 text-sm text-muted-foreground",children:[e.jsx(Og,{className:"mt-1 h-3 w-3 shrink-0"}),e.jsx("span",{className:"line-clamp-1",children:R.title||R.description})]},R.id)),v.length===0&&e.jsx("li",{className:"text-sm text-muted-foreground",children:"You're all caught up."})]})]}),e.jsxs("div",{className:"rounded-xl border border-border/60 bg-muted/30 p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:[e.jsx(zg,{className:"h-3.5 w-3.5"})," Coaching prep"]}),h!=null&&h.submitted?w.length>0?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mt-2 flex items-center justify-between text-sm",children:[e.jsxs("span",{className:"font-semibold text-foreground",children:[S,"/",w.length," complete"]}),e.jsxs("span",{className:"text-muted-foreground",children:[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(Og,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground/50"}),e.jsx("span",{className:Pt("line-clamp-1",R.done?"text-muted-foreground line-through":"text-foreground"),children:R.title})]},R.id))})]}):e.jsxs("p",{className:"mt-2 flex items-start gap-2 text-sm text-muted-foreground",children:[e.jsx(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(wr,{to:"/coaching/onboarding",children:"Start questionnaire"})})]})]})]})]})}function aWs(s){return"EST"}function cse(s){const n=new Intl.DateTimeFormat("en-US",{hour:"numeric",minute:"2-digit",hour12:!0,timeZone:"America/New_York"}).format(s),r=aWs();return`${n} ${r}`}function c8(s){const t=new Date,n=new Date(s),r=Nyt(n,-15),a=Nyt(n,30);return t>a?"ended":IS(t,{start:n,end:a})?"live":IS(t,{start:r,end:n})?"starting_soon":"upcoming"}function int(s){const t=c8(s);return t==="starting_soon"||t==="live"}const iWs=int,oWs=({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=>int(f.event_date));if(i.length===0)return null;const l=i[0],o=c8(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(_b,{className:"h-4 w-4"}),"Live Now"]}):e.jsxs(e.Fragment,{children:[e.jsx(da,{className:"h-4 w-4"}),"Starting Soon"]})})]}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-semibold text-lg text-foreground line-clamp-1",children:l.title}),e.jsx("p",{className:"text-sm text-muted-foreground",children:h?`Started at ${cse(new Date(l.event_date))}`:`Starts at ${cse(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(Fr,{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}=bs(),{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 lWs(){var A;const{user:s}=bs(),{isGmailConnected:t,hasVerifiedSes:n,isLoading:r}=gy(),a=_C(),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)),Y=I.count||0,X=(P.count||0)>0,ae=R.count||0;return{profile:V,profileComplete:G,contactsCount:Y,contactsComplete:Y>=5,eventsRegistered:X,communityComplete:ae>0,nextOnboardingEvent:D.data||null,coachingBooked:W}}}),f=t||n,g=[{id:"profile",complete:!!(h!=null&&h.profileComplete)},{id:"email",complete:f},{id:"contacts",complete:!!(h!=null&&h.contactsComplete)},{id:"event",complete:!!(h!=null&&h.eventsRegistered)},{id:"community",complete:!!(h!=null&&h.communityComplete)}],x=l?g.filter(E=>E.id!=="community"&&E.id!=="event"):g;i&&x.push({id:"coaching",complete:!!(h!=null&&h.coachingBooked)});const y=x.filter(E=>E.complete).length,v=x.length;return{steps:x,completedCount:y,totalCount:v,allComplete:y===v,dismissed:o,dismiss:async()=>{s!=null&&s.id&&(c(!0),await q.from("onboarding_checklist_dismissed").insert({user_id:s.id}))},reopen:async()=>{s!=null&&s.id&&(c(!1),await q.from("onboarding_checklist_dismissed").delete().eq("user_id",s.id))},data:h,isGmailConnected:t,hasVerifiedSes:n,loading:m||r||!d||a.isLoading}}const cWs={profile:{title:"Complete Your Profile",description:"Add your headshot, phone, and short bio so contacts recognize you.",icon:sl,accent:"from-[#2a4c64] to-[#406E71]",cta:"Edit Profile"},email:{title:"Set Up Email Sending",description:"Connect Gmail (recommended) or verify a Mass Email sender to send from your address.",icon:mn,accent:"from-[#406E71] to-[#5b9ea1]",cta:"Connect Email"},contacts:{title:"Add Your First Contacts",description:"Import your database or add contacts one at a time to start building your Inner Circle.",icon: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:Ta,accent:"from-[#8b5cf6] to-[#a78bfa]",cta:"Register"},community:{title:"Say Hi in the Community",description:"Introduce yourself and connect with other LevelUp agents.",icon:eo,accent:"from-[#ec4899] to-[#f472b6]",cta:"Visit Community"},coaching:{title:"Schedule Your Coaching Session",description:"Book your first 1:1 session with your LevelUp coach.",icon:af,accent:"from-[#0ea5e9] to-[#38bdf8]",cta:"Book Session"}};function dWs(){var x,y;const s=Xn(),{user:t}=bs(),{steps:n,completedCount:r,totalCount:a,allComplete:i,dismissed:l,dismiss:o,data:c,loading:d}=lWs(),[u,h]=j.useState(!0);if(d||l||i)return null;const m=(((x=c==null?void 0:c.profile)==null?void 0:x.name)||((y=t==null?void 0:t.user_metadata)==null?void 0:y.name)||"there").split(" ")[0],f=r/a*100,g=async v=>{switch(v){case"profile":s("/profile");break;case"email":s("/mission-control/integrations");break;case"contacts":s("/mission-control/contacts");break;case"event":{const b=c==null?void 0:c.nextOnboardingEvent;if(!b){s("/events");return}if(!(t!=null&&t.id))return;const{error:w}=await q.from("event_registrations").insert({user_id:t.id,event_id:b.id});w&&!String(w.message).toLowerCase().includes("duplicate")?(re.error("Could not register — opening events page."),s("/events")):re.success(`You're registered for ${b.title}!`);break}case"community":s("/community");break;case"coaching":s("/my-coach");break}};return e.jsxs(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(pr,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"hidden sm:flex h-12 w-12 rounded-xl bg-white/15 backdrop-blur items-center justify-center shrink-0",children:e.jsx(Nn,{className:"h-6 w-6 text-[#f5f0e0]"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("h2",{className:"text-xl md:text-2xl font-bold",children:["Welcome to LevelUp, ",m,"! 👋"]}),e.jsx("p",{className:"text-white/80 mt-1 text-sm md:text-base",children:"Let's get you set up in under 10 minutes."}),e.jsxs("div",{className:"mt-4 max-w-md",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs mb-1.5 text-white/90",children:[e.jsxs("span",{className:"font-medium",children:[r," of ",a," complete"]}),e.jsxs("span",{children:[a-r," steps left"]})]}),e.jsx(Yi,{value:f,className:"h-2 bg-white/20 [&>div]:bg-[#f5f0e0]"})]}),e.jsxs("div",{className:"mt-5 flex flex-wrap items-center gap-3",children:[e.jsxs($,{onClick:()=>h(!0),className:"bg-[#f5f0e0] text-[#2a4c64] hover:bg-white font-semibold",children:["Continue Setup ",e.jsx(Qa,{className:"h-4 w-4 ml-1.5"})]}),e.jsx("button",{onClick:()=>h(v=>!v),className:"text-sm text-white/80 hover:text-white flex items-center gap-1",children:u?e.jsxs(e.Fragment,{children:["Hide steps ",e.jsx(yb,{className:"h-4 w-4"})]}):e.jsxs(e.Fragment,{children:["Show steps ",e.jsx(wl,{className:"h-4 w-4"})]})})]})]})]})]}),u&&e.jsx(Ie,{className:"p-4 md:p-6 bg-gradient-to-b from-background to-muted/30",children:e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:n.map(v=>{const b=cWs[v.id],w=b.icon;return e.jsx("div",{className:Pt("relative rounded-xl border p-4 transition-all group",v.complete?"bg-muted/40 border-muted":"bg-card hover:shadow-md hover:border-primary/40 cursor-pointer"),onClick:()=>!v.complete&&g(v.id),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:Pt("h-10 w-10 rounded-lg flex items-center justify-center shrink-0 bg-gradient-to-br text-white",v.complete?"from-emerald-500 to-emerald-600":b.accent),children:v.complete?e.jsx(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",v.complete&&"text-muted-foreground line-through"),children:b.title})}),e.jsx("p",{className:Pt("text-xs text-muted-foreground mt-1 leading-relaxed",v.complete&&"line-through"),children:b.description}),v.id==="event"&&!v.complete&&(c==null?void 0:c.nextOnboardingEvent)&&e.jsxs("div",{className:"mt-2 text-xs font-medium text-primary",children:[new Date(c.nextOnboardingEvent.event_date).toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZone:"America/New_York"})," ","ET"]}),!v.complete&&e.jsxs($,{size:"sm",variant:"ghost",className:"mt-2 h-7 px-2 -ml-2 text-primary hover:text-primary hover:bg-primary/10",onClick:S=>{S.stopPropagation(),g(v.id)},children:[b.cta," ",e.jsx(Qa,{className:"h-3 w-3 ml-1"})]})]}),v.complete&&e.jsx("span",{className:"text-xs font-medium text-emerald-600 shrink-0",children:"✓ Done"})]})},v.id)})})})]})}function uWs(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 hWs(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 mWs(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 fWs(s){const t=Wt();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 pWs(){const s=Wt();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 gWs(s){const t=Wt();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 xWs(){const s=Wt();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 yWs(s){const t=Wt();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 vWs={video:zu,pdf:Jr,link:Wd,event:Ta,graphic:yd},bWs={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 _Ws(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 wWs(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 jWs({item:s}){const t=Xn(),n=vWs[s.content_type]||Wd,r=bWs[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"?_Ws(s.url):null);j.useEffect(()=>{l||!s.url||s.content_type!=="video"||!wWs(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(Ie,{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:en(new Date(s.event_date),"MMM d · h:mm a")})]})]})}function NWs(){const{brokerageId:s}=bs(),t=Xn(),{data:n=[],isLoading:r}=mWs(s,4);return!s||r||n.length===0?null:e.jsxs("section",{className:"mb-10",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ji,{className:"h-5 w-5 text-primary"}),e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Brokerage Content"})]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>t("/brokerage-content"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(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(jWs,{item:a},a.id))})]})}const HUt=({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"}),kWs={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"},SWs={coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",active:"Active",under_contract:"Under Contract",sold:"Sold",withdrawn:"Withdrawn"};function CWs(s){return s>=1e6?`$${(s/1e6).toFixed(1)}M`:`$${(s/1e3).toFixed(0)}K`}function AWs(){const s=Xn(),{data:t,isLoading:n}=E$t(),{data:r,isLoading:a}=T$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(Ie,{className:"p-4",children:e.jsxs("div",{className:"animate-pulse flex items-center gap-4",children:[e.jsx("div",{className:"h-12 w-12 bg-emerald-500/20 rounded-lg"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx("div",{className:"h-4 bg-emerald-500/20 rounded w-1/3"}),e.jsx("div",{className:"h-3 bg-emerald-500/10 rounded w-1/2"})]})]})})}):e.jsxs("section",{className:"mb-10",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Listing Exchange"}),e.jsx(HUt,{})]}),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(Ie,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(va,{className:"h-8 w-8 text-muted-foreground/50 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No listings available yet"}),e.jsx($,{variant:"link",size:"sm",onClick:()=>s("/mission-control/listings/new"),className:"mt-2",children:"Add the first listing"})]})})}):e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3",children:c.map(u=>{var m,f;const h=((m=u.photos)==null?void 0:m.find(g=>g.is_primary))||((f=u.photos)==null?void 0:f[0]);return e.jsxs("div",{onClick:()=>s(`/mission-control/listings/${u.id}`),className:"group cursor-pointer bg-card rounded-xl border border-border overflow-hidden transition-all duration-200 hover:shadow-lg hover:border-primary/30",children:[e.jsxs("div",{className:"aspect-[4/3] bg-muted/50 overflow-hidden relative",children:[h!=null&&h.photo_url?e.jsx("img",{src:h.photo_url,alt:`${u.city}, ${u.state}`,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(va,{className:"h-8 w-8 text-muted-foreground/50"})}),u.is_featured&&e.jsx("div",{className:"absolute top-1.5 left-1.5",children:e.jsxs($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 ${kWs[u.status]}`,children:SWs[u.status]})})]}),e.jsxs("div",{className:"p-2",children:[e.jsx("p",{className:"font-bold text-sm text-foreground",children:CWs(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 GUt(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 WUt(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 KUt(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 YUt(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 EWs(){const{user:s,brokerageId:t,isAdmin:n}=bs();Xn();const r=!!t,[a,i]=j.useState("brokerage"),l=()=>{if(n)return null;if(r)return a==="global"?null:t},{data:o,isLoading:c}=GUt(5,l()),{data:d}=WUt(s==null?void 0:s.id),{data:u}=YUt(s==null?void 0:s.id,l()),{data:h}=KUt(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(Ie,{children:e.jsx("div",{className:"space-y-2",children:[...Array(m?5:3)].map((x,y)=>e.jsx(xn,{className:"h-10 w-full"},y))})})]});const g=x=>x===0?e.jsx(Kl,{className:"h-4 w-4 text-yellow-500 mx-auto"}):x===1?e.jsx("span",{className:"text-sm font-medium text-gray-400",children:"2"}):x===2?e.jsx("span",{className:"text-sm font-medium text-amber-600",children:"3"}):e.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:x+1});if(m){const x=(o==null?void 0:o.slice(0,5))||[];return e.jsxs(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(Ie,{children:[!n&&d&&e.jsx("div",{className:"mb-3 p-2 rounded-lg bg-primary/5 border border-primary/10",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Your Rank:"}),e.jsxs("span",{className:"font-bold text-primary",children:["#",u||"-"]})]}),e.jsxs("div",{className:"flex items-center gap-3 text-sm",children:[e.jsxs("span",{children:[e.jsx("strong",{className:"text-primary",children:d.total_points})," pts"]}),e.jsxs("span",{children:[e.jsx("strong",{children:d.total_events_attended})," events"]})]})]})}),e.jsxs("div",{className:"space-y-2",children:[x.map((y,v)=>{var b,w,S;return e.jsxs("div",{className:`flex items-center gap-2 p-2 rounded-lg ${y.user_id===(s==null?void 0:s.id)?"bg-primary/10 border border-primary/20":v===0?"bg-yellow-500/10":""}`,children:[e.jsx("div",{className:"w-5 text-center",children:g(v)}),e.jsx(Oa,{className:"h-6 w-6",children:e.jsx(za,{className:"text-xs",children:((w=(b=y.profile)==null?void 0:b.name)==null?void 0:w.charAt(0))||"?"})}),e.jsx("span",{className:"flex-1 text-sm font-medium truncate",children:((S=y.profile)==null?void 0:S.name)||"Unknown"}),e.jsx("span",{className:"text-sm font-bold text-primary",children:y.total_points})]},y.user_id)}),x.length===0&&e.jsx("div",{className:"text-center text-muted-foreground py-2 text-sm",children:"No data yet"})]}),e.jsxs(wr,{to:"/reward-store",className:"mt-3 flex items-center justify-center gap-2 p-2 rounded-lg bg-primary/5 hover:bg-primary/10 transition-colors text-sm font-medium text-primary",children:[e.jsx(ul,{className:"h-4 w-4"}),"Spend Points in Reward Store",e.jsx(Di,{className:"h-4 w-4"})]})]})]})}return e.jsxs(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(Ie,{children:d?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"p-3 rounded-lg bg-primary/5 border border-primary/10 text-center",children:[e.jsx("div",{className:"text-2xl font-bold text-primary",children:d.total_points}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Total Points"})]}),e.jsxs("div",{className:"p-3 rounded-lg bg-muted/50 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:d.total_events_attended}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Events Attended"})]})]}),e.jsxs("div",{className:"flex items-center justify-between p-2 rounded-lg bg-orange-500/10 border border-orange-500/20",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(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(wr,{to:"/reward-store",className:"mt-3 flex items-center justify-center gap-2 p-2 rounded-lg bg-primary/5 hover:bg-primary/10 transition-colors text-sm font-medium text-primary",children:[e.jsx(ul,{className:"h-4 w-4"}),"Spend Points in Reward Store",e.jsx(Di,{className:"h-4 w-4"})]})]}):e.jsxs("div",{className:"text-center text-muted-foreground py-4 text-sm",children:[e.jsx(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(wr,{to:"/reward-store",className:"mt-3 inline-flex items-center gap-2 p-2 rounded-lg bg-primary/5 hover:bg-primary/10 transition-colors text-sm font-medium text-primary",children:[e.jsx(ul,{className:"h-4 w-4"}),"Visit Reward Store",e.jsx(Di,{className:"h-4 w-4"})]})]})})]})}const BB=()=>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}}),ont=()=>{const s=Wt(),{user:t}=bs();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"]}),re.success("Lead source added")},onError:n=>{re.error("Failed to add lead source"),console.error(n)}})},TWs=()=>{const s=Wt();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"]}),re.success("Lead source updated")},onError:t=>{re.error(t.message||"Failed to update lead source")}})},MWs=()=>{const s=Wt();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"]}),re.success("Lead source removed")},onError:t=>{re.error(t.message||"Failed to remove lead source")}})},lnt=(s,t)=>{const{user:n,isAdmin:r}=bs(),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})},cnt=s=>{const{user:t,isAdmin:n}=bs(),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})},S6e=()=>{const s=Wt(),{user:t}=bs();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"]}),re.success("Transaction added")},onError:n=>{re.error("Failed to add transaction"),console.error(n)}})},PWs=()=>{const s=Wt();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"]}),re.success("Transaction updated")},onError:t=>{re.error("Failed to update transaction"),console.error(t)}})},IWs=()=>{const s=Wt();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"]}),re.success("Transaction deleted")},onError:t=>{re.error("Failed to delete transaction"),console.error(t)}})},ZUt=(s,t)=>{const{user:n,isAdmin:r}=bs(),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})},LWs=()=>{const s=Wt(),{user:t}=bs();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]}),re.success("Goals saved")},onError:n=>{re.error("Failed to save goals"),console.error(n)}})},C6e=()=>{const{user:s}=bs();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)})},RWs=()=>{const s=Wt(),{user:t}=bs();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"]}),re.success("Settings saved")},onError:n=>{re.error("Failed to save settings"),console.error(n)}})},XUt=(s,t)=>{const{data:n,isLoading:r}=lnt(s,t),{data:a,isLoading:i}=cnt(t),{data:l}=C6e(),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 y=Object.entries(x).map(([A,E])=>({name:A,count:E})).sort((A,E)=>E.count-A.count),v=y[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:v,transactionsByMonth:S,leadSourceBreakdown:y}};return{yearStats:c(n),lifetimeStats:c(a),isLoading:r||i,showCommission:o}},DWs=()=>{const{isAdmin:s}=bs();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})},uP={recency:40,touchpoints:30,transactions:20},fbt={warm:70,cooling:40};function FWs(s){return s===null?0:s<=14?uP.recency:s<=30?uP.recency*.85:s<=60?uP.recency*.65:s<=90?uP.recency*.4:s<=180?uP.recency*.2:uP.recency*.05}function OWs(s){const t=Math.min(s/12,1);return Math.round(uP.touchpoints*t)}function zWs(s){return s?uP.transactions:0}function BWs(){return 0}function $Ws(s){return s>=fbt.warm?"warm":s>=fbt.cooling?"cooling":"at-risk"}function rie(){const{data:s,isLoading:t}=R_(),{data:n}=PUt(),{data:r}=uK(365),{data:a}=cnt(),i=j.useMemo(()=>{if(!s)return[];const o=new Date,c=i8(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?dk(o,new Date(m)):null,g=d[h.id]||0,x=u.has(h.id),y=FWs(f),v=OWs(g),b=zWs(x),w=BWs(),S=Math.round(y+v+b+w),A={score:S,status:$Ws(S),breakdown:{recency:Math.round(y),touchpoints:Math.round(v),transactions:Math.round(b),referrals:Math.round(w)},lastTouchDate:m,daysSinceTouch:f,touchCountLast12Months:g,hasTransaction:x};return{...h,relationshipScore: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 UWs(s){const{contactsWithScores:t,isLoading:n}=rie(),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=Xn(),{stats:t,contactsWithScores:n,isLoading:r}=rie();if(r)return e.jsxs(je,{children:[e.jsx(St,{className:"pb-2",children:e.jsx(xn,{className:"h-5 w-40"})}),e.jsxs(Ie,{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(Ie,{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Add contacts to see your relationship health scores."}),e.jsx($,{variant:"outline",size:"sm",className:"mt-3",onClick:()=>s("/mission-control/contacts?new=true"),children:"Add Your First Contact"})]})]});const a=Math.round(t.warm/t.total*100),i=Math.round(t.cooling/t.total*100),l=Math.round(t.atRisk/t.total*100),o=n.filter(c=>c.relationshipScore.status==="at-risk").sort((c,d)=>c.relationshipScore.score-d.relationshipScore.score).slice(0,3);return e.jsxs(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(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-emerald-500"}),e.jsx("span",{children:"Warm"})]}),e.jsxs("span",{className:"font-medium",children:[t.warm," (",a,"%)"]})]}),e.jsx(Yi,{value:a,className:"h-2 bg-muted [&>div]:bg-emerald-500"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-amber-500"}),e.jsx("span",{children:"Cooling Off"})]}),e.jsxs("span",{className:"font-medium",children:[t.cooling," (",i,"%)"]})]}),e.jsx(Yi,{value:i,className:"h-2 bg-muted [&>div]:bg-amber-500"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-red-500"}),e.jsx("span",{children:"At Risk"})]}),e.jsxs("span",{className:"font-medium",children:[t.atRisk," (",l,"%)"]})]}),e.jsx(Yi,{value:l,className:"h-2 bg-muted [&>div]:bg-red-500"})]})]}),o.length>0&&e.jsxs("div",{className:"pt-3 border-t",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(sC,{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 qWs=()=>{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"},VWs=()=>new Intl.DateTimeFormat("en-US",{weekday:"long",month:"long",day:"numeric",timeZone:"America/New_York"}).format(new Date);function HWs({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 GWs({name:s,eventsThisWeek:t=0}){const n=Xn(),{user:r}=bs(),{data:a}=ent(),{data:i}=AUt(),l=_6e(),{hasAccess:o,hasAssignment:c}=Rzt(),{hasFeature:d}=_C(),{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,y=[m>0?`${m} ${m===1?"person":"people"} to reach out to`:"no follow-ups queued",t>0?`${t} ${t===1?"event":"events"} coming up`:null].filter(Boolean).join(" • "),v=[{label:"New leads (7d)",value:h,to:"/mission-control/contacts"},{label:"Follow-ups due",value:m,to:"/mission-control"},...d("listing_exchange")?[{label:"My listings",value:u??0,to:"/mission-control/listings"}]:[],{label:"Day streak",value:f,to:"/mission-control",icon:sh}],b=[{label:"Add Contact",icon:lc,to:"/mission-control/contacts?new=true"},...d("social")?[{label:"Create Post",icon:Fd,to:"/social-swag-2"}]:[],...d("presentations")?[{label:"Listing Presentation",icon:bb,to:"/mission-control/listing-presentations"}]:[],...o?[{label:"Book Coaching",icon:Cu,to:c?"/my-coach":"/coaching"}]:[],{label:"Ask AI",icon:Nn,to:"/ask-ai"}];return e.jsxs("section",{className:"hub-ink relative overflow-hidden rounded-2xl p-5 sm:p-7 mb-6",children:[e.jsxs("div",{className:"relative flex flex-col gap-6 lg:flex-row lg:items-start lg:justify-between",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-xs uppercase tracking-wider hub-ink-muted",children:VWs()}),e.jsxs("h1",{className:"mt-1 text-2xl sm:text-3xl font-bold",children:[qWs(),", ",s]}),e.jsx("p",{className:"mt-1 text-sm hub-ink-muted",children:y?`Today: ${y}.`:"You're all clear today — go create some momentum."}),e.jsx("div",{className:"mt-5 grid grid-cols-2 gap-2 sm:grid-cols-4",children:v.map(w=>e.jsxs("button",{onClick:()=>n(w.to),className:"hub-glass rounded-xl px-3 py-2.5 text-left transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[w.icon&&e.jsx(w.icon,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),e.jsx("span",{className:"text-xl font-bold",children:w.value})]}),e.jsx("p",{className:"mt-0.5 text-[11px] hub-ink-muted",children:w.label})]},w.label))})]}),e.jsxs("div",{className:"hub-glass flex items-center gap-4 rounded-2xl px-4 py-3 lg:self-center",children:[e.jsx(HWs,{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 XU=24*60*60*1e3,WWs=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}},nde=s=>{const t=WWs(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,YWs=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}},XWs=(s=5)=>{const t=Sa(),{data:n,isLoading:r}=ent(),{data:a,isLoading:i}=R_(),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*XU).toISOString()),q.from("contact_touch_logs").select("contact_id").eq("owner_user_id",t).gte("completed_at",new Date(Date.now()-90*XU).toISOString())]),x=new Set([...(m||[]).map(P=>P.contact_id),...(f||[]).map(P=>P.contact_id)]),y=new Set((g||[]).map(P=>P.contact_id)),v=P=>!x.has(P)&&!c.has(P);for(const P of u){if(!v(P.id))continue;const D=[{days:nde(P.birthday),label:"Birthday"},{days:nde(P.home_anniversary),label:"Home anniversary"},{days:nde(P.wedding_anniversary),label:"Wedding anniversary"},{days:nde(P.spouse_birthday),label:`${P.spouse_name||"Spouse"}'s birthday`}].find(O=>KWs(O.days,7));D&&d({key:`milestone-${P.id}`,contact:P,kind:"milestone",actionLabel:"Send wishes",reason:`${D.label} ${YWs(D.days)}`,priority:D.days===0?1:5+D.days})}const{data:b}=await q.from("contact_signals").select("contact_id, signal_type, title, weight, detected_at").eq("owner_user_id",t).or(`expires_at.is.null,expires_at.gt.${new Date().toISOString()}`).order("weight",{ascending:!1}).order("detected_at",{ascending:!1}).limit(200);for(const P of b||[]){const R=h.get(P.contact_id);if(!R||!v(P.contact_id))continue;const D=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||!v(P.contact_id)||d({key:`deal-${P.contact_id}`,contact:R,kind:"deal",actionLabel:"Check in",reason:`Open deal with no contact in 2 weeks${P.property_address?` · ${P.property_address}`:""}`,priority:30})}const S=Date.now()-3*XU;for(const P of u)v(P.id)&&(y.has(P.id)||new Date(P.created_at).getTime()v(P.id)&&!y.has(P.id)&&new Date(P.created_at).getTime()P.id.localeCompare(R.id));if(E.length>0){const P=new Date().getDate()*7%E.length;for(let R=0;RP.priority-R.priority).slice(0,s)},enabled:!!t&&!r&&!i});return{...l,isLoading:l.isLoading||r||i}},QWs=()=>{const s=Sa(),t=Wt();return mt({mutationFn:async n=>{const r=new Date(Date.now()+14*XU).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"})})},JWs=s=>(s||"?").split(" ").map(t=>t[0]).slice(0,2).join("").toUpperCase(),eKs={plan:{icon:xb,tint:"var(--nav-crm)"},milestone:{icon:Fg,tint:"var(--nav-events)"},signal:{icon:sh,tint:"var(--nav-marketing)"},deal:{icon:kx,tint:"var(--nav-listings)"},new:{icon:Nn,tint:"var(--nav-apps)"},cold:{icon:Xj,tint:"var(--nav-more)"}};function tKs(){const s=Xn(),{data:t,isLoading:n}=XWs(5),r=QWs(),a=_6e(),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(nh,{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(bk,{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=eKs[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:JWs(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(sKs,{contact:d,onOpen:()=>s(`/mission-control/contacts/${d.id}`)}),e.jsxs(iy,{children:[e.jsx(oy,{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(pr,{className:"h-4 w-4"})})}),e.jsx(jx,{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 sKs({contact:s,onOpen:t}){const n=(s==null?void 0:s.phone)||(s==null?void 0:s.mobile_phone),r=s==null?void 0:s.email;return e.jsxs(e.Fragment,{children:[n&&e.jsx($,{asChild:!0,size:"icon",variant:"ghost",className:"h-8 w-8","aria-label":"Call",children:e.jsx("a",{href:`tel:${n}`,onClick:a=>a.stopPropagation(),children:e.jsx(Da,{className:"h-4 w-4"})})}),n&&e.jsx($,{asChild:!0,size:"icon",variant:"ghost",className:"h-8 w-8","aria-label":"Text",children:e.jsx("a",{href:`sms:${n}`,onClick:a=>a.stopPropagation(),children:e.jsx(eo,{className:"h-4 w-4"})})}),r&&e.jsx($,{asChild:!0,size:"icon",variant:"ghost",className:"h-8 w-8","aria-label":"Email",children:e.jsx("a",{href:`mailto:${r}`,onClick:a=>a.stopPropagation(),children:e.jsx(mn,{className:"h-4 w-4"})})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8","aria-label":"Open contact",onClick:t,children:e.jsx(Di,{className:"h-4 w-4"})})]})}const nKs=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 rKs({events:s,registrations:t}){const n=Xn(),{data:r}=Ist(),{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:iWs(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(_b,{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(ua,{className:"h-4 w-4",style:{color:"hsl(var(--nav-events))"}})}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block truncate text-sm font-medium text-foreground group-hover:text-primary",children:l.title}),e.jsxs("span",{className:"block text-xs text-muted-foreground",children:[l.live?"Live now":`${nKs(l.date)} · ${cse(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(Fr,{className:"h-3 w-3"})," Join"]})]})},l.id))})]})}const pbt=s=>s>=1e6?`$${(s/1e6).toFixed(1)}M`:s>=1e3?`$${Math.round(s/1e3)}K`:`$${s}`;function aKs(){const s=Xn(),{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(l2,{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:pbt(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:pbt(t.wonVolume)})," volume"]})]})]})}function iKs(){const s=Xn(),{user:t}=bs(),{hasFeature:n}=_C(),{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:bb,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=MOt(i.to);return!l||n(l)});return a.length<=1?null:e.jsxs("section",{className:"mb-8",children:[e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx(da,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("h3",{className:"text-sm font-semibold uppercase tracking-wide text-muted-foreground",children:"Jump back in"})]}),e.jsx("div",{className:"hub-scroll flex gap-3 overflow-x-auto pb-1",children:a.map(i=>e.jsxs("button",{onClick:()=>s(i.to),className:"hub-card group flex w-[230px] shrink-0 items-center gap-3 p-3 text-left",children:[e.jsx("span",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-xl",style:{background:`hsl(var(${i.hue}) / 0.14)`},children:e.jsx(i.icon,{className:"h-5 w-5",style:{color:`hsl(var(${i.hue}))`}})}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block truncate text-sm font-medium text-foreground group-hover:text-primary",children:i.label}),e.jsx("span",{className:"block text-xs text-muted-foreground",children:i.sub})]}),e.jsx(Qa,{className:"h-4 w-4 shrink-0 text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"})]},i.id))})]})}function oKs({videos:s,kits:t,templates:n,services:r}){const a=Xn(),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:kv,hue:"--nav-apps",items:t,viewAll:"/toolbox",emptyText:"No resource kits yet."},{id:"templates",label:"Templates",icon:qI,hue:"--nav-marketing",items:n,viewAll:"/templates",emptyText:"No new templates yet.",fit:"contain"},{id:"services",label:"Services",icon:Nn,hue:"--nav-crm",items:r,viewAll:"/additional-services",emptyText:"No additional services yet."}],[l,o]=j.useState(i[0].id),c=i.find(d=>d.id===l)||i[0];return e.jsxs("section",{className:"mb-10",children:[e.jsxs("div",{className:"mb-4 flex flex-wrap items-center justify-between gap-3",children:[e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Fresh for you"}),e.jsxs($,{variant:"ghost",size:"sm",className:"gap-1 text-muted-foreground hover:text-foreground",onClick:()=>a(c.viewAll),children:["View All ",e.jsx(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 lKs=()=>{var ne;const{user:s,isAdmin:t}=bs(),n=Xn(),{hasFeature:r}=_C(),[a,i]=j.useState([]),[l,o]=j.useState([]),[c,d]=j.useState([]),[u,h]=j.useState([]),[m,f]=j.useState([]),[g,x]=j.useState([]),[y,v]=j.useState(new Set),[b,w]=j.useState([]),[S,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,_e,he;try{const[ue,ve,Ee,Se,Le,Fe,ke,Be,Ne,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 Ve=((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))||[]);v(ze);const dt=(((_e=ve.data)==null?void 0:_e.filter(rt=>!rt.required_tags||rt.required_tags.length===0?!0:rt.required_tags.some(Ke=>Ve.includes(Ke))))||[]).sort((rt,Ke)=>rt.name==="LevelUp Members Portal"?-1:Ke.name==="LevelUp Members Portal"?1:0);i(dt.slice(0,6));const Xe=((he=Se.data)==null?void 0:he.filter(rt=>c8(rt.event_date)!=="ended"))||[];o(Xe.slice(0,4)),w(Le.data||[]),d(Fe.data||[]),h(ke.data||[]),f(Be.data||[]),x(Ne.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),re.error("Failed to load dashboard data")}finally{O(!1)}},W=async te=>{var ce,_e,he;if(te.target_url.startsWith("/")){q.from("activity_logs").insert({user_id:s==null?void 0:s.id,app_id:te.app_id,app_name:te.name,user_agent:navigator.userAgent}).then(()=>{}),n(te.target_url);return}const J=window.open("about:blank","_blank");try{await q.from("activity_logs").insert({user_id:s==null?void 0:s.id,app_id:te.app_id,app_name:te.name,user_agent:navigator.userAgent});let{data:ue}=await q.auth.getSession();(ce=ue.session)!=null&&ce.access_token||(ue=(await q.auth.refreshSession()).data);const ve=(_e=ue==null?void 0:ue.session)==null?void 0:_e.access_token;if(!ve){J==null||J.close(),re.error("Your session expired — please sign in again to launch this app.");return}const{data:Ee,error:Se}=await q.functions.invoke("sso-launch",{body:{app_id:te.app_id},headers:{Authorization:`Bearer ${ve}`}});if(Se)throw Se;Ee!=null&&Ee.redirect_url?J&&!J.closed?(J.location.href=Ee.redirect_url,(he=J.focus)==null||he.call(J)):window.location.assign(Ee.redirect_url):(J==null||J.close(),re.error("Launch link unavailable"))}catch(ue){J==null||J.close(),console.error("Error launching app:",ue),re.error("Failed to launch app")}},V={"Newsletter Pro":"newsletter","Social AutoPilot":"social","Staging Studio":"marketing_studio",SigFlow:"marketing_studio","Agent Review":"marketing_studio",AgentReview:"marketing_studio"},G=a.filter(te=>{const J=V[te.name]||V[te.app_id];return!J||r(J)}),Y=te=>E.filter(J=>J.section_after===te),X=(P||((ne=s==null?void 0:s.user_metadata)==null?void 0:ne.name)||"there").split(" ")[0],ae=Date.now()+7*24*60*60*1e3,le=l.filter(te=>new Date(te.event_date).getTime()<=ae).length;return e.jsxs(Vs,{title:"Dashboard",children:[r("learn")&&e.jsx(oWs,{events:l,registrations:b,onNavigateToEvents:()=>n("/events")}),e.jsx(tWs,{}),e.jsx(nWs,{}),e.jsx(rWs,{}),e.jsx(GWs,{name:X,eventsThisWeek:le}),e.jsx(dWs,{}),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(tKs,{})}),r("learn")&&e.jsx(rKs,{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(aKs,{}),r("learn")&&e.jsx(EWs,{})]}),e.jsx(iKs,{}),S.length>0&&e.jsx("div",{className:"mb-8",children:e.jsx(MZ,{banners:S})}),e.jsx(NWs,{}),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(oKs,{videos:(r("learn")?m:[]).map(te=>({id:te.id,title:te.title,image:te.thumbnail_url,meta:te.duration,onOpen:()=>n(`/academy/${te.id}`)})),kits:(r("learn")?u:[]).map(te=>({id:te.id,title:te.name,image:te.featured_image_url,onOpen:()=>n(`/toolbox/${te.id}`)})),templates:(r("marketing_studio")?c:[]).map(te=>({id:te.id,title:te.name,image:te.preview_image_url,onOpen:()=>n("/templates")})),services:g.map(te=>({id:te.id,title:te.name,image:te.preview_image_url,onOpen:()=>window.open(te.signup_link_url,"_blank")}))}),Y("academy").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(MZ,{banners:Y("academy")})}),r("listing_exchange")&&e.jsx("div",{className:"mb-10",children:e.jsx(AWs,{})}),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(Ie,{className:"flex items-center justify-center py-12",children:e.jsxs("div",{className:"text-center",children:[e.jsx(E0,{className:"h-8 w-8 text-muted-foreground/50 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No apps available"})]})})}):e.jsx("div",{className:"grid gap-4 md:grid-cols-2 xl:grid-cols-3",children:G.map(te=>{const J=y.has(te.id);return e.jsxs("div",{onClick:()=>W(te),className:"hub-card group flex items-start gap-4 p-5 cursor-pointer",children:[e.jsx("div",{className:"flex-shrink-0 w-14 h-14 rounded-xl bg-primary/10 flex items-center justify-center text-3xl",children:te.icon}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-semibold text-foreground group-hover:text-primary transition-colors truncate",children:te.name}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:te.description})]}),J&&e.jsx(E0,{className:"h-5 w-5 text-primary fill-current flex-shrink-0"})]},te.id)})})]}),Y("templates").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(MZ,{banners:Y("templates")})}),Y("events").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(MZ,{banners:Y("events")})}),Y("toolbox").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(MZ,{banners:Y("toolbox")})})]})},cKs=[{key:"contacts",label:"Contacts",icon:Da,description:"View, add, and edit contacts"},{key:"pipeline",label:"Deal Pipeline",icon:WI,description:"View, add, and move deals"},{key:"client_portal",label:"Client Portals",icon:kv,description:"Manage client portals on deals"},{key:"videos",label:"Videos",icon:ua,description:"View and upload videos"},{key:"listings",label:"Listings",icon:va,description:"View, create, and edit listings"},{key:"scorecard",label:"Scorecard",icon:zg,description:"View and add transactions"},{key:"popbys",label:"Pop-bys",icon:ci,description:"View and log pop-bys"},{key:"digital_card",label:"Digital Card",icon:Nv,description:"Create and edit digital business card"},{key:"guest_book",label:"Guest Book",icon:Xf,description:"Manage open house guest books"},{key:"presentations",label:"Presentations",icon:bb,description:"Create and manage smart presentations"}];function dKs(){var I;const{user:s}=bs(),[t,n]=j.useState([]),[r,a]=j.useState(!0),[i,l]=j.useState(!1),[o,c]=j.useState(!1),[d,u]=j.useState(null),[h,m]=j.useState({email:"",name:"",password:""}),[f,g]=j.useState("create"),[x,y]=j.useState(!1),[v,b]=j.useState(null);j.useEffect(()=>{s&&w()},[s]);const w=async()=>{if(s){a(!0);try{const{data:P,error:R}=await q.from("agent_assistant_assignments").select("id, assistant_id, permissions, created_at").eq("agent_id",s.id);if(R)throw R;if(P&&P.length>0){const D=P.map(W=>W.assistant_id),{data:O}=await q.from("profiles").select("id, name, email").in("id",D),U=P.map(W=>{const V=O==null?void 0:O.find(G=>G.id===W.assistant_id);return{...W,permissions:W.permissions,assistant_profile:V?{name:V.name||"",email:V.email||""}:void 0}});n(U)}else n([])}catch(P){console.error("Error loading assistants:",P)}finally{a(!1)}}},S=async()=>{if(s){if(f==="link"){if(!h.email.trim()){re.error("Please enter the assistant's email");return}y(!0);try{const{data:{session:P}}=await q.auth.getSession();if(!P)throw new Error("Not authenticated");const{data:R,error:D}=await q.from("profiles").select("id, name, email").eq("email",h.email.trim().toLowerCase()).single();if(D||!R){re.error("No account found with that email. Try creating a new assistant instead.");return}const{data:O}=await q.from("agent_assistant_assignments").select("id").eq("agent_id",s.id).eq("assistant_id",R.id);if(O&&O.length>0){re.error("This assistant is already assigned to you");return}const U=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${P.access_token}`},body:JSON.stringify({userId:R.id,role:"assistant",action:"add",agentId:s.id})}),W=await U.json();if(!U.ok)throw new Error(W.error||"Failed to assign assistant role");const{error:V}=await q.from("agent_assistant_assignments").insert({agent_id:s.id,assistant_id:R.id,permissions:{contacts:!0,pipeline:!0,videos:!1,listings:!1,scorecard:!1,popbys:!1,digital_card:!1,client_portal:!1,guest_book:!1,presentations:!1}});if(V)throw V;re.success(`${R.name||R.email} linked as your assistant`),l(!1),m({email:"",name:"",password:""}),w()}catch(P){console.error("Error linking assistant:",P),re.error(P.message||"Failed to link assistant")}finally{y(!1)}return}if(!h.email.trim()||!h.name.trim()||!h.password.trim()){re.error("Please fill in all fields");return}if(h.password.length<6){re.error("Password must be at least 6 characters");return}y(!0);try{const{data:{session:P}}=await q.auth.getSession();if(!P)throw new Error("Not authenticated");const R=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${P.access_token}`},body:JSON.stringify({email:h.email.trim(),password:h.password,name:h.name.trim(),purpose:"assistant"})}),D=await R.json();if(!R.ok)throw new Error(D.error||"Failed to create assistant account");const O=D.userId||D.id;if(!O)throw new Error("No user ID returned");const U=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${P.access_token}`},body:JSON.stringify({userId:O,role:"assistant",action:"add",agentId:s.id})}),W=await U.json();if(!U.ok)throw new Error(W.error||"Failed to assign assistant role");const{error:V}=await q.from("agent_assistant_assignments").insert({agent_id:s.id,assistant_id:O,permissions:{contacts:!0,pipeline:!0,videos:!1,listings:!1,scorecard:!1,popbys:!1,digital_card:!1,client_portal:!1,guest_book:!1,presentations:!1}});if(V)throw V;re.success(`Assistant account created for ${h.name.trim()}`),l(!1),m({email:"",name:"",password:""}),w()}catch(P){console.error("Error adding assistant:",P),re.error(P.message||"Failed to add assistant")}finally{y(!1)}}},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"})}),re.success("Assistant removed"),c(!1),u(null),w()}catch(P){console.error("Error removing assistant:",P),re.error(P.message||"Failed to remove assistant")}},E=async(P,R,D)=>{b(P);try{const O=t.find(V=>V.id===P);if(!O)return;const U={...O.permissions,[R]:D},{error:W}=await q.from("agent_assistant_assignments").update({permissions:U}).eq("id",P);if(W)throw W;n(V=>V.map(G=>G.id===P?{...G,permissions:U}:G))}catch(O){console.error("Error updating permissions:",O),re.error("Failed to update permissions")}finally{b(null)}};return r?e.jsxs(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(Ie,{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(Gn,{children:"Add assistants to help manage your Agent OS"})]}),e.jsxs($,{size:"sm",onClick:()=>{g("create"),l(!0)},children:[e.jsx(dn,{className:"h-4 w-4 mr-1"}),"Add Assistant"]})]})}),e.jsx(Ie,{children:t.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No assistant assigned. Add one to help manage your contacts, deals, and more."}):e.jsx("div",{className:"space-y-4",children:t.map(P=>{var R,D,O,U;return e.jsxs("div",{className:"border rounded-lg p-4 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Oa,{className:"h-10 w-10",children:e.jsx(za,{children:((D=(R=P.assistant_profile)==null?void 0:R.name)==null?void 0:D.split(" ").map(W=>W[0]).join("").toUpperCase())||"A"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((O=P.assistant_profile)==null?void 0:O.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:((U=P.assistant_profile)==null?void 0:U.email)||""})]}),e.jsxs($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(Hn,{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:cKs.map(W=>{const V=W.icon;return e.jsxs("div",{className:"flex items-center justify-between p-2 rounded-md border",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(V,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:W.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:W.description})]})]}),e.jsx(Sn,{checked:P.permissions[W.key]||!1,onCheckedChange:G=>E(P.id,W.key,G),disabled:v===P.id})]},W.key)})})]})]},P.id)})})})]}),e.jsx(zs,{open:i,onOpenChange:l,children:e.jsxs(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Add Assistant"}),e.jsx(Pr,{children:f==="create"?"Create a new account for your assistant.":"Link an existing assistant account by their email."})]}),e.jsxs("div",{className:"flex gap-2 mb-2",children:[e.jsxs($,{variant:f==="create"?"default":"outline",size:"sm",onClick:()=>g("create"),children:[e.jsx(dn,{className:"h-3 w-3 mr-1"}),"Create New"]}),e.jsxs($,{variant:f==="link"?"default":"outline",size:"sm",onClick:()=>g("link"),children:[e.jsx(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(Sr,{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 sb(s){this.content=s}sb.prototype={constructor:sb,find:function(s){for(var t=0;t>1}};sb.from=function(s){if(s instanceof sb)return s;var t=[];if(s)for(var n in s)t.push(n,s[n]);return new sb(t)};function JUt(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 sqt(s){return s>=55296&&s<56320}let ui=class X1{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 X1(r,a)}cutByIndex(t,n){return t==n?X1.empty:t==0&&n==this.content.length?this:new X1(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 X1(a,i)}addToStart(t){return new X1([t].concat(this.content),this.size+t.nodeSize)}addToEnd(t){return new X1(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?rde(n+1,i):rde(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 X1.empty;if(!Array.isArray(n))throw new RangeError("Invalid input for Fragment.fromJSON");return X1.fromArray(n.map(t.nodeFromJSON))}static fromArray(t){if(!t.length)return X1.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 dse 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=rqt(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(nqt(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(ui.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(ui.empty,0,0);function nqt(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(nqt(i.content,t-a-1,n-a-1)))}function rqt(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=rqt(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 uKs(s,t,n){if(n.openStart>s.depth)throw new dse("Inserted content deeper than insertion position");if(s.depth-n.openStart!=t.depth-n.openEnd)throw new dse("Inconsistent open depths");return aqt(s,t,n,0)}function aqt(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 kee(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&&(c7(s.nodeAfter,r),i++));for(let o=i;oa&&VGe(s,t,a+1),l=r.depth>a&&VGe(n,r,a+1),o=[];return kee(null,s,a,o),i&&l&&t.index(a)==n.index(a)?(iqt(i,l),c7(d7(i,oqt(s,t,n,r,a+1)),o)):(i&&c7(d7(i,XEe(s,t,a+1)),o),kee(t,n,a,o),l&&c7(d7(l,XEe(n,r,a+1)),o)),kee(r,null,a,o),new ui(o)}function XEe(s,t,n){let r=[];if(kee(null,s,n,r),s.depth>n){let a=VGe(s,t,n+1);c7(d7(a,XEe(s,t,n+1)),r)}return kee(t,null,n,r),new ui(r)}function hKs(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(ui.from(a));return{start:a.resolveNoCache(s.openStart+n),end:a.resolveNoCache(a.content.size-s.openEnd-n)}}class use{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 QEe(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 use(n,r,i)}static resolveCached(t,n){let r=gbt.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()+")"),lqt(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=ui.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=ui.fromJSON(t,n.content);return t.nodeType(n.type).create(n.attrs,a,r)}};aL.prototype.text=void 0;class JEe extends aL{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):lqt(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 JEe(this.type,this.attrs,this.text,t)}withText(t){return t==this.text?this:new JEe(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 lqt(s,t){for(let n=s.length-1;n>=0;n--)t=s[n].type.name+"("+t+")";return t}function xbt(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 G7{constructor(t){this.validEnd=t,this.next=[],this.wrapCache=[]}static parse(t,n){let r=new gKs(t,n);if(r.next==null)return G7.empty;let a=cqt(r);r.next&&r.err("Unexpected trailing text");let i=jKs(wKs(a));return NKs(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(` `)}}G7.empty=new G7(!0);class gKs{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 cqt(s){let t=[];do t.push(xKs(s));while(s.eat("|"));return t.length==1?t[0]:{type:"choice",exprs:t}}function xKs(s){let t=[];do t.push(yKs(s));while(s.next&&s.next!=")"&&s.next!="|");return t.length==1?t[0]:{type:"seq",exprs:t}}function yKs(s){let t=_Ks(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=vKs(s,t);else break;return t}function ybt(s){/\D/.test(s.next)&&s.err("Expected number, got '"+s.next+"'");let t=Number(s.next);return s.pos++,t}function vKs(s,t){let n=ybt(s),r=n;return s.eat(",")&&(s.next!="}"?r=ybt(s):r=-1),s.eat("}")||s.err("Unclosed braced range"),{type:"range",min:n,max:r,expr:t}}function bKs(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 _Ks(s){if(s.eat("(")){let t=cqt(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=bKs(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 wKs(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 G7(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:hqt(this.attrs,t)}create(t=null,n,r){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new aL(this,this.computeAttrs(t),ui.from(n),Nf.setFrom(r))}createChecked(t=null,n,r){return n=ui.from(n),this.checkContent(n),new aL(this,this.computeAttrs(t),n,Nf.setFrom(r))}createAndFill(t=null,n,r){if(t=this.computeAttrs(t),n=ui.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(ui.empty,!0);return i?new aL(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 fqt(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 kKs(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 SKs{constructor(t,n,r){this.hasDefault=Object.prototype.hasOwnProperty.call(r,"default"),this.default=r.default,this.validate=typeof r.validate=="string"?kKs(t,n,r.validate):r.validate}get isRequired(){return!this.hasDefault}}class A6e{constructor(t,n,r,a){this.name=t,this.rank=n,this.schema=r,this.spec=a,this.attrs=mqt(t,a.attrs),this.excluded=null;let i=uqt(this.attrs);this.instance=i?new Nf(this,i):null}create(t=null){return!t&&this.instance?this.instance:new Nf(this,hqt(this.attrs,t))}static compile(t,n){let r=Object.create(null),a=0;return t.forEach((i,l)=>r[i]=new A6e(i,a++,n,l)),r}removeFromSet(t){for(var n=0;n-1}}let pqt=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=sb.from(t.nodes),n.marks=sb.from(t.marks||{}),this.nodes=bbt.compile(this.spec.nodes,this),this.marks=A6e.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]=G7.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?_bt(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==""?[]:_bt(this,l.split(" "))}this.nodeFromJSON=a=>aL.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 bbt){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 JEe(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 _bt(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 CKs(s){return s.tag!=null}function AKs(s){return s.style!=null}let See=class GGe{constructor(t,n){this.schema=t,this.rules=n,this.tags=[],this.styles=[];let r=this.matchedStyles=[];n.forEach(a=>{if(CKs(a))this.tags.push(a);else if(AKs(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 jbt(this,n,!1);return r.addAll(t,Nf.none,n.from,n.to),r.finish()}parseSlice(t,n={}){let r=new jbt(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=Nbt(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=Nbt(l)),l.node||l.ignore||l.mark||(l.node=a)})}return n}static fromSchema(t){return t.cached.domParser||(t.cached.domParser=new GGe(t,GGe.schemaRules(t)))}};const gqt={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},EKs={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},xqt={ol:!0,ul:!0},hse=1,WGe=2,Cee=4;function wbt(s,t,n){return t!=null?(t?hse:0)|(t==="full"?WGe:0):s&&s.whitespace=="pre"?hse|WGe:n&~Cee}class ade{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&Cee?null:t.contentMatch)}findWrapping(t){if(!this.match){if(!this.type)return[];let n=this.type.contentMatch.fillBefore(ui.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&hse)){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=ui.from(this.content);return!t&&this.match&&(n=n.append(this.match.fillBefore(ui.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&&!gqt.hasOwnProperty(t.parentNode.nodeName.toLowerCase())}}class jbt{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=wbt(null,n.preserveWhitespace,0)|(r?Cee:0);a?i=new ade(a.type,a.attrs,Nf.none,!0,n.topMatch||a.type.contentMatch,l):r?i=new ade(null,null,Nf.none,!0,null,l):i=new ade(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&WGe?"full":this.localPreserveWS||(a.options&hse)>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):kbt(d.type,t))?(c=d.addToSet(c),!1):!0),this.nodes.push(new ade(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|=hse)}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 TKs(s){for(let t=s.firstChild,n=null;t;t=t.nextSibling){let r=t.nodeType==1?t.nodeName.toLowerCase():null;r&&xqt.hasOwnProperty(r)&&n?(n.appendChild(t),t=n):r=="li"?n=t:r&&(n=null)}}function MKs(s,t){return(s.matches||s.msMatchesSelector||s.webkitMatchesSelector||s.mozMatchesSelector).call(s,t)}function Nbt(s){let t={};for(let n in s)t[n]=s[n];return t}function kbt(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&&d3e(ide(r),a(t,n),null,t.attrs)}static renderSpec(t,n,r=null,a){return typeof n=="string"?{dom:t.createTextNode(n)}:d3e(t,n,r,a)}static fromSchema(t){return t.cached.domSerializer||(t.cached.domSerializer=new $B(this.nodesFromSchema(t),this.marksFromSchema(t)))}static nodesFromSchema(t){let n=Sbt(t.nodes);return n.text||(n.text=r=>r.text),n}static marksFromSchema(t){return Sbt(t.marks)}}function Sbt(s){let t={};for(let n in s){let r=s[n].spec.toDOM;r&&(t[n]=r)}return t}function ide(s){return s.document||window.document}const Cbt=new WeakMap;function PKs(s){let t=Cbt.get(s);return t===void 0&&Cbt.set(s,t=IKs(s)),t}function IKs(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}=d3e(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 yqt=65535,vqt=Math.pow(2,16);function LKs(s,t){return s+t*vqt}function Abt(s){return s&yqt}function RKs(s){return(s-(s&yqt))/vqt}const bqt=1,_qt=2,u3e=4,wqt=8;class KGe{constructor(t,n,r){this.pos=t,this.delInfo=n,this.recover=r}get deleted(){return(this.delInfo&wqt)>0}get deletedBefore(){return(this.delInfo&(bqt|u3e))>0}get deletedAfter(){return(this.delInfo&(_qt|u3e))>0}get deletedAcross(){return(this.delInfo&u3e)>0}}class Wj{constructor(t,n=!1){if(this.ranges=t,this.inverted=n,!t.length&&Wj.empty)return Wj.empty}recover(t){let n=0,r=Abt(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:LKs(o/3,t-c),x=t==c?_qt:t==h?bqt:u3e;return(n<0?t!=c:t!=h)&&(x|=wqt),new KGe(f,x,g)}a+=u-d}return r?t+a:new KGe(t+a,0,null)}touches(t,n){let r=0,a=Abt(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 mse;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 By.fromReplace(t,this.from,this.to,i)}invert(){return new g4(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 xI(n.pos,r.pos,this.mark)}merge(t){return t instanceof xI&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from?new xI(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 xI(n.from,n.to,t.markFromJSON(n.mark))}}A1.jsonID("addMark",xI);class g4 extends A1{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(dnt(n.content,a=>a.mark(this.mark.removeFromSet(a.marks)),t),n.openStart,n.openEnd);return By.fromReplace(t,this.from,this.to,r)}invert(){return new xI(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 g4(n.pos,r.pos,this.mark)}merge(t){return t instanceof g4&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from?new g4(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 g4(n.from,n.to,t.markFromJSON(n.mark))}}A1.jsonID("removeMark",g4);class yI extends A1{constructor(t,n){super(),this.pos=t,this.mark=n}apply(t){let n=t.nodeAt(this.pos);if(!n)return By.fail("No node at mark step's position");let r=n.type.create(n.attrs,null,this.mark.addToSet(n.marks));return By.fromReplace(t,this.pos,this.pos+1,new Ki(ui.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 Tv(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 Tv(n.from,n.to,n.gapFrom,n.gapTo,Ki.fromJSON(t,n.slice),n.insert,!!n.structure)}}A1.jsonID("replaceAround",Tv);function YGe(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 DKs(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 FKs(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 A6e){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 g4(l.from,l.to,l.style)))}function unt(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 OKs(s,t,n){return(t==0||s.canReplace(t,s.childCount))&&(n==s.childCount||s.canReplace(0,n))}function fK(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=ui.from(r.node(g).copy(u)),h++):c--;let m=ui.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=ui.from(n[l].type.create(n[l].attrs,r))}let a=t.start,i=t.end;s.step(new Tv(a,i,a,i,new Ki(r,0,0),n.length,!0))}function qKs(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)&&VKs(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&&Nqt(s,l,o,i),unt(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 Tv(h,m,h+1,m-1,new Ki(ui.from(r.create(c,null,l.marks)),0,0),1,!0)),d===!0&&jqt(s,l,o,i),!1}})}function jqt(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 Nqt(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 VKs(s,t,n){let r=s.resolve(t),a=r.index();return r.parent.canReplaceWith(a,a+1,n)}function HKs(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 Tv(t,t+i.nodeSize,t+1,t+i.nodeSize-1,new Ki(ui.from(l),0,0),1,!0))}function UE(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 GKs(s,t,n=1,r){let a=s.doc.resolve(t),i=ui.empty,l=ui.empty;for(let o=a.depth,c=a.depth-n,d=n-1;o>c;o--,d--){i=ui.from(a.node(o).copy(i));let u=r&&r[d];l=ui.from(u?u.type.create(u.attrs,l):a.node(o).copy(l))}s.step(new Ry(t,t,new Ki(i.append(l),n,n),!0))}function c6(s,t){let n=s.resolve(t),r=n.index();return kqt(n.nodeBefore,n.nodeAfter)&&n.parent.canReplace(r,r+1)}function WKs(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&&kqt(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 KKs(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);Nqt(s,u.node(),u.before(),o)}l.inlineContent&&unt(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 Ry(d,c.map(t+n,-1),Ki.empty,!0)),r===!0){let u=s.doc.resolve(d);jqt(s,u.node(),u.before(),s.steps.length)}return s}function YKs(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 T6e(s,t,n=t,r=Ki.empty){if(t==n&&!r.size)return null;let a=s.resolve(t),i=s.resolve(n);return Cqt(a,i,r)?new Ry(t,n,r):new ZKs(a,i,r).fit()}function Cqt(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=ui.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=ui.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 Tv(r.pos,t,this.$to.pos,this.$to.end(),c,n):c.size||r.pos!=this.$to.pos?new Ry(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=Tbt(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(ui.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 Mbt(t,-1)<=n?!1:(this.unplaced.size>1&&Mbt(t,1)>r&&r++,this.unplaced=new Ki(t,n+1,r),!0)}dropNode(){let{content:t,openStart:n,openEnd:r}=this.unplaced,a=Tbt(t,n);if(a.childCount<=1&&n>0){let i=t.size-n<=n+a.size;this.unplaced=new Ki(cQ(t,n-1,1),n-1,i?n-1:r)}else this.unplaced=new Ki(cQ(t,n,1),n,r)}placeNodes({sliceDepth:t,frontierDepth:n,parent:r,inject:a,wrap:i}){for(;this.depth>n;)this.closeFrontierNode();if(i)for(let x=0;x1||c==0||x.content.size)&&(h=y,u.push(Aqt(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=dQ(this.placed,n,ui.from(u)),this.frontier[n].match=h,g&&f<0&&r&&r.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let x=0,y=o;x1&&a==this.$to.end(--r);)++a;return a}findCloseLevel(t){e:for(let n=Math.min(this.depth,t.depth);n>=0;n--){let{match:r,type:a}=this.frontier[n],i=n=0;o--){let{match:c,type:d}=this.frontier[o],u=eBe(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=dQ(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=dQ(this.placed,this.depth,ui.from(t.create(n,r))),this.frontier.push({type:t,match:t.contentMatch})}closeFrontierNode(){let n=this.frontier.pop().match.fillBefore(ui.empty,!0);n.childCount&&(this.placed=dQ(this.placed,this.frontier.length,n))}}function cQ(s,t,n){return t==0?s.cutByIndex(n,s.childCount):s.replaceChild(0,s.firstChild.copy(cQ(s.firstChild.content,t-1,n)))}function dQ(s,t,n){return t==0?s.append(n):s.replaceChild(s.childCount-1,s.lastChild.copy(dQ(s.lastChild.content,t-1,n)))}function Tbt(s,t){for(let n=0;n1&&(r=r.replaceChild(0,Aqt(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(ui.empty,!0)))),s.copy(r)}function eBe(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&&!XKs(n,i.content,l)?o:null}function XKs(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=QKs(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 Eqt(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(ui.empty,!0))}return s}function eYs(s,t,n,r){if(!r.isInline&&t==n&&s.doc.resolve(t).parent.content.size){let a=YKs(s.doc,t,r.type);a!=null&&(t=n=a)}s.replaceRange(t,n,new Ki(ui.from(r),0,0))}function tYs(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=Tqt(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 Tqt(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 jV extends A1{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 By.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 By.fromReplace(t,this.pos,this.pos+1,new Ki(ui.from(a),0,n.isLeaf?0:1))}getMap(){return Wj.empty}invert(t){return new jV(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 jV(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 jV(n.pos,n.attr,n.value)}}A1.jsonID("attr",jV);class fse extends A1{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 By.ok(r)}getMap(){return Wj.empty}invert(t){return new fse(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 fse(n.attr,n.value)}}A1.jsonID("docAttr",fse);let MG=class extends Error{};MG=function s(t){let n=Error.call(this,t);return n.__proto__=s.prototype,n};MG.prototype=Object.create(Error.prototype);MG.prototype.constructor=MG;MG.prototype.name="TransformError";let mnt=class{constructor(t){this.doc=t,this.steps=[],this.docs=[],this.mapping=new mse}get before(){return this.docs.length?this.docs[0]:this.doc}step(t){let n=this.maybeStep(t);if(n.failed)throw new MG(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=T6e(this.doc,t,n,r);return a&&this.step(a),this}replaceWith(t,n,r){return this.replace(t,n,new Ki(ui.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 JKs(this,t,n,r),this}replaceRangeWith(t,n,r){return eYs(this,t,n,r),this}deleteRange(t,n){return tYs(this,t,n),this}lift(t,n){return zKs(this,t,n),this}join(t,n=1){return KKs(this,t,n),this}wrap(t,n){return UKs(this,t,n),this}setBlockType(t,n=t,r,a=null){return qKs(this,t,n,r,a),this}setNodeMarkup(t,n,r=null,a){return HKs(this,t,n,r,a),this}setNodeAttribute(t,n,r){return this.step(new jV(t,n,r)),this}setDocAttribute(t,n){return this.step(new fse(t,n)),this}addNodeMark(t,n){return this.step(new yI(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 W7(t,n));else{let a=r.marks,i,l=[];for(;i=n.isInSet(a);)l.push(new W7(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 GKs(this,t,n,r),this}addMark(t,n,r){return DKs(this,t,n,r),this}removeMark(t,n,r){return FKs(this,t,n,r),this}clearIncompatible(t,n,r){return unt(this,t,n,r),this}};const tBe=Object.create(null);class Nc{constructor(t,n,r){this.$anchor=t,this.$head=n,this.ranges=r||[new Mqt(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?gU(t.node(0),t.node(i),t.before(i+1),t.index(i),n,r):gU(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 p2(t.node(0))}static atStart(t){return gU(t,t,0,0,1)||new p2(t)}static atEnd(t){return gU(t,t,t.content.size,t.childCount,-1)||new p2(t)}static fromJSON(t,n){if(!n||!n.type)throw new RangeError("Invalid input for Selection.fromJSON");let r=tBe[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 tBe)throw new RangeError("Duplicate use of selection JSON ID "+t);return tBe[t]=n,n.prototype.jsonID=t,n}getBookmark(){return El.between(this.$anchor,this.$head).getBookmark()}}Nc.prototype.visible=!0;class Mqt{constructor(t,n){this.$from=t,this.$to=n}}let Pbt=!1;function Ibt(s){!Pbt&&!s.parent.inlineContent&&(Pbt=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+s.parent.type.name+")"))}class El extends Nc{constructor(t,n=t){Ibt(t),Ibt(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 Nc.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 M6e(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=Nc.findFrom(n,r,!0)||Nc.findFrom(n,-r,!0);if(i)n=i.$head;else return Nc.near(n,r)}return t.parent.inlineContent||(a==0?t=n:(t=(Nc.findFrom(t,-r,!0)||Nc.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=gU(s,o,n+a,a<0?o.childCount:0,a,i);if(c)return c}n+=o.nodeSize*a}return null}function Lbt(s,t,n){let r=s.steps.length-1;if(r{l==null&&(l=u)}),s.setSelection(Nc.near(s.doc.resolve(l),n))}const Rbt=1,ode=2,Dbt=4;class nYs extends mnt{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|=ode,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&ode)>0}addStep(t,n){super.addStep(t,n),this.updated=this.updated&~ode,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(Nc.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|=Dbt,this}get scrolledIntoView(){return(this.updated&Dbt)>0}}function Fbt(s,t){return!t||!s?s:s.bind(t)}class uQ{constructor(t,n,r){this.name=t,this.init=Fbt(n.init,r),this.apply=Fbt(n.apply,r)}}const rYs=[new uQ("doc",{init(s){return s.doc||s.schema.topNodeType.createAndFill()},apply(s){return s.doc}}),new uQ("selection",{init(s,t){return s.selection||Nc.atStart(t.doc)},apply(s){return s.selection}}),new uQ("storedMarks",{init(s){return s.storedMarks||null},apply(s,t,n,r){return r.selection.$cursor?s.storedMarks:null}}),new uQ("scrollToSelection",{init(){return 0},apply(s,t){return s.scrolledIntoView?t+1:t}})];class sBe{constructor(t,n){this.schema=t,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=rYs.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 uQ(r.key,r.spec.state,r))})}}class QU{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 sBe(t.schema,t.plugins),i=new QU(a);return a.fields.forEach(l=>{if(l.name=="doc")i.doc=aL.fromJSON(t.schema,n.doc);else if(l.name=="selection")i.selection=Nc.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 Pqt(s,t,n){for(let r in s){let a=s[r];a instanceof Function?a=a.bind(t):r=="handleDOMEvents"&&(a=Pqt(a,t,{})),n[r]=a}return n}class z0{constructor(t){this.spec=t,this.props={},t.props&&Pqt(t.props,this,this.props),this.key=t.key?t.key.key:Iqt("plugin")}getState(t){return t[this.key]}}const nBe=Object.create(null);function Iqt(s){return s in nBe?s+"$"+ ++nBe[s]:(nBe[s]=0,s+"$")}class E1{constructor(t="key"){this.key=Iqt(t)}get(t){return t.config.pluginsByKey[this.key]}getState(t){return t[this.key]}}const ab=function(s){for(var t=0;;t++)if(s=s.previousSibling,!s)return t},PG=function(s){let t=s.assignedSlot||s.parentNode;return t&&t.nodeType==11?t.host:t};let ZGe=null;const CA=function(s,t,n){let r=ZGe||(ZGe=document.createRange());return r.setEnd(s,n??s.nodeValue.length),r.setStart(s,t||0),r},aYs=function(){ZGe=null},K7=function(s,t,n,r){return n&&(Obt(s,t,n,r,-1)||Obt(s,t,n,r,1))},iYs=/^(img|br|input|textarea|hr)$/i;function Obt(s,t,n,r,a){for(var i;;){if(s==n&&t==r)return!0;if(t==(a<0?0:RN(s))){let l=s.parentNode;if(!l||l.nodeType!=1||aie(s)||iYs.test(s.nodeName)||s.contentEditable=="false")return!1;t=ab(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?RN(s):0}else return!1}}function RN(s){return s.nodeType==3?s.nodeValue.length:s.childNodes.length}function oYs(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=RN(s)}else if(s.parentNode&&!aie(s))t=ab(s),s=s.parentNode;else return null}}function lYs(s,t){for(;;){if(s.nodeType==3&&t2),NN=IG||(Z4?/Mac/.test(Z4.platform):!1),Dqt=Z4?/Win/.test(Z4.platform):!1,vE=/Android \d/.test(d6),iie=!!zbt&&"webkitFontSmoothing"in zbt.documentElement.style,hYs=iie?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function mYs(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 X3(s,t){return typeof s=="number"?s:s[t]}function fYs(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 Bbt(s,t,n){if(!eWe(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=PG(l);continue}let o=l,c=o==i.body,d=c?mYs(i):fYs(o),u=0,h=0;if(t.topd.bottom-X3(r,"bottom")&&(h=t.bottom-t.top>d.bottom-d.top?t.top+X3(a,"top")-d.top:t.bottom-d.bottom+X3(a,"bottom")),t.leftd.right-X3(r,"right")&&(u=t.right-d.right+X3(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,y=o.scrollTop-g;t={left:t.left-x,top:t.top-y,right:t.right-x,bottom:t.bottom-y}}let m=c?"fixed":getComputedStyle(l).position;if(/^(fixed|sticky)$/.test(m))break;l=m=="absolute"?l.offsetParent:PG(l)}}function pYs(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:Fqt(s.dom)}}function Fqt(s){let t=[],n=s.ownerDocument;for(let r=s;r&&(t.push({dom:r,top:r.scrollTop,left:r.scrollLeft}),s!=n);r=PG(r));return t}function gYs({refDOM:s,refTop:t,stack:n}){let r=s?s.getBoundingClientRect().top:0;Oqt(n,r==0?0:r-t)}function Oqt(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?yYs(n,a):!n||r&&n.nodeType==1?{node:s,offset:i}:zqt(n,a)}function yYs(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 pnt(s,t){return s.left>=t.left-1&&s.left<=t.right+1&&s.top>=t.top-1&&s.top<=t.bottom+1}function vYs(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 _Ys(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 Bqt(s,t,n){let r=s.childNodes.length;if(r&&n.topt.top&&a++}let d;iie&&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=_Ys(s,r,a,t))}o==null&&(o=bYs(s,l,t));let c=s.docView.nearestDesc(l,!0);return{pos:o,inside:c?c.posAtStart-c.border:-1}}function eWe(s){return s.top=0&&a==r.nodeValue.length?(c--,u=1):n<0?c--:d++,PZ(GM(CA(r,c,d),u),u<0)}if(!s.state.doc.resolve(t-(i||0)).parent.inlineContent){if(i==null&&a&&(n<0||a==RN(r))){let c=r.childNodes[a-1];if(c.nodeType==1)return rBe(c.getBoundingClientRect(),!1)}if(i==null&&a=0)}if(i==null&&a&&(n<0||a==RN(r))){let c=r.childNodes[a-1],d=c.nodeType==3?CA(c,RN(c)-(l?0:1)):c.nodeType==1&&(c.nodeName!="BR"||!c.nextSibling)?c:null;if(d)return PZ(GM(d,1),!1)}if(i==null&&a=0)}function PZ(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 rBe(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 Uqt(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 NYs(s,t,n){let r=t.selection,a=n=="up"?r.$from:r.$to;return Uqt(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=$qt(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=CA(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 kYs=/[\u0590-\u08ac]/;function SYs(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?!kYs.test(r.parent.textContent)||!o.modify?n=="left"||n=="backward"?i:l:Uqt(s,t,()=>{let{focusNode:c,focusOffset:d,anchorNode:u,anchorOffset:h}=s.domSelectionRange(),m=o.caretBidiLevel;o.modify("move",n,"character");let f=r.depth?s.docView.domAfterPos(r.before()):s.dom,{focusNode:g,focusOffset:x}=s.domSelectionRange(),y=g&&!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),y}):r.pos==r.start()||r.pos==r.end()}let $bt=null,Ubt=null,qbt=!1;function CYs(s,t,n){return $bt==t&&Ubt==n?qbt:($bt=t,Ubt=n,qbt=n=="up"||n=="down"?NYs(s,t,n):SYs(s,t,n))}const nk=0,Vbt=1,d8=2,iC=3;class oie{constructor(t,n,r,a){this.parent=t,this.children=n,this.dom=r,this.contentDOM=a,this.dirty=nk,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;nab(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 Vqt){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 qqt&&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?ab(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=ab(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?d8:Vbt,t==o&&n==c&&(i.contentLost||i.dom.parentNode!=this.contentDOM)?i.dirty=iC:i.markDirty(t-o,n-o);return}else i.dirty=i.dom==i.contentDOM&&i.dom.parentNode==this.contentDOM&&!i.children.length?d8:iC}r=l}this.dirty=d8}markParentsDirty(){let t=1;for(let n=this.parent;n;n=n.parent,t++){let r=t==1?d8:Vbt;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==nk&&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 AYs extends oie{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 oL extends oie{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=$B.renderSpec(document,n.type.spec.toDOM(n,r),null,n.attrs)),new oL(t,n,l.dom,l.contentDOM||l.dom,l)}parseRule(){return this.dirty&iC||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(t){return this.dirty!=iC&&this.mark.eq(t)}markDirty(t,n){if(super.markDirty(t,n),this.dirty!=nk){let r=this.parent;for(;!r.node;)r=r.parent;r.dirty0&&(i=sWe(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}=$B.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=Wqt(u,r,n),d?c=new EYs(t,n,r,a,u,h||null,m,d):n.isText?new I6e(t,n,r,a,u,m):new lL(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=()=>ui.empty}}return n}matchesNode(t,n,r){return this.dirty==nk&&t.eq(this.node)&&eTe(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 MYs(this,l&&l.node,t);LYs(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==d8)&&(l&&this.protectLocalComposition(t,l),Hqt(this.contentDOM,this.children,t),IG&&RYs(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=DYs(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 AYs(this,i,n,a);t.input.compositionNodes.push(l),this.children=sWe(this.children,r,r+a.length,t,l)}update(t,n,r,a){return this.dirty==iC||!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=nk}updateOuterDeco(t){if(eTe(t,this.outerDeco))return;let n=this.nodeDOM.nodeType!=1,r=this.dom;this.dom=Gqt(this.dom,this.nodeDOM,tWe(this.outerDeco,this.node,n),tWe(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 Hbt(s,t,n,r,a){Wqt(r,t,s);let i=new lL(void 0,s,t,n,r,r,r);return i.contentDOM&&i.updateChildren(a,0),i}class I6e extends lL{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==iC||this.dirty!=nk&&!this.inParent()||!t.sameMarkup(this.node)?!1:(this.updateOuterDeco(n),(this.dirty!=nk||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=nk,!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 I6e(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=iC)}get domAtom(){return!1}isText(t){return this.node.text==t}}class Vqt extends oie{parseRule(){return{ignore:!0}}matchesHack(t){return this.dirty==nk&&this.dom.nodeName==t}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}}class EYs extends lL{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==iC)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 Hqt(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=oL.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 oL)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 IYs(s,t){return s.type.side-t.type.side}function LYs(s,t,n,r){let a=t.locals(s),i=0;if(a.length==0){for(let d=0;di;)o.push(a[l++]);let g=i+m.nodeSize;if(m.isText){let y=g;l!y.inline):o.slice();r(m,x,t.forChild(i,m),f),i=g}}function RYs(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 DYs(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 sWe(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 gnt(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(P6e(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&&cYs(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(()=>{(!Kqt(s)||s.state.selection.visible)&&s.dom.classList.remove("ProseMirror-hideselection")},20))})}function OYs(s){let t=s.domSelection();if(!t)return;let n=s.cursorWrapper.dom,r=n.nodeName=="IMG";r?t.collapse(n.parentNode,ab(n)+1):t.collapse(n,0),!r&&!s.state.selection.visible&&Mw&&iL<=11&&(n.disabled=!0,n.disabled=!1)}function Yqt(s,t){if(t instanceof Tl){let n=s.docView.descAt(t.from);n!=s.lastSelectedViewDesc&&(Zbt(s),n&&n.selectNode(),s.lastSelectedViewDesc=n)}else Zbt(s)}function Zbt(s){s.lastSelectedViewDesc&&(s.lastSelectedViewDesc.parent&&s.lastSelectedViewDesc.deselectNode(),s.lastSelectedViewDesc=void 0)}function xnt(s,t,n,r){return s.someProp("createSelectionBetween",a=>a(s,t,n))||El.between(t,n,r)}function Xbt(s){return s.editable&&!s.hasFocus()?!1:Zqt(s)}function Zqt(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 zYs(s){let t=s.docView.domFromPos(s.state.selection.anchor,0),n=s.domSelectionRange();return K7(t.node,t.offset,n.anchorNode,n.anchorOffset)}function nWe(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&&Nc.findFrom(i,t)}function hP(s,t){return s.dispatch(s.state.tr.setSelection(t).scrollIntoView()),!0}function Qbt(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 hP(s,new El(r.$anchor,l))}else if(r.empty){if(s.endOfTextblock(t>0?"forward":"backward")){let a=nWe(s.state,t);return a&&a instanceof Tl?hP(s,a):!1}else if(!(NN&&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)?hP(s,new Tl(t<0?s.state.doc.resolve(a.pos-i.nodeSize):a)):iie?hP(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 hP(s,new El(t>0?r.$to:r.$from));{let a=nWe(s.state,t);return a?hP(s,a):!1}}}function tTe(s){return s.nodeType==3?s.nodeValue.length:s.childNodes.length}function Eee(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 j$(s,t){return t<0?BYs(s):$Ys(s)}function BYs(s){let t=s.domSelectionRange(),n=t.focusNode,r=t.focusOffset;if(!n)return;let a,i,l=!1;for(sk&&n.nodeType==1&&r0){if(n.nodeType!=1)break;{let o=n.childNodes[r-1];if(Eee(o,-1))a=n,i=--r;else if(o.nodeType==3)n=o,r=n.nodeValue.length;else break}}else{if(Xqt(n))break;{let o=n.previousSibling;for(;o&&Eee(o,-1);)a=n.parentNode,i=ab(o),o=o.previousSibling;if(o)n=o,r=tTe(n);else{if(n=n.parentNode,n==s.dom)break;r=0}}}l?rWe(s,n,r):a&&rWe(s,a,i)}function $Ys(s){let t=s.domSelectionRange(),n=t.focusNode,r=t.focusOffset;if(!n)return;let a=tTe(n),i,l;for(;;)if(r{s.state==a&&qE(s)},50)}function Jbt(s,t){let n=s.state.doc.resolve(t);if(!(mb||Dqt)&&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 e1t(s,t,n){let r=s.state.selection;if(r instanceof El&&!r.empty||n.indexOf("s")>-1||NN&&n.indexOf("m")>-1)return!1;let{$from:a,$to:i}=r;if(!a.parent.inlineContent||s.endOfTextblock(t<0?"up":"down")){let l=nWe(s.state,t);if(l&&l instanceof Tl)return hP(s,l)}if(!a.parent.inlineContent){let l=t<0?a:i,o=r instanceof p2?Nc.near(l,t):Nc.findFrom(l,t);return o?hP(s,o):!1}return!1}function t1t(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 s1t(s,t,n){s.domObserver.stop(),t.contentEditable=n,s.domObserver.start()}function VYs(s){if(!N1||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;s1t(s,r,"true"),setTimeout(()=>s1t(s,r,"false"),20)}return!1}function HYs(s){let t="";return s.ctrlKey&&(t+="c"),s.metaKey&&(t+="m"),s.altKey&&(t+="a"),s.shiftKey&&(t+="s"),t}function GYs(s,t){let n=t.keyCode,r=HYs(t);if(n==8||NN&&n==72&&r=="c")return t1t(s,-1)||j$(s,-1);if(n==46&&!t.shiftKey||NN&&n==68&&r=="c")return t1t(s,1)||j$(s,1);if(n==13||n==27)return!0;if(n==37||NN&&n==66&&r=="c"){let a=n==37?Jbt(s,s.state.selection.from)=="ltr"?-1:1:-1;return Qbt(s,a,r)||j$(s,a)}else if(n==39||NN&&n==70&&r=="c"){let a=n==39?Jbt(s,s.state.selection.from)=="ltr"?1:-1:1;return Qbt(s,a,r)||j$(s,a)}else{if(n==38||NN&&n==80&&r=="c")return e1t(s,-1,r)||j$(s,-1);if(n==40||NN&&n==78&&r=="c")return VYs(s)||e1t(s,1,r)||j$(s,1);if(r==(NN?"m":"c")&&(n==66||n==73||n==89||n==90))return!0}return!1}function ynt(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")||$B.fromSchema(s.state.schema),o=nVt(),c=o.createElement("div");c.appendChild(l.serializeFragment(r,{document:o}));let d=c.firstChild,u,h=0;for(;d&&d.nodeType==1&&(u=sVt[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(ui.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=$B.fromSchema(f);l=document.createElement("div"),t.split(/(?:\r\n?|\n)+/).forEach(x=>{let y=l.appendChild(document.createElement("p"));x&&y.appendChild(g.serializeNode(f.text(x,m)))})}}else s.someProp("transformPastedHTML",h=>{n=h(n,s)}),l=ZYs(n),iie&&XYs(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")||See.fromSchema(s.state.schema)).parseSlice(l,{preserveWhitespace:!!(c||u),context:a,ruleFromNode(m){return m.nodeName=="BR"&&!m.nextSibling&&m.parentNode&&!WYs.test(m.parentNode.nodeName)?{ignore:!0}:null}})),u)o=QYs(n1t(o,+u[1],+u[2]),u[4]);else if(o=Ki.maxOpen(KYs(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 WYs=/^(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 KYs(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&&eVt(c,i,o,l[l.length-1],0))l[l.length-1]=d;else{l.length&&(l[l.length-1]=tVt(l[l.length-1],i.length));let u=Jqt(o,c);l.push(u),a=a.matchType(u.type),i=c}}),l)return ui.from(l)}return s}function Jqt(s,t,n=0){for(let r=t.length-1;r>=n;r--)s=t[r].create(null,ui.from(s));return s}function eVt(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(ui.empty,!0))),s.replaceChild(t<0?0:s.childCount-1,l.copy(o))}function n1t(s,t,n){return tn})}return IZ.createHTML(s)}function ZYs(s){let t=/^(\s*]*>)*/.exec(s);t&&(s=s.slice(t[0].length));let n=nVt(),r=n.body,a=/<([a-z][^>\s]+)/i.exec(s),i;if((i=a&&sVt[a[1].toLowerCase()])&&(s=i.map(l=>"<"+l+">").join("")+s+i.map(l=>"").reverse().join("")),r.innerHTML=YYs(s),i)for(let l=0;l=0;o-=2){let c=n.nodes[r[o]];if(!c||c.hasRequiredAttrs())break;try{a=ui.from(c.create(r[o+1],a))}catch{break}i++,l++}return new Ki(a,i,l)}const M_={},P_={},JYs={touchstart:!0,touchmove:!0};class eZs{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 tZs(s){for(let t in M_){let n=M_[t];s.dom.addEventListener(t,s.input.eventHandlers[t]=r=>{nZs(s,r)&&!vnt(s,r)&&(s.editable||!(r.type in P_))&&n(s,r)},JYs[t]?{passive:!0}:void 0)}N1&&s.dom.addEventListener("input",()=>null),iWe(s)}function bE(s,t){s.input.lastSelectionOrigin=t,s.input.lastSelectionTime=Date.now()}function sZs(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 iWe(s){s.someProp("handleDOMEvents",t=>{for(let n in t)s.input.eventHandlers[n]||s.dom.addEventListener(n,s.input.eventHandlers[n]=r=>vnt(s,r))})}function vnt(s,t){return s.someProp("handleDOMEvents",n=>{let r=n[t.type];return r?r(s,t)||t.defaultPrevented:!1})}function nZs(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 rZs(s,t){!vnt(s,t)&&M_[t.type]&&(s.editable||!(t.type in P_))&&M_[t.type](s,t)}P_.keydown=(s,t)=>{let n=t;if(s.input.shiftKey=n.keyCode==16||n.shiftKey,!oVt(s)&&(s.input.lastKeyCode=n.keyCode,s.input.lastKeyCodeTime=Date.now(),!(vE&&mb&&n.keyCode==13)))if(n.keyCode!=229&&s.domObserver.forceFlush(),IG&&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,WO(13,"Enter"))),s.input.lastIOSEnter=0)},200)}else s.someProp("handleKeyDown",r=>r(s,n))||GYs(s,n)?n.preventDefault():bE(s,"key")};P_.keyup=(s,t)=>{t.keyCode==16&&(s.input.shiftKey=!1)};P_.keypress=(s,t)=>{let n=t;if(oVt(s)||!n.charCode||n.ctrlKey&&!n.altKey||NN&&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 lie(s){return{left:s.clientX,top:s.clientY}}function aZs(s,t){let n=t.x-s.clientX,r=t.y-s.clientY;return n*n+r*r<100}function bnt(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 cie(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 iZs(s,t){if(t==-1)return!1;let n=s.state.doc.resolve(t),r=n.nodeAfter;return r&&r.isAtom&&Tl.isSelectable(r)?(cie(s,new Tl(n)),!0):!1}function oZs(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?(cie(s,Tl.create(s.state.doc,a)),!0):!1}function lZs(s,t,n,r,a){return bnt(s,"handleClickOn",t,n,r)||s.someProp("handleClick",i=>i(s,t,r))||(a?oZs(s,n):iZs(s,n))}function cZs(s,t,n,r){return bnt(s,"handleDoubleClickOn",t,n,r)||s.someProp("handleDoubleClick",a=>a(s,t,r))}function dZs(s,t,n,r){return bnt(s,"handleTripleClickOn",t,n,r)||s.someProp("handleTripleClick",a=>a(s,t,r))||uZs(s,n,r)}function uZs(s,t,n){if(n.button!=0)return!1;let r=rVt(s,t,!0),a=s.state.doc;return r?(cie(s,r),r instanceof El&&a.eq(s.state.doc)&&(s.input.mouseDown=new mZs(s,r)),!0):!1}function rVt(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 _nt(s){return sTe(s)}const aVt=NN?"metaKey":"ctrlKey";M_.mousedown=(s,t)=>{let n=t;s.input.shiftKey=n.shiftKey;let r=_nt(s),a=Date.now(),i="singleClick";a-s.input.lastClick.time<500&&aZs(n,s.input.lastClick)&&!n[aVt]&&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(lie(n));l&&(i=="singleClick"?s.input.mouseDown=new hZs(s,l,n,!!r):(i=="doubleClick"?cZs:dZs)(s,l.pos,l.inside,n)?n.preventDefault():bE(s,"pointer"))};class iVt{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 hZs extends iVt{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[aVt],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&&sk&&!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()),bE(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||qE(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(lie(t))),this.updateAllowDefault(t),this.allowDefault||!n?bE(this.view,"pointer"):lZs(this.view,n.pos,n.inside,t,this.selectNode)?t.preventDefault():t.button==0&&(this.flushed||N1&&this.mightDrag&&!this.mightDrag.node.isAtom||mb&&!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)?(cie(this.view,Nc.near(this.view.state.doc.resolve(n.pos))),t.preventDefault()):bE(this.view,"pointer")}move(t){this.updateAllowDefault(t),bE(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 mZs extends iVt{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(),bE(this.view,"pointer");let n=this.view.posAtCoords(lie(t)),r=n&&rVt(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(),_nt(s),bE(s,"pointer")};M_.touchmove=s=>{s.input.lastTouch=Date.now(),bE(s,"pointer")};M_.contextmenu=s=>_nt(s);function oVt(s,t){return s.composing?!0:N1&&Math.abs(Date.now()-s.input.compositionEndedAt)<500?(s.input.compositionEndedAt=-2e8,!0):!1}const fZs=vE?5e3:-1;P_.compositionstart=P_.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)||mb&&Dqt&&pZs(s)))s.markCursor=s.state.storedMarks||n.marks(),sTe(s,!0),s.markCursor=null;else if(sTe(s,!t.selection.empty),sk&&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}lVt(s,fZs)};function pZs(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"}P_.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++,lVt(s,20))};function lVt(s,t){clearTimeout(s.input.composingTimeout),t>-1&&(s.input.composingTimeout=setTimeout(()=>sTe(s),t))}function cVt(s){for(s.composing&&(s.input.composing=!1,s.input.compositionEndedAt=Date.now());s.input.compositionNodes.length>0;)s.input.compositionNodes.pop().markParentsDirty()}function gZs(s){let t=s.domSelectionRange();if(!t.focusNode)return null;let n=oYs(t.focusNode,t.focusOffset),r=lYs(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 sTe(s,t=!1){if(!(vE&&s.domObserver.flushingSoon>=0)){if(s.domObserver.forceFlush(),cVt(s),t||s.docView&&s.docView.dirty){let n=gnt(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 xZs(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 pse=Mw&&iL<15||IG&&hYs<604;M_.copy=P_.cut=(s,t)=>{let n=t,r=s.state.selection,a=n.type=="cut";if(r.empty)return;let i=pse?null:n.clipboardData,l=r.content(),{dom:o,text:c}=ynt(s,l);i?(n.preventDefault(),i.clearData(),i.setData("text/html",o.innerHTML),i.setData("text/plain",c)):xZs(s,o),a&&s.dispatch(s.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function yZs(s){return s.openStart==0&&s.openEnd==0&&s.content.childCount==1?s.content.firstChild:null}function vZs(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?gse(s,r.value,null,a,t):gse(s,r.textContent,r.innerHTML,a,t)},50)}function gse(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=yZs(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 dVt(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," "):""}P_.paste=(s,t)=>{let n=t;if(s.composing&&!vE)return;let r=pse?null:n.clipboardData,a=s.input.shiftKey&&s.input.lastKeyCode!=45;r&&gse(s,dVt(r),r.getData("text/html"),a,n)?n.preventDefault():vZs(s,n)};class uVt{constructor(t,n,r){this.slice=t,this.move=n,this.node=r}}const bZs=NN?"altKey":"ctrlKey";function hVt(s,t){let n;return s.someProp("dragCopies",r=>{n=n||r(t)}),n!=null?!n:!t[bZs]}M_.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(lie(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}=ynt(s,o);(!n.dataTransfer.files.length||!mb||Rqt>120)&&n.dataTransfer.clearData(),n.dataTransfer.setData(pse?"Text":"text/html",c.innerHTML),n.dataTransfer.effectAllowed="copyMove",pse||n.dataTransfer.setData("text/plain",d),s.dragging=new uVt(u,hVt(s,n),l)};M_.dragend=s=>{let t=s.dragging;window.setTimeout(()=>{s.dragging==t&&(s.dragging=null)},50)};P_.dragover=P_.dragenter=(s,t)=>t.preventDefault();P_.drop=(s,t)=>{try{_Zs(s,t,s.dragging)}finally{s.dragging=null}};function _Zs(s,t,n){if(!t.dataTransfer)return;let r=s.posAtCoords(lie(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,dVt(t.dataTransfer),pse?null:t.dataTransfer.getData("text/html"),!1,a);let l=!!(n&&hVt(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?Sqt(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,y,v)=>f=v),c.setSelection(xnt(s,m,c.doc.resolve(f)))}s.focus(),s.dispatch(c.setMeta("uiEvent","drop"))}M_.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())&&qE(s)},20))};M_.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)};M_.beforeinput=(s,t)=>{if(vE&&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,WO(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 P_)M_[s]=P_[s];function xse(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 nTe{constructor(t,n){this.toDOM=t,this.spec=n||u7,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 x_(i-r,i-r,this)}valid(){return!0}eq(t){return this==t||t instanceof nTe&&(this.spec.key&&this.spec.key==t.spec.key||this.toDOM==t.toDOM&&xse(this.spec,t.spec))}destroy(t){this.spec.destroy&&this.spec.destroy(t)}}class cL{constructor(t,n){this.attrs=t,this.spec=n||u7}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 x_(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==o1||t.maps.length==0?this:this.mapInner(t,n,0,0,r||u7)}mapInner(t,n,r,a,i){let l;for(let o=0;o{let d=c+r,u;if(u=fVt(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 cL){let d=Math.max(i,c.from)-i,u=Math.min(l,c.to)-i;da.map(t,n,u7));return kP.from(r)}forChild(t,n){if(n.isLeaf)return vx.empty;let r=[];for(let a=0;an instanceof vx)?t:t.reduce((n,r)=>n.concat(r instanceof vx?r:r.members),[]))}}forEachSet(t){for(let n=0;n{let y=x-g-(f-m);for(let v=0;vb+u-h)continue;let w=o[v]+u-h;f>=w?o[v+1]=m<=w?-2:-1:m>=u&&y&&(o[v]+=y,o[v+1]+=y)}h+=y}),u=n.maps[d].map(u,-1)}let c=!1;for(let d=0;d=r.content.size){c=!0;continue}let m=n.map(s[d+1]+i,-1),f=m-a,{index:g,offset:x}=r.content.findIndex(h),y=r.maybeChild(g);if(y&&x==h&&x+y.nodeSize==f){let v=o[d+2].mapInner(n,y,u+1,s[d]+i+1,l);v!=o1?(o[d]=h,o[d+1]=f,o[d+2]=v):(o[d+1]=-2,c=!0)}else c=!0}if(c){let d=jZs(o,s,t,n,a,i,l),u=rTe(d,r,0,l);t=u.local;for(let h=0;hn&&l.to{let d=fVt(s,o,c+n);if(d){i=!0;let u=rTe(d,o,n+c+1,r);u!=o1&&a.push(c,c+o.nodeSize,u)}});let l=mVt(i?pVt(s):s,-n).sort(h7);for(let o=0;o0;)t++;s.splice(t,0,n)}function iBe(s){let t=[];return s.someProp("decorations",n=>{let r=n(s.state);r&&r!=o1&&t.push(r)}),s.cursorWrapper&&t.push(vx.create(s.state.doc,[s.cursorWrapper.deco])),kP.from(t)}const NZs={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},kZs=Mw&&iL<=11;class SZs{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 CZs{constructor(t,n){this.view=t,this.handleDOMChange=n,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new SZs,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():N1&&t.composing&&r.some(a=>a.type=="childList"&&a.target.nodeName=="TR")?(t.input.badSafariComposition=!0,this.flushSoon()):this.flush()}),kZs&&(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,NZs)),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(Xbt(this.view)){if(this.suppressingSelectionUpdates)return qE(this.view);if(Mw&&iL<=11&&!this.view.state.selection.empty){let t=this.view.domSelectionRange();if(t.focusNode&&K7(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=PG(i))n.add(i);for(let i=t.anchorNode;i;i=PG(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)&&Xbt(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||mb&&(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(sk&&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||TZs(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),AZs(t)),t.input.badSafariComposition&&(t.input.badSafariComposition=!1,MZs(t,c)),this.handleDOMChange(i,l,o,c),t.docView&&t.docView.dirty?t.updateState(t.state):this.currentSelection.eq(r)||qE(t),this.currentSelection.set(r))}registerMutation(t,n){if(n.indexOf(t.target)>-1)return null;let r=this.view.docView.nearestDesc(t.target);if(t.type=="attributes"&&(r==this.view.docView||t.attributeName=="contenteditable"||t.attributeName=="style"&&!t.oldValue&&!t.target.getAttribute("style"))||!r||r.ignoreMutation(t))return null;if(t.type=="childList"){for(let u=0;ui;v--){let b=a.childNodes[v-1],w=b.pmViewDesc;if(b.nodeName=="BR"&&!w){l=v;break}if(!w||w.size)break}let m=s.state.doc,f=s.someProp("domParser")||See.fromSchema(s.state.schema),g=m.resolve(o),x=null,y=f.parse(a,{topNode:g.parent,topMatch:g.parent.contentMatchAt(g.index()),topOpen:!0,from:i,to:l,preserveWhitespace:g.parent.type.whitespace=="pre"?"full":!0,findPositions:u,ruleFromNode:IZs(r),context:g});if(u&&u[0].pos!=null){let v=u[0].pos,b=u[1]&&u[1].pos;b==null&&(b=v),x={anchor:v+o,head:b+o}}return{doc:y,sel:x,from:o,to:c}}const IZs=s=>t=>{let n=t.pmViewDesc;if(n)return n.parseRule(s);if(t.nodeName=="BR"&&t.parentNode){if(N1&&/^(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||N1&&/^(tr|table)$/i.test(t.parentNode.nodeName))return{ignore:!0}}else if(t.nodeName=="IMG"&&t.getAttribute("mark-placeholder"))return{ignore:!0};return null},LZs=/^(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 RZs(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=gnt(s,I);if(P&&!s.state.selection.eq(P)){if(mb&&vE&&s.input.lastKeyCode===13&&Date.now()-100D(s,WO(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=PZs(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||vE)&&a.some(I=>I.nodeType==1&&!LZs.test(I.nodeName))&&(!g||g.endA>=g.endB)&&s.someProp("handleKeyDown",I=>I(s,WO(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=l1t(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)),Mw&&iL<=11&&g.endB==g.start+1&&g.endA==g.start&&g.start>d.from&&d.doc.textBetween(g.start-d.from-1,g.start-d.from+1)=="  "&&(g.start--,g.endA--,g.endB--);let x=d.doc.resolveNoCache(g.start-d.from),y=d.doc.resolveNoCache(g.endB-d.from),v=u.resolve(g.start),b=x.sameParent(y)&&x.parent.inlineContent&&v.end()>=g.endA;if((IG&&s.input.lastIOSEnter>Date.now()-225&&(!b||a.some(I=>I.nodeName=="DIV"||I.nodeName=="P"))||!b&&OZs(d.doc,x.pos,y.pos))&&s.someProp("handleKeyDown",I=>I(s,WO(13,"Enter")))){s.input.lastIOSEnter=0;return}if(s.state.selection.anchor>g.start&&FZs(u,g.start,g.endA,x,y)&&s.someProp("handleKeyDown",I=>I(s,WO(8,"Backspace")))){vE&&mb&&s.domObserver.suppressSelectionUpdates();return}mb&&g.endB==g.start&&(s.input.lastChromeDelete=Date.now()),vE&&!b&&x.start()!=y.start()&&y.parentOffset==0&&x.depth==y.depth&&d.sel&&d.sel.anchor==d.sel.head&&d.sel.head==g.endA&&(g.endB-=2,y=d.doc.resolveNoCache(g.endB-d.from),setTimeout(()=>{s.someProp("handleKeyDown",function(I){return I(s,WO(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=l1t(s,P.doc,d.sel);R&&!(mb&&s.composing&&R.empty&&(g.start!=g.endB||s.input.lastChromeDeleteqE(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=DZs(x.parent.content.cut(x.parentOffset,y.parentOffset),v.parent.content.cut(v.parentOffset,g.endA-v.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()==y.index()-(y.textOffset?0:1)){let I=x.parent.textBetween(x.parentOffset,y.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 l1t(s,t,n){return Math.max(n.anchor,n.head)>t.content.size?null:xnt(s,t.resolve(n.anchor),t.resolve(n.head))}function DZs(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||oBe(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 zZs(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 gVt{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 eZs,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=n,this.state=n.state,this.directPlugins=n.plugins||[],this.directPlugins.forEach(m1t),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=u1t(this),d1t(this),this.nodeViews=h1t(this),this.docView=Hbt(this.state.doc,c1t(this),iBe(this),this.dom,this),this.domObserver=new CZs(this,(r,a,i,l)=>RZs(this,r,a,i,l)),this.domObserver.start(),tZs(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&&iWe(this);let n=this._props;this._props=t,t.plugins&&(t.plugins.forEach(m1t),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&&(cVt(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=h1t(this);$Zs(f,this.nodeViews)&&(this.nodeViews=f,i=!0)}(o||n.handleDOMEvents!=this._props.handleDOMEvents)&&iWe(this),this.editable=u1t(this),d1t(this);let c=iBe(this),d=c1t(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&&pYs(this);if(l){this.domObserver.stop();let f=h&&(Mw||mb)&&!this.composing&&!a.selection.empty&&!t.selection.empty&&BZs(a.selection,t.selection);if(h){let x=mb?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=gZs(this)),(i||!this.docView.update(t.doc,d,c,this))&&(this.docView.updateOuterDeco(d),this.docView.destroy(),this.docView=Hbt(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())&&zYs(this)&&g.delaySelUpdate())?qE(this,f):(Yqt(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&&gYs(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&&Bbt(this,n.getBoundingClientRect(),t)}else Bbt(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 wYs(this,t)}coordsAtPos(t,n=1){return $qt(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 CYs(this,n||this.state,t)}pasteHTML(t,n){return gse(this,"",t,!1,n||new ClipboardEvent("paste"))}pasteText(t,n){return gse(this,t,null,!0,n||new ClipboardEvent("paste"))}serializeForClipboard(t){return ynt(this,t)}destroy(){this.docView&&(sZs(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],iBe(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,aYs())}get isDestroyed(){return this.docView==null}dispatchEvent(t){return rZs(this,t)}domSelectionRange(){let t=this.domSelection();return t?N1&&this.root.nodeType===11&&dYs(this.dom.ownerDocument)==this.dom&&EZs(this,t)||t:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}}gVt.prototype.dispatch=function(s){let t=this._props.dispatchTransaction;t?t.call(this,s):this.updateState(this.state.apply(s))};function c1t(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"),[x_.node(0,s.state.doc.content.size,t)]}function d1t(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:x_.widget(s.state.selection.from,t,{raw:!0,marks:s.markCursor})}}else s.cursorWrapper=null}function u1t(s){return!s.someProp("editable",t=>t(s.state)===!1)}function BZs(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 h1t(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 $Zs(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 m1t(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 IL={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:"'"},aTe={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},UZs=typeof navigator<"u"&&/Mac/.test(navigator.platform),qZs=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(var ib=0;ib<10;ib++)IL[48+ib]=IL[96+ib]=String(ib);for(var ib=1;ib<=24;ib++)IL[ib+111]="F"+ib;for(var ib=65;ib<=90;ib++)IL[ib]=String.fromCharCode(ib+32),aTe[ib]=String.fromCharCode(ib);for(var lBe in IL)aTe.hasOwnProperty(lBe)||(aTe[lBe]=IL[lBe]);function VZs(s){var t=UZs&&s.metaKey&&s.shiftKey&&!s.ctrlKey&&!s.altKey||qZs&&s.shiftKey&&s.key&&s.key.length==1||s.key=="Unidentified",n=!t&&s.key||(s.shiftKey?aTe:IL)[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 HZs=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),GZs=typeof navigator<"u"&&/Win/.test(navigator.platform);function WZs(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 xVt(s,t){let{$cursor:n}=s.selection;return!n||(t?!t.endOfTextblock("backward",s):n.parentOffset>0)?null:n}const yVt=(s,t,n)=>{let r=xVt(s,n);if(!r)return!1;let a=Snt(r);if(!a){let l=r.blockRange(),o=l&&fK(l);return o==null?!1:(t&&t(s.tr.lift(l,o).scrollIntoView()),!0)}let i=a.nodeBefore;if(CVt(s,a,t,-1))return!0;if(r.parent.content.size==0&&(LG(i,"end")||Tl.isSelectable(i)))for(let l=r.depth;;l--){let o=T6e(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=xVt(s,n);if(!r)return!1;let a=Snt(r);return a?vVt(s,a,t):!1},XZs=(s,t,n)=>{let r=_Vt(s,n);if(!r)return!1;let a=Cnt(r);return a?vVt(s,a,t):!1};function vVt(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=T6e(s.doc,i,c,Ki.empty);if(!d||d.from!=i||d instanceof Ry&&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 LG(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 bVt=(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=Snt(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 Snt(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 _Vt(s,t){let{$cursor:n}=s.selection;return!n||(t?!t.endOfTextblock("forward",s):n.parentOffset{let r=_Vt(s,n);if(!r)return!1;let a=Cnt(r);if(!a)return!1;let i=a.nodeAfter;if(CVt(s,a,t,1))return!0;if(r.parent.content.size==0&&(LG(i,"start")||Tl.isSelectable(i))){let l=T6e(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||!c6(s.doc,n.from))return!1;a=n.from}else if(a=E6e(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},JZs=(s,t)=>{let n=s.selection,r;if(n instanceof Tl){if(n.node.isTextblock||!c6(s.doc,n.to))return!1;r=n.to}else if(r=E6e(s.doc,n.to,1),r==null)return!1;return t&&t(s.tr.join(r).scrollIntoView()),!0},eXs=(s,t)=>{let{$from:n,$to:r}=s.selection,a=n.blockRange(r),i=a&&fK(a);return i==null?!1:(t&&t(s.tr.lift(a,i).scrollIntoView()),!0)},NVt=(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 Ant(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=Ant(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(Nc.near(c.doc.resolve(o),1)),t(c.scrollIntoView())}return!0},kVt=(s,t)=>{let n=s.selection,{$from:r,$to:a}=n;if(n instanceof p2||r.parent.inlineContent||a.parent.inlineContent)return!1;let i=Ant(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(UE(s.doc,i))return t&&t(s.tr.split(i).scrollIntoView()),!0}let r=n.blockRange(),a=r&&fK(r);return a==null?!1:(t&&t(s.tr.lift(r,a).scrollIntoView()),!0)};function sXs(s){return(t,n)=>{if(t.selection instanceof Tl&&t.selection.node.isBlock){let{$from:f}=t.selection;return!f.parentOffset||!UE(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 p2)&&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=Ant(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=UE(r.doc,h,l.length,l);if(m||(l[0]=c?{type:c}:null,m=UE(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 nXs=sXs(),rXs=(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 aXs(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||c6(s.doc,t.pos))?!1:(n&&n(s.tr.join(t.pos).scrollIntoView()),!0)}function CVt(s,t,n,r){let a=t.nodeBefore,i=t.nodeAfter,l,o,c=a.type.spec.isolating||i.type.spec.isolating;if(!c&&aXs(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=ui.empty;for(let v=l.length-1;v>=0;v--)g=ui.from(l[v].create(null,g));g=ui.from(a.copy(g));let x=s.tr.step(new Tv(t.pos-1,f,t.pos,f,new Ki(g,1,0),l.length,!0)),y=x.doc.resolve(f+2*l.length);y.nodeAfter&&y.nodeAfter.type==a.type&&c6(x.doc,y.pos)&&x.join(y.pos),n(x.scrollIntoView())}return!0}let u=i.type.spec.isolating||r>0&&c?null:Nc.findFrom(t,1),h=u&&u.$from.blockRange(u.$to),m=h&&fK(h);if(m!=null&&m>=t.depth)return n&&n(s.tr.lift(h,m).scrollIntoView()),!0;if(d&&LG(i,"start",!0)&&LG(a,"end")){let f=a,g=[];for(;g.push(f),!f.isTextblock;)f=f.lastChild;let x=i,y=1;for(;!x.isTextblock;x=x.firstChild)y++;if(f.canReplace(f.childCount,f.childCount,x.content)){if(n){let v=ui.empty;for(let w=g.length-1;w>=0;w--)v=ui.from(g[w].copy(v));let b=s.tr.step(new Tv(t.pos-g.length,t.pos+i.nodeSize,t.pos+y,t.pos+i.nodeSize-y,new Ki(v,g.length,0),0,!0));n(b.scrollIntoView())}return!0}}return!1}function AVt(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 iXs=AVt(-1),oXs=AVt(1);function lXs(s,t=null){return function(n,r){let{$from:a,$to:i}=n.selection,l=a.blockRange(i),o=l&&hnt(l,s,t);return o?(r&&r(n.tr.wrap(l,o).scrollIntoView()),!0):!1}}function f1t(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 QEe(c,c,t.depth),t.endIndex=0;u--)i=ui.from(n[u].type.create(n[u].attrs,i));s.step(new Tv(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?mXs(t,n,s,i):fXs(t,n,i):!0:!1}}function mXs(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?ui.empty:ui.from(a))))return!1;let h=i.pos,m=h+l.nodeSize;return r.step(new Tv(h-(o?1:0),m+(c?1:0),h+1,m-1,new Ki((o?ui.empty:ui.from(a.copy(ui.empty))).append(c?ui.empty:ui.from(a.copy(ui.empty))),o?0:1,c?0:1),o?0:1)),t(r.scrollIntoView()),!0}function pXs(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=ui.from(d?s.create():null),h=new Ki(ui.from(s.create(null,ui.from(o.type.create(null,u)))),d?3:1,0),m=i.start,f=i.end;n(t.tr.step(new Tv(m-(d?3:1),f,m,f,h,1,!0)).scrollIntoView())}return!0}}function L6e(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 R6e=class{constructor(t){this.editor=t.editor,this.rawCommands=this.editor.extensionManager.commands,this.customState=t.state}get hasCustomState(){return!!this.customState}get state(){return this.customState||this.editor.state}get commands(){const{rawCommands:t,editor:n,state:r}=this,{view:a}=n,{tr:i}=r,l=this.buildProps(i);return Object.fromEntries(Object.entries(t).map(([o,c])=>[o,(...u)=>{const h=c(...u)(l);return!i.getMeta("preventDispatch")&&!this.hasCustomState&&a.dispatch(i),h}]))}get chain(){return()=>this.createChain()}get can(){return()=>this.createCan()}createChain(t,n=!0){const{rawCommands:r,editor:a,state:i}=this,{view:l}=a,o=[],c=!!t,d=t||i.tr,u=()=>(!c&&n&&!d.getMeta("preventDispatch")&&!this.hasCustomState&&l.dispatch(d),o.every(m=>m===!0)),h={...Object.fromEntries(Object.entries(r).map(([m,f])=>[m,(...x)=>{const y=this.buildProps(d,n),v=f(...x)(y);return o.push(v),h}])),run:u};return h}createCan(t){const{rawCommands:n,state:r}=this,a=!1,i=t||r.tr,l=this.buildProps(i,a);return{...Object.fromEntries(Object.entries(n).map(([c,d])=>[c,(...u)=>d(...u)({...l,dispatch:void 0})])),chain:()=>this.createChain(i,a)}}buildProps(t,n=!0){const{rawCommands:r,editor:a,state:i}=this,{view:l}=a,o={tr:t,editor:a,view:l,state:L6e({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}},gXs=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 D6e(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 EVt(s){const t=[],{nodeExtensions:n,markExtensions:r}=D6e(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 Pv(s,t){if(typeof s=="string"){if(!t.nodes[s])throw Error(`There is no node type named '${s}'. Maybe you forgot to add the extension?`);return t.nodes[s]}return s}function ep(...s){return s.filter(t=>!!t).reduce((t,n)=>{const r={...t};return Object.entries(n).forEach(([a,i])=>{if(a==="__proto__"){Object.defineProperty(r,a,{configurable:!0,enumerable:!0,value:i,writable:!0});return}if(!r[a]){r[a]=i;return}if(a==="class"){const o=i?String(i).split(" "):[],c=r[a]?r[a].split(" "):[],d=o.filter(u=>!c.includes(u));r[a]=[...c,...d].join(" ")}else if(a==="style"){const o=i?i.split(";").map(u=>u.trim()).filter(Boolean):[],c=r[a]?r[a].split(";").map(u=>u.trim()).filter(Boolean):[],d=new Map;c.forEach(u=>{const[h,m]=u.split(":").map(f=>f.trim());d.set(h,m)}),o.forEach(u=>{const[h,m]=u.split(":").map(f=>f.trim());d.set(h,m)}),r[a]=Array.from(d.entries()).map(([u,h])=>`${u}: ${h}`).join("; ")}else r[a]=i}),r},{})}function oWe(s,t){return t.filter(n=>n.type===s.type.name).filter(n=>n.attribute.rendered).map(n=>n.attribute.renderHTML?n.attribute.renderHTML(s.attrs)||{}:{[n.name]:s.attrs[n.name]}).reduce((n,r)=>ep(n,r),{})}function TVt(s){return typeof s=="function"}function wd(s,t=void 0,...n){return TVt(s)?t?s.bind(t)(...n):s(...n):s}function xXs(s={}){return Object.keys(s).length===0&&s.constructor===Object}function yXs(s){return typeof s!="string"?s:s.match(/^[+-]?(?:\d*\.)?\d+$/)?Number(s):s==="true"?!0:s==="false"?!1:s}function p1t(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):yXs(n.getAttribute(l.name));return o==null?i:{...i,[l.name]:o}},{});return{...r,...a}}}}function g1t(s){return Object.fromEntries(Object.entries(s).filter(([t,n])=>t==="attrs"&&xXs(n)?!1:n!=null))}function vXs(s,t){var n;const r=EVt(s),{nodeExtensions:a,markExtensions:i}=D6e(s),l=(n=a.find(d=>Uo(d,"topNode")))===null||n===void 0?void 0:n.name,o=Object.fromEntries(a.map(d=>{const u=r.filter(v=>v.type===d.name),h={name:d.name,options:d.options,storage:d.storage,editor:t},m=s.reduce((v,b)=>{const w=Uo(b,"extendNodeSchema",h);return{...v,...w?w(d):{}}},{}),f=g1t({...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(v=>{var b;return[v.name,{default:(b=v==null?void 0:v.attribute)===null||b===void 0?void 0:b.default}]}))}),g=wd(Uo(d,"parseHTML",h));g&&(f.parseDOM=g.map(v=>p1t(v,u)));const x=Uo(d,"renderHTML",h);x&&(f.toDOM=v=>x({node:v,HTMLAttributes:oWe(v,u)}));const y=Uo(d,"renderText",h);return y&&(f.toText=y),[d.name,f]})),c=Object.fromEntries(i.map(d=>{const u=r.filter(y=>y.type===d.name),h={name:d.name,options:d.options,storage:d.storage,editor:t},m=s.reduce((y,v)=>{const b=Uo(v,"extendMarkSchema",h);return{...y,...b?b(d):{}}},{}),f=g1t({...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(y=>{var v;return[y.name,{default:(v=y==null?void 0:y.attribute)===null||v===void 0?void 0:v.default}]}))}),g=wd(Uo(d,"parseHTML",h));g&&(f.parseDOM=g.map(y=>p1t(y,u)));const x=Uo(d,"renderHTML",h);return x&&(f.toDOM=y=>x({mark:y,HTMLAttributes:oWe(y,u)})),[d.name,f]}));return new pqt({topNode:l,nodes:o,marks:c})}function dBe(s,t){return t.nodes[s]||t.marks[s]||null}function x1t(s,t){return Array.isArray(t)?t.some(n=>(typeof n=="string"?n:n.name)===s.name):t}function Tnt(s,t){const n=$B.fromSchema(t).serializeFragment(s),a=document.implementation.createHTMLDocument().createElement("div");return a.appendChild(n),a.innerHTML}const bXs=(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 Mnt(s){return Object.prototype.toString.call(s)==="[object RegExp]"}class F6e{constructor(t){this.find=t.find,this.handler=t.handler}}const _Xs=(s,t)=>{if(Mnt(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 lde(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=bXs(d)+i;return l.forEach(m=>{if(u)return;const f=_Xs(h,m.find);if(!f)return;const g=c.state.tr,x=L6e({state:c.state,transaction:g}),y={from:r-(f[0].length-i.length),to:a},{commands:v,chain:b,can:w}=new R6e({editor:n,state:x});m.handler({state:x,range:y,match:f,commands:v,chain:b,can:w})===null||!g.steps.length||(g.setMeta(o,{transform:g,from:r,to:a,text:i}),c.dispatch(g),u=!0)}),u}function wXs(s){const{editor:t,rules:n}=s,r=new z0({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=Tnt(ui.from(u),l.schema);const{from:h}=c,m=h+u.length;lde({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 lde({editor:t,from:i,to:l,text:o,rules:n,plugin:r})},handleDOMEvents:{compositionend:a=>(setTimeout(()=>{const{$cursor:i}=a.state.selection;i&&lde({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?lde({editor:t,from:l.pos,to:l.pos,text:` `,rules:n,plugin:r}):!1}},isInputRules:!0});return r}function jXs(s){return Object.prototype.toString.call(s).slice(8,-1)}function cde(s){return jXs(s)!=="Object"?!1:s.constructor===Object&&Object.getPrototypeOf(s)===Object.prototype}function O6e(s,t){const n={...s};return cde(s)&&cde(t)&&Object.keys(t).forEach(r=>{cde(t[r])&&cde(s[r])?n[r]=O6e(s[r],t[r]):n[r]=t[r]}),n}class pC{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 pC(t)}configure(t={}){const n=this.extend({...this.config,addOptions:()=>O6e(this.options,t)});return n.name=this.name,n.parent=this.parent,n}extend(t={}){const n=new pC(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 NXs(s){return typeof s=="number"}class MVt{constructor(t){this.find=t.find,this.handler=t.handler}}const kXs=(s,t,n)=>{if(Mnt(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 SXs(s){const{editor:t,state:n,from:r,to:a,rule:i,pasteEvent:l,dropEvent:o}=s,{commands:c,chain:d,can:u}=new R6e({editor:t,state:n}),h=[];return n.doc.nodesBetween(r,a,(f,g)=>{if(!f.isTextblock||f.type.spec.code)return;const x=Math.max(r,g),y=Math.min(a,g+f.content.size),v=f.textBetween(x-g,y-g,void 0,"");kXs(v,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 dde=null;const CXs=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 AXs(s){const{editor:t,rules:n}=s;let r=null,a=!1,i=!1,l=typeof ClipboardEvent<"u"?new ClipboardEvent("paste"):null,o;try{o=typeof DragEvent<"u"?new DragEvent("drop"):null}catch{o=null}const c=({state:u,from:h,to:m,rule:f,pasteEvt:g})=>{const x=u.tr,y=L6e({state:u,transaction:x});if(!(!SXs({editor:t,state:y,from:Math.max(h-1,0),to:m.b-1,rule:f,pasteEvent:g,dropEvent:o})||!x.steps.length)){try{o=typeof DragEvent<"u"?new DragEvent("drop"):null}catch{o=null}return l=typeof ClipboardEvent<"u"?new ClipboardEvent("paste"):null,x}};return n.map(u=>new z0({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&&(dde=t)},f=()=>{dde&&(dde=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=dde;f!=null&&f.isEditable&&setTimeout(()=>{const g=f.state.selection;g&&f.commands.deleteRange({from:g.from,to:g.to})},10)}return!1},paste:(h,m)=>{var f;const g=(f=m.clipboardData)===null||f===void 0?void 0:f.getData("text/html");return l=m,a=!!(g!=null&&g.includes("data-pm-slice")),!1}}},appendTransaction:(h,m,f)=>{const g=h[0],x=g.getMeta("uiEvent")==="paste"&&!a,y=g.getMeta("uiEvent")==="drop"&&!i,v=g.getMeta("applyPasteRules"),b=!!v;if(!x&&!y&&!b)return;if(b){let{text:A}=v;typeof A=="string"?A=A:A=Tnt(ui.from(A),f.schema);const{from:E}=v,I=E+A.length,P=CXs(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(!(!NXs(w)||!S||w===S.b))return c({rule:u,state:f,from:w,to:S,pasteEvt:l})}}))}function EXs(s){const t=s.filter((n,r)=>s.indexOf(n)!==r);return Array.from(new Set(t))}class JU{constructor(t,n){this.splittableMarks=[],this.editor=n,this.extensions=JU.resolve(t),this.schema=vXs(this.extensions,n),this.setupExtensions()}static resolve(t){const n=JU.sort(JU.flatten(t)),r=EXs(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:dBe(n.name,this.schema)},a=Uo(n,"addCommands",r);return a?{...t,...a()}:t},{})}get plugins(){const{editor:t}=this,n=JU.sort([...this.extensions].reverse()),r=[],a=[],i=n.map(l=>{const o={name:l.name,options:l.options,storage:l.storage,editor:t,type:dBe(l.name,this.schema)},c=[],d=Uo(l,"addKeyboardShortcuts",o);let u={};if(l.type==="mark"&&Uo(l,"exitable",o)&&(u.ArrowRight=()=>pC.handleExit({editor:t,mark:l})),d){const x=Object.fromEntries(Object.entries(d()).map(([y,v])=>[y,()=>v({editor:t})]));u={...u,...x}}const h=YZs(u);c.push(h);const m=Uo(l,"addInputRules",o);x1t(l,t.options.enableInputRules)&&m&&r.push(...m());const f=Uo(l,"addPasteRules",o);x1t(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[wXs({editor:t,rules:r}),...AXs({editor:t,rules:a}),...i]}get attributes(){return EVt(this.extensions)}get nodeViews(){const{editor:t}=this,{nodeExtensions:n}=D6e(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:Pv(r.name,this.schema)},l=Uo(r,"addNodeView",i);if(!l)return[];const o=(c,d,u,h,m)=>{const f=oWe(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:dBe(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 Cb{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 Cb(t)}configure(t={}){const n=this.extend({...this.config,addOptions:()=>O6e(this.options,t)});return n.name=this.name,n.parent=this.parent,n}extend(t={}){const n=new Cb({...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 PVt(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 IVt(s){return Object.fromEntries(Object.entries(s.nodes).filter(([,t])=>t.spec.toText).map(([t,n])=>[t,n.spec.toText]))}const TXs=Cb.create({name:"clipboardTextSerializer",addOptions(){return{blockSeparator:void 0}},addProseMirrorPlugins(){return[new z0({key:new E1("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=IVt(n);return PVt(r,{from:l,to:o},{...this.options.blockSeparator!==void 0?{blockSeparator:this.options.blockSeparator}:{},textSerializers:c})}}})]}}),MXs=()=>({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),PXs=(s=!1)=>({commands:t})=>t.setContent("",s),IXs=()=>({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=fK(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},LXs=s=>t=>s(t),RXs=()=>({state:s,dispatch:t})=>kVt(s,t),DXs=(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},FXs=()=>({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},OXs=s=>({tr:t,state:n,dispatch:r})=>{const a=Pv(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},zXs=s=>({tr:t,dispatch:n})=>{const{from:r,to:a}=s;return n&&t.delete(r,a),!0},BXs=()=>({state:s,dispatch:t})=>knt(s,t),$Xs=()=>({commands:s})=>s.keyboardShortcut("Enter"),UXs=()=>({state:s,dispatch:t})=>tXs(s,t);function iTe(s,t,n={strict:!0}){const r=Object.keys(t);return r.length?r.every(a=>n.strict?t[a]===s[a]:Mnt(t[a])?t[a].test(s[a]):t[a]===s[a]):!0}function LVt(s,t,n={}){return s.find(r=>r.type===t&&iTe(Object.fromEntries(Object.keys(n).map(a=>[a,r.attrs[a]])),n))}function y1t(s,t,n={}){return!!LVt(s,t,n)}function Pnt(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),!LVt([...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&&y1t([...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=u6(s,r.schema),{doc:l,selection:o}=n,{$from:c,from:d,to:u}=o;if(a){const h=Pnt(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},VXs=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=()=>{(oTe()||v1t())&&r.dom.focus(),requestAnimationFrame(()=>{n.isDestroyed||(r.focus(),HXs()&&!oTe()&&!v1t()&&r.dom.focus({preventScroll:!0}))})};if(r.hasFocus()&&s===null||s===!1)return!0;if(i&&s===null&&!RVt(n.state.selection))return l(),!0;const o=DVt(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},WXs=(s,t)=>n=>s.every((r,a)=>t(r,{...n,index:a})),KXs=(s,t)=>({tr:n,commands:r})=>r.insertContentAt({from:n.selection.from,to:n.selection.to},s,t),FVt=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&&FVt(r)}return s};function ude(s){const t=`${s}`,n=new window.DOMParser().parseFromString(t,"text/html").body;return FVt(n)}function yse(s,t,n){if(s instanceof aL||s instanceof ui)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 ui.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),yse("",t,n)}if(a){if(n.errorOnInvalidContent){let l=!1,o="";const c=new pqt({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?See.fromSchema(c).parseSlice(ude(s),n.parseOptions):See.fromSchema(c).parse(ude(s),n.parseOptions),n.errorOnInvalidContent&&l)throw new Error("[tiptap error]: Invalid HTML content",{cause:new Error(`Invalid element found: ${o}`)})}const i=See.fromSchema(t);return n.slice?i.parseSlice(ude(s),n.parseOptions).content:i.parse(ude(s),n.parseOptions)}return yse("",t,n)}function YXs(s,t,n){const r=s.steps.length-1;if(r{l===0&&(l=u)}),s.setSelection(Nc.near(s.doc.resolve(l),n))}const ZXs=s=>!("type"in s),XXs=(s,t,n)=>({tr:r,dispatch:a,editor:i})=>{var l;if(a){n={parseOptions:i.options.parseOptions,updateSelection:!0,applyInputRules:!1,applyPasteRules:!1,...n};let o;const c=y=>{i.emit("contentError",{editor:i,error:y,disableCollaboration:()=>{i.storage.collaboration&&(i.storage.collaboration.isDisabled=!0)}})},d={preserveWhitespace:"full",...n.parseOptions};if(!n.errorOnInvalidContent&&!i.options.enableContentCheck&&i.options.emitContentError)try{yse(t,i.schema,{parseOptions:d,errorOnInvalidContent:!0})}catch(y){c(y)}try{o=yse(t,i.schema,{parseOptions:d,errorOnInvalidContent:(l=n.errorOnInvalidContent)!==null&&l!==void 0?l:i.options.enableContentCheck})}catch(y){return c(y),!1}let{from:u,to:h}=typeof s=="number"?{from:s,to:s}:{from:s.from,to:s.to},m=!0,f=!0;if((ZXs(o)?o:[o]).forEach(y=>{y.check(),m=m?y.isText&&y.marks.length===0:!1,f=f?y.isBlock:!1}),u===h&&f){const{parent:y}=r.doc.resolve(u);y.isTextblock&&!y.type.spec.code&&!y.childCount&&(u-=1,h+=1)}let x;if(m){if(Array.isArray(t))x=t.map(y=>y.text||"").join("");else if(t instanceof ui){let y="";t.forEach(v=>{v.text&&(y+=v.text)}),x=y}else typeof t=="object"&&t&&t.text?x=t.text:x=t;r.insertText(x,u,h)}else x=o,r.replaceWith(u,h,x);n.updateSelection&&YXs(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},QXs=()=>({state:s,dispatch:t})=>QZs(s,t),JXs=()=>({state:s,dispatch:t})=>JZs(s,t),eQs=()=>({state:s,dispatch:t})=>yVt(s,t),tQs=()=>({state:s,dispatch:t})=>wVt(s,t),sQs=()=>({state:s,dispatch:t,tr:n})=>{try{const r=E6e(s.doc,s.selection.$from.pos,-1);return r==null?!1:(n.join(r,2),t&&t(n),!0)}catch{return!1}},nQs=()=>({state:s,dispatch:t,tr:n})=>{try{const r=E6e(s.doc,s.selection.$from.pos,1);return r==null?!1:(n.join(r,2),t&&t(n),!0)}catch{return!1}},rQs=()=>({state:s,dispatch:t})=>ZZs(s,t),aQs=()=>({state:s,dispatch:t})=>XZs(s,t);function OVt(){return typeof navigator<"u"?/Mac/.test(navigator.platform):!1}function iQs(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=iQs(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 vse(s,t,n={}){const{from:r,to:a,empty:i}=s.selection,l=t?Pv(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=>iTe(h.node.attrs,n,{strict:!1}));return i?!!d.length:d.reduce((h,m)=>h+m.to-m.from,0)>=c}const lQs=(s,t={})=>({state:n,dispatch:r})=>{const a=Pv(s,n.schema);return vse(n,a,t)?eXs(n,r):!1},cQs=()=>({state:s,dispatch:t})=>SVt(s,t),dQs=s=>({state:t,dispatch:n})=>{const r=Pv(s,t.schema);return hXs(r)(t,n)},uQs=()=>({state:s,dispatch:t})=>NVt(s,t);function z6e(s,t){return t.nodes[s]?"node":t.marks[s]?"mark":null}function b1t(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 hQs=(s,t)=>({tr:n,state:r,dispatch:a})=>{let i=null,l=null;const o=z6e(typeof s=="string"?s:s.name,r.schema);return o?(o==="node"&&(i=Pv(s,r.schema)),o==="mark"&&(l=u6(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,b1t(d.attrs,t)),l&&d.marks.length&&d.marks.forEach(h=>{l===h.type&&n.addMark(u,u+d.nodeSize,l.create(b1t(h.attrs,t)))})})}),!0):!1},mQs=()=>({tr:s,dispatch:t})=>(t&&s.scrollIntoView(),!0),fQs=()=>({tr:s,dispatch:t})=>{if(t){const n=new p2(s.doc);s.setSelection(n)}return!0},pQs=()=>({state:s,dispatch:t})=>bVt(s,t),gQs=()=>({state:s,dispatch:t})=>jVt(s,t),xQs=()=>({state:s,dispatch:t})=>rXs(s,t),yQs=()=>({state:s,dispatch:t})=>oXs(s,t),vQs=()=>({state:s,dispatch:t})=>iXs(s,t);function lWe(s,t,n={},r={}){return yse(s,t,{slice:!1,parseOptions:n,errorOnInvalidContent:r.errorOnInvalidContent})}const bQs=(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=lWe(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 zVt(s,t){const n=u6(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 _Qs(s,t){const n=new mnt(s);return t.forEach(r=>{r.steps.forEach(a=>{n.step(a)})}),n}function wQs(s){for(let t=0;t{n(a)&&r.push({node:a,pos:i})}),r}function BVt(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 Int(s){return t=>BVt(t.$from,s)}function NQs(s,t){const n={from:0,to:s.content.size};return PVt(s,n,t)}function kQs(s,t){const n=Pv(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 $Vt(s,t){const n=z6e(typeof t=="string"?t:t.name,s.schema);return n==="node"?kQs(s,t):n==="mark"?zVt(s,t):{}}function SQs(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 CQs(s){const t=SQs(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 AQs(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}})})}),CQs(r)}function Lnt(s,t,n){const r=[];return s===t?n.resolve(s).marks().forEach(a=>{const i=n.resolve(s),l=Pnt(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 h3e(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 cWe(s,t,n={}){const{empty:r,ranges:a}=s.selection,i=t?u6(t,s.schema):null;if(r)return!!(s.storedMarks||s.selection.$from.marks()).filter(h=>i?i.name===h.type.name:!0).find(h=>iTe(h.attrs,n,{strict:!1}));let l=0;const o=[];if(a.forEach(({$from:h,$to:m})=>{const f=h.pos,g=m.pos;s.doc.nodesBetween(f,g,(x,y)=>{if(!x.isText&&!x.marks.length)return;const v=Math.max(f,y),b=Math.min(g,y+x.nodeSize),w=b-v;l+=w,o.push(...x.marks.map(S=>({mark:S,from:v,to:b})))})}),l===0)return!1;const c=o.filter(h=>i?i.name===h.mark.type.name:!0).filter(h=>iTe(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 EQs(s,t,n={}){if(!t)return vse(s,null,n)||cWe(s,null,n);const r=z6e(t,s.schema);return r==="node"?vse(s,t,n):r==="mark"?cWe(s,t,n):!1}function _1t(s,t){const{nodeExtensions:n}=D6e(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 Rnt(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&&(Rnt(i,{ignoreWhitespace:n,checkChildren:t})||(a=!1))}),a}return!1}function TQs(s){return s instanceof Tl}function MQs(s,t,n){var r;const{selection:a}=t;let i=null;if(RVt(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 PQs=(s,t={})=>({tr:n,state:r,dispatch:a})=>{const{selection:i}=n,{empty:l,ranges:o}=i,c=u6(s,r.schema);if(a)if(l){const d=zVt(r,c);n.addStoredMark(c.create({...d,...t}))}else o.forEach(d=>{const u=d.$from.pos,h=d.$to.pos;r.doc.nodesBetween(u,h,(m,f)=>{const g=Math.max(f,u),x=Math.min(f+m.nodeSize,h);m.marks.find(v=>v.type===c)?m.marks.forEach(v=>{c===v.type&&n.addMark(g,x,c.create({...v.attrs,...t}))}):n.addMark(g,x,c.create(t))})});return MQs(r,n,c)},IQs=(s,t)=>({tr:n})=>(n.setMeta(s,t),!0),LQs=(s,t={})=>({state:n,dispatch:r,chain:a})=>{const i=Pv(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})=>f1t(i,{...l,...t})(n)?!0:o.clearNodes()).command(({state:o})=>f1t(i,{...l,...t})(o,r)).run():(console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'),!1)},RQs=s=>({tr:t,dispatch:n})=>{if(n){const{doc:r}=t,a=h8(s,0,r.content.size),i=Tl.create(r,a);t.setSelection(i)}return!0},DQs=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=h8(a,l,o),d=h8(i,l,o),u=El.create(r,c,d);t.setSelection(u)}return!0},FQs=s=>({state:t,dispatch:n})=>{const r=Pv(s,t.schema);return pXs(r)(t,n)};function w1t(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 OQs=({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=h3e(d,o.node().type.name,o.node().attrs);if(i instanceof Tl&&i.node.isBlock)return!o.parentOffset||!UE(l,o.pos)?!1:(r&&(s&&w1t(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:wQs(o.node(-1).contentMatchAt(o.indexAfter(-1)));let f=h&&m?[{type:m,attrs:u}]:void 0,g=UE(t.doc,t.mapping.map(o.pos),1,f);if(!f&&!g&&UE(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()),y=t.doc.resolve(x);o.node(-1).canReplaceWith(y.index(),y.index()+1,m)&&t.setNodeMarkup(t.mapping.map(o.before()),m)}s&&w1t(n,a.extensionManager.splittableMarks),t.scrollIntoView()}return g},zQs=(s,t={})=>({tr:n,state:r,dispatch:a,editor:i})=>{var l;const o=Pv(s,r.schema),{$from:c,$to:d}=r.selection,u=r.selection.node;if(u&&u.isBlock||c.depth<2||!c.sameParent(d))return!1;const h=c.node(-1);if(h.type!==o)return!1;const m=i.extensionManager.attributes;if(c.parent.content.size===0&&c.node(-1).childCount===c.indexAfter(-1)){if(c.depth===2||c.node(-3).type!==o||c.index(-2)!==c.node(-2).childCount-1)return!1;if(a){let v=ui.empty;const b=c.index(-1)?1:c.index(-2)?2:3;for(let P=c.depth-b;P>=c.depth-3;P-=1)v=ui.from(c.node(P).copy(v));const w=c.indexAfter(-1){if(I>-1)return!1;P.isTextblock&&P.content.size===0&&(I=R+1)}),I>-1&&n.setSelection(El.near(n.doc.resolve(I))),n.scrollIntoView()}return!0}const f=d.pos===c.end()?h.contentMatchAt(0).defaultType:null,g={...h3e(m,h.type.name,h.attrs),...t},x={...h3e(m,c.node().type.name,c.node().attrs),...t};n.delete(c.pos,d.pos);const y=f?[{type:o,attrs:g},{type:f,attrs:x}]:[{type:o,attrs:g}];if(!UE(n.doc,c.pos,2))return!1;if(a){const{selection:v,storedMarks:b}=r,{splittableMarks:w}=i.extensionManager,S=b||v.$to.parentOffset&&v.$from.marks();if(n.split(c.pos,2,y).scrollIntoView(),!S||!a)return!0;const A=S.filter(E=>w.includes(E.type.name));n.ensureMarks(A)}return!0},uBe=(s,t)=>{const n=Int(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)&&c6(s.doc,n.pos)&&s.join(n.pos),!0},hBe=(s,t)=>{const n=Int(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)&&c6(s.doc,r)&&s.join(r),!0},BQs=(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=Pv(s,l.schema),g=Pv(t,l.schema),{selection:x,storedMarks:y}=l,{$from:v,$to:b}=x,w=v.blockRange(b),S=y||x.$to.parentOffset&&x.$from.marks();if(!w)return!1;const A=Int(E=>_1t(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(_1t(A.node.type.name,h)&&f.validContent(A.node.content)&&o)return c().command(()=>(i.setNodeMarkup(A.pos,f),!0)).command(()=>uBe(i,f)).command(()=>hBe(i,f)).run()}return!n||!S||!o?c().command(()=>u().wrapInList(f,r)?!0:d.clearNodes()).wrapInList(f,r).command(()=>uBe(i,f)).command(()=>hBe(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(()=>uBe(i,f)).command(()=>hBe(i,f)).run()},$Qs=(s,t={},n={})=>({state:r,commands:a})=>{const{extendEmptyMarkRange:i=!1}=n,l=u6(s,r.schema);return cWe(r,l,t)?a.unsetMark(l,{extendEmptyMarkRange:i}):a.setMark(l,t)},UQs=(s,t,n={})=>({state:r,commands:a})=>{const i=Pv(s,r.schema),l=Pv(t,r.schema),o=vse(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})},qQs=(s,t={})=>({state:n,commands:r})=>{const a=Pv(s,n.schema);return vse(n,a,t)?r.lift(a):r.wrapIn(a,t)},VQs=()=>({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},HQs=()=>({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},GQs=(s,t={})=>({tr:n,state:r,dispatch:a})=>{var i;const{extendEmptyMarkRange:l=!1}=t,{selection:o}=n,c=u6(s,r.schema),{$from:d,empty:u,ranges:h}=o;if(!a)return!0;if(u&&l){let{from:m,to:f}=o;const g=(i=d.marks().find(y=>y.type===c))===null||i===void 0?void 0:i.attrs,x=Pnt(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},WQs=(s,t={})=>({tr:n,state:r,dispatch:a})=>{let i=null,l=null;const o=z6e(typeof s=="string"?s:s.name,r.schema);return o?(o==="node"&&(i=Pv(s,r.schema)),o==="mark"&&(l=u6(s,r.schema)),a&&n.selection.ranges.forEach(c=>{const d=c.$from.pos,u=c.$to.pos;let h,m,f,g;n.selection.empty?r.doc.nodesBetween(d,u,(x,y)=>{i&&i===x.type&&(f=Math.max(y,d),g=Math.min(y+x.nodeSize,u),h=y,m=x)}):r.doc.nodesBetween(d,u,(x,y)=>{y=d&&y<=u&&(i&&i===x.type&&n.setNodeMarkup(y,void 0,{...x.attrs,...t}),l&&x.marks.length&&x.marks.forEach(v=>{if(l===v.type){const b=Math.max(y,d),w=Math.min(y+x.nodeSize,u);n.addMark(b,w,l.create({...v.attrs,...t}))}}))}),m&&(h!==void 0&&n.setNodeMarkup(h,void 0,{...m.attrs,...t}),l&&m.marks.length&&m.marks.forEach(x=>{l===x.type&&n.addMark(f,g,l.create({...x.attrs,...t}))}))}),!0):!1},KQs=(s,t={})=>({state:n,dispatch:r})=>{const a=Pv(s,n.schema);return lXs(a,t)(n,r)},YQs=(s,t={})=>({state:n,dispatch:r})=>{const a=Pv(s,n.schema);return cXs(a,t)(n,r)};var ZQs=Object.freeze({__proto__:null,blur:MXs,clearContent:PXs,clearNodes:IXs,command:LXs,createParagraphNear:RXs,cut:DXs,deleteCurrentNode:FXs,deleteNode:OXs,deleteRange:zXs,deleteSelection:BXs,enter:$Xs,exitCode:UXs,extendMarkRange:qXs,first:VXs,focus:GXs,forEach:WXs,insertContent:KXs,insertContentAt:XXs,joinBackward:eQs,joinDown:JXs,joinForward:tQs,joinItemBackward:sQs,joinItemForward:nQs,joinTextblockBackward:rQs,joinTextblockForward:aQs,joinUp:QXs,keyboardShortcut:oQs,lift:lQs,liftEmptyBlock:cQs,liftListItem:dQs,newlineInCode:uQs,resetAttributes:hQs,scrollIntoView:mQs,selectAll:fQs,selectNodeBackward:pQs,selectNodeForward:gQs,selectParentNode:xQs,selectTextblockEnd:yQs,selectTextblockStart:vQs,setContent:bQs,setMark:PQs,setMeta:IQs,setNode:LQs,setNodeSelection:RQs,setTextSelection:DQs,sinkListItem:FQs,splitBlock:OQs,splitListItem:zQs,toggleList:BQs,toggleMark:$Qs,toggleNode:UQs,toggleWrap:qQs,undoInputRule:VQs,unsetAllMarks:HQs,unsetMark:GQs,updateAttributes:WQs,wrapIn:KQs,wrapInList:YQs});const XQs=Cb.create({name:"commands",addCommands(){return{...ZQs}}}),QQs=Cb.create({name:"drop",addProseMirrorPlugins(){return[new z0({key:new E1("tiptapDrop"),props:{handleDrop:(s,t,n,r)=>{this.editor.emit("drop",{editor:this.editor,event:t,slice:n,moved:r})}}})]}}),JQs=Cb.create({name:"editable",addProseMirrorPlugins(){return[new z0({key:new E1("editable"),props:{editable:()=>this.editor.options.editable}})]}}),eJs=new E1("focusEvents"),tJs=Cb.create({name:"focusEvents",addProseMirrorPlugins(){const{editor:s}=this;return[new z0({key:eJs,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}}}})]}}),sJs=Cb.create({name:"keymap",addKeyboardShortcuts(){const s=()=>this.editor.commands.first(({commands:l})=>[()=>l.undoInputRule(),()=>l.command(({tr:o})=>{const{selection:c,doc:d}=o,{empty:u,$anchor:h}=c,{pos:m,parent:f}=h,g=h.parent.isTextblock&&m>0?o.doc.resolve(m-1):h,x=g.parent.type.spec.isolating,y=h.pos-h.parentOffset,v=x&&g.parent.childCount===1?y===h.pos:Nc.atStart(d).from===m;return!u||!f.type.isTextblock||f.textContent.length||!v||v&&h.parent.type.name==="paragraph"?!1:l.clearNodes()}),()=>l.deleteSelection(),()=>l.joinBackward(),()=>l.selectNodeBackward()]),t=()=>this.editor.commands.first(({commands:l})=>[()=>l.deleteSelection(),()=>l.deleteCurrentNode(),()=>l.joinForward(),()=>l.selectNodeForward()]),r={Enter:()=>this.editor.commands.first(({commands:l})=>[()=>l.newlineInCode(),()=>l.createParagraphNear(),()=>l.liftEmptyBlock(),()=>l.splitBlock()]),"Mod-Enter":()=>this.editor.commands.exitCode(),Backspace:s,"Mod-Backspace":s,"Shift-Backspace":s,Delete:t,"Mod-Delete":t,"Mod-a":()=>this.editor.commands.selectAll()},a={...r},i={...r,"Ctrl-h":s,"Alt-Backspace":s,"Ctrl-d":t,"Ctrl-Alt-Backspace":t,"Alt-Delete":t,"Alt-d":t,"Ctrl-a":()=>this.editor.commands.selectTextblockStart(),"Ctrl-e":()=>this.editor.commands.selectTextblockEnd()};return oTe()||OVt()?i:a},addProseMirrorPlugins(){return[new z0({key:new E1("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=Nc.atStart(t.doc).from,d=Nc.atEnd(t.doc).to;if(i||!(l===c&&o===d)||!Rnt(n.doc))return;const m=n.tr,f=L6e({state:n,transaction:m}),{commands:g}=new R6e({editor:this.editor,state:f});if(g.clearNodes(),!!m.steps.length)return m}})]}}),nJs=Cb.create({name:"paste",addProseMirrorPlugins(){return[new z0({key:new E1("tiptapPaste"),props:{handlePaste:(s,t,n)=>{this.editor.emit("paste",{editor:this.editor,event:t,slice:n})}}})]}}),rJs=Cb.create({name:"tabindex",addProseMirrorPlugins(){return[new z0({key:new E1("tabindex"),props:{attributes:()=>this.editor.isEditable?{tabindex:"0"}:{}}})]}});class KO{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 KO(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 KO(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 KO(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 KO(o,this.editor,a,a?n:null);a&&(c.actualDepth=this.depth+1),t.push(new KO(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 aJs=`.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 iJs(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 oJs extends gXs{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=iJs(aJs,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=TVt(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?[JQs,TXs.configure({blockSeparator:(n=(t=this.options.coreExtensionOptions)===null||t===void 0?void 0:t.clipboardTextSerializer)===null||n===void 0?void 0:n.blockSeparator}),XQs,tJs,sJs,rJs,QQs,nJs].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 JU(a,this)}createCommandManager(){this.commandManager=new R6e({editor:this})}createSchema(){this.schema=this.extensionManager.schema}createView(){var t;let n;try{n=lWe(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=lWe(this.options.content,this.schema,this.options.parseOptions,{errorOnInvalidContent:!1})}const r=DVt(n,this.options.autofocus);this.view=new gVt(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:QU.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 $Vt(this.state,t)}isActive(t,n){const r=typeof t=="string"?t:null,a=typeof t=="string"?n:t;return EQs(this.state,r,a)}getJSON(){return this.state.doc.toJSON()}getHTML(){return Tnt(this.state.doc.content,this.schema)}getText(t){const{blockSeparator:n=` `,textSerializers:r={}}=t||{};return NQs(this.state.doc,{blockSeparator:n,textSerializers:{...IVt(this.schema),...r}})}get isEmpty(){return Rnt(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 KO(n,this)}get $doc(){return this.$pos(0)}}function RG(s){return new F6e({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(Lnt(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 UVt(s){return new F6e({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 dWe(s){return new F6e({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 bse(s){return new F6e({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&&hnt(c,s.type,i);if(!d)return null;if(l.wrap(c,d),s.keepMarks&&s.editor){const{selection:h,storedMarks:m}=t,{splittableMarks:f}=s.editor.extensionManager,g=m||h.$to.parentOffset&&h.$from.marks();if(g){const x=g.filter(y=>f.includes(y.type.name));l.ensureMarks(x)}}if(s.keepAttributes){const h=s.type.name==="bulletList"||s.type.name==="orderedList"?"listItem":"taskList";a().updateAttributes(h,i).run()}const u=l.doc.resolve(n.from-1).nodeBefore;u&&u.type===s.type&&c6(l.doc,n.from-1)&&(!s.joinPredicate||s.joinPredicate(r,u))&&l.join(n.from-1)}})}let Iv=class uWe{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 uWe(t)}configure(t={}){const n=this.extend({...this.config,addOptions:()=>O6e(this.options,t)});return n.name=this.name,n.parent=this.parent,n}extend(t={}){const n=new uWe(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 Y7(s){return new MVt({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(Lnt(n.from,n.to,t.doc).filter(g=>g.mark.type.excluded.find(y=>y===s.type&&y!==g.mark.type)).filter(g=>g.to>h).length)return null;mn.from&&l.delete(n.from+u,h),d=n.from+u+o.length,l.addMark(n.from+u,d,s.type.create(i||{})),l.removeStoredMark(s.type)}}})}function lJs(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 cJs(s){return new MVt({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 dJs(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var qVt={exports:{}},mBe={};/** * @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 j1t;function uJs(){if(j1t)return mBe;j1t=1;var s=Gt;function t(h,m){return h===m&&(h!==0||1/h===1/m)||h!==h&&m!==m}var n=typeof Object.is=="function"?Object.is:t,r=s.useState,a=s.useEffect,i=s.useLayoutEffect,l=s.useDebugValue;function o(h,m){var f=m(),g=r({inst:{value:f,getSnapshot:m}}),x=g[0].inst,y=g[1];return i(function(){x.value=f,x.getSnapshot=m,c(x)&&y({inst:x})},[h,f,m]),a(function(){return c(x)&&y({inst:x}),h(function(){c(x)&&y({inst:x})})},[h]),l(f),f}function c(h){var m=h.getSnapshot;h=h.value;try{var f=m();return!n(h,f)}catch{return!0}}function d(h,m){return m()}var u=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?d:o;return mBe.useSyncExternalStore=s.useSyncExternalStore!==void 0?s.useSyncExternalStore:u,mBe}qVt.exports=uJs();var Dnt=qVt.exports;const hJs=(...s)=>t=>{s.forEach(n=>{typeof n=="function"?n(t):n&&(n.current=t)})},mJs=({contentComponent:s})=>{const t=Dnt.useSyncExternalStore(s.subscribe,s.getSnapshot,s.getServerSnapshot);return Gt.createElement(Gt.Fragment,null,Object.values(t))};function fJs(){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]:z6t.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 pJs extends Gt.Component{constructor(t){var n;super(t),this.editorContentRef=Gt.createRef(),this.initialized=!1,this.state={hasContentComponentInitialized:!!(!((n=t.editor)===null||n===void 0)&&n.contentComponent)}}componentDidMount(){this.init()}componentDidUpdate(){this.init()}init(){const t=this.props.editor;if(t&&!t.isDestroyed&&t.options.element){if(t.contentComponent)return;const n=this.editorContentRef.current;n.append(...t.options.element.childNodes),t.setOptions({element:n}),t.contentComponent=fJs(),this.state.hasContentComponentInitialized||(this.unsubscribeToContentComponent=t.contentComponent.subscribe(()=>{this.setState(r=>r.hasContentComponentInitialized?r:{hasContentComponentInitialized:!0}),this.unsubscribeToContentComponent&&this.unsubscribeToContentComponent()})),t.createNodeViews(),this.initialized=!0}}componentWillUnmount(){const t=this.props.editor;if(!t||(this.initialized=!1,t.isDestroyed||t.view.setProps({nodeViews:{}}),this.unsubscribeToContentComponent&&this.unsubscribeToContentComponent(),t.contentComponent=null,!t.options.element.firstChild))return;const n=document.createElement("div");n.append(...t.options.element.childNodes),t.setOptions({element:n})}render(){const{editor:t,innerRef:n,...r}=this.props;return Gt.createElement(Gt.Fragment,null,Gt.createElement("div",{ref:hJs(n,this.editorContentRef),...r}),(t==null?void 0:t.contentComponent)&&Gt.createElement(mJs,{contentComponent:t.contentComponent}))}}const gJs=j.forwardRef((s,t)=>{const n=Gt.useMemo(()=>Math.floor(Math.random()*4294967295).toString(),[s.editor]);return Gt.createElement(pJs,{key:n,innerRef:t,...s})}),B6e=Gt.memo(gJs);var xJs=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},yJs=dJs(xJs),VVt={exports:{}},fBe={};/** * @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 N1t;function vJs(){if(N1t)return fBe;N1t=1;var s=Gt,t=Dnt;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 fBe.useSyncExternalStoreWithSelector=function(d,u,h,m,f){var g=i(null);if(g.current===null){var x={hasValue:!1,value:null};g.current=x}else x=g.current;g=o(function(){function v(E){if(!b){if(b=!0,w=E,E=m(E),f!==void 0&&x.hasValue){var I=x.value;if(f(I,E))return S=I}return S=E}if(I=S,r(w,E))return I;var P=m(E);return f!==void 0&&f(I,P)?I:(w=E,S=P)}var b=!1,w,S,A=h===void 0?null:h;return[function(){return v(u())},A===null?void 0:function(){return v(A())}]},[u,h,m,f]);var y=a(d,g[0],g[1]);return l(function(){x.hasValue=!0,x.value=y},[y]),c(y),y},fBe}VVt.exports=vJs();var bJs=VVt.exports;const _Js=typeof window<"u"?j.useLayoutEffect:j.useEffect;class wJs{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 jJs(s){var t;const[n]=j.useState(()=>new wJs(s.editor)),r=bJs.useSyncExternalStoreWithSelector(n.subscribe,n.getSnapshot,n.getServerSnapshot,s.selector,(t=s.equalityFn)!==null&&t!==void 0?t:yJs);return _Js(()=>n.watch(s.editor),[s.editor,n]),j.useDebugValue(r),r}const NJs=!1,hWe=typeof window>"u",kJs=hWe||!!(typeof window<"u"&&window.next);class Fnt{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?hWe||kJs?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 oJs(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?Fnt.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 $6e(s={},t=[]){const n=j.useRef(s);n.current=s;const[r]=j.useState(()=>new Fnt(n)),a=Dnt.useSyncExternalStore(r.subscribe,r.getEditor,r.getServerSnapshot);return j.useDebugValue(a),j.useEffect(r.onRender(t)),jJs({editor:a,selector:({transactionNumber:i})=>s.shouldRerenderOnTransaction===!1?null:s.immediatelyRender&&i===0?0:i+1}),a}const SJs=j.createContext({editor:null});SJs.Consumer;const CJs=j.createContext({onDragStart:void 0}),AJs=()=>j.useContext(CJs);Gt.forwardRef((s,t)=>{const{onDragStart:n}=AJs(),r=s.as||"div";return Gt.createElement(r,{...s,ref:t,"data-node-view-wrapper":"",onDragStart:n,style:{whiteSpace:"normal",...s.style}})});const EJs=/^\s*>\s$/,TJs=Iv.create({name:"blockquote",addOptions(){return{HTMLAttributes:{}}},content:"block+",group:"block",defining:!0,parseHTML(){return[{tag:"blockquote"}]},renderHTML({HTMLAttributes:s}){return["blockquote",ep(this.options.HTMLAttributes,s),0]},addCommands(){return{setBlockquote:()=>({commands:s})=>s.wrapIn(this.name),toggleBlockquote:()=>({commands:s})=>s.toggleWrap(this.name),unsetBlockquote:()=>({commands:s})=>s.lift(this.name)}},addKeyboardShortcuts(){return{"Mod-Shift-b":()=>this.editor.commands.toggleBlockquote()}},addInputRules(){return[bse({find:EJs,type:this.type})]}}),MJs=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,PJs=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,IJs=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,LJs=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g,RJs=pC.create({name:"bold",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"strong"},{tag:"b",getAttrs:s=>s.style.fontWeight!=="normal"&&null},{style:"font-weight=400",clearMark:s=>s.type.name===this.name},{style:"font-weight",getAttrs:s=>/^(bold(er)?|[5-9]\d{2,})$/.test(s)&&null}]},renderHTML({HTMLAttributes:s}){return["strong",ep(this.options.HTMLAttributes,s),0]},addCommands(){return{setBold:()=>({commands:s})=>s.setMark(this.name),toggleBold:()=>({commands:s})=>s.toggleMark(this.name),unsetBold:()=>({commands:s})=>s.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-b":()=>this.editor.commands.toggleBold(),"Mod-B":()=>this.editor.commands.toggleBold()}},addInputRules(){return[RG({find:MJs,type:this.type}),RG({find:IJs,type:this.type})]},addPasteRules(){return[Y7({find:PJs,type:this.type}),Y7({find:LJs,type:this.type})]}}),DJs="listItem",k1t="textStyle",S1t=/^\s*([-+*])\s$/,FJs=Iv.create({name:"bulletList",addOptions(){return{itemTypeName:"listItem",HTMLAttributes:{},keepMarks:!1,keepAttributes:!1}},group:"block list",content(){return`${this.options.itemTypeName}+`},parseHTML(){return[{tag:"ul"}]},renderHTML({HTMLAttributes:s}){return["ul",ep(this.options.HTMLAttributes,s),0]},addCommands(){return{toggleBulletList:()=>({commands:s,chain:t})=>this.options.keepAttributes?t().toggleList(this.name,this.options.itemTypeName,this.options.keepMarks).updateAttributes(DJs,this.editor.getAttributes(k1t)).run():s.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-8":()=>this.editor.commands.toggleBulletList()}},addInputRules(){let s=bse({find:S1t,type:this.type});return(this.options.keepMarks||this.options.keepAttributes)&&(s=bse({find:S1t,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:()=>this.editor.getAttributes(k1t),editor:this.editor})),[s]}}),OJs=/(^|[^`])`([^`]+)`(?!`)/,zJs=/(^|[^`])`([^`]+)`(?!`)/g,BJs=pC.create({name:"code",addOptions(){return{HTMLAttributes:{}}},excludes:"_",code:!0,exitable:!0,parseHTML(){return[{tag:"code"}]},renderHTML({HTMLAttributes:s}){return["code",ep(this.options.HTMLAttributes,s),0]},addCommands(){return{setCode:()=>({commands:s})=>s.setMark(this.name),toggleCode:()=>({commands:s})=>s.toggleMark(this.name),unsetCode:()=>({commands:s})=>s.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-e":()=>this.editor.commands.toggleCode()}},addInputRules(){return[RG({find:OJs,type:this.type})]},addPasteRules(){return[Y7({find:zJs,type:this.type})]}}),$Js=/^```([a-z]+)?[\s\n]$/,UJs=/^~~~([a-z]+)?[\s\n]$/,qJs=Iv.create({name:"codeBlock",addOptions(){return{languageClassPrefix:"language-",exitOnTripleEnter:!0,exitOnArrowDown:!0,defaultLanguage:null,HTMLAttributes:{}}},content:"text*",marks:"",group:"block",code:!0,defining:!0,addAttributes(){return{language:{default:this.options.defaultLanguage,parseHTML:s=>{var t;const{languageClassPrefix:n}=this.options,i=[...((t=s.firstElementChild)===null||t===void 0?void 0:t.classList)||[]].filter(l=>l.startsWith(n)).map(l=>l.replace(n,""))[0];return i||null},rendered:!1}}},parseHTML(){return[{tag:"pre",preserveWhitespace:"full"}]},renderHTML({node:s,HTMLAttributes:t}){return["pre",ep(this.options.HTMLAttributes,t),["code",{class:s.attrs.language?this.options.languageClassPrefix+s.attrs.language:null},0]]},addCommands(){return{setCodeBlock:s=>({commands:t})=>t.setNode(this.name,s),toggleCodeBlock:s=>({commands:t})=>t.toggleNode(this.name,"paragraph",s)}},addKeyboardShortcuts(){return{"Mod-Alt-c":()=>this.editor.commands.toggleCodeBlock(),Backspace:()=>{const{empty:s,$anchor:t}=this.editor.state.selection,n=t.pos===1;return!s||t.parent.type.name!==this.name?!1:n||!t.parent.textContent.length?this.editor.commands.clearNodes():!1},Enter:({editor:s})=>{if(!this.options.exitOnTripleEnter)return!1;const{state:t}=s,{selection:n}=t,{$from:r,empty:a}=n;if(!a||r.parent.type!==this.type)return!1;const i=r.parentOffset===r.parent.nodeSize-2,l=r.parent.textContent.endsWith(` `);return!i||!l?!1:s.chain().command(({tr:o})=>(o.delete(r.pos-2,r.pos),!0)).exitCode().run()},ArrowDown:({editor:s})=>{if(!this.options.exitOnArrowDown)return!1;const{state:t}=s,{selection:n,doc:r}=t,{$from:a,empty:i}=n;if(!i||a.parent.type!==this.type||!(a.parentOffset===a.parent.nodeSize-2))return!1;const o=a.after();return o===void 0?!1:r.nodeAt(o)?s.commands.command(({tr:d})=>(d.setSelection(Nc.near(r.resolve(o))),!0)):s.commands.exitCode()}}},addInputRules(){return[dWe({find:$Js,type:this.type,getAttributes:s=>({language:s[1]})}),dWe({find:UJs,type:this.type,getAttributes:s=>({language:s[1]})})]},addProseMirrorPlugins(){return[new z0({key:new E1("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}}})]}}),VJs=Iv.create({name:"doc",topNode:!0,content:"block+"});function HJs(s={}){return new z0({view(t){return new GJs(t,s)}})}class GJs{constructor(t,n){var r;this.editorView=t,this.cursorPos=null,this.element=null,this.timeout=-1,this.lastDragEvent=null,this.width=(r=n.width)!==null&&r!==void 0?r:1,this.color=n.color===!1?void 0:n.color||"black",this.class=n.class,this.handlers=["dragover","dragend","drop","dragleave"].map(a=>{let i=l=>{this[a](l)};return t.dom.addEventListener(a,i),{name:a,handler:i}})}destroy(){this.setCursor(null),this.handlers.forEach(({name:t,handler:n})=>this.editorView.dom.removeEventListener(t,n))}update(t,n){if(this.cursorPos!=null&&n.doc!=t.state.doc)if(this.lastDragEvent){let r=this.computeTarget(this.lastDragEvent);r==this.cursorPos?this.updateOverlay():this.setCursor(r)}else this.updateOverlay()}setCursor(t){t!=this.cursorPos&&(this.cursorPos=t,t==null?(this.element.parentNode.removeChild(this.element),this.element=null):this.updateOverlay())}updateOverlay(){let t=this.editorView.state.doc.resolve(this.cursorPos),n=!t.parent.inlineContent,r,a=this.editorView.dom,i=a.getBoundingClientRect(),l=i.width/a.offsetWidth,o=i.height/a.offsetHeight;if(n){let h=t.nodeBefore,m=t.nodeAfter;if(h||m){let f=this.editorView.nodeDOM(this.cursorPos-(h?h.nodeSize:0));if(f){let g=f.getBoundingClientRect(),x=h?g.bottom:g.top;h&&m&&(x=(x+this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top)/2);let y=this.width/2*o;r={left:g.left,right:g.right,top:x-y,bottom:x+y}}}}if(!r){let h=this.editorView.coordsAtPos(this.cursorPos),m=this.width/2*l;r={left:h.left-m,right:h.left+m,top:h.top,bottom:h.bottom}}let c=this.editorView.dom.offsetParent;this.element||(this.element=c.appendChild(document.createElement("div")),this.class&&(this.element.className=this.class),this.element.style.cssText="position: absolute; z-index: 50; pointer-events: none;",this.color&&(this.element.style.backgroundColor=this.color)),this.element.classList.toggle("prosemirror-dropcursor-block",n),this.element.classList.toggle("prosemirror-dropcursor-inline",!n);let d,u;if(!c||c==document.body&&getComputedStyle(c).position=="static")d=-pageXOffset,u=-pageYOffset;else{let h=c.getBoundingClientRect(),m=h.width/c.offsetWidth,f=h.height/c.offsetHeight;d=h.left-c.scrollLeft*m,u=h.top-c.scrollTop*f}this.element.style.left=(r.left-d)/l+"px",this.element.style.top=(r.top-u)/o+"px",this.element.style.width=(r.right-r.left)/l+"px",this.element.style.height=(r.bottom-r.top)/o+"px"}scheduleRemoval(t){clearTimeout(this.timeout),this.timeout=setTimeout(()=>this.setCursor(null),t)}computeTarget(t){let n=this.editorView.posAtCoords({left:t.clientX,top:t.clientY}),r=n&&n.inside>=0&&this.editorView.state.doc.nodeAt(n.inside),a=r&&r.type.spec.disableDropCursor,i=typeof a=="function"?a(this.editorView,n,t):a;if(!n||i)return null;let l=n.pos;if(this.editorView.dragging&&this.editorView.dragging.slice){let o=Sqt(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 WJs=Cb.create({name:"dropCursor",addOptions(){return{color:"currentColor",width:1,class:void 0}},addProseMirrorPlugins(){return[HJs(this.options)]}});class bx extends Nc{constructor(t){super(t,t)}map(t,n){let r=t.resolve(n.map(this.head));return bx.valid(r)?new bx(r):Nc.near(r)}content(){return Ki.empty}eq(t){return t instanceof bx&&t.head==this.head}toJSON(){return{type:"gapcursor",pos:this.head}}static fromJSON(t,n){if(typeof n.pos!="number")throw new RangeError("Invalid input for GapCursor.fromJSON");return new bx(t.resolve(n.pos))}getBookmark(){return new Ont(this.anchor)}static valid(t){let n=t.parent;if(n.inlineContent||!KJs(t)||!YJs(t))return!1;let r=n.type.spec.allowGapCursor;if(r!=null)return r;let a=n.contentMatchAt(t.index()).defaultType;return a&&a.isTextblock}static findGapCursorFrom(t,n,r=!1){e:for(;;){if(!r&&bx.valid(t))return t;let a=t.pos,i=null;for(let l=t.depth;;l--){let o=t.node(l);if(n>0?t.indexAfter(l)0){i=o.child(n>0?t.indexAfter(l):t.index(l)-1);break}else if(l==0)return null;a+=n;let c=t.doc.resolve(a);if(bx.valid(c))return c}for(;;){let l=n>0?i.firstChild:i.lastChild;if(!l){if(i.isAtom&&!i.isText&&!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(bx.valid(o))return o}return null}}}bx.prototype.visible=!1;bx.findFrom=bx.findGapCursorFrom;Nc.jsonID("gapcursor",bx);class Ont{constructor(t){this.pos=t}map(t){return new Ont(t.map(this.pos))}resolve(t){let n=t.resolve(this.pos);return bx.valid(n)?new bx(n):Nc.near(n)}}function HVt(s){return s.isAtom||s.spec.isolating||s.spec.createGapCursor}function KJs(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||HVt(a.type))return!0;if(a.inlineContent)return!1}}return!0}function YJs(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||HVt(a.type))return!0;if(a.inlineContent)return!1}}return!0}function ZJs(){return new z0({props:{decorations:een,createSelectionBetween(s,t,n){return t.pos==n.pos&&bx.valid(n)?new bx(n):null},handleClick:QJs,handleKeyDown:XJs,handleDOMEvents:{beforeinput:JJs}}})}const XJs=Nnt({ArrowLeft:hde("horiz",-1),ArrowRight:hde("horiz",1),ArrowUp:hde("vert",-1),ArrowDown:hde("vert",1)});function hde(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=bx.findGapCursorFrom(o,t,c);return d?(a&&a(r.tr.setSelection(new bx(d))),!0):!1}}function QJs(s,t,n){if(!s||!s.editable)return!1;let r=s.state.doc.resolve(t);if(!bx.valid(r))return!1;let a=s.posAtCoords({left:n.clientX,top:n.clientY});return a&&a.inside>-1&&Tl.isSelectable(s.state.doc.nodeAt(a.inside))?!1:(s.dispatch(s.state.tr.setSelection(new bx(r))),!0)}function JJs(s,t){if(t.inputType!="insertCompositionText"||!(s.state.selection instanceof bx))return!1;let{$from:n}=s.state.selection,r=n.parent.contentMatchAt(n.index()).findWrapping(s.state.schema.nodes.text);if(!r)return!1;let a=ui.empty;for(let l=r.length-1;l>=0;l--)a=ui.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 een(s){if(!(s.selection instanceof bx))return null;let t=document.createElement("div");return t.className="ProseMirror-gapcursor",vx.create(s.doc,[x_.widget(s.selection.head,t,{key:"gapcursor"})])}const ten=Cb.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}}}),sen=Iv.create({name:"hardBreak",addOptions(){return{keepMarks:!0,HTMLAttributes:{}}},inline:!0,group:"inline",selectable:!1,linebreakReplacement:!0,parseHTML(){return[{tag:"br"}]},renderHTML({HTMLAttributes:s}){return["br",ep(this.options.HTMLAttributes,s)]},renderText(){return` `},addCommands(){return{setHardBreak:()=>({commands:s,chain:t,state:n,editor:r})=>s.first([()=>s.exitCode(),()=>s.command(()=>{const{selection:a,storedMarks:i}=n;if(a.$from.parent.type.spec.isolating)return!1;const{keepMarks:l}=this.options,{splittableMarks:o}=r.extensionManager,c=i||a.$to.parentOffset&&a.$from.marks();return t().insertContent({type:this.name}).command(({tr:d,dispatch:u})=>{if(u&&c&&l){const h=c.filter(m=>o.includes(m.type.name));d.ensureMarks(h)}return!0}).run()})])}},addKeyboardShortcuts(){return{"Mod-Enter":()=>this.editor.commands.setHardBreak(),"Shift-Enter":()=>this.editor.commands.setHardBreak()}}}),nen=Iv.create({name:"heading",addOptions(){return{levels:[1,2,3,4,5,6],HTMLAttributes:{}}},content:"inline*",group:"block",defining:!0,addAttributes(){return{level:{default:1,rendered:!1}}},parseHTML(){return this.options.levels.map(s=>({tag:`h${s}`,attrs:{level:s}}))},renderHTML({node:s,HTMLAttributes:t}){return[`h${this.options.levels.includes(s.attrs.level)?s.attrs.level:this.options.levels[0]}`,ep(this.options.HTMLAttributes,t),0]},addCommands(){return{setHeading:s=>({commands:t})=>this.options.levels.includes(s.level)?t.setNode(this.name,s):!1,toggleHeading:s=>({commands:t})=>this.options.levels.includes(s.level)?t.toggleNode(this.name,"paragraph",s):!1}},addKeyboardShortcuts(){return this.options.levels.reduce((s,t)=>({...s,[`Mod-Alt-${t}`]:()=>this.editor.commands.toggleHeading({level:t})}),{})},addInputRules(){return this.options.levels.map(s=>dWe({find:new RegExp(`^(#{${Math.min(...this.options.levels)},${s}})\\s$`),type:this.type,getAttributes:{level:s}}))}});var lTe=200,Mv=function(){};Mv.prototype.append=function(t){return t.length?(t=Mv.from(t),!this.length&&t||t.length=n?Mv.empty:this.sliceInner(Math.max(0,t),Math.min(this.length,n))};Mv.prototype.get=function(t){if(!(t<0||t>=this.length))return this.getInner(t)};Mv.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)};Mv.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};Mv.from=function(t){return t instanceof Mv?t:t&&t.length?new GVt(t):Mv.empty};var GVt=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<=lTe)return new t(this.values.concat(a.flatten()))},t.prototype.leafPrepend=function(a){if(this.length+a.length<=lTe)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}(Mv);Mv.empty=new GVt([]);var ren=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}(Mv);const aen=500;class $S{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 wM(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 wM(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 $S(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;uoen&&(o=ien(o,d),l-=d),new $S(o.append(i),l)}remapping(t,n){let r=new mse;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 $S(this.items.append(t.map(n=>new wM(n))),this.eventCount)}rebased(t,n){if(!this.eventCount)return this;let r=[],a=Math.max(0,this.items.length-n),i=t.mapping,l=t.steps.length,o=this.eventCount;this.items.forEach(m=>{m.selection&&o--},a);let c=n;this.items.forEach(m=>{let f=i.getMirror(--c);if(f==null)return;l=Math.min(l,f);let g=i.maps[f];if(m.step){let x=t.steps[f].invert(t.docs[f]),y=m.selection&&m.selection.map(i.slice(c+1,f));y&&o++,r.push(new wM(g,x,y))}else r.push(new wM(g))},a);let d=[];for(let m=n;maen&&(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 wM(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 $S(Mv.from(a.reverse()),i)}}$S.empty=new $S(Mv.empty,0);function ien(s,t){let n;return s.forEach((r,a)=>{if(r.selection&&t--==0)return n=a,!1}),s.slice(n)}let wM=class WVt{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 WVt(n.getMap().invert(),n,this.selection)}}};class mP{constructor(t,n,r,a,i){this.done=t,this.undone=n,this.prevRanges=r,this.prevTime=a,this.prevComposition=i}}const oen=20;function len(s,t,n,r){let a=n.getMeta(m7),i;if(a)return a.historyState;n.getMeta(uen)&&(s=new mP(s.done,s.undone,null,0,-1));let l=n.getMeta("appendedTransaction");if(n.steps.length==0)return s;if(l&&l.getMeta(m7))return l.getMeta(m7).redo?new mP(s.done.addTransform(n,void 0,r,m3e(t)),s.undone,C1t(n.mapping.maps),s.prevTime,s.prevComposition):new mP(s.done,s.undone.addTransform(n,void 0,r,m3e(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||!cen(n,s.prevRanges)),d=l?pBe(s.prevRanges,n.mapping):C1t(n.mapping.maps);return new mP(s.done.addTransform(n,c?t.selection.getBookmark():void 0,r,m3e(t)),$S.empty,d,n.time,o??s.prevComposition)}else return(i=n.getMeta("rebased"))?new mP(s.done.rebased(n,i),s.undone.rebased(n,i),pBe(s.prevRanges,n.mapping),s.prevTime,s.prevComposition):new mP(s.done.addMaps(n.mapping.maps),s.undone.addMaps(n.mapping.maps),pBe(s.prevRanges,n.mapping),s.prevTime,s.prevComposition)}function cen(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 C1t(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 pBe(s,t){if(!s)return null;let n=[];for(let r=0;r{let a=m7.getState(n);if(!a||(s?a.undone:a.done).eventCount==0)return!1;if(r){let i=den(a,n,s);i&&r(t?i.scrollIntoView():i)}return!0}}const YVt=KVt(!1,!0),ZVt=KVt(!0,!0),men=Cb.create({name:"history",addOptions(){return{depth:100,newGroupDelay:500}},addCommands(){return{undo:()=>({state:s,dispatch:t})=>YVt(s,t),redo:()=>({state:s,dispatch:t})=>ZVt(s,t)}},addProseMirrorPlugins(){return[hen(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()}}}),fen=Iv.create({name:"horizontalRule",addOptions(){return{HTMLAttributes:{}}},group:"block",parseHTML(){return[{tag:"hr"}]},renderHTML({HTMLAttributes:s}){return["hr",ep(this.options.HTMLAttributes,s)]},addCommands(){return{setHorizontalRule:()=>({chain:s,state:t})=>{if(!lJs(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}):TQs(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[UVt({find:/^(?:---|—-|___\s|\*\*\*\s)$/,type:this.type})]}}),pen=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,gen=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,xen=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,yen=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g,ven=pC.create({name:"italic",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"em"},{tag:"i",getAttrs:s=>s.style.fontStyle!=="normal"&&null},{style:"font-style=normal",clearMark:s=>s.type.name===this.name},{style:"font-style=italic"}]},renderHTML({HTMLAttributes:s}){return["em",ep(this.options.HTMLAttributes,s),0]},addCommands(){return{setItalic:()=>({commands:s})=>s.setMark(this.name),toggleItalic:()=>({commands:s})=>s.toggleMark(this.name),unsetItalic:()=>({commands:s})=>s.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-i":()=>this.editor.commands.toggleItalic(),"Mod-I":()=>this.editor.commands.toggleItalic()}},addInputRules(){return[RG({find:pen,type:this.type}),RG({find:xen,type:this.type})]},addPasteRules(){return[Y7({find:gen,type:this.type}),Y7({find:yen,type:this.type})]}}),ben=Iv.create({name:"listItem",addOptions(){return{HTMLAttributes:{},bulletListTypeName:"bulletList",orderedListTypeName:"orderedList"}},content:"paragraph block*",defining:!0,parseHTML(){return[{tag:"li"}]},renderHTML({HTMLAttributes:s}){return["li",ep(this.options.HTMLAttributes,s),0]},addKeyboardShortcuts(){return{Enter:()=>this.editor.commands.splitListItem(this.name),Tab:()=>this.editor.commands.sinkListItem(this.name),"Shift-Tab":()=>this.editor.commands.liftListItem(this.name)}}}),_en="listItem",E1t="textStyle",T1t=/^(\d+)\.\s$/,wen=Iv.create({name:"orderedList",addOptions(){return{itemTypeName:"listItem",HTMLAttributes:{},keepMarks:!1,keepAttributes:!1}},group:"block list",content(){return`${this.options.itemTypeName}+`},addAttributes(){return{start:{default:1,parseHTML:s=>s.hasAttribute("start")?parseInt(s.getAttribute("start")||"",10):1},type:{default:null,parseHTML:s=>s.getAttribute("type")}}},parseHTML(){return[{tag:"ol"}]},renderHTML({HTMLAttributes:s}){const{start:t,...n}=s;return t===1?["ol",ep(this.options.HTMLAttributes,n),0]:["ol",ep(this.options.HTMLAttributes,s),0]},addCommands(){return{toggleOrderedList:()=>({commands:s,chain:t})=>this.options.keepAttributes?t().toggleList(this.name,this.options.itemTypeName,this.options.keepMarks).updateAttributes(_en,this.editor.getAttributes(E1t)).run():s.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-7":()=>this.editor.commands.toggleOrderedList()}},addInputRules(){let s=bse({find:T1t,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=bse({find:T1t,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:t=>({start:+t[1],...this.editor.getAttributes(E1t)}),joinPredicate:(t,n)=>n.childCount+n.attrs.start===+t[1],editor:this.editor})),[s]}}),jen=Iv.create({name:"paragraph",priority:1e3,addOptions(){return{HTMLAttributes:{}}},group:"block",content:"inline*",parseHTML(){return[{tag:"p"}]},renderHTML({HTMLAttributes:s}){return["p",ep(this.options.HTMLAttributes,s),0]},addCommands(){return{setParagraph:()=>({commands:s})=>s.setNode(this.name)}},addKeyboardShortcuts(){return{"Mod-Alt-0":()=>this.editor.commands.setParagraph()}}}),Nen=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))$/,ken=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))/g,Sen=pC.create({name:"strike",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"s"},{tag:"del"},{tag:"strike"},{style:"text-decoration",consuming:!1,getAttrs:s=>s.includes("line-through")?{}:!1}]},renderHTML({HTMLAttributes:s}){return["s",ep(this.options.HTMLAttributes,s),0]},addCommands(){return{setStrike:()=>({commands:s})=>s.setMark(this.name),toggleStrike:()=>({commands:s})=>s.toggleMark(this.name),unsetStrike:()=>({commands:s})=>s.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-Shift-s":()=>this.editor.commands.toggleStrike()}},addInputRules(){return[RG({find:Nen,type:this.type})]},addPasteRules(){return[Y7({find:ken,type:this.type})]}}),Cen=Iv.create({name:"text",group:"inline"}),U6e=Cb.create({name:"starterKit",addExtensions(){const s=[];return this.options.bold!==!1&&s.push(RJs.configure(this.options.bold)),this.options.blockquote!==!1&&s.push(TJs.configure(this.options.blockquote)),this.options.bulletList!==!1&&s.push(FJs.configure(this.options.bulletList)),this.options.code!==!1&&s.push(BJs.configure(this.options.code)),this.options.codeBlock!==!1&&s.push(qJs.configure(this.options.codeBlock)),this.options.document!==!1&&s.push(VJs.configure(this.options.document)),this.options.dropcursor!==!1&&s.push(WJs.configure(this.options.dropcursor)),this.options.gapcursor!==!1&&s.push(ten.configure(this.options.gapcursor)),this.options.hardBreak!==!1&&s.push(sen.configure(this.options.hardBreak)),this.options.heading!==!1&&s.push(nen.configure(this.options.heading)),this.options.history!==!1&&s.push(men.configure(this.options.history)),this.options.horizontalRule!==!1&&s.push(fen.configure(this.options.horizontalRule)),this.options.italic!==!1&&s.push(ven.configure(this.options.italic)),this.options.listItem!==!1&&s.push(ben.configure(this.options.listItem)),this.options.orderedList!==!1&&s.push(wen.configure(this.options.orderedList)),this.options.paragraph!==!1&&s.push(jen.configure(this.options.paragraph)),this.options.strike!==!1&&s.push(Sen.configure(this.options.strike)),this.options.text!==!1&&s.push(Cen.configure(this.options.text)),s}}),Aen="aaa1rp3bb0ott3vie4c1le2ogado5udhabi7c0ademy5centure6ountant0s9o1tor4d0s1ult4e0g1ro2tna4f0l1rica5g0akhan5ency5i0g1rbus3force5tel5kdn3l0ibaba4pay4lfinanz6state5y2sace3tom5m0azon4ericanexpress7family11x2fam3ica3sterdam8nalytics7droid5quan4z2o0l2partments8p0le4q0uarelle8r0ab1mco4chi3my2pa2t0e3s0da2ia2sociates9t0hleta5torney7u0ction5di0ble3o3spost5thor3o0s4w0s2x0a2z0ure5ba0by2idu3namex4d1k2r0celona5laycard4s5efoot5gains6seball5ketball8uhaus5yern5b0c1t1va3cg1n2d1e0ats2uty4er2rlin4st0buy5t2f1g1h0arti5i0ble3d1ke2ng0o3o1z2j1lack0friday9ockbuster8g1omberg7ue3m0s1w2n0pparibas9o0ats3ehringer8fa2m1nd2o0k0ing5sch2tik2on4t1utique6x2r0adesco6idgestone9oadway5ker3ther5ussels7s1t1uild0ers6siness6y1zz3v1w1y1z0h3ca0b1fe2l0l1vinklein9m0era3p2non3petown5ital0one8r0avan4ds2e0er0s4s2sa1e1h1ino4t0ering5holic7ba1n1re3c1d1enter4o1rn3f0a1d2g1h0anel2nel4rity4se2t2eap3intai5ristmas6ome4urch5i0priani6rcle4sco3tadel4i0c2y3k1l0aims4eaning6ick2nic1que6othing5ud3ub0med6m1n1o0ach3des3ffee4llege4ogne5m0mbank4unity6pany2re3uter5sec4ndos3struction8ulting7tact3ractors9oking4l1p2rsica5untry4pon0s4rses6pa2r0edit0card4union9icket5own3s1uise0s6u0isinella9v1w1x1y0mru3ou3z2dad1nce3ta1e1ing3sun4y2clk3ds2e0al0er2s3gree4livery5l1oitte5ta3mocrat6ntal2ist5si0gn4v2hl2iamonds6et2gital5rect0ory7scount3ver5h2y2j1k1m1np2o0cs1tor4g1mains5t1wnload7rive4tv2ubai3pont4rban5vag2r2z2earth3t2c0o2deka3u0cation8e1g1mail3erck5nergy4gineer0ing9terprises10pson4quipment8r0icsson6ni3s0q1tate5t1u0rovision8s2vents5xchange6pert3osed4ress5traspace10fage2il1rwinds6th3mily4n0s2rm0ers5shion4t3edex3edback6rrari3ero6i0delity5o2lm2nal1nce1ial7re0stone6mdale6sh0ing5t0ness6j1k1lickr3ghts4r2orist4wers5y2m1o0o0d1tball6rd1ex2sale4um3undation8x2r0ee1senius7l1ogans4ntier7tr2ujitsu5n0d2rniture7tbol5yi3ga0l0lery3o1up4me0s3p1rden4y2b0iz3d0n2e0a1nt0ing5orge5f1g0ee3h1i0ft0s3ves2ing5l0ass3e1obal2o4m0ail3bh2o1x2n1odaddy5ld0point6f2odyear5g0le4p1t1v2p1q1r0ainger5phics5tis4een3ipe3ocery4up4s1t1u0cci3ge2ide2tars5ru3w1y2hair2mburg5ngout5us3bo2dfc0bank7ealth0care8lp1sinki6re1mes5iphop4samitsu7tachi5v2k0t2m1n1ockey4ldings5iday5medepot5goods5s0ense7nda3rse3spital5t0ing5t0els3mail5use3w2r1sbc3t1u0ghes5yatt3undai7ibm2cbc2e1u2d1e0ee3fm2kano4l1m0amat4db2mo0bilien9n0c1dustries8finiti5o2g1k1stitute6urance4e4t0ernational10uit4vestments10o1piranga7q1r0ish4s0maili5t0anbul7t0au2v3jaguar4va3cb2e0ep2tzt3welry6io2ll2m0p2nj2o0bs1urg4t1y2p0morgan6rs3uegos4niper7kaufen5ddi3e0rryhotels6properties14fh2g1h1i0a1ds2m1ndle4tchen5wi3m1n1oeln3matsu5sher5p0mg2n2r0d1ed3uokgroup8w1y0oto4z2la0caixa5mborghini8er3nd0rover6xess5salle5t0ino3robe5w0yer5b1c1ds2ease3clerc5frak4gal2o2xus4gbt3i0dl2fe0insurance9style7ghting6ke2lly3mited4o2ncoln4k2ve1ing5k1lc1p2oan0s3cker3us3l1ndon4tte1o3ve3pl0financial11r1s1t0d0a3u0ndbeck6xe1ury5v1y2ma0drid4if1son4keup4n0agement7go3p1rket0ing3s4riott5shalls7ttel5ba2c0kinsey7d1e0d0ia3et2lbourne7me1orial6n0u2rck0msd7g1h1iami3crosoft7l1ni1t2t0subishi9k1l0b1s2m0a2n1o0bi0le4da2e1i1m1nash3ey2ster5rmon3tgage6scow4to0rcycles9v0ie4p1q1r1s0d2t0n1r2u0seum3ic4v1w1x1y1z2na0b1goya4me2vy3ba2c1e0c1t0bank4flix4work5ustar5w0s2xt0direct7us4f0l2g0o2hk2i0co2ke1on3nja3ssan1y5l1o0kia3rton4w0ruz3tv4p1r0a1w2tt2u1yc2z2obi1server7ffice5kinawa6layan0group9lo3m0ega4ne1g1l0ine5oo2pen3racle3nge4g0anic5igins6saka4tsuka4t2vh3pa0ge2nasonic7ris2s1tners4s1y3y2ccw3e0t2f0izer5g1h0armacy6d1ilips5one2to0graphy6s4ysio5ics1tet2ures6d1n0g1k2oneer5zza4k1l0ace2y0station9umbing5s3m1n0c2ohl2ker3litie5rn2st3r0axi3ess3ime3o0d0uctions8f1gressive8mo2perties3y5tection8u0dential9s1t1ub2w0c2y2qa1pon3uebec3st5racing4dio4e0ad1lestate6tor2y4cipes5d0umbrella9hab3ise0n3t2liance6n0t0als5pair3ort3ublican8st0aurant8view0s5xroth6ich0ardli6oh3l1o1p2o0cks3deo3gers4om3s0vp3u0gby3hr2n2w0e2yukyu6sa0arland6fe0ty4kura4le1on3msclub4ung5ndvik0coromant12ofi4p1rl2s1ve2xo3b0i1s2c0b1haeffler7midt4olarships8ol3ule3warz5ience5ot3d1e0arch3t2cure1ity6ek2lect4ner3rvices6ven3w1x0y3fr2g1h0angrila6rp3ell3ia1ksha5oes2p0ping5uji3w3i0lk2na1gles5te3j1k0i0n2y0pe4l0ing4m0art3ile4n0cf3o0ccer3ial4ftbank4ware6hu2lar2utions7ng1y2y2pa0ce3ort2t3r0l2s1t0ada2ples4r1tebank4farm7c0group6ockholm6rage3e3ream4udio2y3yle4u0cks3pplies3y2ort5rf1gery5zuki5v1watch4iss4x1y0dney4stems6z2tab1ipei4lk2obao4rget4tamotors6r2too4x0i3c0i2d0k2eam2ch0nology8l1masek5nnis4va3f1g1h0d1eater2re6iaa2ckets5enda4ps2res2ol4j0maxx4x2k0maxx5l1m0all4n1o0day3kyo3ols3p1ray3shiba5tal3urs3wn2yota3s3r0ade1ing4ining5vel0ers0insurance16ust3v2t1ube2i1nes3shu4v0s2w1z2ua1bank3s2g1k1nicom3versity8o2ol2ps2s1y1z2va0cations7na1guard7c1e0gas3ntures6risign5mögensberater2ung14sicherung10t2g1i0ajes4deo3g1king4llas4n1p1rgin4sa1ion4va1o3laanderen9n1odka3lvo3te1ing3o2yage5u2wales2mart4ter4ng0gou5tch0es6eather0channel12bcam3er2site5d0ding5ibo2r3f1hoswho6ien2ki2lliamhill9n0dows4e1ners6me2oodside6rk0s2ld3w2s1tc1f3xbox3erox4ihuan4n2xx2yz3yachts4hoo3maxun5ndex5e1odobashi7ga2kohama6u0tube6t1un3za0ppos4ra3ero3ip2m1one3uerich6w2",Een="ελ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",mWe="numeric",fWe="ascii",pWe="alpha",Tee="asciinumeric",hQ="alphanumeric",gWe="domain",XVt="emoji",Ten="scheme",Men="slashscheme",xBe="whitespace";function Pen(s,t){return s in t||(t[s]=[]),t[s]}function m8(s,t,n){t[mWe]&&(t[Tee]=!0,t[hQ]=!0),t[fWe]&&(t[Tee]=!0,t[pWe]=!0),t[Tee]&&(t[hQ]=!0),t[pWe]&&(t[hQ]=!0),t[hQ]&&(t[gWe]=!0),t[XVt]&&(t[gWe]=!0);for(const r in t){const a=Pen(r,n);a.indexOf(s)<0&&a.push(s)}}function Ien(s,t){const n={};for(const r in t)t[r].indexOf(s)>=0&&(n[r]=!0);return n}function gw(s=null){this.j={},this.jr=[],this.jd=null,this.t=s}gw.groups={};gw.prototype={accepts(){return!!this.t},go(s){const t=this,n=t.j[s];if(n)return n;for(let r=0;rs.ta(t,n,r,a),lx=(s,t,n,r,a)=>s.tr(t,n,r,a),M1t=(s,t,n,r,a)=>s.ts(t,n,r,a),_i=(s,t,n,r,a)=>s.tt(t,n,r,a),yA="WORD",xWe="UWORD",QVt="ASCIINUMERICAL",JVt="ALPHANUMERICAL",_se="LOCALHOST",yWe="TLD",vWe="UTLD",f3e="SCHEME",yU="SLASH_SCHEME",znt="NUM",bWe="WS",Bnt="NL",Mee="OPENBRACE",Pee="CLOSEBRACE",cTe="OPENBRACKET",dTe="CLOSEBRACKET",uTe="OPENPAREN",hTe="CLOSEPAREN",mTe="OPENANGLEBRACKET",fTe="CLOSEANGLEBRACKET",pTe="FULLWIDTHLEFTPAREN",gTe="FULLWIDTHRIGHTPAREN",xTe="LEFTCORNERBRACKET",yTe="RIGHTCORNERBRACKET",vTe="LEFTWHITECORNERBRACKET",bTe="RIGHTWHITECORNERBRACKET",_Te="FULLWIDTHLESSTHAN",wTe="FULLWIDTHGREATERTHAN",jTe="AMPERSAND",NTe="APOSTROPHE",kTe="ASTERISK",fP="AT",STe="BACKSLASH",CTe="BACKTICK",ATe="CARET",f8="COLON",$nt="COMMA",ETe="DOLLAR",w5="DOT",TTe="EQUALS",Unt="EXCLAMATION",pN="HYPHEN",Iee="PERCENT",MTe="PIPE",PTe="PLUS",ITe="POUND",Lee="QUERY",qnt="QUOTE",eHt="FULLWIDTHMIDDLEDOT",Vnt="SEMI",j5="SLASH",Ree="TILDE",LTe="UNDERSCORE",tHt="EMOJI",RTe="SYM";var sHt=Object.freeze({__proto__:null,ALPHANUMERICAL:JVt,AMPERSAND:jTe,APOSTROPHE:NTe,ASCIINUMERICAL:QVt,ASTERISK:kTe,AT:fP,BACKSLASH:STe,BACKTICK:CTe,CARET:ATe,CLOSEANGLEBRACKET:fTe,CLOSEBRACE:Pee,CLOSEBRACKET:dTe,CLOSEPAREN:hTe,COLON:f8,COMMA:$nt,DOLLAR:ETe,DOT:w5,EMOJI:tHt,EQUALS:TTe,EXCLAMATION:Unt,FULLWIDTHGREATERTHAN:wTe,FULLWIDTHLEFTPAREN:pTe,FULLWIDTHLESSTHAN:_Te,FULLWIDTHMIDDLEDOT:eHt,FULLWIDTHRIGHTPAREN:gTe,HYPHEN:pN,LEFTCORNERBRACKET:xTe,LEFTWHITECORNERBRACKET:vTe,LOCALHOST:_se,NL:Bnt,NUM:znt,OPENANGLEBRACKET:mTe,OPENBRACE:Mee,OPENBRACKET:cTe,OPENPAREN:uTe,PERCENT:Iee,PIPE:MTe,PLUS:PTe,POUND:ITe,QUERY:Lee,QUOTE:qnt,RIGHTCORNERBRACKET:yTe,RIGHTWHITECORNERBRACKET:bTe,SCHEME:f3e,SEMI:Vnt,SLASH:j5,SLASH_SCHEME:yU,SYM:RTe,TILDE:Ree,TLD:yWe,UNDERSCORE:LTe,UTLD:vWe,UWORD:xWe,WORD:yA,WS:bWe});const Q3=/[a-z]/,LZ=new RegExp("\\p{L}","u"),yBe=new RegExp("\\p{Emoji}","u"),J3=/\d/,vBe=/\s/,P1t="\r",bBe=` `,Len="️",Ren="‍",_Be="";let mde=null,fde=null;function Den(s=[]){const t={};gw.groups=t;const n=new gw;mde==null&&(mde=I1t(Aen)),fde==null&&(fde=I1t(Een)),_i(n,"'",NTe),_i(n,"{",Mee),_i(n,"}",Pee),_i(n,"[",cTe),_i(n,"]",dTe),_i(n,"(",uTe),_i(n,")",hTe),_i(n,"<",mTe),_i(n,">",fTe),_i(n,"(",pTe),_i(n,")",gTe),_i(n,"「",xTe),_i(n,"」",yTe),_i(n,"『",vTe),_i(n,"』",bTe),_i(n,"<",_Te),_i(n,">",wTe),_i(n,"&",jTe),_i(n,"*",kTe),_i(n,"@",fP),_i(n,"`",CTe),_i(n,"^",ATe),_i(n,":",f8),_i(n,",",$nt),_i(n,"$",ETe),_i(n,".",w5),_i(n,"=",TTe),_i(n,"!",Unt),_i(n,"-",pN),_i(n,"%",Iee),_i(n,"|",MTe),_i(n,"+",PTe),_i(n,"#",ITe),_i(n,"?",Lee),_i(n,'"',qnt),_i(n,"/",j5),_i(n,";",Vnt),_i(n,"~",Ree),_i(n,"_",LTe),_i(n,"\\",STe),_i(n,"・",eHt);const r=lx(n,J3,znt,{[mWe]:!0});lx(r,J3,r);const a=lx(r,Q3,QVt,{[Tee]:!0}),i=lx(r,LZ,JVt,{[hQ]:!0}),l=lx(n,Q3,yA,{[fWe]:!0});lx(l,J3,a),lx(l,Q3,l),lx(a,J3,a),lx(a,Q3,a);const o=lx(n,LZ,xWe,{[pWe]:!0});lx(o,Q3),lx(o,J3,i),lx(o,LZ,o),lx(i,J3,i),lx(i,Q3),lx(i,LZ,i);const c=_i(n,bBe,Bnt,{[xBe]:!0}),d=_i(n,P1t,bWe,{[xBe]:!0}),u=lx(n,vBe,bWe,{[xBe]:!0});_i(n,_Be,u),_i(d,bBe,c),_i(d,_Be,u),lx(d,vBe,u),_i(u,P1t),_i(u,bBe),lx(u,vBe,u),_i(u,_Be,u);const h=lx(n,yBe,tHt,{[XVt]:!0});_i(h,"#"),lx(h,yBe,h),_i(h,Len,h);const m=_i(h,Ren);_i(m,"#"),lx(m,yBe,h);const f=[[Q3,l],[J3,a]],g=[[Q3,null],[LZ,o],[J3,i]];for(let x=0;xx[0]>y[0]?1:-1);for(let x=0;x=0?b[gWe]=!0:Q3.test(y)?J3.test(y)?b[Tee]=!0:b[fWe]=!0:b[mWe]=!0,M1t(n,y,y,b)}return M1t(n,"localhost",_se,{ascii:!0}),n.jd=new gw(RTe),{start:n,tokens:Object.assign({groups:t},sHt)}}function nHt(s,t){const n=Fen(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 Fen(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 jM(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 wse={defaultProtocol:"http",events:null,format:L1t,formatHref:L1t,nl2br:!1,tagName:"a",target:null,rel:null,validate:!0,truncate:1/0,className:null,attributes:null,ignoreTags:[],render:null};function Hnt(s,t=null){let n=Object.assign({},wse);s&&(n=Object.assign(n,s instanceof Hnt?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=wse.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 q6e(s,t){class n extends rHt{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 Oen=q6e("email",{isLink:!0,toHref(){return"mailto:"+this.toString()}}),R1t=q6e("text"),zen=q6e("nl"),pde=q6e("url",{isLink:!0,toHref(s=wse.defaultProtocol){return this.hasProtocol()?this.v:`${s}://${this.v}`},hasProtocol(){const s=this.tk;return s.length>=2&&s[0].t!==_se&&s[1].t===f8}}),tN=s=>new gw(s);function Ben({groups:s}){const t=s.domain.concat([jTe,kTe,fP,STe,CTe,ATe,ETe,TTe,pN,znt,Iee,MTe,PTe,ITe,j5,RTe,Ree,LTe]),n=[NTe,f8,$nt,w5,Unt,Iee,Lee,qnt,Vnt,mTe,fTe,Mee,Pee,dTe,cTe,uTe,hTe,pTe,gTe,xTe,yTe,vTe,bTe,_Te,wTe],r=[jTe,NTe,kTe,STe,CTe,ATe,ETe,TTe,pN,Mee,Pee,Iee,MTe,PTe,ITe,Lee,j5,RTe,Ree,LTe],a=tN(),i=_i(a,Ree);eu(i,r,i),eu(i,s.domain,i);const l=tN(),o=tN(),c=tN();eu(a,s.domain,l),eu(a,s.scheme,o),eu(a,s.slashscheme,c),eu(l,r,i),eu(l,s.domain,l);const d=_i(l,fP);_i(i,fP,d),_i(o,fP,d),_i(c,fP,d);const u=_i(i,w5);eu(u,r,i),eu(u,s.domain,i);const h=tN();eu(d,s.domain,h),eu(h,s.domain,h);const m=_i(h,w5);eu(m,s.domain,h);const f=tN(Oen);eu(m,s.tld,f),eu(m,s.utld,f),_i(d,_se,f);const g=_i(h,pN);_i(g,pN,g),eu(g,s.domain,h),eu(f,s.domain,h),_i(f,w5,m),_i(f,pN,g);const x=_i(l,pN),y=_i(l,w5);_i(x,pN,x),eu(x,s.domain,l),eu(y,r,i),eu(y,s.domain,l);const v=tN(pde);eu(y,s.tld,v),eu(y,s.utld,v),eu(v,s.domain,l),eu(v,r,i),_i(v,w5,y),_i(v,pN,x),_i(v,fP,d);const b=_i(v,f8),w=tN(pde);eu(b,s.numeric,w);const S=tN(pde),A=tN();eu(S,t,S),eu(S,n,A),eu(A,t,S),eu(A,n,A),_i(v,j5,S),_i(w,j5,S);const E=_i(o,f8),I=_i(c,f8),P=_i(I,j5),R=_i(P,j5);eu(o,s.domain,l),_i(o,w5,y),_i(o,pN,x),eu(c,s.domain,l),_i(c,w5,y),_i(c,pN,x),eu(E,s.domain,S),_i(E,j5,S),_i(E,Lee,S),eu(R,s.domain,S),eu(R,t,S),_i(R,j5,S);const D=[[Mee,Pee],[cTe,dTe],[uTe,hTe],[mTe,fTe],[pTe,gTe],[xTe,yTe],[vTe,bTe],[_Te,wTe]];for(let O=0;O=0&&m++,a++,u++;if(m<0)a-=u,a0&&(i.push(wBe(R1t,t,l)),l=[]),a-=m,u-=m;const f=h.t,g=n.slice(a-u,a);i.push(wBe(f,t,g))}}return l.length>0&&i.push(wBe(R1t,t,l)),i}function wBe(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 Uen=typeof console<"u"&&console&&console.warn||(()=>{}),qen="until manual call of linkify.init(). Register all schemes and plugins before invoking linkify the first time.",bp={scanner:null,parser:null,tokenQueue:[],pluginQueue:[],customSchemes:[],initialized:!1};function Ven(){return gw.groups={},bp.scanner=null,bp.parser=null,bp.tokenQueue=[],bp.pluginQueue=[],bp.customSchemes=[],bp.initialized=!1,bp}function D1t(s,t=!1){if(bp.initialized&&Uen(`linkifyjs: already initialized - will not register custom scheme "${s}" ${qen}`),!/^[0-9a-z]+(-[0-9a-z]+)*$/.test(s))throw new Error(`linkifyjs: incorrect scheme format. 1. Must only contain digits, lowercase ASCII letters or "-" 2. Cannot start or end with "-" 3. "-" cannot repeat`);bp.customSchemes.push([s,t])}function Hen(){bp.scanner=Den(bp.customSchemes);for(let s=0;s{const a=t.some(d=>d.docChanged)&&!n.doc.eq(r.doc),i=t.some(d=>d.getMeta("preventAutolink"));if(!a||i)return;const{tr:l}=r,o=_Qs(n.doc,[...t]);if(AQs(o).forEach(({newRange:d})=>{const u=jQs(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(!Wen.test(f))return;h=u[0],m=r.doc.textBetween(h.pos,d.to,void 0," ")}if(h&&m){const f=m.split(Gen).filter(Boolean);if(f.length<=0)return!1;const g=f[f.length-1],x=h.pos+m.lastIndexOf(g);if(!g)return!1;const y=Gnt(g).map(v=>v.toObject(s.defaultProtocol));if(!Yen(y))return!1;y.filter(v=>v.isLink).map(v=>({...v,from:x+v.start+1,to:x+v.end+1})).filter(v=>r.schema.marks.code?!r.doc.rangeHasMark(v.from,v.to,r.schema.marks.code):!0).filter(v=>s.validate(v.value)).filter(v=>s.shouldAutoLink(v.value)).forEach(v=>{Lnt(v.from,v.to,r.doc).some(b=>b.mark.type===s.type)||l.addMark(v.from,v.to,s.type.create({href:v.href}))})}}),!!l.steps.length)return l}})}function Xen(s){return new z0({key:new E1("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=$Vt(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 Qen(s){return new z0({key:new E1("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=aHt(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 fR(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(Ken,"").match(new RegExp(`^(?:(?:${n.join("|")}):|[^a-z]|[a-z0-9+.-]+(?:[^a-z+.-:]|$))`,"i"))}const V6e=pC.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"){D1t(s);return}D1t(s.scheme,s.optionalSlashes)})},onDestroy(){Ven()},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)=>!!fR(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=>!!fR(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=>!!fR(t,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?["a",ep(this.options.HTMLAttributes,s),0]:["a",ep(this.options.HTMLAttributes,{...s,href:""}),0]},addCommands(){return{setLink:s=>({chain:t})=>{const{href:n}=s;return this.options.isAllowedUri(n,{defaultValidate:r=>!!fR(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=>!!fR(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[Y7({find:s=>{const t=[];if(s){const{protocols:n,defaultProtocol:r}=this.options,a=aHt(s).filter(i=>i.isLink&&this.options.isAllowedUri(i.value,{defaultValidate:l=>!!fR(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=>!!fR(a,t),protocols:t,defaultProtocol:n}),shouldAutoLink:this.options.shouldAutoLink})),this.options.openOnClick===!0&&s.push(Xen({type:this.type})),this.options.linkOnPaste&&s.push(Qen({editor:this.editor,defaultProtocol:this.options.defaultProtocol,type:this.type})),s}}),H6e=Cb.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")}}}),Jen=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}`)})},Knt=pC.create({name:"textStyle",priority:101,addOptions(){return{HTMLAttributes:{},mergeNestedSpanStyles:!1}},parseHTML(){return[{tag:"span",getAttrs:s=>s.hasAttribute("style")?(this.options.mergeNestedSpanStyles&&Jen(s),{}):!1}]},renderHTML({HTMLAttributes:s}){return["span",ep(this.options.HTMLAttributes,s),0]},addCommands(){return{removeEmptyTextStyle:()=>({tr:s})=>{const{selection:t}=s;return s.doc.nodesBetween(t.from,t.to,(n,r)=>{if(n.isTextblock)return!0;n.marks.filter(a=>a.type===this.type).some(a=>Object.values(a.attrs).some(i=>!!i))||s.removeMark(r,r+n.nodeSize,this.type)}),!0}}}}),etn=/(?:^|\s)(!\[(.+|:?)]\((\S+)(?:(?:\s+)["'](\S+)["'])?\))$/,iHt=Iv.create({name:"image",addOptions(){return{inline:!1,allowBase64:!1,HTMLAttributes:{}}},inline(){return this.options.inline},group(){return this.options.inline?"inline":"block"},draggable:!0,addAttributes(){return{src:{default:null},alt:{default:null},title:{default:null}}},parseHTML(){return[{tag:this.options.allowBase64?"img[src]":'img[src]:not([src^="data:"])'}]},renderHTML({HTMLAttributes:s}){return["img",ep(this.options.HTMLAttributes,s)]},addCommands(){return{setImage:s=>({commands:t})=>t.insertContent({type:this.name,attrs:s})}},addInputRules(){return[UVt({find:etn,type:this.type,getAttributes:s=>{const[,,t,n,r]=s;return{src:n,alt:t,title:r}}})]}});let _We,wWe;if(typeof WeakMap<"u"){let s=new WeakMap;_We=t=>s.get(t),wWe=(t,n)=>(s.set(t,n),n)}else{const s=[];let n=0;_We=r=>{for(let a=0;a(n==10&&(n=0),s[n++]=r,s[n++]=a)}var _x=class{constructor(s,t,n,r){this.width=s,this.height=t,this.map=n,this.problems=r}findCell(s){for(let t=0;t=n){(i||(i=[])).push({type:"overlong_rowspan",pos:u,n:v-w});break}const S=a+w*t;for(let 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 ntn(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 atn(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 wC(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 G6e(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=Z7(t.$head)||itn(t.$head);if(n)return n;throw new RangeError(`No cell found around position ${t.head}`)}function itn(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 jWe(s){return s.parent.type.spec.tableRole=="row"&&!!s.nodeAfter}function otn(s){return s.node(0).resolve(s.pos+s.nodeAfter.nodeSize)}function Ynt(s,t){return s.depth==t.depth&&s.pos>=t.start(-1)&&s.pos<=t.end(-1)}function oHt(s,t,n){const r=s.node(-1),a=_x.get(r),i=s.start(-1),l=a.nextCell(s.pos-i,t,n);return l==null?null:s.node(0).resolve(i+l)}function X7(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 lHt(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 Mqt(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(jWe(r)&&jWe(a)&&Ynt(r,a)){const i=this.$anchorCell.node(-1)!=r.node(-1);return i&&this.isRowSelection()?vA.rowSelection(r,a):i&&this.isColSelection()?vA.colSelection(r,a):new vA(r,a)}return El.between(r,a)}content(){const t=this.$anchorCell.node(-1),n=_x.get(t),r=this.$anchorCell.start(-1),a=n.rectBetween(this.$anchorCell.pos-r,this.$headCell.pos-r),i={},l=[];for(let c=a.top;c0||y>0){let v=g.attrs;if(x>0&&(v=X7(v,0,x)),y>0&&(v=X7(v,v.colspan-y,y)),f.lefta.bottom){const v={...g.attrs,rowspan:Math.min(f.bottom,a.bottom)-Math.max(f.top,a.top)};f.top0)return!1;const r=t+this.$anchorCell.nodeAfter.attrs.rowspan,a=n+this.$headCell.nodeAfter.attrs.rowspan;return Math.max(r,a)==this.$headCell.node(-1).childCount}static colSelection(t,n=t){const r=t.node(-1),a=_x.get(r),i=t.start(-1),l=a.findCell(t.pos-i),o=a.findCell(n.pos-i),c=t.node(0);return l.top<=o.top?(l.top>0&&(t=c.resolve(i+a.map[l.left])),o.bottom0&&(n=c.resolve(i+a.map[o.left])),l.bottom0)return!1;const l=a+this.$anchorCell.nodeAfter.attrs.colspan,o=i+this.$headCell.nodeAfter.attrs.colspan;return Math.max(l,o)==n.width}eq(t){return t instanceof vA&&t.$anchorCell.pos==this.$anchorCell.pos&&t.$headCell.pos==this.$headCell.pos}static rowSelection(t,n=t){const r=t.node(-1),a=_x.get(r),i=t.start(-1),l=a.findCell(t.pos-i),o=a.findCell(n.pos-i),c=t.node(0);return l.left<=o.left?(l.left>0&&(t=c.resolve(i+a.map[l.top*a.width])),o.right0&&(n=c.resolve(i+a.map[o.top*a.width])),l.right{t.push(x_.node(r,r+n.nodeSize,{class:"selectedCell"}))}),vx.create(s.doc,t)}function utn({$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 htn({$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 mtn(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=Jf.create(a,r.from);else if(l=="row"){const o=a.resolve(r.from+1);i=Jf.rowSelection(o,o)}else if(!n){const o=_x.get(r.node),c=r.from+1,d=c+o.map[o.width*o.height-1];i=Jf.create(a,c+1,d)}}else r instanceof El&&utn(r)?i=El.create(a,r.from):r instanceof El&&htn(r)&&(i=El.create(a,r.$from.start(),r.$from.end()));return i&&(t||(t=s.tr)).setSelection(i),t}const ftn=new E1("fix-tables");function dHt(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=ptn(s,a,i,n))};return t?t.doc!=s.doc&&dHt(t.doc,s.doc,0,r):s.doc.descendants(r),n}function ptn(s,t,n,r){const a=_x.get(t);if(!a.problems)return r;r||(r=s.tr);const i=[];for(let c=0;c0){let f="cell";u.firstChild&&(f=u.firstChild.type.spec.tableRole);const g=[];for(let y=0;y0?-1:0;ltn(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;btn(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=F1t(d)?c+1:u;i.replaceWith(h+r.tableStart,u+r.tableStart,o)}i.setSelection(new Jf(i.doc.resolve(c+r.tableStart))),t(i)}return!0}function z1t(s,t){const n=k1(s.schema);return Stn(({node:r})=>n[r.type.spec.tableRole])(s,t)}function Stn(s){return(t,n)=>{const r=t.selection;let a,i;if(r instanceof Jf){if(r.$anchorCell.pos!=r.$headCell.pos)return!1;a=r.$anchorCell.nodeAfter,i=r.$anchorCell.pos}else{var l;if(a=atn(r.$from),!a)return!1;i=(l=Z7(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=o3(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 Atn(s){return function(t,n){if(!wC(t))return!1;if(n){const r=k1(t.schema),a=o3(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}}jse("row",{useDeprecatedLogic:!0});jse("column",{useDeprecatedLogic:!0});const Etn=jse("cell",{useDeprecatedLogic:!0});function Ttn(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 gde(s,t){const n=s.selection;if(!(n instanceof Jf))return!1;if(t){const r=s.tr,a=k1(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 Ptn(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(ui.empty),n[a]r&&(m=m.type.createChecked(X7(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(ui.from(c))}n=i,t=a}return{width:s,height:t,rows:n}}function Rtn(s,t,n,r,a,i,l){const o=s.doc.type.schema,c=k1(o);let d,u;if(a>t.width)for(let h=0,m=0;ht.height){const h=[];for(let g=0,x=(t.height-1)*t.width;g=t.width?!1:n.nodeAt(t.map[x+g]).type==c.header_cell;h.push(y?u||(u=c.header_cell.createAndFill()):d||(d=c.cell.createAndFill()))}const m=c.row.create(null,ui.from(h)),f=[];for(let g=t.height;g{if(!a)return!1;const i=n.selection;if(i instanceof Jf)return p3e(n,r,Nc.near(i.$headCell,t));if(s!="horiz"&&!i.empty)return!1;const l=fHt(a,s,t);if(l==null)return!1;if(s=="horiz")return p3e(n,r,Nc.near(n.doc.resolve(i.head+t),t));{const o=n.doc.resolve(l),c=oHt(o,s,t);let d;return c?d=Nc.near(c,1):t<0?d=Nc.near(n.doc.resolve(o.before(-1)),-1):d=Nc.near(n.doc.resolve(o.after(-1)),1),p3e(n,r,d)}}}function yde(s,t){return(n,r,a)=>{if(!a)return!1;const i=n.selection;let l;if(i instanceof Jf)l=i;else{const c=fHt(a,s,t);if(c==null)return!1;l=new Jf(n.doc.resolve(c))}const o=oHt(l.$headCell,s,t);return o?p3e(n,r,new Jf(l.$anchorCell,o)):!1}}function Ftn(s,t){const n=s.state.doc,r=Z7(n.resolve(t));return r?(s.dispatch(s.state.tr.setSelection(new Jf(r))),!0):!1}function Otn(s,t,n){if(!wC(s.state))return!1;let r=Ptn(n);const a=s.state.selection;if(a instanceof Jf){r||(r={width:1,height:1,rows:[ui.from(NWe(k1(s.state.schema).cell,n))]});const i=a.$anchorCell.node(-1),l=a.$anchorCell.start(-1),o=_x.get(i).rectBetween(a.$anchorCell.pos-l,a.$headCell.pos-l);return r=Ltn(r,o.right-o.left,o.bottom-o.top),V1t(s.state,s.dispatch,l,o,r),!0}else if(r){const i=G6e(s.state),l=i.start(-1);return V1t(s.state,s.dispatch,l,_x.get(i.node(-1)).findCell(i.pos-l),r),!0}else return!1}function ztn(s,t){var n;if(t.button!=0||t.ctrlKey||t.metaKey)return;const r=H1t(s,t.target);let a;if(t.shiftKey&&s.state.selection instanceof Jf)i(s.state.selection.$anchorCell,t),t.preventDefault();else if(t.shiftKey&&r&&(a=Z7(s.state.selection.$anchor))!=null&&((n=jBe(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=jBe(s,d);const h=SP.getState(s.state)==null;if(!u||!Ynt(c,u))if(h)u=c;else return;const m=new Jf(c,u);if(h||!s.state.selection.eq(m)){const f=s.state.tr.setSelection(m);h&&f.setMeta(SP,c.pos),s.dispatch(f)}}function l(){s.root.removeEventListener("mouseup",l),s.root.removeEventListener("dragstart",l),s.root.removeEventListener("mousemove",o),SP.getState(s.state)!=null&&s.dispatch(s.state.tr.setMeta(SP,-1))}function o(c){const d=c,u=SP.getState(s.state);let h;if(u!=null)h=s.state.doc.resolve(u);else if(H1t(s,d.target)!=r&&(h=jBe(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 fHt(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 H1t(s,t){for(;t&&t!=s.dom;t=t.parentNode)if(t.nodeName=="TD"||t.nodeName=="TH")return t;return null}function jBe(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&&Z7(s.state.doc.resolve(r))||Z7(s.state.doc.resolve(a))}var Btn=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")),kWe(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,kWe(t,this.colgroup,this.table,this.defaultCellMinWidth),!0)}ignoreMutation(t){return t.type=="attributes"&&(t.target==this.table||this.colgroup.contains(t.target))}};function kWe(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 Utn(-1,!1)},apply(l,o){return o.apply(l)}},props:{attributes:l=>{const o=Kj.getState(l);return o&&o.activeHandle>-1?{class:"resize-cursor"}:{}},handleDOMEvents:{mousemove:(l,o)=>{qtn(l,o,s,a)},mouseleave:l=>{Vtn(l)},mousedown:(l,o)=>{Htn(l,o,t,n)}},decorations:l=>{const o=Kj.getState(l);if(o&&o.activeHandle>-1)return Ztn(l,o.activeHandle)},nodeViews:{}}});return i}var Utn=class g3e{constructor(t,n){this.activeHandle=t,this.dragging=n}apply(t){const n=this,r=t.getMeta(Kj);if(r&&r.setHandle!=null)return new g3e(r.setHandle,!1);if(r&&r.setDragging!==void 0)return new g3e(n.activeHandle,r.setDragging);if(n.activeHandle>-1&&t.docChanged){let a=t.mapping.map(n.activeHandle,-1);return jWe(t.doc.resolve(a))||(a=-1),new g3e(a,n.dragging)}return n}};function qtn(s,t,n,r){if(!s.editable)return;const a=Kj.getState(s.state);if(a&&!a.dragging){const i=Wtn(t.target);let l=-1;if(i){const{left:o,right:c}=i.getBoundingClientRect();t.clientX-o<=n?l=G1t(s,t,"left",n):c-t.clientX<=n&&(l=G1t(s,t,"right",n))}if(l!=a.activeHandle){if(!r&&l!==-1){const o=s.state.doc.resolve(l),c=o.node(-1),d=_x.get(c),u=o.start(-1);if(d.colCount(o.pos-u)+o.nodeAfter.attrs.colspan-1==d.width-1)return}pHt(s,l)}}}function Vtn(s){if(!s.editable)return;const t=Kj.getState(s.state);t&&t.activeHandle>-1&&!t.dragging&&pHt(s,-1)}function Htn(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=Kj.getState(s.state);if(!l||l.activeHandle==-1||l.dragging)return!1;const o=s.state.doc.nodeAt(l.activeHandle),c=Gtn(s,l.activeHandle,o.attrs);s.dispatch(s.state.tr.setMeta(Kj,{setDragging:{startX:t.clientX,startWidth:c}}));function d(h){i.removeEventListener("mouseup",d),i.removeEventListener("mousemove",u);const m=Kj.getState(s.state);m!=null&&m.dragging&&(Ktn(s,m.activeHandle,W1t(m.dragging,h,n)),s.dispatch(s.state.tr.setMeta(Kj,{setDragging:null})))}function u(h){if(!h.which)return d(h);const m=Kj.getState(s.state);if(m&&m.dragging){const f=W1t(m.dragging,h,n);K1t(s,m.activeHandle,f,r)}}return K1t(s,l.activeHandle,c,r),i.addEventListener("mouseup",d),i.addEventListener("mousemove",u),t.preventDefault(),!0}function Gtn(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 tsn(s,t,n,r,a){const i=esn(s),l=[],o=[];for(let d=0;d{const{selection:t}=s.state;if(!ssn(t))return!1;let n=0;const r=BVt(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},nsn=Iv.create({name:"table",addOptions(){return{HTMLAttributes:{},resizable:!1,renderWrapper:!1,handleWidth:5,cellMinWidth:25,View:Qtn,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}=Jtn(s,this.options.cellMinWidth),i=["table",ep(this.options.HTMLAttributes,t,{style:r?`width: ${r}`:`min-width: ${a}`}),n,["tbody",0]];return this.options.renderWrapper?["div",{class:"tableWrapper"},i]:i},addCommands(){return{insertTable:({rows:s=3,cols:t=3,withHeaderRow:n=!0}={})=>({tr:r,dispatch:a,editor:i})=>{const l=tsn(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})=>gtn(s,t),addColumnAfter:()=>({state:s,dispatch:t})=>xtn(s,t),deleteColumn:()=>({state:s,dispatch:t})=>vtn(s,t),addRowBefore:()=>({state:s,dispatch:t})=>_tn(s,t),addRowAfter:()=>({state:s,dispatch:t})=>wtn(s,t),deleteRow:()=>({state:s,dispatch:t})=>Ntn(s,t),deleteTable:()=>({state:s,dispatch:t})=>Mtn(s,t),mergeCells:()=>({state:s,dispatch:t})=>O1t(s,t),splitCell:()=>({state:s,dispatch:t})=>z1t(s,t),toggleHeaderColumn:()=>({state:s,dispatch:t})=>jse("column")(s,t),toggleHeaderRow:()=>({state:s,dispatch:t})=>jse("row")(s,t),toggleHeaderCell:()=>({state:s,dispatch:t})=>Etn(s,t),mergeOrSplit:()=>({state:s,dispatch:t})=>O1t(s,t)?!0:z1t(s,t),setCellAttribute:(s,t)=>({state:n,dispatch:r})=>Ctn(s,t)(n,r),goToNextCell:()=>({state:s,dispatch:t})=>$1t(1)(s,t),goToPreviousCell:()=>({state:s,dispatch:t})=>$1t(-1)(s,t),fixTables:()=>({state:s,dispatch:t})=>(t&&uHt(s),!0),setCellSelection:s=>({tr:t,dispatch:n})=>{if(n){const r=Jf.create(t.doc,s.anchorCell,s.headCell);t.setSelection(r)}return!0}}},addKeyboardShortcuts(){return{Tab:()=>this.editor.commands.goToNextCell()?!0:this.editor.can().addRowAfter()?this.editor.chain().addRowAfter().goToNextCell().run():!1,"Shift-Tab":()=>this.editor.commands.goToPreviousCell(),Backspace:vde,"Mod-Backspace":vde,Delete:vde,"Mod-Delete":vde}},addProseMirrorPlugins(){return[...this.options.resizable&&this.editor.isEditable?[$tn({handleWidth:this.options.handleWidth,cellMinWidth:this.options.cellMinWidth,defaultCellMinWidth:this.options.cellMinWidth,View:this.options.View,lastColumnResizable:this.options.lastColumnResizable})]:[],Xtn({allowTableNodeSelection:this.options.allowTableNodeSelection})]},extendNodeSchema(s){const t={name:s.name,options:s.options,storage:s.storage};return{tableRole:wd(Uo(s,"tableRole",t))}}}),rsn=Iv.create({name:"tableRow",addOptions(){return{HTMLAttributes:{}}},content:"(tableCell | tableHeader)*",tableRole:"row",parseHTML(){return[{tag:"tr"}]},renderHTML({HTMLAttributes:s}){return["tr",ep(this.options.HTMLAttributes,s),0]}}),asn=Iv.create({name:"tableCell",addOptions(){return{HTMLAttributes:{}}},content:"block+",addAttributes(){return{colspan:{default:1},rowspan:{default:1},colwidth:{default:null,parseHTML:s=>{const t=s.getAttribute("colwidth");return t?t.split(",").map(r=>parseInt(r,10)):null}}}},tableRole:"cell",isolating:!0,parseHTML(){return[{tag:"td"}]},renderHTML({HTMLAttributes:s}){return["td",ep(this.options.HTMLAttributes,s),0]}}),isn=Iv.create({name:"tableHeader",addOptions(){return{HTMLAttributes:{}}},content:"block+",addAttributes(){return{colspan:{default:1},rowspan:{default:1},colwidth:{default:null,parseHTML:s=>{const t=s.getAttribute("colwidth");return t?t.split(",").map(r=>parseInt(r,10)):null}}}},tableRole:"header_cell",isolating:!0,parseHTML(){return[{tag:"th"}]},renderHTML({HTMLAttributes:s}){return["th",ep(this.options.HTMLAttributes,s),0]}});function Sk({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=$6e({extensions:[U6e,V6e.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline"}}),H6e.configure({types:["heading","paragraph"]}),Knt,iHt.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}),nsn.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}),rsn.extend({addAttributes(){var x;return{...(x=this.parent)==null?void 0:x.call(this),style:{default:null}}}}),asn.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}}}}),isn.extend({addAttributes(){var x;return{...(x=this.parent)==null?void 0:x.call(this),style:{default:null},width:{default:null},colspan:{default:1},rowspan:{default:1}}}})],content:s,onUpdate:({editor:x})=>{t(x.getHTML())},editorProps:{attributes:{class:"outline-none","data-placeholder":n},handlePaste:(x,y)=>{var b;const v=(b=y.clipboardData)==null?void 0:b.items;if(!v)return!1;for(const w of Array.from(v))if(w.type.startsWith("image/")){y.preventDefault();const S=w.getAsFile();if(!S)continue;const 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||"",y=h.getAttributes("link").target;c(x),u(y==="_blank"),l(!0)},f=()=>{h&&(o===""?h.chain().focus().extendMarkRange("link").unsetLink().run():h.chain().focus().extendMarkRange("link").setLink({href:o,target:d?"_blank":null,rel:d?"noopener noreferrer nofollow":null}).run(),l(!1),c(""))},g=()=>{h&&h.chain().focus().extendMarkRange("link").unsetLink().run()};return h?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-0.5 p-2 border-b bg-muted/30",children:[e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().toggleHeading({level:1}).run(),className:h.isActive("heading",{level:1})?"bg-muted":"",title:"Heading 1",children:e.jsx(Rq,{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($z,{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(SE,{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(EE,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().toggleBulletList().run(),className:h.isActive("bulletList")?"bg-muted":"",title:"Bullet List",children:e.jsx(T0,{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(u2,{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(FI,{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(DI,{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(OI,{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(OE,{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(DE,{className:"h-4 w-4"})})]}),e.jsx(B6e,{editor:h,className:"prose prose-sm max-w-none p-3 focus:outline-none [&_.ProseMirror]:outline-none [&_.ProseMirror_img]:max-w-none [&_.ProseMirror_table]:border-none [&_.ProseMirror_table]:border-collapse [&_.ProseMirror_td]:border-none [&_.ProseMirror_td]:p-0 [&_.ProseMirror_td]:align-top [&_.ProseMirror_th]:border-none [&_.ProseMirror_th]:p-0 [&_.ProseMirror_tr]:border-none",style:{minHeight:r}})]}),e.jsx(zs,{open:i,onOpenChange:l,children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Insert Link"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"link-url",children:"URL"}),e.jsx(pe,{id:"link-url",value:o,onChange:x=>c(x.target.value),placeholder:"https://example.com"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Sn,{id:"link-new-tab",checked:d,onCheckedChange:u}),e.jsx(ee,{htmlFor:"link-new-tab",children:"Open in new tab"})]})]}),e.jsxs(Sr,{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 Znt={x:0,y:0,width:0,height:0,unit:"px"},N$=(s,t,n)=>Math.min(Math.max(s,t),n),osn=(...s)=>s.filter(t=>t&&typeof t=="string").join(" "),X1t=(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 lsn(s,t,n,r){let a=N5(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==="%"?pP(a,n,r):a}function csn(s,t,n){let r=N5(s,t,n);return r.x=(t-r.width)/2,r.y=(n-r.height)/2,s.unit==="%"?pP(r,t,n):r}function pP(s,t,n){return s.unit==="%"?{...Znt,...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 N5(s,t,n){return!s.unit||s.unit==="px"?{...Znt,...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 Q1t(s,t,n,r,a,i=0,l=0,o=r,c=a){let d={...s},u=Math.min(i,r),h=Math.min(l,a),m=Math.min(o,r),f=Math.min(c,a);t&&(t>1?(u=l?l*t:u,h=u/t,m=o*t):(h=i?i/t:h,u=h*t,f=c/t)),d.y<0&&(d.height=Math.max(d.height+d.y,h),d.y=0),d.x<0&&(d.width=Math.max(d.width+d.x,u),d.x=0);let g=r-(d.x+d.width);g<0&&(d.x=Math.min(d.x,r-u),d.width+=g);let x=a-(d.y+d.height);if(x<0&&(d.y=Math.min(d.y,a-h),d.height+=x),d.widthm&&((n==="sw"||n=="nw")&&(d.x-=m-d.width),d.width=m),d.height>f&&((n==="nw"||n=="ne")&&(d.y-=f-d.height),d.height=f),t){let y=d.width/d.height;if(yt){let v=Math.max(d.height*t,u);(n==="sw"||n=="nw")&&(d.x-=v-d.width),d.width=v}}return d}function dsn(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 k$={capture:!0,passive:!1},usn=0,px,hsn=(px=class extends j.PureComponent{constructor(){super(...arguments);Nr(this,"docMoveBound",!1);Nr(this,"mouseDownOnCrop",!1);Nr(this,"dragStarted",!1);Nr(this,"evData",{startClientX:0,startClientY:0,startCropX:0,startCropY:0,clientX:0,clientY:0,isResize:!0});Nr(this,"componentRef",j.createRef());Nr(this,"mediaRef",j.createRef());Nr(this,"resizeObserver");Nr(this,"initChangeCalled",!1);Nr(this,"instanceId",`rc-${usn++}`);Nr(this,"state",{cropIsActive:!1,newCropIsBeingDrawn:!1});Nr(this,"onCropPointerDown",n=>{let{crop:r,disabled:a}=this.props,i=this.getBox();if(!r)return;let l=N5(r,i.width,i.height);if(a)return;n.cancelable&&n.preventDefault(),this.bindDocMove(),this.componentRef.current.focus({preventScroll:!0});let o=n.target.dataset.ord,c=!!o,d=n.clientX,u=n.clientY,h=l.x,m=l.y;if(o){let f=n.clientX-i.x,g=n.clientY-i.y,x=0,y=0;o==="ne"||o=="e"?(x=f-(l.x+l.width),y=g-l.y,h=l.x,m=l.y+l.height):o==="se"||o==="s"?(x=f-(l.x+l.width),y=g-(l.y+l.height),h=l.x,m=l.y):o==="sw"||o=="w"?(x=f-l.x,y=g-(l.y+l.height),h=l.x+l.width,m=l.y):(o==="nw"||o=="n")&&(x=f-l.x,y=g-l.y,h=l.x+l.width,m=l.y+l.height),d=h+i.x+x,u=m+i.y+y}this.evData={startClientX:d,startClientY:u,startCropX:h,startCropY:m,clientX:n.clientX,clientY:n.clientY,isResize:c,ord:o},this.mouseDownOnCrop=!0,this.setState({cropIsActive:!0})});Nr(this,"onComponentPointerDown",n=>{let{crop:r,disabled:a,locked:i,keepSelection:l,onChange:o}=this.props,c=this.getBox();if(a||i||l&&r)return;n.cancelable&&n.preventDefault(),this.bindDocMove(),this.componentRef.current.focus({preventScroll:!0});let d=n.clientX-c.x,u=n.clientY-c.y,h={unit:"px",x:d,y:u,width:0,height:0};this.evData={startClientX:n.clientX,startClientY:n.clientY,startCropX:d,startCropY:u,clientX:n.clientX,clientY:n.clientY,isResize:!0},this.mouseDownOnCrop=!0,o(N5(h,c.width,c.height),pP(h,c.width,c.height)),this.setState({cropIsActive:!0,newCropIsBeingDrawn:!0})});Nr(this,"onDocPointerMove",n=>{let{crop:r,disabled:a,onChange:i,onDragStart:l}=this.props,o=this.getBox();if(a||!r||!this.mouseDownOnCrop)return;n.cancelable&&n.preventDefault(),this.dragStarted||(this.dragStarted=!0,l&&l(n));let{evData:c}=this;c.clientX=n.clientX,c.clientY=n.clientY;let d;d=c.isResize?this.resizeCrop():this.dragCrop(),X1t(r,d)||i(N5(d,o.width,o.height),pP(d,o.width,o.height))});Nr(this,"onComponentKeyDown",n=>{let{crop:r,disabled:a,onChange:i,onComplete:l}=this.props;if(a)return;let o=n.key,c=!1;if(!r)return;let d=this.getBox(),u=this.makePixelCrop(d),h=(navigator.platform.match("Mac")?n.metaKey:n.ctrlKey)?px.nudgeStepLarge:n.shiftKey?px.nudgeStepMedium:px.nudgeStep;if(o==="ArrowLeft"?(u.x-=h,c=!0):o==="ArrowRight"?(u.x+=h,c=!0):o==="ArrowUp"?(u.y-=h,c=!0):o==="ArrowDown"&&(u.y+=h,c=!0),c){n.cancelable&&n.preventDefault(),u.x=N$(u.x,0,d.width-u.width),u.y=N$(u.y,0,d.height-u.height);let m=N5(u,d.width,d.height),f=pP(u,d.width,d.height);i(m,f),l&&l(m,f)}});Nr(this,"onHandlerKeyDown",(n,r)=>{let{aspect:a=0,crop:i,disabled:l,minWidth:o=0,minHeight:c=0,maxWidth:d,maxHeight:u,onChange:h,onComplete:m}=this.props,f=this.getBox();if(l||!i)return;if(n.key==="ArrowUp"||n.key==="ArrowDown"||n.key==="ArrowLeft"||n.key==="ArrowRight")n.stopPropagation(),n.preventDefault();else return;let g=(navigator.platform.match("Mac")?n.metaKey:n.ctrlKey)?px.nudgeStepLarge:n.shiftKey?px.nudgeStepMedium:px.nudgeStep,x=Q1t(dsn(N5(i,f.width,f.height),n.key,g,r),a,r,f.width,f.height,o,c,d,u);if(!X1t(i,x)){let y=pP(x,f.width,f.height);h(x,y),m&&m(x,y)}});Nr(this,"onDocPointerDone",n=>{let{crop:r,disabled:a,onComplete:i,onDragEnd:l}=this.props,o=this.getBox();this.unbindDocMove(),!(a||!r)&&this.mouseDownOnCrop&&(this.mouseDownOnCrop=!1,this.dragStarted=!1,l&&l(n),i&&i(N5(r,o.width,o.height),pP(r,o.width,o.height)),this.setState({cropIsActive:!1,newCropIsBeingDrawn:!1}))});Nr(this,"onDragFocus",()=>{var n;(n=this.componentRef.current)==null||n.scrollTo(0,0)})}get document(){return document}getBox(){let n=this.mediaRef.current;if(!n)return{x:0,y:0,width:0,height:0};let{x:r,y:a,width:i,height:l}=n.getBoundingClientRect();return{x:r,y:a,width:i,height:l}}componentDidUpdate(n){let{crop:r,onComplete:a}=this.props;if(a&&!n.crop&&r){let{width:i,height:l}=this.getBox();i&&l&&a(N5(r,i,l),pP(r,i,l))}}componentWillUnmount(){this.resizeObserver&&this.resizeObserver.disconnect(),this.unbindDocMove()}bindDocMove(){this.docMoveBound||(this.docMoveBound=(this.document.addEventListener("pointermove",this.onDocPointerMove,k$),this.document.addEventListener("pointerup",this.onDocPointerDone,k$),this.document.addEventListener("pointercancel",this.onDocPointerDone,k$),!0))}unbindDocMove(){this.docMoveBound&&(this.docMoveBound=(this.document.removeEventListener("pointermove",this.onDocPointerMove,k$),this.document.removeEventListener("pointerup",this.onDocPointerDone,k$),this.document.removeEventListener("pointercancel",this.onDocPointerDone,k$),!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=N$(n.startCropX+i,0,r.width-a.width),a.y=N$(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=Q1t(g,r,u,l.width,l.height,o,c,a,i);return r||px.xyOrds.indexOf(h)>-1?d=x:px.xOrds.indexOf(h)>-1?(d.x=x.x,d.width=x.width):px.yOrds.indexOf(h)>-1&&(d.y=x.y,d.height=x.height),d.x=N$(d.x,0,l.width-d.width),d.y=N$(d.y,0,l.height-d.height),d}renderCropSelection(){let{ariaLabels:n=px.defaultProps.ariaLabels,disabled:r,locked:a,renderSelectionAddon:i,ruleOfThirds:l,crop:o}=this.props,c=this.getCropStyle();if(o)return Gt.createElement("div",{style:c,className:"ReactCrop__crop-selection",onPointerDown:this.onCropPointerDown,"aria-label":n.cropArea,tabIndex:0,onKeyDown:this.onComponentKeyDown,role:"group"},!r&&!a&&Gt.createElement("div",{className:"ReactCrop__drag-elements",onFocus:this.onDragFocus},Gt.createElement("div",{className:"ReactCrop__drag-bar ord-n","data-ord":"n"}),Gt.createElement("div",{className:"ReactCrop__drag-bar ord-e","data-ord":"e"}),Gt.createElement("div",{className:"ReactCrop__drag-bar ord-s","data-ord":"s"}),Gt.createElement("div",{className:"ReactCrop__drag-bar ord-w","data-ord":"w"}),Gt.createElement("div",{className:"ReactCrop__drag-handle ord-nw","data-ord":"nw",tabIndex:0,"aria-label":n.nwDragHandle,onKeyDown:d=>this.onHandlerKeyDown(d,"nw"),role:"button"}),Gt.createElement("div",{className:"ReactCrop__drag-handle ord-n","data-ord":"n",tabIndex:0,"aria-label":n.nDragHandle,onKeyDown:d=>this.onHandlerKeyDown(d,"n"),role:"button"}),Gt.createElement("div",{className:"ReactCrop__drag-handle ord-ne","data-ord":"ne",tabIndex:0,"aria-label":n.neDragHandle,onKeyDown:d=>this.onHandlerKeyDown(d,"ne"),role:"button"}),Gt.createElement("div",{className:"ReactCrop__drag-handle ord-e","data-ord":"e",tabIndex:0,"aria-label":n.eDragHandle,onKeyDown:d=>this.onHandlerKeyDown(d,"e"),role:"button"}),Gt.createElement("div",{className:"ReactCrop__drag-handle ord-se","data-ord":"se",tabIndex:0,"aria-label":n.seDragHandle,onKeyDown:d=>this.onHandlerKeyDown(d,"se"),role:"button"}),Gt.createElement("div",{className:"ReactCrop__drag-handle ord-s","data-ord":"s",tabIndex:0,"aria-label":n.sDragHandle,onKeyDown:d=>this.onHandlerKeyDown(d,"s"),role:"button"}),Gt.createElement("div",{className:"ReactCrop__drag-handle ord-sw","data-ord":"sw",tabIndex:0,"aria-label":n.swDragHandle,onKeyDown:d=>this.onHandlerKeyDown(d,"sw"),role:"button"}),Gt.createElement("div",{className:"ReactCrop__drag-handle ord-w","data-ord":"w",tabIndex:0,"aria-label":n.wDragHandle,onKeyDown:d=>this.onHandlerKeyDown(d,"w"),role:"button"})),i&&Gt.createElement("div",{className:"ReactCrop__selection-addon",onPointerDown:d=>d.stopPropagation()},i(this.state)),l&&Gt.createElement(Gt.Fragment,null,Gt.createElement("div",{className:"ReactCrop__rule-of-thirds-hz"}),Gt.createElement("div",{className:"ReactCrop__rule-of-thirds-vt"})))}makePixelCrop(n){return N5({...Znt,...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=osn("ReactCrop",i,h&&"ReactCrop--active",o&&"ReactCrop--disabled",c&&"ReactCrop--locked",m&&"ReactCrop--new-crop",l&&n&&"ReactCrop--fixed-aspect",l&&a&&"ReactCrop--circular-crop",l&&u&&"ReactCrop--rule-of-thirds",!this.dragStarted&&l&&!l.width&&!l.height&&"ReactCrop--invisible-crop",a&&"ReactCrop--no-animate");return Gt.createElement("div",{ref:this.componentRef,className:g,style:d},Gt.createElement("div",{ref:this.mediaRef,className:"ReactCrop__child-wrapper",onPointerDown:this.onComponentPointerDown},r),l?Gt.createElement("svg",{className:"ReactCrop__crop-mask",width:"100%",height:"100%"},Gt.createElement("defs",null,Gt.createElement("mask",{id:`hole-${this.instanceId}`},Gt.createElement("rect",{width:"100%",height:"100%",fill:"white"}),a?Gt.createElement("ellipse",{cx:`${l.x+l.width/2}${l.unit}`,cy:`${l.y+l.height/2}${l.unit}`,rx:`${l.width/2}${l.unit}`,ry:`${l.height/2}${l.unit}`,fill:"black"}):Gt.createElement("rect",{x:`${l.x}${l.unit}`,y:`${l.y}${l.unit}`,width:`${l.width}${l.unit}`,height:`${l.height}${l.unit}`,fill:"black"}))),Gt.createElement("rect",{fill:"black",fillOpacity:.5,width:"100%",height:"100%",mask:`url(#hole-${this.instanceId})`})):void 0,f)}},Nr(px,"xOrds",["e","w"]),Nr(px,"yOrds",["n","s"]),Nr(px,"xyOrds",["nw","ne","se","sw"]),Nr(px,"nudgeStep",1),Nr(px,"nudgeStepMedium",10),Nr(px,"nudgeStepLarge",100),Nr(px,"defaultProps",{ariaLabels:{cropArea:"Use the arrow keys to move the crop selection area",nwDragHandle:"Use the arrow keys to move the north west drag handle to change the crop selection area",nDragHandle:"Use the up and down arrow keys to move the north drag handle to change the crop selection area",neDragHandle:"Use the arrow keys to move the north east drag handle to change the crop selection area",eDragHandle:"Use the up and down arrow keys to move the east drag handle to change the crop selection area",seDragHandle:"Use the arrow keys to move the south east drag handle to change the crop selection area",sDragHandle:"Use the up and down arrow keys to move the south drag handle to change the crop selection area",swDragHandle:"Use the arrow keys to move the south west drag handle to change the crop selection area",wDragHandle:"Use the up and down arrow keys to move the west drag handle to change the crop selection area"}}),px);function msn(s,t,n){return csn(lsn({unit:"%",width:90},n,s,t),s,t)}const Xnt=({open:s,onClose:t,imageSrc:n,onCropComplete:r,aspectRatio:a=1})=>{const i=j.useRef(null),[l,o]=j.useState(),[c,d]=j.useState(),[u,h]=j.useState(1),[m,f]=j.useState(0),g=j.useCallback(v=>{const{width:b,height:w}=v.currentTarget;o(msn(b,w,a))},[a]),x=j.useCallback(async()=>{const v=i.current;if(!v||!c)return;const b=document.createElement("canvas"),w=b.getContext("2d");if(!w)return;const S=v.naturalWidth/v.width,A=v.naturalHeight/v.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(v,I,P,R,D,0,0,E,E),w.restore(),new Promise((V,G)=>{b.toBlob(Y=>{Y?V(Y):G(new Error("Canvas is empty"))},"image/jpeg",.95)})},[c,u,m]),y=async()=>{try{const v=await x();v&&(r(v),t())}catch(v){console.error("Error cropping image:",v)}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-lg",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Crop Your Photo"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"relative max-h-[400px] overflow-hidden rounded-lg bg-muted flex items-center justify-center",children:e.jsx(hsn,{crop:l,onChange:(v,b)=>o(b),onComplete:v=>d(v),aspect:a,circularCrop:!0,className:"max-h-[400px]",children:e.jsx("img",{ref:i,src:n,alt:"Crop preview",style:{transform:`scale(${u}) rotate(${m}deg)`,maxHeight:"400px",width:"auto"},onLoad:g})})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(fV,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(Nx,{value:[u],min:.5,max:3,step:.1,onValueChange:([v])=>h(v),className:"flex-1"}),e.jsx(tL,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Zz,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(Nx,{value:[m],min:-180,max:180,step:1,onValueChange:([v])=>f(v),className:"flex-1"}),e.jsxs("span",{className:"text-sm text-muted-foreground w-12",children:[m,"°"]})]})]})]}),e.jsxs(Sr,{children:[e.jsx($,{variant:"outline",onClick:t,children:"Cancel"}),e.jsx($,{onClick:y,children:"Save Photo"})]})]})})},J1t="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 fsn(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 psn(){const{user:s}=bs(),{toast:t}=Bi(),[n,r]=j.useState(!0),[a,i]=j.useState(!1),[l,o]=j.useState(""),[c,d]=j.useState(!1),[u,h]=j.useState(!1),[m,f]=j.useState(null),[g,x]=j.useState(!1);j.useEffect(()=>{s!=null&&s.id&&(async()=>{const{data:b}=await q.from("profiles").select("phone, phone_e164, sms_consent, sms_consent_at").eq("id",s.id).maybeSingle(),w=b;w&&(o(w.phone_e164||w.phone||""),h(!!w.sms_consent),d(!!w.sms_consent),f(w.sms_consent_at||null)),r(!1)})()},[s==null?void 0:s.id]);const y=async()=>{const b=fsn(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:J1t,sms_consent_source:"profile_page",sms_opted_out_at:null}).eq("id",s.id);if(i(!1),w){t({title:"Error",description:w.message,variant:"destructive"});return}h(!0),f(new Date().toISOString()),t({title:"You're opted in",description:"You'll now receive text alerts for new leads and account notifications."})},v=async()=>{i(!0);const{error:b}=await q.from("profiles").update({sms_consent:!1,sms_opted_out_at:new Date().toISOString()}).eq("id",s.id);if(i(!1),b){t({title:"Error",description:b.message,variant:"destructive"});return}h(!1),d(!1),t({title:"Opted out",description:"You will no longer receive text messages from LevelUp."})};return e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(eo,{className:"h-5 w-5"}),"Text Message (SMS) Alerts",u&&e.jsx($e,{variant:"secondary",children:"Opted in"})]}),e.jsx(Gn,{children:"Get a text the moment a new lead comes in, plus important account notifications."})]}),e.jsx(Ie,{className:"space-y-4",children:n?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(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:J1t})]})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Message types: new lead alerts, account notifications, service updates, customer support. Frequency varies. Msg & data rates may apply. Reply STOP to opt out, HELP for help. No mobile information will be shared with third parties or affiliates for marketing purposes."}),u&&m&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Consent recorded on ",new Date(m).toLocaleString("en-US",{timeZone:"America/New_York"}),"."]}),g&&!u&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"You chose not to enroll in text alerts. Nothing was saved and your account is unaffected."}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs($,{onClick:y,disabled:a||u&&!l,children:[a&&e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}),u?"Update Number":"Opt in to SMS"]}),u?e.jsx($,{variant:"outline",onClick:v,disabled:a,children:"Opt out"}):e.jsx($,{variant:"outline",type:"button",disabled:a,onClick:()=>{o(""),d(!1),x(!0),t({title:"SMS skipped",description:"No consent was recorded. You can keep using LevelUp normally."})},children:"Skip SMS / Continue without text alerts"})]})]})})]})}const e_t="#2a4c64",t_t="#B8965A",s_t="Inter",n_t="Inter";function vU(s){if(typeof s!="string")return null;const t=s.trim();return t.length?t:null}function Q_(s,t=null){for(const[n,r]of s){const a=vU(r);if(a)return{value:a,source:n}}return{value:t,source:"default"}}function gsn(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=Q_(l(t.brand_color,n.primary_color,r.brand_color),e_t),c=Q_(l(t.accent_color,n.accent_color,r.accent_color),t_t),d=Q_([["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=Q_(u),m=Q_([["brokerage",n.logo_url],["legacy",r.brokerage_logo_url]]),f=Q_([["agent",t.headshot_url],["legacy",r.avatar_url]]),g=Q_([["agent",t.tagline],["legacy",r.tagline||r.title]]),x=Q_([["agent",t.preferred_font],["brokerage",n.heading_font]],s_t),y=Q_([["brokerage",n.body_font]],n_t),v=Q_([["agent",t.license_number],["legacy",r.license_number]]),b=Q_([["agent",t.license_state],["legacy",r.license_state],["brokerage",n.license_state]]),w=Q_([["agent",t.website_url],["legacy",r.website_url]]),S=Q_([["brokerage",n.legal_name],["legacy",r.brokerage_name]]),A=Q_([["brokerage",n.compliance_line]]);return{agent_name:vU(r.name),brokerage_name:S.value,brand_color:o.value??e_t,secondary_color:d.value,accent_color:c.value??t_t,heading_font:x.value??s_t,body_font:y.value??n_t,logo_url:h.value,logo_dark_url:vU(n.logo_dark_url),brokerage_logo_url:m.value,icon_mark_url:vU(n.icon_mark_url),headshot_url:f.value,tagline:g.value,license_number:v.value,license_state:b.value,website_url:w.value,email:vU(r.email),phone:vU(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:y.source,license_number:v.source,license_state:b.source,website_url:w.source,brokerage_name:S.source,compliance_line:A.source}}}function xsn(){const{user:s}=bs();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 ysn(){const{user:s}=bs(),t=Wt();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 vsn(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 bsn(s){const{user:t}=bs(),n=Wt();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 gHt(){const{user:s}=bs();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 gsn({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 xHt(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 _sn=["Inter","Playfair Display","Montserrat","Poppins","Lora","Work Sans"];function wsn(){const{user:s}=bs(),{toast:t}=Bi(),{data:n,isLoading:r}=xsn(),{data:a}=gHt(),i=ysn(),l=j.useRef(null),[o,c]=j.useState(!1),[d,u]=j.useState({brand_color:"",accent_color:"",logo_url:"",tagline:"",preferred_font:"",license_number:"",license_state:"",website_url:""});j.useEffect(()=>{n&&u({brand_color:n.brand_color||"",accent_color:n.accent_color||"",logo_url:n.logo_url||"",tagline:n.tagline||"",preferred_font:n.preferred_font||"",license_number:n.license_number||"",license_state:n.license_state||"",website_url:n.website_url||""})},[n]);const h=!!(a!=null&&a.locked.colors),m=!!(a!=null&&a.locked.logo),f=(y,v)=>u(b=>({...b,[y]:v})),g=async y=>{if(s){c(!0);try{const v=await xHt(s.id,y,"logo");f("logo_url",v),t({title:"Logo uploaded"})}catch(v){t({title:"Upload failed",description:v.message,variant:"destructive"})}finally{c(!1)}}},x=async()=>{try{await i.mutateAsync({brand_color:d.brand_color||null,accent_color:d.accent_color||null,logo_url:d.logo_url||null,tagline:d.tagline||null,preferred_font:d.preferred_font||null,license_number:d.license_number||null,license_state:d.license_state||null,website_url:d.website_url||null}),t({title:"Brand kit saved"})}catch(y){t({title:"Could not save",description:y.message,variant:"destructive"})}};return e.jsxs(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(Gn,{children:"Used by AI tools (ChatGPT via the LevelUp connector), flyers, presentations and your public pages. Anything you leave blank falls back to your brokerage's brand, then LevelUp defaults."})]}),e.jsx(Ie,{className:"space-y-6",children:r?e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-sm",children:[e.jsx(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(pc,{className:"h-3 w-3"})," Set by brokerage"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{type:"color",className:"h-10 w-14 p-1",value:d.brand_color||(a==null?void 0:a.brand_color)||"#2a4c64",disabled:h,onChange:y=>f("brand_color",y.target.value)}),e.jsx(pe,{value:d.brand_color,placeholder:(a==null?void 0:a.brand_color)||"#2a4c64",disabled:h,onChange:y=>f("brand_color",y.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Accent color"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{type:"color",className:"h-10 w-14 p-1",value:d.accent_color||(a==null?void 0:a.accent_color)||"#B8965A",disabled:h,onChange:y=>f("accent_color",y.target.value)}),e.jsx(pe,{value:d.accent_color,placeholder:(a==null?void 0:a.accent_color)||"#B8965A",disabled:h,onChange:y=>f("accent_color",y.target.value)})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{className:"flex items-center gap-2",children:["Personal / team logo",m&&e.jsxs($e,{variant:"secondary",className:"gap-1",children:[e.jsx(pc,{className:"h-3 w-3"})," Brokerage logo required"]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[d.logo_url&&e.jsx("img",{src:d.logo_url,alt:"Your logo",className:"h-12 w-auto rounded border bg-background p-1"}),e.jsx("input",{ref:l,type:"file",accept:"image/*",className:"hidden",onChange:y=>{var v;return((v=y.target.files)==null?void 0:v[0])&&g(y.target.files[0])}}),e.jsxs($,{type:"button",variant:"outline",disabled:o||m,onClick:()=>{var y;return(y=l.current)==null?void 0:y.click()},children:[o?e.jsx(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:y=>f("tagline",y.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"brand-font",children:"Preferred font"}),e.jsx(pe,{id:"brand-font",list:"brand-font-options",value:d.preferred_font,placeholder:(a==null?void 0:a.heading_font)||"Inter",onChange:y=>f("preferred_font",y.target.value)}),e.jsx("datalist",{id:"brand-font-options",children:_sn.map(y=>e.jsx("option",{value:y},y))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"brand-license",children:"License number"}),e.jsx(pe,{id:"brand-license",value:d.license_number,placeholder:(a==null?void 0:a.license_number)||"DRE #01234567",onChange:y=>f("license_number",y.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"brand-license-state",children:"License state"}),e.jsx(pe,{id:"brand-license-state",value:d.license_state,placeholder:(a==null?void 0:a.license_state)||"CA",onChange:y=>f("license_state",y.target.value)})]}),e.jsxs("div",{className:"space-y-2 sm:col-span-2",children:[e.jsx(ee,{htmlFor:"brand-website",children:"Website"}),e.jsx(pe,{id:"brand-website",value:d.website_url,placeholder:(a==null?void 0:a.website_url)||"https://yoursite.com",onChange:y=>f("website_url",y.target.value)})]})]}),(a==null?void 0:a.compliance_line)&&e.jsxs("div",{className:"rounded-md border bg-muted/40 p-3 text-sm text-muted-foreground",children:[e.jsx("span",{className:"font-medium text-foreground",children:"Required disclaimer from your brokerage: "}),a.compliance_line]}),e.jsxs($,{onClick:x,disabled:i.isPending,children:[i.isPending?e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(tl,{className:"mr-2 h-4 w-4"}),"Save brand kit"]})]})})]})}const NBe="id, name, address, notes, created_at, locked_style, share_token, share_enabled, share_headline, share_message, share_views";function aSr(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 jsn(){var o,c,d;const{user:s}=bs(),t=Wt(),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 iSr(){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 oSr(){const{user:s}=bs(),t=Wt(),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(NBe).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(NBe).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(NBe).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 lSr(){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 cSr(s){const{user:t}=bs(),n=Wt(),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 dSr(){const s=Wt();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 uSr(s){return new Promise((t,n)=>{const r=new FileReader;r.onload=()=>t(r.result),r.onerror=n,r.readAsDataURL(s)})}function Nsn(){try{return window.open("","_blank")}catch{return null}}function ksn(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 Ssn(s){try{s&&!s.closed&&s.close()}catch{}}async function Csn(s,t){if(s instanceof kae)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 Asn(){var i;const s=jsn(),[t,n]=j.useState(!1);if(s.isLoading)return null;const r=s.unlimited&&s.unlimitedReason==="plan",a=async()=>{if(t)return;const l=Nsn();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");ksn(l,o.url)}catch(o){Ssn(l);const c=await Csn(o,"We could not open your billing portal. Contact support and we will sort it out.");console.error("[staging-portal]",c,o),re.error(c)}finally{n(!1)}};return e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(Nn,{className:"h-5 w-5"}),"Staging Studio Billing"]}),e.jsx(Gn,{children:"Manage the plan and credits that power your AI photo staging"})]}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx($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(Nv,{className:"mr-1.5 h-3.5 w-3.5"}),"Manage billing"]}),e.jsx($,{variant:"ghost",size:"sm",asChild:!0,children:e.jsxs(wr,{to:"/apps/staging-studio/credits",children:["Credits & history ",e.jsx(Fr,{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 r_t=["image/png","image/jpeg","image/jpg","image/svg+xml","image/webp"],Esn=5*1024*1024;function Tsn({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(!r_t.includes(g.type)){re.error("Please upload a PNG, JPG, SVG or WebP file");return}if(g.size>Esn){re.error("Please choose a logo under 5MB");return}d(!0);try{const x=(g.name.split(".").pop()||"png").toLowerCase(),y=`${s}/brokerage-logo-${Date.now()}.${x}`,{error:v}=await q.storage.from("card-logos").upload(y,g,{cacheControl:"3600",upsert:!0,contentType:g.type});if(v)throw v;const{data:b}=q.storage.from("card-logos").getPublicUrl(y),w=b.publicUrl;r&&await q.from("profiles").update({brokerage_logo_url:w}).eq("id",s),n(w),re.success("Brokerage logo uploaded")}catch(x){re.error((x==null?void 0:x.message)||"Upload failed")}finally{d(!1)}},f=async()=>{r&&await q.from("profiles").update({brokerage_logo_url:null}).eq("id",s),n(null)};return e.jsxs("div",{className:Pt("space-y-2",l),children:[e.jsx(ee,{children:a}),e.jsxs("div",{onDragOver:g=>{g.preventDefault(),h(!0)},onDragLeave:()=>h(!1),onDrop:g=>{var y;g.preventDefault(),h(!1);const x=(y=g.dataTransfer.files)==null?void 0:y[0];x&&m(x)},onClick:()=>{var g;return!c&&((g=o.current)==null?void 0:g.click())},className:Pt("flex cursor-pointer items-center gap-4 rounded-xl border border-dashed p-4 transition-colors",u?"border-primary bg-primary/5":"border-border hover:bg-muted/50"),children:[e.jsx("div",{className:"flex h-16 w-24 shrink-0 items-center justify-center overflow-hidden rounded-lg bg-muted",children:t?e.jsx("img",{src:t,alt:"Brokerage logo",className:"h-full w-full object-contain p-1"}):e.jsx(ji,{className:"h-6 w-6 text-muted-foreground"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm font-medium",children:c?"Uploading…":t?"Logo added":"Drag & drop your brokerage logo"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:i})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[e.jsxs($,{type:"button",variant:"outline",size:"sm",disabled:c,onClick:g=>{var x;g.stopPropagation(),(x=o.current)==null||x.click()},children:[c?e.jsx(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(Hn,{className:"h-4 w-4 text-muted-foreground"})})]})]}),e.jsx("input",{ref:o,type:"file",accept:r_t.join(","),className:"hidden",onChange:g=>{var y;const x=(y=g.target.files)==null?void 0:y[0];x&&m(x),g.target.value=""}})]})}const Msn=()=>{const{user:s}=bs(),{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(Nv,{className:"h-5 w-5"}),"Subscription"]})}),e.jsx(Ie,{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(Nv,{className:"h-5 w-5"}),"Subscription"]}),e.jsx(Gn,{children:"Manage your subscription and billing"})]}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Status"}),e.jsx("div",{className:"mt-1",children:u()})]}),(l==null?void 0:l.endDate)&&l.status==="active"&&e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Next billing date"}),e.jsx("p",{className:"font-medium",children:new Date(l.endDate).toLocaleDateString()})]})]}),l!=null&&l.isGrandfathered?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Your membership is active and included with your account. To update or manage billing, please reach out to support."}):(l==null?void 0:l.status)==="active"||(l==null?void 0:l.status)==="trialing"?e.jsxs(e.Fragment,{children:[(l==null?void 0:l.status)==="trialing"&&(l==null?void 0:l.endDate)&&e.jsxs("p",{className:"text-sm text-muted-foreground mb-3",children:["Your trial ends on ",new Date(l.endDate).toLocaleDateString(),". After the trial, you'll be charged automatically."]}),e.jsxs($,{onClick:d,variant:"outline",disabled:a,children:[a?e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Fr,{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."})]})]})},Psn=()=>{const{user:s}=bs(),t=Xn(),{toast:n}=Bi(),[r]=gc(),a=r.get("setup")==="true",i=r.get("reset")==="true",l=i&&r.get("activation")==="1",{isSupported:o,isSubscribed:c,isLoading:d,subscribe:u,unsubscribe:h}=o7t(),[m,f]=j.useState(!1),[g,x]=j.useState(""),[y,v]=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),[Y,X]=j.useState(!1),[ae,le]=j.useState(!1),[ne,te]=j.useState({newPassword:"",confirmPassword:""});j.useEffect(()=>{s&&J()},[s]),j.useEffect(()=>{i&&s&&setTimeout(()=>{var ke;(ke=document.getElementById("change-password-section"))==null||ke.scrollIntoView({behavior:"smooth",block:"center"})},500)},[i,s]);const J=async()=>{var ke,Be,Ne,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:Ve}=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(Ve)throw console.error("Profile query error:",Ve),Ve;if(Ce){console.log("Profile loaded successfully:",Ce);const qe=((ke=Ce.brokerages)==null?void 0:ke.name)||"";O(!!Ce.brokerage_id),R({name:Ce.name||"",email:Ce.email||"",phone:Ce.phone||"",title:Ce.title||"",bio:Ce.bio||"",areas_served:Ce.areas_served||"",years_experience:((Be=Ce.years_experience)==null?void 0:Be.toString())||"",brokerage_name:Ce.brokerage_id?qe:Ce.brokerage_name||"",instagram_url:Ce.instagram_url||"",facebook_url:Ce.facebook_url||"",linkedin_url:Ce.linkedin_url||"",google_business_url:Ce.google_business_url||"",zillow_profile_url:Ce.zillow_profile_url||"",realtor_profile_url:Ce.realtor_profile_url||"",specialties:Ce.specialties||"",email_signature:Ce.email_signature||"",use_email_signature:Ce.use_email_signature||!1}),W(Ce.digest_opt_out||!1),X(Ce.event_invite_opt_out||!1),v(Ce.brokerage_logo_url||null)}else console.warn("No profile found for user"),R({name:((Ne=s.user_metadata)==null?void 0:Ne.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:qe}=q.storage.from("avatars").getPublicUrl(`${s.id}/${ze[0].name}`);x(qe.publicUrl)}}catch(Ce){console.error("Error loading profile:",Ce),n({title:"Error",description:Ce.message||"Failed to load profile",variant:"destructive"})}},ce=ke=>{var Ae;const Be=(Ae=ke.target.files)==null?void 0:Ae[0];if(!Be)return;const Ne=new FileReader;Ne.onloadend=()=>{I(Ne.result),A(!0)},Ne.readAsDataURL(Be),ke.target.value=""},_e=async ke=>{if(s){w(!0);try{const{data:Be}=await q.storage.from("avatars").list(`${s.id}`),Ne=(Be??[]).filter(dt=>/^avatar[.-]/i.test(dt.name));Ne.length>0&&await q.storage.from("avatars").remove(Ne.map(dt=>`${s.id}/${dt.name}`));const Ce=`${s.id}/avatar.jpg`,{error:Ve}=await q.storage.from("avatars").upload(Ce,ke,{upsert:!0,contentType:"image/jpeg"});if(Ve)throw Ve;const{data:ze}=q.storage.from("avatars").getPublicUrl(Ce),qe=ze.publicUrl;x(`${qe}?t=${Date.now()}`),await q.from("profiles").update({avatar_url:qe}).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)}}},he=async()=>{if(!P.name.trim()||!P.email.trim()){n({title:"Error",description:"Name and email are required",variant:"destructive"});return}f(!0);try{const ke=P.email.trim().toLowerCase(),Be=((s==null?void 0:s.email)||"").toLowerCase(),Ne=!!ke&&ke!==Be;if(Ne){const{data:Ce,error:Ve}=await q.functions.invoke("update-own-email",{body:{newEmail:ke}}),ze=Ve||(Ce==null?void 0:Ce.error);if(ze)throw new Error(typeof ze=="string"?ze:"Could not update your login email. Please try a different address.")}const{error:Ae}=await q.from("profiles").update({name:P.name.trim(),email:ke,phone:P.phone.trim()||null,title:P.title.trim()||null,bio:P.bio.trim()||null,areas_served:P.areas_served.trim()||null,years_experience:P.years_experience?parseInt(P.years_experience):null,...D?{}:{brokerage_name:P.brokerage_name.trim()||null},instagram_url:P.instagram_url.trim()||null,facebook_url:P.facebook_url.trim()||null,linkedin_url:P.linkedin_url.trim()||null,google_business_url:P.google_business_url.trim()||null,zillow_profile_url:P.zillow_profile_url.trim()||null,realtor_profile_url:P.realtor_profile_url.trim()||null,specialties:P.specialties.trim()||null,email_signature:P.email_signature||"",use_email_signature:P.use_email_signature}).eq("id",s==null?void 0:s.id);if(Ae)throw Ae;n({title:"Success",description:Ne?"Profile updated. Your login email is now "+ke:"Profile updated successfully"})}catch(ke){console.error("Error updating profile:",ke),n({title:"Error",description:ke.message||"Failed to update profile",variant:"destructive"})}finally{f(!1)}},ue=async()=>{if(!ne.newPassword){n({title:"Error",description:"Please enter a new password",variant:"destructive"});return}if(ne.newPassword.length<6){n({title:"Error",description:"Password must be at least 6 characters",variant:"destructive"});return}if(ne.newPassword!==ne.confirmPassword){n({title:"Error",description:"Passwords do not match",variant:"destructive"});return}f(!0);try{const{error:ke}=await q.auth.updateUser({password:ne.newPassword});if(ke)throw ke;n({title:"Success",description:"Password updated successfully"}),te({newPassword:"",confirmPassword:""}),a&&setTimeout(()=>t("/dashboard"),1e3)}catch(ke){console.error("Error updating password:",ke),n({title:"Error",description:ke.message||"Failed to update password",variant:"destructive"})}finally{f(!1)}},ve=[P.name,P.email,P.phone,P.title,P.bio,P.areas_served,P.brokerage_name,g],Ee=ve.filter(ke=>ke.trim()).length,Se=Math.round(Ee/ve.length*100),Le=P.name.split(" ").filter(Boolean).map(ke=>ke[0]).join("").toUpperCase().slice(0,2)||"U",Fe=ke=>{var Be;(Be=document.getElementById(ke))==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:Le})]}),e.jsx("input",{type:"file",id:"avatar-upload",accept:"image/*",className:"hidden",onChange:ce,disabled:b}),e.jsx($,{type:"button",size:"icon",className:"profile-avatar-button",onClick:()=>{var ke;return(ke=document.getElementById("avatar-upload"))==null?void 0:ke.click()},disabled:b,"aria-label":"Change profile photo",children:b?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Sx,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"mt-6 text-center",children:[e.jsx("h2",{className:"profile-name",children:P.name||"Your profile"}),e.jsx("p",{className:"profile-role",children:P.title||"Real estate professional"}),P.brokerage_name&&e.jsx("p",{className:"profile-brokerage",children:P.brokerage_name})]}),e.jsxs("div",{className:"profile-completion",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{children:"Profile strength"}),e.jsxs("strong",{children:[Se,"%"]})]}),e.jsx("div",{className:"profile-progress","aria-label":`Profile ${Se}% complete`,children:e.jsx("span",{style:{width:`${Se}%`}})}),e.jsx("p",{children:Se===100?"Your professional profile is complete.":"Complete your details to strengthen your presence across LevelUp."})]}),e.jsxs("nav",{className:"profile-section-nav","aria-label":"Profile sections",children:[e.jsxs($,{variant:"ghost",onClick:()=>Fe("profile-details"),children:[e.jsx(iP,{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(ZS,{className:"h-4 w-4"})," Notifications"]}),e.jsxs($,{variant:"ghost",onClick:()=>Fe("profile-billing"),children:[e.jsx(Kq,{className:"h-4 w-4"})," Billing"]})]}),e.jsxs($,{className:"profile-save",onClick:he,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(Gn,{children:"Update your profile details"})]}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"name",children:"Name"}),e.jsx(pe,{id:"name",value:P.name,onChange:ke=>R({...P,name:ke.target.value}),maxLength:100})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"email",children:"Email"}),e.jsx(pe,{id:"email",type:"email",value:P.email,onChange:ke=>R({...P,email:ke.target.value}),maxLength:255}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Changing this also updates the email you use to sign in."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"phone",children:"Phone Number"}),e.jsx(pe,{id:"phone",type:"tel",value:P.phone,onChange:ke=>R({...P,phone:ke.target.value}),placeholder:"e.g., +14155551234",maxLength:20}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Used for SMS lead notifications from your website — if you have a local authority site"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"title",children:"Job Title"}),e.jsx(pe,{id:"title",value:P.title,onChange:ke=>R({...P,title:ke.target.value}),placeholder:"e.g., Broker Associate, Team Lead",maxLength:100})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"bio",children:"Bio"}),e.jsx(Ls,{id:"bio",value:P.bio,onChange:ke=>R({...P,bio:ke.target.value}),placeholder:"A short description about yourself",maxLength:500,className:"min-h-[120px] resize-y"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"areas_served",children:"Areas Served"}),e.jsx(pe,{id:"areas_served",value:P.areas_served,onChange:ke=>R({...P,areas_served:ke.target.value}),placeholder:"e.g., Downtown, Suburbs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"years_experience",children:"Years Experience"}),e.jsx(pe,{id:"years_experience",type:"number",min:"0",value:P.years_experience,onChange:ke=>R({...P,years_experience:ke.target.value}),placeholder:"e.g., 5"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{htmlFor:"brokerage_name",children:["Brokerage ",D&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(managed)"})]}),e.jsx(pe,{id:"brokerage_name",value:P.brokerage_name,onChange:ke=>R({...P,brokerage_name:ke.target.value}),placeholder:"e.g., Keller Williams Realty",disabled:D,maxLength:150}),e.jsx("p",{className:"text-xs text-muted-foreground",children:D?"Your brokerage is managed by your office and can't be changed here.":"Used as your brokerage name across ReelFlow, branding, and email signatures."})]}),s&&e.jsx(Tsn,{userId:s.id,value:y,onChange:v,description:"PNG, JPG, SVG or WebP up to 5MB. Used on your agent website, marketing and email signatures."}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Social Links"}),e.jsxs("div",{className:"grid grid-cols-1 gap-3",children:[e.jsx(pe,{value:P.linkedin_url,onChange:ke=>R({...P,linkedin_url:ke.target.value}),placeholder:"LinkedIn URL"}),e.jsx(pe,{value:P.instagram_url,onChange:ke=>R({...P,instagram_url:ke.target.value}),placeholder:"Instagram URL"}),e.jsx(pe,{value:P.facebook_url,onChange:ke=>R({...P,facebook_url:ke.target.value}),placeholder:"Facebook URL"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"AI Search & Verified Profiles"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Adding these helps ChatGPT, Perplexity, Google and other AI assistants confirm who you are and recommend you for local searches."}),e.jsxs("div",{className:"grid grid-cols-1 gap-3",children:[e.jsx(pe,{value:P.google_business_url,onChange:ke=>R({...P,google_business_url:ke.target.value}),placeholder:"Google Business Profile URL"}),e.jsx(pe,{value:P.zillow_profile_url,onChange:ke=>R({...P,zillow_profile_url:ke.target.value}),placeholder:"Zillow agent profile URL"}),e.jsx(pe,{value:P.realtor_profile_url,onChange:ke=>R({...P,realtor_profile_url:ke.target.value}),placeholder:"Realtor.com profile URL"}),e.jsx(pe,{value:P.specialties,onChange:ke=>R({...P,specialties:ke.target.value}),placeholder:"Specialties (e.g. Waterfront homes, Acreage & farms, First-time buyers)"})]})]}),e.jsxs($,{onClick:he,disabled:m,className:"profile-inline-save",children:[e.jsx(tl,{className:"mr-2 h-4 w-4"}),"Save Changes"]})]})]}),e.jsxs(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(Gn,{children:"Add a signature that will be appended to emails sent via Gmail"})]}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Use email signature in all emails"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:P.use_email_signature?"Your signature will be added to every email sent via Gmail":"Signature is currently disabled"})]}),e.jsx(Sn,{checked:P.use_email_signature,onCheckedChange:ke=>R({...P,use_email_signature:ke})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Signature"}),e.jsx(Sk,{content:P.email_signature,onChange:ke=>R({...P,email_signature:ke}),placeholder:"Paste your Gmail signature here or create one...",minHeight:"120px",compact:!0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Tip: Copy your signature from Gmail Settings and paste it here — images and formatting will be preserved."})]}),e.jsxs($,{onClick:he,disabled:m,children:[e.jsx(tl,{className:"mr-2 h-4 w-4"}),"Save Signature"]})]})]}),e.jsx("div",{className:"profile-embedded-section",children:e.jsx(wsn,{})}),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(Gn,{children:a||l?"Create a secure password for your account":"Update your password to keep your account secure"})]}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"newPassword",children:"New Password"}),e.jsx(pe,{id:"newPassword",type:"password",value:ne.newPassword,onChange:ke=>te({...ne,newPassword:ke.target.value}),placeholder:"Min 6 characters"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"confirmPassword",children:"Confirm Password"}),e.jsx(pe,{id:"confirmPassword",type:"password",value:ne.confirmPassword,onChange:ke=>te({...ne,confirmPassword:ke.target.value}),placeholder:"Re-enter your new password"})]}),e.jsxs($,{onClick:ue,disabled:m,children:[e.jsx(tl,{className:"mr-2 h-4 w-4"}),a?"Complete Setup":"Update Password"]}),a&&e.jsx($,{variant:"outline",onClick:()=>t("/dashboard"),className:"ml-2",children:"Skip for Now"})]})]}),e.jsxs(je,{id:"profile-notifications",children:[e.jsxs(St,{children:[e.jsxs(Et,{className:"flex items-center gap-2",children:[c?e.jsx(Uy,{className:"h-5 w-5"}):e.jsx(YS,{className:"h-5 w-5"}),"Push Notifications"]}),e.jsx(Gn,{children:"Receive browser notifications when new content is added"})]}),e.jsx(Ie,{children:o?e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:c?"Notifications enabled":"Notifications disabled"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:c?"You'll receive notifications about new templates, videos, and events":"Enable to get notified about new content"})]}),e.jsx(Sn,{checked:c,onCheckedChange:ke=>{ke?u():h()},disabled:d})]}):e.jsxs("div",{className:"text-sm text-muted-foreground space-y-2",children:[e.jsx("p",{children:"Push notifications are not available in this browser."}),e.jsxs("p",{className:"text-xs space-y-1",children:[e.jsx("strong",{children:"Desktop:"})," Use Chrome, Firefox, or Edge.",e.jsx("br",{}),e.jsx("strong",{children:"Android:"})," Use Chrome or Firefox.",e.jsx("br",{}),e.jsx("strong",{children:"iPhone/iPad:"})," Push notifications on iOS ",e.jsx("em",{children:"only"})," work when this site is installed as an app from ",e.jsx("strong",{children:"Safari"}),". Open this site in Safari → tap the ",e.jsx("strong",{children:"Share"})," button → ",e.jsx("strong",{children:"Add to Home Screen"}),". Other browsers (Chrome, Firefox, etc.) on iOS do not support push notifications due to Apple restrictions."]})]})})]}),e.jsx("div",{className:"profile-embedded-section",children:e.jsx(psn,{})}),e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsxs(Et,{className:"flex items-center gap-2",children:[U?e.jsx(YI,{className:"h-5 w-5"}):e.jsx(mn,{className:"h-5 w-5"}),"Email Preferences"]}),e.jsx(Gn,{children:"Manage your email subscription settings"})]}),e.jsxs(Ie,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Weekly Digest"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:U?"You won't receive weekly digest emails":"Receive a weekly summary of new content, events, and your progress"})]}),e.jsx(Sn,{checked:!U,onCheckedChange:async ke=>{G(!0);try{const{error:Be}=await q.from("profiles").update({digest_opt_out:!ke}).eq("id",s==null?void 0:s.id);if(Be)throw Be;W(!ke),n({title:ke?"Subscribed":"Unsubscribed",description:ke?"You will now receive weekly digest emails":"You will no longer receive weekly digest emails"})}catch(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:Y?"You won't receive event invite emails (weekly digest is unaffected)":"Get invited to LevelUp live trainings and special events"})]}),e.jsx(Sn,{checked:!Y,onCheckedChange:async ke=>{le(!0);try{const{error:Be}=await q.from("profiles").update({event_invite_opt_out:!ke}).eq("id",s==null?void 0:s.id);if(Be)throw Be;X(!ke),n({title:ke?"Subscribed":"Unsubscribed",description:ke?"You will now receive event invite emails":"You will no longer receive event invite emails"})}catch(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(dKs,{})}),e.jsx("div",{id:"profile-billing",className:"profile-embedded-section",children:e.jsx(Msn,{})}),e.jsx("div",{className:"profile-embedded-section",children:e.jsx(Asn,{})})]})]})]}),e.jsx(Xnt,{open:S,onClose:()=>A(!1),imageSrc:E,onCropComplete:_e,aspectRatio:1})]})})};var Isn=Object.defineProperty,Lsn=(s,t)=>Isn(s,"name",{value:t,configurable:!0}),Rsn=j.forwardRef(Lsn(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")),Dsn=Rsn;const Fsn=Dsn;function Osn(){const{user:s}=bs(),t=Wt(),[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:y}=await q.from("profiles").update({calendar_token:x}).eq("id",s==null?void 0:s.id);if(y)throw y;return x},onSuccess:()=>{t.invalidateQueries({queryKey:["calendar-token",s==null?void 0:s.id]}),re.success("Calendar subscription URL generated!")},onError:g=>{re.error("Failed to generate calendar URL: "+g.message)}}),d=l!=null&&l.calendar_token?`https://dashboard.relevelup.com/api/calendar/${l.calendar_token}.ics`:null,u=async()=>{d&&(await navigator.clipboard.writeText(d),r(!0),re.success("Calendar URL copied to clipboard!"),setTimeout(()=>r(!1),2e3))},h=()=>{d&&(window.location.href=d.replace("https://","webcal://"))},m=()=>{if(d){const g=d.replace("https://","webcal://"),x=`https://calendar.google.com/calendar/r?cid=${encodeURIComponent(g)}`;window.open(x,"_blank")}},f=()=>{if(d){const g=`https://outlook.live.com/calendar/0/addfromweb?url=${encodeURIComponent(d)}&name=Level%20Up%20Events`;window.open(g,"_blank")}};return e.jsxs(zs,{open:a,onOpenChange:i,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{variant:"outline",className:"gap-2",children:[e.jsx(Ta,{className:"h-4 w-4"}),"Subscribe to Calendar"]})}),e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(Ta,{className:"h-5 w-5 text-primary"}),"Subscribe to Events Calendar"]}),e.jsx(Pr,{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(ca,{className:"h-4 w-4 text-green-500"}):e.jsx(Ha,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Quick Add"}),e.jsxs("div",{className:"grid gap-2",children:[e.jsxs($,{variant:"outline",className:"w-full justify-start gap-2",onClick:h,children:[e.jsx("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("path",{d:"M18.71 19.5c-.83 1.24-1.71 2.45-3.05 2.47-1.34.03-1.77-.79-3.29-.79-1.53 0-2 .77-3.27.82-1.31.05-2.3-1.32-3.14-2.53C4.25 17 2.94 12.45 4.7 9.39c.87-1.52 2.43-2.48 4.12-2.51 1.28-.02 2.5.87 3.29.87.78 0 2.26-1.07 3.81-.91.65.03 2.47.26 3.64 1.98-.09.06-2.17 1.28-2.15 3.81.03 3.02 2.65 4.03 2.68 4.04-.03.07-.42 1.44-1.38 2.83M13 3.5c.73-.83 1.94-1.46 2.94-1.5.13 1.17-.34 2.35-1.04 3.19-.69.85-1.83 1.51-2.95 1.42-.15-1.15.41-2.35 1.05-3.11z"})}),"Add to Apple Calendar",e.jsx(Fr,{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(Fr,{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(Fr,{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(Ta,{className:"h-4 w-4 mr-2"}),"Generate Calendar URL"]})})]})})]})]})}const zsn={first_timer:ei,regular:TE,dedicated:Im,veteran:Kl,streak_master:sh,century:Kl},Bsn={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 a_t(s){return s===1?e.jsx(Kl,{className:"h-5 w-5 text-yellow-500"}):s===2?e.jsx(TE,{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 yHt({showUserStats:s=!0,compact:t=!1,brokerageId:n,title:r="Event Leaderboard"}){const{user:a}=bs(),{data:i,isLoading:l}=GUt(t?5:10,n),{data:o}=WUt(a==null?void 0:a.id),{data:c}=YUt(a==null?void 0:a.id),{data:d}=KUt(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(Ie,{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(Ie,{children:[s&&o&&e.jsxs("div",{className:"mb-4 p-3 rounded-lg bg-primary/5 border border-primary/10",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("span",{className:"text-sm font-medium",children:"Your Stats"}),c&&e.jsxs($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=zsn[u.badge_type]||ei;return e.jsxs($e,{variant:"outline",className:`text-xs ${Bsn[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(ha,{defaultValue:"points",className:"w-full",children:[e.jsxs(ma,{className:"w-full mb-3",children:[e.jsx(Zt,{value:"points",className:"flex-1",children:"By Points"}),e.jsx(Zt,{value:"events",className:"flex-1",children:"By Events"})]}),e.jsx(Xt,{value:"points",className:"mt-0",children:e.jsxs("div",{className:"space-y-2",children:[i==null?void 0:i.map((u,h)=>{var m,f,g;return e.jsxs("div",{className:`flex items-center gap-3 p-2 rounded-lg ${u.user_id===(a==null?void 0:a.id)?"bg-primary/5 border border-primary/10":""} ${h===0?"bg-yellow-500/5":""}`,children:[e.jsx("div",{className:"w-6 flex justify-center",children:a_t(h+1)}),e.jsx(Oa,{className:"h-8 w-8",children:e.jsx(za,{className:"text-xs",children:((f=(m=u.profile)==null?void 0:m.name)==null?void 0:f.charAt(0))||"?"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium text-sm truncate",children:[((g=u.profile)==null?void 0:g.name)||"Unknown",u.user_id===(a==null?void 0:a.id)&&e.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:"(You)"})]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[u.total_events_attended," events"]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("div",{className:"font-bold text-primary",children:u.total_points}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"pts"})]})]},u.user_id)}),(!i||i.length===0)&&e.jsx("div",{className:"text-center text-muted-foreground py-4 text-sm",children:"No attendance data yet. Attend an event to get on the leaderboard!"})]})}),e.jsx(Xt,{value:"events",className:"mt-0",children:e.jsx("div",{className:"space-y-2",children:[...i||[]].sort((u,h)=>h.total_events_attended-u.total_events_attended).map((u,h)=>{var m,f,g;return e.jsxs("div",{className:`flex items-center gap-3 p-2 rounded-lg ${u.user_id===(a==null?void 0:a.id)?"bg-primary/5 border border-primary/10":""} ${h===0?"bg-yellow-500/5":""}`,children:[e.jsx("div",{className:"w-6 flex justify-center",children:a_t(h+1)}),e.jsx(Oa,{className:"h-8 w-8",children:e.jsx(za,{className:"text-xs",children:((f=(m=u.profile)==null?void 0:m.name)==null?void 0:f.charAt(0))||"?"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium text-sm truncate",children:[((g=u.profile)==null?void 0:g.name)||"Unknown",u.user_id===(a==null?void 0:a.id)&&e.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:"(You)"})]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[u.total_points," points"]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("div",{className:"font-bold",children:u.total_events_attended}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"events"})]})]},u.user_id)})})})]})]})]})}function $sn(){const s=Xn(),{user:t,isAdmin:n}=bs(),r=Wt(),[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?re.success("Successfully registered! You'll receive a Zoom confirmation email."):re.success("Successfully registered for the event!")},onError:E=>{re.error("Failed to register: "+E.message)}}),f=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"]}),re.success("Registration cancelled and removed from Zoom")},onError:E=>{re.error("Failed to cancel: "+E.message)}}),g=E=>u==null?void 0:u.some(I=>I.event_id===E),x=E=>{const I=u==null?void 0:u.find(P=>P.event_id===E);return I==null?void 0:I.zoom_join_url},y=E=>E.capacity?((h==null?void 0:h[E.id])||0)>=E.capacity:!1,v=(c==null?void 0:c.filter(E=>c8(E.event_date)!=="ended"))||[],b=(c==null?void 0:c.filter(E=>c8(E.event_date)==="ended"))||[],w=v.filter(E=>c8(E.event_date)==="live").length,S=v.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.":v.length>0?`Next up: ${v[0].title}`:"No upcoming events scheduled — replays are below."})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(Osn,{}),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:v.length,icon:Ta},{label:"You're registered",value:S,icon:ca},{label:"Live now",value:w,icon:_b},{label:"Past events",value:b.length,icon:Aw}].map(E=>e.jsxs("div",{className:"hub-glass rounded-xl px-3 py-2.5",children:[e.jsx("span",{className:"text-xl font-bold",children:E.value}),e.jsxs("p",{className:"mt-0.5 flex items-center gap-1 text-[11px] hub-ink-muted",children:[e.jsx(E.icon,{className:"h-3 w-3"}),E.label]})]},E.label))})]})}),e.jsxs("div",{className:`grid grid-cols-1 gap-6 ${n?"lg:grid-cols-3":""}`,children:[e.jsxs("div",{className:`space-y-6 ${n?"lg:col-span-2":""}`,children:[d?e.jsx("div",{className:"grid gap-6 md:grid-cols-2",children:[0,1].map(E=>e.jsx("div",{className:"h-72 animate-pulse rounded-2xl border bg-muted/40"},E))}):v.length===0?e.jsx(je,{className:"rounded-2xl border-dashed py-12 text-center",children:e.jsxs(Ie,{className:"space-y-2",children:[e.jsx(Ta,{className:"mx-auto h-10 w-10 text-muted-foreground"}),e.jsx("p",{className:"text-muted-foreground",children:"No upcoming events at the moment. Check back soon!"})]})}):e.jsx("div",{className:"grid gap-6 md:grid-cols-2",children:v.map(E=>{const I=c8(E.event_date),P=int(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(_b,{className:"h-3.5 w-3.5"}),"LIVE NOW"]}):e.jsxs(e.Fragment,{children:[e.jsx(da,{className:"h-3.5 w-3.5"}),"STARTING SOON"]})]}),E.image_url&&e.jsxs(Fsn,{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(Ta,{className:"h-3 w-3"}),new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",timeZone:"America/New_York"}).format(new Date(E.event_date))]}),g(E.id)&&e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full bg-emerald-500/10 px-2.5 py-1 text-[11px] font-semibold text-emerald-600 dark:text-emerald-400",children:[e.jsx(ca,{className:"h-3 w-3"}),"Registered"]})]}),e.jsx(Et,{className:"line-clamp-2 pt-1",children:E.title}),E.description&&e.jsx(Gn,{className:"line-clamp-2",children:E.description.replace(/<[^>]*>/g,"")})]}),e.jsxs(Ie,{className:"flex-1 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Ta,{className:"h-4 w-4"}),new Intl.DateTimeFormat("en-US",{weekday:"long",year:"numeric",month:"long",day:"numeric",timeZone:"America/New_York"}).format(new Date(E.event_date))]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(da,{className:"h-4 w-4"}),cse(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(yEe,{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(pr,{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(Fr,{className:"h-4 w-4 mr-2"}),"Join Zoom"]})]}):e.jsx($,{className:"w-full",onClick:()=>m.mutate(E.id),disabled:m.isPending||y(E),children:y(E)?"Event Full":e.jsxs(e.Fragment,{children:[e.jsx(ca,{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(Aw,{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(yHt,{showUserStats:!0})})]})]})})}const kBe=[{value:"all",label:"All Roles",icon:Yn},{value:"newest",label:"Newest Members",icon:da},{value:"brokerage_manager",label:"Brokerage Managers",icon:aee},{value:"admin",label:"Admins",icon:Tf}];function Usn({open:s,onOpenChange:t,resourceType:n,resourceId:r,resourceTitle:a}){var Le,Fe;const{user:i,isAdmin:l,isBrokerageManager:o}=bs(),[c,d]=j.useState([]),[u,h]=j.useState([]),[m,f]=j.useState([]),[g,x]=j.useState([]),[y,v]=j.useState(""),[b,w]=j.useState(""),[S,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({}),Y=l||o;j.useEffect(()=>{s&&i&&(l?X():ae())},[s,i,l]),j.useEffect(()=>{s||(f([]),x([]),v(""),w(""),A(""),O("agents"),W("all"))},[s]);const X=async()=>{if(i){I(!0);try{const{data:ke,error:Be}=await q.from("brokerages").select("id, name").order("name");if(Be)throw Be;const Ne=1e3,Ae={};let Ce=0,Ve=!0;for(;Ve;){const{data:dt,error:Xe}=await q.from("profiles").select("brokerage_id").range(Ce*Ne,(Ce+1)*Ne-1);if(Xe)throw Xe;dt==null||dt.forEach(at=>{at.brokerage_id&&(Ae[at.brokerage_id]=(Ae[at.brokerage_id]||0)+1)}),Ve=(dt==null?void 0:dt.length)===Ne,Ce++}h((ke==null?void 0:ke.map(dt=>({...dt,agent_count:Ae[dt.id]||0})))||[]);const ze=[];for(Ce=0,Ve=!0;Ve;){const{data:dt,error:Xe}=await q.from("profiles").select("id, name, email, brokerage_id, created_at, brokerages(name)").neq("id",i.id).order("name").range(Ce*Ne,(Ce+1)*Ne-1);if(Xe)throw Xe;dt&&ze.push(...dt),Ve=(dt==null?void 0:dt.length)===Ne,Ce++}const qe={};for(Ce=0,Ve=!0;Ve;){const{data:dt,error:Xe}=await q.from("user_roles").select("user_id, role").range(Ce*Ne,(Ce+1)*Ne-1);if(Xe)throw Xe;dt==null||dt.forEach(at=>{qe[at.user_id]||(qe[at.user_id]=[]),qe[at.user_id].push(at.role)}),Ve=(dt==null?void 0:dt.length)===Ne,Ce++}G(qe),d(ze.map(dt=>{var Xe;return{id:dt.id,name:dt.name,email:dt.email,brokerage_name:((Xe=dt.brokerages)==null?void 0:Xe.name)||"No Brokerage",roles:qe[dt.id]||[],created_at:dt.created_at}}))}catch(ke){console.error("Error loading data:",ke),re.error("Failed to load agents and brokerages")}finally{I(!1)}}},ae=async()=>{if(i){I(!0);try{const{data:ke}=await q.from("profiles").select("brokerage_id").eq("id",i.id).single();if(!(ke!=null&&ke.brokerage_id)){re.error("You must be part of a brokerage to share resources"),t(!1);return}const{data:Be,error:Ne}=await q.from("profiles").select("id, name, email").eq("brokerage_id",ke.brokerage_id).neq("id",i.id).order("name");if(Ne)throw Ne;d(Be||[])}catch(ke){console.error("Error loading agents:",ke),re.error("Failed to load agents")}finally{I(!1)}}},le=c.filter(ke=>{var Ne;const Be=ke.name.toLowerCase().includes(y.toLowerCase())||ke.email.toLowerCase().includes(y.toLowerCase())||((Ne=ke.brokerage_name)==null?void 0:Ne.toLowerCase().includes(y.toLowerCase()));if(l&&U!=="all"&&U!=="newest"){const Ae=V[ke.id]||[];return Be&&Ae.includes(U)}return Be}).sort((ke,Be)=>U==="newest"?(Be.created_at||"").localeCompare(ke.created_at||""):0),ne=u.filter(ke=>ke.name.toLowerCase().includes(b.toLowerCase())),te=()=>{m.length===le.length?f([]):f(le.map(ke=>ke.id))},J=()=>{g.length===ne.length?x([]):x(ne.map(ke=>ke.id))},ce=ke=>{if(!Y){f([ke]);return}f(Be=>Be.includes(ke)?Be.filter(Ne=>Ne!==ke):[...Be,ke])},_e=ke=>{x(Be=>Be.includes(ke)?Be.filter(Ne=>Ne!==ke):[...Be,ke])},he=async()=>{if(!(m.length>0||g.length>0)){re.error("Please select at least one agent or brokerage to share with");return}R(!0);try{const{data:Be,error:Ne}=await q.functions.invoke("send-share-notification",{body:{recipientIds:m,brokerageIds:g,resourceType:n,resourceId:r,resourceTitle:a,message:S.trim()||void 0}});if(Ne)throw Ne;const Ae=(Be==null?void 0:Be.sharesCreated)||m.length;re.success(`Shared with ${Ae} agent${Ae!==1?"s":""}`),t(!1)}catch(Be){console.error("Error sharing resource:",Be),re.error("Failed to share resource")}finally{R(!1)}},ue=ke=>ke.split(" ").map(Be=>Be[0]).join("").toUpperCase().slice(0,2),ve=ke=>{const Be=V[ke]||[];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,Se=U!=="all"&&U!=="newest"?le.length:null;return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-lg max-h-[90vh] overflow-hidden flex flex-col",children:[e.jsxs(Us,{className:"flex-shrink-0",children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(Kr,{className:"h-5 w-5 text-primary"}),"Share Resource"]}),e.jsxs(Pr,{className:"line-clamp-2",children:['Share "',a,'" with ',l?"agents or brokerages":"agents in your brokerage"]})]}),e.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col space-y-4",children:[l?e.jsxs(ha,{value:D,onValueChange:O,className:"flex-1 flex flex-col overflow-hidden",children:[e.jsxs(ma,{className:"grid w-full grid-cols-2 flex-shrink-0",children:[e.jsxs(Zt,{value:"agents",className:"flex items-center gap-2",children:[e.jsx(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(Zt,{value:"brokerages",className:"flex items-center gap-2",children:[e.jsx(ji,{className:"h-4 w-4"}),e.jsx("span",{children:"Brokerages"}),g.length>0&&e.jsx($e,{variant:"default",className:"h-5 min-w-5 px-1.5 text-xs",children:g.length})]})]}),e.jsxs(Xt,{value:"agents",className:"flex-1 flex flex-col space-y-3 mt-3 overflow-hidden",children:[e.jsxs("div",{className:"flex gap-2 flex-shrink-0",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Zr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search by name, email, or brokerage...",value:y,onChange:ke=>v(ke.target.value),className:"pl-9"})]}),e.jsxs(ms,{value:U,onValueChange:W,children:[e.jsxs(us,{className:"w-[180px]",children:[e.jsx(Cw,{className:"h-4 w-4 mr-2 text-muted-foreground"}),e.jsx(fs,{placeholder:"Filter by role"})]}),e.jsx(hs,{children:kBe.map(ke=>e.jsx(Ge,{value:ke.value,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ke.icon,{className:"h-4 w-4"}),e.jsx("span",{children:ke.label})]})},ke.value))})]})]}),e.jsxs("div",{className:"flex items-center justify-between px-1 flex-shrink-0",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:te,className:"text-xs h-8",disabled: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:[Se!==null&&e.jsxs("span",{className:"text-primary font-medium",children:[Se," ",(Le=kBe.find(ke=>ke.value===U))==null?void 0:Le.label]}),e.jsxs("span",{className:"font-medium",children:[m.length," selected"]})]})]}),e.jsx(uo,{className:"h-[300px] border rounded-lg",children:E?e.jsx("div",{className:"flex items-center justify-center h-[200px]",children:e.jsx(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=kBe.find(ke=>ke.value===U))==null?void 0:Fe.label.toLowerCase()} found`:"No agents found"})]}):e.jsx("div",{className:"p-2 space-y-1",children:le.map(ke=>e.jsxs("div",{className:`flex items-center gap-3 p-2.5 rounded-lg cursor-pointer hover:bg-accent/50 transition-colors ${m.includes(ke.id)?"bg-accent":""}`,onClick:()=>ce(ke.id),children:[e.jsx(ai,{checked:m.includes(ke.id),onCheckedChange:()=>ce(ke.id),className:"flex-shrink-0"}),e.jsx(Oa,{className:"h-9 w-9 flex-shrink-0",children:e.jsx(za,{className:"text-xs bg-primary/10 text-primary",children:ue(ke.name)})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:ke.name}),ve(ke.id)]}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[ke.email,ke.brokerage_name&&e.jsxs("span",{className:"ml-1 opacity-75",children:["• ",ke.brokerage_name]})]})]})]},ke.id))})})]}),e.jsxs(Xt,{value:"brokerages",className:"flex-1 flex flex-col space-y-3 mt-3 overflow-hidden",children:[e.jsxs("div",{className:"relative flex-shrink-0",children:[e.jsx(Zr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search brokerages...",value:b,onChange:ke=>w(ke.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex items-center justify-between px-1 flex-shrink-0",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:J,className:"text-xs h-8",disabled:ne.length===0,children:[e.jsx(ji,{className:"h-3.5 w-3.5 mr-1.5"}),g.length===ne.length&&ne.length>0?"Deselect All":"Select All"]}),e.jsxs("span",{className:"text-xs text-muted-foreground font-medium",children:[g.length," selected"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground px-1 flex-shrink-0",children:"Selecting a brokerage will send to all agents in that brokerage."}),e.jsx(uo,{className:"h-[250px] border rounded-lg",children:E?e.jsx("div",{className:"flex items-center justify-center h-[180px]",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):ne.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-[180px] text-muted-foreground",children:[e.jsx(ji,{className:"h-8 w-8 mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No brokerages found"})]}):e.jsx("div",{className:"p-2 space-y-1",children:ne.map(ke=>e.jsxs("div",{className:`flex items-center gap-3 p-2.5 rounded-lg cursor-pointer hover:bg-accent/50 transition-colors ${g.includes(ke.id)?"bg-accent":""}`,onClick:()=>_e(ke.id),children:[e.jsx(ai,{checked:g.includes(ke.id),onCheckedChange:()=>_e(ke.id),className:"flex-shrink-0"}),e.jsx("div",{className:"h-9 w-9 rounded-lg bg-primary/10 flex items-center justify-center flex-shrink-0",children:e.jsx(ji,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:ke.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[ke.agent_count," agent",ke.agent_count!==1?"s":""]})]})]},ke.id))})})]})]}):e.jsxs("div",{className:"flex-1 flex flex-col space-y-3 overflow-hidden",children:[e.jsxs("div",{className:"relative flex-shrink-0",children:[e.jsx(Zr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search agents...",value:y,onChange:ke=>v(ke.target.value),className:"pl-9"})]}),Y&&e.jsxs("div",{className:"flex items-center justify-between px-1 flex-shrink-0",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:te,className:"text-xs h-8",disabled: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(uo,{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(ke=>e.jsxs("div",{className:`flex items-center gap-3 p-2.5 rounded-lg cursor-pointer hover:bg-accent/50 transition-colors ${m.includes(ke.id)?"bg-accent":""}`,onClick:()=>ce(ke.id),children:[e.jsx(ai,{checked:m.includes(ke.id),onCheckedChange:()=>ce(ke.id),className:"flex-shrink-0"}),e.jsx(Oa,{className:"h-9 w-9 flex-shrink-0",children:e.jsx(za,{className:"text-xs bg-primary/10 text-primary",children:ue(ke.name)})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:ke.name}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:ke.email})]})]},ke.id))})})]}),e.jsxs("div",{className:"space-y-2 flex-shrink-0",children:[e.jsx(ee,{htmlFor:"message",className:"text-sm font-medium",children:"Add a message (optional)"}),e.jsx(Ls,{id:"message",placeholder:"I thought you might find this useful...",value:S,onChange:ke=>A(ke.target.value),rows:2,className:"resize-none"})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2 flex-shrink-0",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx($,{onClick:he,disabled:Ee===0||P,children:P?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),"Sharing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Kr,{className:"h-4 w-4 mr-2"}),"Share"]})})]})]})]})})}function pK({resourceType:s,resourceId:t,resourceTitle:n,variant:r="outline",size:a="sm",className:i=""}){const[l,o]=j.useState(!1),{user:c}=bs();return c?e.jsxs(e.Fragment,{children:[e.jsxs($,{variant:r,size:a,onClick:()=>o(!0),className:i,children:[e.jsx(Fd,{className:"h-4 w-4 mr-2"}),"Share"]}),e.jsx(Usn,{open:l,onOpenChange:o,resourceType:s,resourceId:t,resourceTitle:n})]}):null}function qsn(){const{eventId:s}=Wi(),t=Xn(),{user:n}=bs(),[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),re.error("Failed to load event"),t("/events")}finally{u(!1)}},g=async()=>{if(!(!n||!r)){m(!0);try{const{error:w}=await q.auth.refreshSession();if(w){console.error("Session refresh failed:",w),re.error("Your session has expired. Please log in again.");return}if(i){const{error:S}=await q.functions.invoke("zoom-unregister",{body:{event_id:r.id}});if(S)throw S;re.success("Successfully cancelled registration"),l(null),c(A=>A-1)}else{const{data:S,error:A}=await q.functions.invoke("zoom-register",{body:{event_id:r.id}});if(A)throw A;re.success("Successfully registered for event!"),l({id:S.registration_id,zoom_join_url:S.zoom_join_url}),c(E=>E+1)}}catch(w){console.error("Registration error:",w),re.error(i?"Failed to cancel registration":"Failed to register for event")}finally{m(!1)}}},x=w=>{var S,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 y=D4(new Date(r.event_date)),v=r.capacity&&o>=r.capacity,b=(i==null?void 0:i.zoom_join_url)||r.zoom_link;return e.jsx(Vs,{title:r.title,children:e.jsxs("div",{className:"max-w-4xl mx-auto",children:[e.jsxs($,{variant:"ghost",className:"mb-6 gap-2",onClick:()=>t("/events"),children:[e.jsx(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"}),y&&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(pK,{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(Ie,{className:"p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Ta,{className:"h-5 w-5 text-primary mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:new Intl.DateTimeFormat("en-US",{weekday:"long",year:"numeric",month:"long",day:"numeric",timeZone:"America/New_York"}).format(new Date(r.event_date))}),e.jsx("p",{className:"text-sm text-muted-foreground",children:cse(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:[!y&&e.jsx(e.Fragment,{children:i?e.jsxs(e.Fragment,{children:[e.jsxs($,{className:"w-full gap-2",onClick:()=>window.open(b,"_blank"),children:[e.jsx(Fr,{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||(v??!1),children:h?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):v?"Event Full":"Register Now"})}),y&&i&&e.jsxs($,{variant:"outline",className:"w-full gap-2",onClick:()=>window.open(r.zoom_link,"_blank"),children:[e.jsx(Fr,{className:"h-4 w-4"}),"View Recording"]})]})]})})})]})]})})}const Vsn=[{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 Hsn(){const{isAdmin:s}=bs(),t=Vsn.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(oP,{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 DTe=[{id:"market-listing",title:"Market a Listing",blurb:"Presentations, copy, pages and video",icon:va,color:"bg-violet-500/15 text-violet-600"},{id:"follow-up",title:"Follow Up With My Database",blurb:"Emails, cards, mail and check-ins",icon:mn,color:"bg-emerald-500/15 text-emerald-600"},{id:"social-content",title:"Create Social Content",blurb:"Reels, posts and captions",icon: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:i2,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"}];DTe.reduce((s,t)=>({...s,[t.id]:t}),{});const Gsn=[{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"}],vHt=[{id:"scheduler",name:"LevelUp Scheduler",description:"Share your booking link, sync Google Calendar and let clients book you",icon:Cu,path:"/mission-control/scheduler",color:"bg-blue-500/15 text-blue-600",isNew:!0,goals:["follow-up","new-business","brand"],categories:["database","leads","brand"],keywords:["scheduler","calendar","booking link","book a meeting","appointments","calendly","availability"]},{id:"quickvid",name:"QuickVid",description:"Record and share personalized video messages",icon:ua,path:"/mission-control/video/record",color:"bg-rose-500/15 text-rose-600",popular:!0,goals:["follow-up","social-content","open-house"],categories:["database","social","open-houses"],keywords:["video","record a video","send a video","video email","screen record"]},{id:"smart-card",name:"Smart Card",description:"Your digital business card in one shareable link",icon:Nv,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:bb,path:"/mission-control/presentations",color:"bg-amber-500/15 text-amber-600",goals:["market-listing","brand"],categories:["listings","brand"],keywords:["buyer presentation","listing presentation","pitch","slides"]},{id:"landing-pages",name:"Landing Pages",description:"Custom landing pages that capture leads",icon:Jr,path:"/mission-control/landing-pages",color:"bg-emerald-500/15 text-emerald-600",goals:["market-listing","new-business","open-house"],categories:["listings","leads","open-houses"],keywords:["landing page","capture leads","promote an open house","single property site"]},{id:"guest-book",name:"Guest Book",description:"Digital open house sign-in that captures visitors",icon:Xf,path:"/mission-control/guest-book",color:"bg-orange-500/15 text-orange-600",popular:!0,goals:["open-house","new-business"],categories:["open-houses","leads"],keywords:["open house sign in","sign-in sheet","visitors","host an open house"]},{id:"card-studio",name:"Card Studio",description:"Animated cards for birthdays and milestones",icon:Nn,path:"/mission-control/card-studio",color:"bg-pink-500/15 text-pink-600",goals:["follow-up","social-content"],categories:["database","social"],keywords:["birthday card","anniversary","greeting","thank you card"]},{id:"direct-mail",name:"Direct Mail",description:"Send professional postcards to your contacts",icon:mn,path:"/mission-control/direct-mail",color:"bg-indigo-500/15 text-indigo-600",adminOnly:!0,beta:!0,goals:["follow-up","open-house"],categories:["database","open-houses"],keywords:["postcard","mailer","farming","direct mail"]},{id:"reelflow",name:"ReelFlow",description:"Turn property photos into cinematic reels with AI",icon: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:Kr,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:Vq,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:QN,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:bb,path:"/apps/listing-presentation-studio",color:"bg-emerald-500/15 text-emerald-600",isNew:!0,popular:!0,goals:["market-listing"],categories:["listings"],keywords:["make a listing presentation","seller presentation","pdf","pre-listing"]},{id:"listing-revival",name:"Listing Revival",description:"Turn expired listings into appointments",icon:Nn,path:"/apps/listing-revival",color:"bg-amber-500/15 text-amber-600",isNew:!0,goals:["new-business"],categories:["leads","listings","ai"],keywords:["expired listing","expired","withdrawn","revival letter"]},{id:"fsbo-breakthrough",name:"By-Owner Breakthrough",description:"Convert FSBO sellers with letters, guides and pages",icon:va,path:"/apps/fsbo-breakthrough",color:"bg-[#5b8a5c]/15 text-[#5b8a5c]",isNew:!0,goals:["new-business"],categories:["leads","ai"],keywords:["fsbo","for sale by owner","by owner","convert fsbo"]},{id:"staging-studio",name:"Staging Studio",description:"Virtually stage, declutter and brighten listing photos",icon:tV,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"]}],i_t=vHt.reduce((s,t)=>({...s,[t.id]:t}),{}),Wsn={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"]}},Ksn={AgentReview:"Replaced by the new built-in Reviews app"};function Ysn(s){return Wsn[s]??{goals:[],categories:[],keywords:[]}}const Qnt=[{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:i2,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"}]}],Q7=Qnt.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 Xsn({item:s,isFavorite:t,onOpen:n,onToggleFavorite:r}){const a=typeof s.icon=="string"?null:s.icon,i=!!s.lockedFeature,l=i?{label:"Upgrade",className:"bg-muted text-muted-foreground"}:s.isNew?{label:"New",className:"bg-primary/10 text-primary"}:s.beta?{label:"Beta",className:"bg-amber-500/15 text-amber-600"}:s.popular?{label:"Popular",className:"bg-emerald-500/15 text-emerald-600"}:s.kind==="app"&&s.deprecated?{label:"Going away soon",className:"bg-amber-500/15 text-amber-700"}:s.kind==="app"?{label:"Connected",className:"bg-muted text-muted-foreground"}:null;return e.jsxs("div",{role:"button",tabIndex:0,onClick:()=>n(s),onKeyDown:o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),n(s))},className:Pt("group h-full text-left bg-card border border-border rounded-2xl p-5 flex flex-col gap-3 cursor-pointer transition-all hover:border-primary/40 hover:shadow-md focus:outline-none focus-visible:ring-2 focus-visible:ring-primary",i&&"opacity-80"),children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:Pt("flex-shrink-0 w-12 h-12 rounded-xl flex items-center justify-center text-2xl",s.color),children:i?e.jsx(pc,{className:"h-5 w-5"}):a?e.jsx(a,{className:"h-6 w-6"}):e.jsx("span",{children:s.icon})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("h3",{className:"font-semibold text-foreground group-hover:text-primary transition-colors",children:s.name}),l&&e.jsx("span",{className:Pt("text-[11px] font-medium px-2 py-0.5 rounded-full",l.className),children:l.label})]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:s.description})]}),e.jsx("button",{type:"button","aria-label":t?`Remove ${s.name} from favorites`:`Add ${s.name} to favorites`,onClick:o=>{o.stopPropagation(),r(s)},className:Pt("flex-shrink-0 p-2 -m-1 rounded-lg transition-colors",t?"text-primary":"text-muted-foreground/40 hover:text-primary"),children:e.jsx(E0,{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 f7({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(Xsn,{item:a,isFavorite:t(a),onOpen:n,onToggleFavorite:r},a.key))})}const Qsn="bg-primary/10 text-primary";function die(){const{user:s,isAdmin:t}=bs(),n=_C(),r=Xn(),{hasAccess:a}=xLe(),{isFeatureEnabled:i}=Tae(),[l,o]=j.useState([]),[c,d]=j.useState(!0),[u,h]=j.useState(new Set),[m,f]=j.useState(new Set),[g,x]=j.useState(!1),[y,v]=j.useState([]),[b,w]=j.useState(""),S=j.useCallback(async()=>{if(s!=null&&s.id)try{const[{data:G},{data:Y},{data:X},{data:ae},{data:le},{data:ne},{data:te}]=await Promise.all([q.from("user_tags").select("tag").eq("user_id",s.id),q.from("app_tiles").select("*").order("name"),q.from("user_favorites").select("app_id").eq("user_id",s.id),q.from("user_tool_favorites").select("tool_id").eq("user_id",s.id),q.from("lead_sites").select("id, mls_provider_id, no_mls_mode, is_active").eq("agent_id",s.id),q.from("activity_logs").select("app_id, app_name, launched_at").eq("user_id",s.id).order("launched_at",{ascending:!1}).limit(40),q.from("profiles").select("name").eq("id",s.id).maybeSingle()]),J=(G||[]).map(ve=>ve.tag);x((le||[]).some(ve=>ve.is_active&&ve.mls_provider_id&&!ve.no_mls_mode)),h(new Set((X||[]).map(ve=>ve.app_id))),f(new Set((ae||[]).map(ve=>ve.tool_id)));const ce=(Y||[]).filter(ve=>ve.app_id==="newsletter_studio"?!1:!ve.required_tags||ve.required_tags.length===0?!0:ve.required_tags.some(Ee=>J.includes(Ee)));o(ce.sort((ve,Ee)=>ve.name==="LevelUp Members Portal"?-1:Ee.name==="LevelUp Members Portal"?1:0));const _e=new Set,he=[];for(const ve of ne||[])if(!(!ve.app_id||_e.has(ve.app_id))&&(_e.add(ve.app_id),he.push({appId:ve.app_id,name:ve.app_name,at:ve.launched_at}),he.length>=8))break;v(he);const ue=te==null?void 0:te.name;w(ue?ue.trim().split(" ")[0]:"")}catch(G){console.error("Error loading app catalog:",G),re.error("Failed to load apps")}finally{d(!1)}},[s==null?void 0:s.id]);j.useEffect(()=>{S()},[S]);const A=j.useMemo(()=>{const G=le=>{if(!n.isRestricted)return null;const ne=SCs(le);return ne&&!n.hasFeature(ne)?ne:null},Y=vHt.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 ne=Ysn(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:Qsn,goals:ne.goals,categories:ne.categories,keywords:ne.keywords,lockedFeature:n.isRestricted&&te&&!n.hasFeature(te)?te:null,deprecated:!!Ksn[le.app_id],tile:le}});return[...Y,...ae]},[l,t,g,a,i,n.isRestricted,n.features]),E=j.useCallback(G=>{var Y;return G.kind==="tool"?m.has(G.id):u.has(((Y=G.tile)==null?void 0:Y.id)??"")},[m,u]),I=j.useMemo(()=>A.filter(E),[A,E]),P=j.useMemo(()=>{const G=new Map(A.map(Y=>[Y.id,Y]));return y.map(Y=>G.get(Y.appId)).filter(Boolean)},[A,y]),R=j.useMemo(()=>A.filter(G=>G.kind==="app"),[A]),D=j.useCallback(async(G,Y)=>{try{await q.from("activity_logs").insert({user_id:s==null?void 0:s.id,app_id:G,app_name:Y,user_agent:navigator.userAgent})}catch{}},[s==null?void 0:s.id]),O=j.useCallback(async G=>{var X;if(G.target_url.startsWith("/")){await D(G.app_id,G.name),r(G.target_url);return}try{const ae=new URL(G.target_url);if(new Set([window.location.hostname,"dashboard.relevelup.com"]).has(ae.hostname)){await D(G.app_id,G.name),r(ae.pathname+ae.search+ae.hash);return}}catch{}const Y=window.open("about:blank","_blank");try{const{data:ae,error:le}=await q.auth.getSession();if(le||!ae.session){Y==null||Y.close(),re.error("Session expired. Please refresh the page and try again.");return}await D(G.app_id,G.name);const{data:ne,error:te}=await q.functions.invoke("sso-launch",{body:{app_id:G.app_id},headers:{Authorization:`Bearer ${ae.session.access_token}`}});if(te)throw te;ne!=null&&ne.redirect_url?Y&&!Y.closed?(Y.location.href=ne.redirect_url,(X=Y.focus)==null||X.call(Y)):window.location.assign(ne.redirect_url):(Y==null||Y.close(),re.error("Launch link unavailable"))}catch(ae){Y==null||Y.close(),console.error("Error launching app:",ae),re.error("Failed to launch app. Please try again.")}},[D,r]),U=j.useCallback(G=>{if(G.lockedFeature){r(`/upgrade/${G.lockedFeature}`);return}if(G.kind==="app"&&G.tile){O(G.tile);return}G.tool&&(D(G.tool.id,G.tool.name),r(G.tool.path))},[O,D,r]),W=j.useCallback(async G=>{var te;if(!(s!=null&&s.id))return;const Y=E(G),X=G.kind==="tool"?"user_tool_favorites":"user_favorites",ae=G.kind==="tool"?"tool_id":"app_id",le=G.kind==="tool"?G.id:(te=G.tile)==null?void 0:te.id;if(!le)return;const ne=G.kind==="tool"?f:h;ne(J=>{const ce=new Set(J);return Y?ce.delete(le):ce.add(le),ce});try{if(Y){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),re.error("Failed to update favorites"),ne(ce=>{const _e=new Set(ce);return Y?_e.add(le):_e.delete(le),_e})}},[E,s==null?void 0:s.id]),V=j.useCallback((G,Y=A)=>{const X=G.trim().toLowerCase();if(!X)return Y;const ae=X.split(/\s+/);return Y.filter(le=>{if(le.deprecated)return!1;const ne=[le.name,le.description,...le.keywords,...le.categories,...le.goals].join(" ").toLowerCase();return ae.every(te=>ne.includes(te))||ne.includes(X)})},[A]);return{loading:c,items:A,favoriteItems:I,recentItems:P,connectedItems:R,recent:y,firstName:b,isFavorite:E,toggleFavorite:W,openItem:U,search:V,reload:S}}function SBe(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 W6e(s){const t=Q7[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 K6e(){const{user:s}=bs(),[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(SBe))}catch(m){console.error("Error loading workflow runs:",m)}finally{a(!1)}},[s==null?void 0:s.id]);j.useEffect(()=>{i()},[i]);const l=j.useCallback(async(m,f)=>{var g;if(!(s!=null&&s.id))return null;try{const{data:x,error:y}=await q.from("workflow_runs").insert({user_id:s.id,workflow_id:m,run_name:f.trim()||((g=Q7[m])==null?void 0:g.title)||"Untitled"}).select("*").single();if(y)throw y;const v=SBe(x);return n(b=>[v,...b]),v}catch(x){return console.error("Error starting workflow:",x),re.error("Could not start this workflow"),null}},[s==null?void 0:s.id]),o=j.useCallback(async(m,f)=>{const g={...f,last_activity_at:new Date().toISOString()};n(y=>y.map(v=>v.id===m?SBe({...v,...g}):v));const{error:x}=await q.from("workflow_runs").update(g).eq("id",m);x&&(console.error("Error updating workflow run:",x),re.error("Could not save your progress"))},[]),c=j.useCallback(async(m,f,g)=>{const x={...m.step_state};g?x[f]=g:delete x[f];const y=Q7[m.workflow_id],v=y?y.steps.every(b=>x[b.key]):!1;await o(m.id,{step_state:x,status:v?"completed":"in_progress",completed_at:v?new Date().toISOString():null}),v&&m.status!=="completed"&&re.success("Workflow complete — nice work!")},[o]),d=j.useCallback((m,f)=>o(m.id,{run_name:f.trim()}),[o]),u=j.useCallback(m=>o(m.id,{status:"in_progress",completed_at:null}),[o]),h=j.useCallback(async m=>{n(g=>g.filter(x=>x.id!==m));const{error:f}=await q.from("workflow_runs").delete().eq("id",m);f&&(console.error("Error deleting workflow run:",f),re.error("Could not delete this workflow"))},[]);return{runs:t,loading:r,activeRuns:t.filter(m=>m.status==="in_progress"),completedRuns:t.filter(m=>m.status==="completed"),startRun:l,setStep:c,renameRun:d,reopenRun:u,deleteRun:h,reload:i}}function Jsn(){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 enn(){const s=Xn(),{items:t,firstName:n,recentItems:r,favoriteItems:a,isFavorite:i,toggleFavorite:l,openItem:o,search:c}=die(),{isAdmin:d}=bs(),{activeRuns:u}=K6e(),h=d?u:[],[m,f]=j.useState(""),g=j.useMemo(()=>m.trim()?c(m).slice(0,8):[],[m,c]),x=j.useMemo(()=>{const v=new Set(r.map(S=>S.id)),b=[],w=S=>{for(const A of S){if(b.length>=4)break;b.some(E=>E.key===A.key)||b.push(A)}};return w(a.filter(S=>!v.has(S.id))),w(t.filter(S=>S.isNew&&!v.has(S.id))),w(t.filter(S=>S.popular&&!v.has(S.id))),b},[t,a,r]),y=v=>s(`/apps/browse?goal=${v.id}`);return e.jsxs("div",{className:"space-y-8",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl sm:text-3xl font-bold text-foreground",children:[Jsn(),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(Zr,{className:"absolute left-4 top-1/2 -translate-y-1/2 h-5 w-5 text-muted-foreground"}),e.jsx(pe,{value:m,onChange:v=>f(v.target.value),onKeyDown:v=>{v.key==="Enter"&&m.trim()&&s(`/apps/browse?q=${encodeURIComponent(m.trim())}`)},placeholder:"Search apps or tell us what you want to do…",className:"pl-12 h-14 text-base rounded-2xl"})]}),m.trim()&&e.jsx("div",{className:"mt-4 max-w-2xl bg-card border border-border rounded-2xl divide-y divide-border overflow-hidden",children:g.length===0?e.jsxs("p",{className:"p-4 text-sm text-muted-foreground",children:["Nothing matched “",m,"”. Try “open house”, “email my database” or “reel”."]}):g.map(v=>{const b=typeof v.icon=="string"?null:v.icon;return e.jsxs("button",{type:"button",onClick:()=>o(v),className:"w-full flex items-center gap-3 p-4 text-left hover:bg-muted/50 transition-colors",children:[e.jsx("span",{className:Pt("w-10 h-10 rounded-lg flex items-center justify-center text-xl flex-shrink-0",v.color),children:b?e.jsx(b,{className:"h-5 w-5"}):v.icon}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block font-medium text-foreground",children:v.name}),e.jsx("span",{className:"block text-sm text-muted-foreground truncate",children:v.description})]})]},v.key)})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-8",children:[e.jsxs("div",{className:"lg:col-span-2 space-y-8",children:[e.jsxs("section",{children:[e.jsx("h2",{className:"text-lg font-semibold text-foreground mb-4",children:"Start with a goal"}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:DTe.map(v=>e.jsx(Zsn,{goal:v,onSelect:y},v.id))})]}),(h.length>0||r.length>0)&&e.jsxs("section",{children:[e.jsxs("h2",{className:"text-lg font-semibold text-foreground mb-4 flex items-center gap-2",children:[e.jsx(da,{className:"h-4 w-4 text-muted-foreground"})," Continue working"]}),h.length>0&&e.jsx("div",{className:"space-y-3 mb-4",children:h.slice(0,2).map(v=>{const b=Q7[v.workflow_id],w=W6e(v);return e.jsxs("button",{type:"button",onClick:()=>s(`/apps/workflows/${v.id}`),className:"w-full text-left bg-card border border-border rounded-2xl p-4 hover:border-primary/40 transition-colors",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium text-foreground truncate",children:v.run_name}),e.jsxs("p",{className:"text-sm text-muted-foreground truncate",children:[b==null?void 0:b.title," · Step ",Math.min(w.touched+1,w.total)," of ",w.total]})]}),e.jsx(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}%`}})})]},v.id)})}),r.length>0&&e.jsx("div",{className:"flex gap-3 overflow-x-auto pb-2 -mx-4 px-4 sm:mx-0 sm:px-0 scrollbar-hide",children:r.slice(0,6).map(v=>{const b=typeof v.icon=="string"?null:v.icon;return e.jsxs("button",{type:"button",onClick:()=>o(v),className:"flex-shrink-0 w-44 bg-card border border-border rounded-2xl p-4 text-left hover:border-primary/40 transition-colors",children:[e.jsx("span",{className:Pt("w-10 h-10 rounded-lg flex items-center justify-center text-xl mb-3",v.color),children:b?e.jsx(b,{className:"h-5 w-5"}):v.icon}),e.jsx("span",{className:"block font-medium text-sm text-foreground truncate",children:v.name}),e.jsx("span",{className:"block text-xs text-muted-foreground",children:"Open again"})]},v.key)})})]})]}),x.length>0&&e.jsxs("aside",{className:"space-y-4",children:[e.jsxs("h2",{className:"text-lg font-semibold text-foreground flex items-center gap-2",children:[e.jsx(Nn,{className:"h-4 w-4 text-primary"})," Recommended for you"]}),e.jsx("div",{className:"space-y-3",children:x.map(v=>{const b=typeof v.icon=="string"?null:v.icon;return e.jsxs("button",{type:"button",onClick:()=>o(v),className:"w-full flex items-start gap-3 bg-card border border-border rounded-2xl p-4 text-left hover:border-primary/40 transition-colors",children:[e.jsx("span",{className:Pt("w-10 h-10 rounded-lg flex items-center justify-center text-xl flex-shrink-0",v.color),children:b?e.jsx(b,{className:"h-5 w-5"}):v.icon}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block font-medium text-foreground",children:v.name}),e.jsx("span",{className:"block text-sm text-muted-foreground line-clamp-2",children:v.description})]})]},v.key)})}),e.jsx($,{variant:"outline",className:"w-full",onClick:()=>s("/apps/browse"),children:"Browse all apps"})]})]}),a.length>0&&e.jsxs("section",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"Your favorites"}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>s("/apps/my-apps"),children:"View all"})]}),e.jsx(f7,{items:a.slice(0,6),isFavorite:i,onOpen:o,onToggleFavorite:l})]})]})}function bHt({workflow:s,activeRun:t,onStart:n,onResume:r}){const a=s.icon,i=t?W6e(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 _Ht({workflow:s,onClose:t,onStart:n}){const[r,a]=j.useState(""),[i,l]=j.useState(!1);j.useEffect(()=>{a(""),l(!1)},[s==null?void 0:s.id]);const o=async()=>{s&&(l(!0),await n(s,r.trim()||s.title),l(!1))};return e.jsx(zs,{open:!!s,onOpenChange:c=>!c&&t(),children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:s==null?void 0:s.title}),e.jsxs(Pr,{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(Sr,{children:[e.jsx($,{variant:"outline",onClick:t,disabled:i,children:"Cancel"}),e.jsx($,{onClick:o,disabled:i,children:i?"Starting…":"Start workflow"})]})]})})}function tnn(){const s=Xn(),[t,n]=gc(),{items:r,isFavorite:a,toggleFavorite:i,openItem:l,search:o}=die(),{isAdmin:c}=bs(),{activeRuns:d,startRun:u}=K6e(),h=t.get("goal"),m=t.get("category")??null,[f,g]=j.useState(t.get("q")??""),[x,y]=j.useState(null);j.useEffect(()=>{g(t.get("q")??"")},[t]);const v=(E,I)=>{const P=new URLSearchParams(t);I?P.set(E,I):P.delete(E),n(P,{replace:!0})},b=()=>{const E=new URLSearchParams(t);E.delete("category"),E.delete("goal"),E.delete("q"),n(E,{replace:!0}),g("")},w=j.useMemo(()=>{let E=r;return h&&(E=E.filter(I=>I.goals.includes(h))),m&&(E=E.filter(I=>I.categories.includes(m))),f.trim()&&(E=o(f,E)),E},[r,h,m,f,o]),S=j.useMemo(()=>h||m||f.trim()?null:DTe.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?DTe.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(Zr,{className:"absolute left-4 top-1/2 -translate-y-1/2 h-5 w-5 text-muted-foreground"}),e.jsx(pe,{value:f,onChange:E=>{g(E.target.value),v("q",E.target.value||null)},placeholder:"Search apps or tell us what you want to do…",className:"pl-12 h-12 rounded-2xl"})]}),e.jsx("div",{className:"-mx-4 px-4 sm:mx-0 sm:px-0 overflow-x-auto scrollbar-hide",children:e.jsxs("div",{className:"inline-flex gap-2 min-w-max pb-1",children:[e.jsx("button",{type:"button",onClick:b,className:Pt("px-4 py-2 rounded-full text-sm font-medium border transition-colors whitespace-nowrap",!m&&!h&&!f.trim()?"bg-primary text-primary-foreground border-primary":"bg-card text-muted-foreground border-border hover:text-foreground"),children:"All"}),Gsn.map(E=>e.jsx("button",{type:"button",onClick:()=>v("category",m===E.id?null:E.id),className:Pt("px-4 py-2 rounded-full text-sm font-medium border transition-colors whitespace-nowrap",m===E.id?"bg-primary text-primary-foreground border-primary":"bg-card text-muted-foreground border-border hover:text-foreground"),children:E.label},E.id))]})}),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:()=>v("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:Qnt.map(E=>e.jsx(bHt,{workflow:E,activeRun:d.find(I=>I.workflow_id===E.id),onStart:y,onResume:I=>s(`/apps/workflows/${I.id}`)},E.id))})]}),S?S.map(({goal:E,apps:I})=>e.jsxs("section",{children:[e.jsx("h2",{className:"text-lg font-semibold text-foreground mb-4",children:E.title}),e.jsx(f7,{items:I,isFavorite:a,onOpen:l,onToggleFavorite:i})]},E.id)):w.length>0?e.jsx(f7,{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(Zr,{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(_Ht,{workflow:x,onClose:()=>y(null),onStart:async(E,I)=>{const P=await u(E.id,I);y(null),P&&s(`/apps/workflows/${P.id}`)}})]})}function snn(){const s=Xn(),{favoriteItems:t,recentItems:n,connectedItems:r,isFavorite:a,toggleFavorite:i,openItem:l}=die(),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(E0,{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(E0,{className:"h-4 w-4 text-primary"})," Favorites"]}),e.jsx(f7,{items:t,isFavorite:a,onOpen:l,onToggleFavorite:i})]}),n.length>0&&e.jsxs("section",{children:[e.jsxs("h2",{className:"text-lg font-semibold text-foreground mb-4 flex items-center gap-2",children:[e.jsx(da,{className:"h-4 w-4 text-muted-foreground"})," Recently used"]}),e.jsx(f7,{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(Fj,{className:"h-4 w-4 text-muted-foreground"})," Activated for your account"]}),e.jsx(f7,{items:r,isFavorite:a,onOpen:l,onToggleFavorite:i})]})]})}function nnn(){const{connectedItems:s,isFavorite:t,toggleFavorite:n,openItem:r}=die();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(Wd,{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(f7,{items:s,isFavorite:t,onOpen:r,onToggleFavorite:n})]})}function rnn(){const s=Xn(),{activeRuns:t,completedRuns:n,startRun:r,reopenRun:a,deleteRun:i}=K6e(),[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=Q7[c.workflow_id],u=W6e(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:Qnt.map(c=>e.jsx(bHt,{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=Q7[c.workflow_id])==null?void 0:d.title})]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>a(c),children:[e.jsx(Ax,{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(Hn,{className:"h-4 w-4 text-muted-foreground"})})]},c.id)})})]}),e.jsx(_Ht,{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 ann(){const{runId:s}=Wi(),t=Xn(),{runs:n,loading:r,setStep:a,renameRun:i,reopenRun:l,deleteRun:o}=K6e(),{items:c,openItem:d}=die(),[u,h]=j.useState(!1),[m,f]=j.useState(""),g=j.useMemo(()=>n.find(w=>w.id===s),[n,s]),x=g?Q7[g.workflow_id]:void 0;if(r)return e.jsx("p",{className:"text-muted-foreground",children:"Loading…"});if(!g||!x)return e.jsxs("div",{className:"text-center py-16 bg-card border border-border rounded-2xl",children:[e.jsx("p",{className:"font-medium text-foreground",children:"This workflow isn't available"}),e.jsx($,{className:"mt-4",onClick:()=>t("/apps/workflows"),children:"Back to workflows"})]});const y=W6e(g),v=x.icon,b=w=>{if(!w)return;const S=c.find(E=>E.kind==="tool"&&E.id===w);if(S){d(S);return}const A=i_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(v,{className:"h-6 w-6"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[u?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pe,{value:m,onChange:w=>f(w.target.value),autoFocus:!0,onKeyDown:w=>{w.key==="Enter"&&(i(g,m),h(!1))}}),e.jsx($,{size:"sm",onClick:()=>{i(g,m),h(!1)},children:"Save"})]}):e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h1",{className:"text-xl font-bold text-foreground truncate",children:g.run_name}),e.jsx("button",{type:"button","aria-label":"Rename workflow",onClick:()=>{f(g.run_name),h(!0)},className:"text-muted-foreground hover:text-foreground",children:e.jsx(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:[y.touched," of ",y.total," steps done"]}),e.jsxs("span",{children:[y.pct,"%"]})]}),e.jsx("div",{className:"h-2 rounded-full bg-muted overflow-hidden",children:e.jsx("div",{className:"h-full bg-primary transition-all",style:{width:`${y.pct}%`}})})]}),g.status==="completed"&&e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-3 rounded-xl bg-emerald-500/10 p-3",children:[e.jsxs("p",{className:"text-sm font-medium text-emerald-700 flex items-center gap-2",children:[e.jsx(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?i_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(ca,{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(Fr,{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(ca,{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(QJ,{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(Hn,{className:"h-4 w-4 mr-1"})," Delete this workflow"]})})]})}const inn=()=>{const{isAdmin:s}=bs();return e.jsx(Vs,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Hsn,{}),e.jsxs(pG,{children:[e.jsx(rs,{index:!0,element:e.jsx(enn,{})}),e.jsx(rs,{path:"browse",element:e.jsx(tnn,{})}),e.jsx(rs,{path:"my-apps",element:e.jsx(snn,{})}),e.jsx(rs,{path:"connected",element:e.jsx(nnn,{})}),s&&e.jsx(rs,{path:"workflows",element:e.jsx(rnn,{})}),s&&e.jsx(rs,{path:"workflows/:runId",element:e.jsx(ann,{})}),e.jsx(rs,{path:"*",element:e.jsx(Rd,{to:"/apps",replace:!0})})]})]})})},onn=()=>{var w;const s=Xn(),{isAdmin:t}=bs(),[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:ne}=await G().range(X,X+1e3-1);if(ne)throw ne;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(Y=>{W.set(Y.resource_id,(W.get(Y.resource_id)||0)+1)}),(S||[]).map(G=>({...G,links:(E||[]).filter(Y=>Y.template_id===G.id)||[],likesCount:O.get(G.id)||0,commentsCount:U.get(G.id)||0,viewsCount:W.get(G.id)||0}))}}),g=m.filter(S=>{var P;const 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")},y=n||a!=="all"||l!=="all",v=(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===v&&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(Ie,{className:"p-3",children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 text-sm",children:S.name}),S.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-1",children:zte(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(Zr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search templates...",value:n,onChange:S=>r(S.target.value),className:"pl-9"})]}),e.jsxs(ms,{value:a,onValueChange:i,children:[e.jsx(us,{className:"w-full sm:w-48",children:e.jsx(fs,{placeholder:"All Categories"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Categories"}),u.map(S=>e.jsx(Ge,{value:S.id,children:S.name},S.id))]})]}),e.jsxs(ms,{value:l,onValueChange:o,children:[e.jsx(us,{className:"w-full sm:w-48",children:e.jsx(fs,{placeholder:"All Types"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Types"}),h.map(S=>e.jsx(Ge,{value:S.id,children:S.name},S.id))]})]}),e.jsxs("div",{className:"flex gap-2",children:[y&&e.jsx($,{variant:"outline",size:"sm",onClick:x,children:"Clear Filters"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{variant:c==="grid"?"secondary":"outline",size:"icon",onClick:()=>d("grid"),className:"rounded-full",children:e.jsx(Qf,{className:"h-4 w-4"})}),e.jsx($,{variant:c==="list"?"secondary":"outline",size:"icon",onClick:()=>d("list"),className:"rounded-full",children:e.jsx(T0,{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(Ie,{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:y?"No templates match your filters":"No templates available yet"}),y&&e.jsx($,{variant:"outline",onClick:x,children:"Clear Filters"})]}),!f&&g.length>0&&e.jsx("div",{className:c==="grid"?"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6":"space-y-4",children:g.map(S=>e.jsxs(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===v&&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(Ie,{className:`p-4 flex flex-col ${c==="list"?"flex-1":""}`,children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 mb-1",children:S.name}),S.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3 flex-1",children:zte(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(qy,{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(Ca,{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(Fr,{className:"h-4 w-4"}),"View Template"]})]})]},S.id))})]})})},lnn=()=>{const{templateId:s}=Wi(),t=Xn(),{user:n,isAdmin:r}=bs(),{toast:a}=Bi(),i=Wt(),{trackEngagement:l}=hK(),[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"})}}),y=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]})}}),v=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(wr,{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(wr,{to:`/admin/templates?edit=${d.id}`,children:[e.jsx(pi,{className:"h-4 w-4"}),e.jsx("span",{children:"Edit"})]})}),e.jsx(pK,{resourceType:"template",resourceId:d.id,resourceTitle:d.name,size:"default",className:"rounded-full"}),e.jsxs($,{variant:v?"default":"outline",className:"gap-2 rounded-full",onClick:()=>y.mutate(),disabled:!n||y.isPending,children:[e.jsx(qy,{className:`h-4 w-4 ${v?"fill-current":""}`}),m.length," ",m.length===1?"Like":"Likes"]})]})]}),d.description&&e.jsx("div",{className:"text-muted-foreground prose prose-sm max-w-none dark:prose-invert [&>p]:mb-4 [&>p:last-child]:mb-0 whitespace-pre-line",dangerouslySetInnerHTML:{__html:d.description}})]}),e.jsx(je,{children:e.jsxs(Ie,{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(Fr,{className:"h-4 w-4 text-muted-foreground"})]},S.id))})]})}),d.video_url&&e.jsx(je,{children:e.jsx(Ie,{className:"pt-6",children:e.jsx("div",{className:"aspect-video w-full rounded-lg overflow-hidden",children:e.jsx("iframe",{src:d.video_url,className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})})}),d.guides&&d.guides.length>0&&e.jsx(je,{children:e.jsxs(Ie,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Jr,{className:"h-4 w-4"}),"Guide Files"]}),e.jsx("div",{className:"grid gap-2",children:d.guides.map(S=>e.jsxs($,{variant:"outline",className:"w-full justify-between gap-2 h-auto py-3",onClick:()=>{l("template",d.id,d.name,"click_pdf"),window.open(S.file_url,"_blank")},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Jr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"font-medium",children:S.name}),S.file_size&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",(S.file_size/1024).toFixed(0)," KB)"]})]}),e.jsx(xi,{className:"h-4 w-4 text-muted-foreground"})]},S.id))})]})}),h.length>0&&e.jsx(je,{children:e.jsxs(Ie,{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(Ls,{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(Kr,{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(Ie,{className:"py-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No comments yet. Be the first to share your thoughts!"})})}):f.map(S=>e.jsx(je,{children:e.jsx(Ie,{className:"pt-4 pb-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Oa,{className:"h-10 w-10 flex-shrink-0",children:e.jsx(za,{className:"text-sm",children:b(S.user_name||"U")})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-medium",children:S.user_name}),e.jsx("span",{className:"text-sm text-muted-foreground",children: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(Hn,{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(wr,{to:"/templates",children:"Back to Templates"})})]})})},o_t=({program:s,enrolled:t})=>{const{notOpenYet:n,closed:r,opensLabel:a}=k6e(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(Nn,{className:"h-10 w-10 text-primary/60"})}),e.jsxs("div",{className:"absolute left-3 top-3 flex gap-2",children:[s.is_featured&&e.jsx($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(Ie,{className:"space-y-4 p-5",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("h2",{className:"text-lg font-semibold leading-tight",children:s.name}),s.subtitle&&e.jsx("p",{className:"text-sm text-muted-foreground",children:s.subtitle})]}),e.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1.5 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(da,{className:"h-3.5 w-3.5"}),s.duration_weeks," weeks"]}),s.kickoff_at&&e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(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":Sg(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 ",ose(s.duration_weeks)," — no subscription",s.charge_at?` · charged ${th(s.charge_at)}`:""]}):null]}),e.jsx($,{asChild:!0,size:"sm",children:e.jsxs(wr,{to:t?`/programs/${s.slug}/workspace`:`/programs/${s.slug}`,children:[t?"Open program":n?"Preview details":"View details",e.jsx(Qa,{className:"ml-1.5 h-4 w-4"})]})})]})]})]})},cnn=()=>{const{data:s=[],isLoading:t}=zUt(),{data:n=[]}=rnt(),r=new Set(n.filter(l=>TG(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(o_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(Ie,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(Nn,{className:"h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"font-medium",children:"No programs are open right now"}),e.jsx("p",{className:"max-w-md text-sm text-muted-foreground",children:"New cohorts are announced inside the Hub. Check back soon — seats are limited when they open."})]})}):e.jsx("div",{className:"grid gap-6 md:grid-cols-2 lg:grid-cols-3",children:i.map(l=>e.jsx(o_t,{program:l,enrolled:!1},l.id))})]})]})]})})},dnn=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},unn=({url:s,headline:t,posterUrl:n})=>{const[r,a]=j.useState(!1),i=(s||"").trim();if(!i)return null;const l=dnn(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 hnn=Object.defineProperty,uie=(s,t)=>hnn(s,"name",{value:t,configurable:!0}),Jnt="Collapsible",[mnn,wHt]=tp(Jnt),[fnn,ert]=mnn(Jnt),pnn=j.forwardRef(uie(function(t,n){const{__scopeCollapsible:r,open:a,defaultOpen:i,disabled:l,onOpenChange:o,...c}=t,[d,u]=hy({prop:a,defaultProp:i??!1,onChange:o,caller:Jnt});return e.jsx(fnn,{scope:r,disabled:l,contentId:uy(),open:d,onOpenToggle:j.useCallback(()=>u(h=>!h),[u]),children:e.jsx(Ei.div,{"data-state":Y6e(d),"data-disabled":l?"":void 0,...c,ref:n})})},"Collapsible")),gnn="CollapsibleTrigger",jHt=j.forwardRef(uie(function(t,n){const{__scopeCollapsible:r,...a}=t,i=ert(gnn,r);return e.jsx(Ei.button,{type:"button","aria-controls":i.open?i.contentId:void 0,"aria-expanded":i.open||!1,"data-state":Y6e(i.open),"data-disabled":i.disabled?"":void 0,disabled:i.disabled,...a,ref:n,onClick:Ra(t.onClick,i.onOpenToggle)})},"CollapsibleTrigger")),NHt="CollapsibleContent",kHt=j.forwardRef(uie(function(t,n){const{forceMount:r,...a}=t,i=ert(NHt,t.__scopeCollapsible);return e.jsx(py,{present:r||i.open,children:({present:l})=>e.jsx(xnn,{...a,ref:n,present:l})})},"CollapsibleContent")),xnn=j.forwardRef(uie(function(t,n){const{__scopeCollapsible:r,present:a,children:i,...l}=t,o=ert(NHt,r),[c,d]=j.useState(a),u=j.useRef(null),h=Vo(n,u),m=j.useRef(0),f=m.current,g=j.useRef(0),x=g.current,y=o.open||c,v=j.useRef(y),b=j.useRef(void 0);return j.useEffect(()=>{const w=requestAnimationFrame(()=>v.current=!1);return()=>cancelAnimationFrame(w)},[]),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,v.current||(w.style.transitionDuration=b.current.transitionDuration,w.style.animationName=b.current.animationName),d(a)}},[o.open,a]),e.jsx(Ei.div,{"data-state":Y6e(o.open),"data-disabled":o.disabled?"":void 0,id:o.contentId,hidden:!y,...l,ref:h,style:{"--radix-collapsible-content-height":f?`${f}px`:void 0,"--radix-collapsible-content-width":x?`${x}px`:void 0,...t.style},children:y&&i})},"CollapsibleContentImpl"));function Y6e(s){return s?"open":"closed"}uie(Y6e,"getState");var SHt=pnn,ynn=jHt,vnn=kHt,bnn=Object.defineProperty,g2=(s,t)=>bnn(s,"name",{value:t,configurable:!0}),l3="Accordion",_nn=["Home","End","ArrowDown","ArrowUp","ArrowLeft","ArrowRight"],[trt,wnn,jnn]=EB(l3),[Z6e,hSr]=tp(l3,[jnn,wHt]),srt=wHt(),Nnn=j.forwardRef(g2(function(t,n){const{type:r,...a}=t,i=a,l=a;return e.jsx(trt.Provider,{scope:t.__scopeAccordion,children:r==="multiple"?e.jsx(Ann,{...l,ref:n}):e.jsx(Cnn,{...i,ref:n})})},"Accordion")),[CHt,knn]=Z6e(l3),[AHt,Snn]=Z6e(l3,{collapsible:!1}),Cnn=j.forwardRef(g2(function(t,n){const{value:r,defaultValue:a,onValueChange:i=g2(()=>{},"onValueChange"),collapsible:l=!1,...o}=t,[c,d]=hy({prop:r,defaultProp:a??"",onChange:i,caller:l3});return e.jsx(CHt,{scope:t.__scopeAccordion,value:j.useMemo(()=>c?[c]:[],[c]),onItemOpen:d,onItemClose:j.useCallback(()=>l&&d(""),[l,d]),children:e.jsx(AHt,{scope:t.__scopeAccordion,collapsible:l,children:e.jsx(EHt,{...o,ref:n})})})},"AccordionImplSingle")),Ann=j.forwardRef(g2(function(t,n){const{value:r,defaultValue:a,onValueChange:i=g2(()=>{},"onValueChange"),...l}=t,[o,c]=hy({prop:r,defaultProp:a??[],onChange:i,caller:l3}),d=j.useCallback(h=>c((m=[])=>[...m,h]),[c]),u=j.useCallback(h=>c((m=[])=>m.filter(f=>f!==h)),[c]);return e.jsx(CHt,{scope:t.__scopeAccordion,value:o,onItemOpen:d,onItemClose:u,children:e.jsx(AHt,{scope:t.__scopeAccordion,collapsible:!0,children:e.jsx(EHt,{...l,ref:n})})})},"AccordionImplMultiple")),[Enn,X6e]=Z6e(l3),EHt=j.forwardRef(g2(function(t,n){const{__scopeAccordion:r,disabled:a,dir:i,orientation:l="vertical",...o}=t,c=j.useRef(null),d=Vo(c,n),u=wnn(r),m=i3(i)==="ltr",f=Ra(t.onKeyDown,g=>{var R;if(!_nn.includes(g.key))return;const x=g.target,y=u().filter(D=>{var O;return!((O=D.ref.current)!=null&&O.disabled)}),v=y.findIndex(D=>D.ref.current===x),b=y.length;if(v===-1)return;g.preventDefault();let w=v;const S=0,A=b-1,E=g2(()=>{w=v+1,w>A&&(w=S)},"moveNext"),I=g2(()=>{w=v-1,w{m?o.onItemOpen(a):o.onItemClose(a)}})})},"AccordionItem")),Pnn="AccordionHeader",Inn=j.forwardRef(g2(function(t,n){const{__scopeAccordion:r,...a}=t,i=X6e(l3,r),l=nrt(Pnn,r);return e.jsx(Ei.h3,{"data-orientation":i.orientation,"data-state":rrt(l.open),"data-disabled":l.disabled?"":void 0,...a,ref:n})},"AccordionHeader")),l_t="AccordionTrigger",Lnn=j.forwardRef(g2(function(t,n){const{__scopeAccordion:r,...a}=t,i=X6e(l3,r),l=nrt(l_t,r),o=Snn(l_t,r),c=srt(r);return e.jsx(trt.ItemSlot,{scope:r,children:e.jsx(ynn,{"aria-disabled":l.open&&!o.collapsible||void 0,"data-orientation":i.orientation,id:l.triggerId,...c,...a,ref:n})})},"AccordionTrigger")),Rnn="AccordionContent",Dnn=j.forwardRef(g2(function(t,n){const{__scopeAccordion:r,...a}=t,i=X6e(l3,r),l=nrt(Rnn,r),o=srt(r);return e.jsx(vnn,{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 rrt(s){return s?"open":"closed"}g2(rrt,"getState");var Fnn=Nnn,Onn=Mnn,znn=Inn,THt=Lnn,MHt=Dnn;const UB=Fnn,h6=j.forwardRef(({className:s,...t},n)=>e.jsx(Onn,{ref:n,className:Pt("border-b",s),...t}));h6.displayName="AccordionItem";const m6=j.forwardRef(({className:s,children:t,...n},r)=>e.jsx(znn,{className:"flex",children:e.jsxs(THt,{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"})]})}));m6.displayName=THt.displayName;const f6=j.forwardRef(({className:s,children:t,...n},r)=>e.jsx(MHt,{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})}));f6.displayName=MHt.displayName;const Bnn=({programId:s,opensLabel:t})=>{const{data:n,isLoading:r}=XGs(s),a=QGs(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(ZS,{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(ca,{className:"mr-2 h-4 w-4"}):e.jsx(ZS,{className:"mr-2 h-4 w-4"}),i?"You're on the list":"Notify me"]})]})},$nn=()=>{const{slug:s}=Wi(),{data:t,isLoading:n}=nnt(s),{data:r}=BUt(t==null?void 0:t.id),{data:a}=ant(t==null?void 0:t.id),i=TG(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(wr,{to:"/programs",children:"Back to Programs"})})]})});const f=typeof r=="number"&&r<=0&&!i,{notOpenYet:g,closed:x,opensLabel:y}=k6e(t),v=!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(unn,{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":Sg(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 ",ose(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(Nv,{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:[UGe(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:!v,size:"lg",disabled:v,children:v?e.jsx("span",{children:b}):e.jsxs(wr,{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(wr,{to:"/programs",children:"All programs"})})]}),g&&!i&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"inline-flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(Wc,{className:"h-3.5 w-3.5"}),"Enrollment opens ",y]}),e.jsx(Bnn,{programId:t.id,opensLabel:y})]})]})]}),t.description&&e.jsxs("section",{className:"space-y-3",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"What this program is"}),e.jsx("div",{className:"whitespace-pre-line text-muted-foreground",children:t.description})]}),o.length>0&&e.jsxs("section",{className:"space-y-4",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"What you'll walk away with"}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:o.map((S,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(Ie,{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(Nn,{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(Ie,{className:"space-y-3 p-5",children:[e.jsx("h3",{className:"font-semibold",children:"This is for you if…"}),e.jsx("ul",{className:"space-y-2 text-sm text-muted-foreground",children:d.map((S,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(Ie,{className:"space-y-3 p-5",children:[e.jsx("h3",{className:"font-semibold",children:"This isn't for you if…"}),e.jsx("ul",{className:"space-y-2 text-sm text-muted-foreground",children:u.map((S,A)=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx(da,{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(UB,{type:"single",collapsible:!0,className:"rounded-xl border border-border/60 px-4",children:h.map((S,A)=>e.jsxs(h6,{value:`faq-${A}`,children:[e.jsx(m6,{className:"text-left text-sm font-medium",children:S.q}),e.jsx(f6,{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(ua,{className:"mx-auto h-8 w-8 text-primary"}),e.jsx("h2",{className:"mt-4 text-2xl font-bold",children:l.closing_headline||"Ready to commit?"}),e.jsx("p",{className:"mx-auto mt-2 max-w-xl text-muted-foreground",children:l.closing_body||`Seats are capped at ${t.capacity} so every member gets attention. Reserve yours and we'll take it from there.`}),e.jsxs("div",{className:"mt-6 flex flex-wrap items-center justify-center gap-3",children:[e.jsx($,{asChild:!v,size:"lg",disabled:v,children:v?e.jsx("span",{children:b}):e.jsxs(wr,{to:w,children:[b,e.jsx(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 ",y]}):t.enrollment_close_at?e.jsxs("p",{className:"mt-3 inline-flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(Wc,{className:"h-3.5 w-3.5"}),"Enrollment closes ",th(t.enrollment_close_at)]}):null)]})]})]})},bde=["Your business","Your content","Your goals","Reserve your seat"],Unn=()=>{const{slug:s}=Wi(),t=Xn(),[n,r]=gc(),{user:a}=bs(),{data:i,isLoading:l}=nnt(s),{data:o}=BUt(i==null?void 0:i.id),{data:c,refetch:d}=ant(i==null?void 0:i.id),{data:u}=$Ut(i==null?void 0:i.id),h=AGs(),m=EGs(),f=OGs(),g=zGs(),[x,y]=j.useState(0),[v,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({}),Y=j.useRef(!1),X=(ze,qe)=>{W.current={...W.current,[ze]:qe},G(W.current)};j.useEffect(()=>{Y.current||(u?(W.current={...u},G(W.current),Y.current=!0):a&&(W.current={email:a.email,...W.current},G(W.current)))},[u,a]),j.useEffect(()=>{const ze=c;!i||!(ze!=null&&ze.discount_code)||O||U({code:ze.discount_code,discount_cents:ze.discount_cents||0,amount_cents:ze.amount_cents??i.price_cents,original_cents:i.price_cents})},[c,i,O]);const ae=O?O.amount_cents:(i==null?void 0:i.price_cents)??0,le=j.useMemo(()=>lse(i),[i]),ne=ze=>CGs(le,ze),te=ze=>mbt(le,ze)?e.jsx("span",{className:"text-destructive",children:" *"}):null,J=(ze,qe)=>{const dt={...W.current.extra||{},[ze]:qe};X("extra",dt)},ce=ze=>le.custom.filter((qe,dt)=>dt%3===ze),_e=ze=>{const qe=ce(ze);if(!qe.length)return null;const dt=V.extra||{};return e.jsx("div",{className:"space-y-4",children:qe.map(Xe=>e.jsxs("div",{className:"space-y-2",children:[Xe.type==="checkbox"?e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border border-border/60 p-4",children:[e.jsx(ai,{id:Xe.id,checked:!!dt[Xe.id],onCheckedChange:at=>J(Xe.id,!!at)}),e.jsxs(ee,{htmlFor:Xe.id,className:"text-sm font-normal leading-relaxed",children:[Xe.label,Xe.required&&e.jsx("span",{className:"text-destructive",children:" *"})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(ee,{htmlFor:Xe.id,children:[Xe.label,Xe.required&&e.jsx("span",{className:"text-destructive",children:" *"})]}),Xe.type==="long_text"?e.jsx(Ls,{id:Xe.id,rows:3,value:dt[Xe.id]||"",onChange:at=>J(Xe.id,at.target.value)}):Xe.type==="select"?e.jsxs(ms,{value:dt[Xe.id]||"",onValueChange:at=>J(Xe.id,at),children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Select"})}),e.jsx(hs,{children:(Xe.options||[]).map(at=>e.jsx(Ge,{value:at,children:at},at))})]}):e.jsx(pe,{id:Xe.id,value:dt[Xe.id]||"",onChange:at=>J(Xe.id,at.target.value)})]}),Xe.help&&e.jsx("p",{className:"text-xs text-muted-foreground",children:Xe.help})]},Xe.id))})},he=ze=>{const qe=W.current,dt=Ke=>Ke==null||Ke===""||Ke===!1,Xe=snt.find(Ke=>Ke.step===ze&&mbt(le,Ke.key)&&dt(Ke.key==="timezone"?qe.timezone||(i==null?void 0:i.timezone):qe[Ke.key]));if(Xe)return Xe.label;const at=qe.extra||{},rt=ce(ze).find(Ke=>Ke.required&&dt(at[Ke.id]));return rt?rt.label:null},ue=()=>{if(x<=2){const ze=he(x);if(ze)return re.error(`Please answer: ${ze}`)}y(ze=>ze+1)},ve=async()=>{if(!(!i||!R.trim()))try{let ze=c==null?void 0:c.id;(!ze||(c==null?void 0:c.status)==="canceled")&&(ze=await m.mutateAsync(i.id));const qe=await f.mutateAsync({enrollmentId:ze,code:R});U(qe),D(""),await d(),re.success(`Code applied — you save ${Sg(qe.discount_cents,i.currency)}`)}catch(ze){re.error(ze.message||"That code could not be applied")}},Ee=async()=>{if(!(c!=null&&c.id))return U(null);try{await g.mutateAsync(c.id),U(null),await d()}catch(ze){re.error(ze.message||"Could not remove the code")}},Se=n.get("setup"),Le=n.get("session_id"),Fe=j.useRef(!1);j.useEffect(()=>{Se!=="success"||!Le||!(c!=null&&c.id)||Fe.current||(Fe.current=!0,S(!0),(async()=>{const{data:ze,error:qe}=await q.functions.invoke("program-enroll",{body:{action:"verify",enrollment_id:c.id,session_id:Le}});if(S(!1),qe||ze!=null&&ze.error||(ze==null?void 0:ze.success)===!1){re.error((ze==null?void 0:ze.error)||(qe==null?void 0:qe.message)||"We could not confirm your card");return}await d(),n.delete("setup"),n.delete("session_id"),r(n,{replace:!0}),re.success("Your seat is confirmed")})())},[Se,Le,c==null?void 0:c.id]),j.useEffect(()=>{Se==="cancelled"&&re.info("Checkout cancelled — your seat is held for a short while.")},[Se]);const ke=j.useMemo(()=>c&&["reserved","scheduled_for_charge","paid","completed"].includes(c.status),[c]),Be=async()=>{if(i){if(!A||i.payment_mode!=="free"&&!I){re.error("Please confirm the checkboxes to continue");return}b(!0);try{let ze=c==null?void 0:c.id;(!ze||(c==null?void 0:c.status)==="canceled")&&(ze=await m.mutateAsync(i.id)),await h.mutateAsync({...W.current,id:void 0,program_id:i.id,enrollment_id:ze,created_at:void 0,updated_at:void 0,user_id:void 0});const{data:qe,error:dt}=await q.functions.invoke("program-enroll",{body:{action:"setup",enrollment_id:ze}});if(dt||qe!=null&&qe.error)throw new Error((qe==null?void 0:qe.error)||(dt==null?void 0:dt.message));if(qe!=null&&qe.free){await d(),re.success("You're in"),t(`/programs/${i.slug}/workspace`);return}qe!=null&&qe.url&&(window.location.href=qe.url)}catch(ze){re.error(ze.message||"Could not start enrollment")}finally{b(!1)}}};if(l)return e.jsx(Vs,{children:e.jsxs("div",{className:"mx-auto max-w-2xl space-y-4 p-8",children:[e.jsx(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(wr,{to:"/programs",children:"Back to Programs"})})]})});if(TG(c)&&ke&&Se!=="success")return e.jsx(Vs,{children:e.jsxs("div",{className:"mx-auto max-w-xl space-y-4 p-12 text-center",children:[e.jsx(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(wr,{to:`/programs/${i.slug}/workspace`,children:"Open your program workspace"})})]})});const Ne=typeof o=="number"&&o<=0,{notOpenYet:Ae,closed:Ce,opensLabel:Ve}=k6e(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 ${Ve}. Come back then to reserve your seat.`:`Enrollment for ${i.name} has closed. Watch the Hub for the next cohort.`}),e.jsx($,{asChild:!0,children:e.jsx(wr,{to:`/programs/${i.slug}`,children:"Back to program details"})})]})}):e.jsx(Vs,{children:e.jsxs("div",{className:"mx-auto w-full max-w-3xl space-y-6 p-4 md:p-8",children:[e.jsx($,{asChild:!0,variant:"ghost",size:"sm",className:"-ml-2",children:e.jsxs(wr,{to:`/programs/${i.slug}`,children:[e.jsx(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?`${UGe(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:bde[x]}),e.jsxs("span",{children:["Step ",x+1," of ",bde.length]})]}),e.jsx(Yi,{value:(x+1)/bde.length*100})]}),w&&e.jsx(je,{className:"border-primary/40 bg-primary/5",children:e.jsxs(Ie,{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(Ie,{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:[ne("full_name")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{htmlFor:"full_name",children:["Full name",te("full_name")]}),e.jsx(pe,{id:"full_name",value:V.full_name||"",onChange:ze=>X("full_name",ze.target.value)})]}),ne("phone")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{htmlFor:"phone",children:["Mobile number",te("phone")]}),e.jsx(pe,{id:"phone",value:V.phone||"",onChange:ze=>X("phone",ze.target.value)})]}),ne("instagram_handle")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{htmlFor:"instagram_handle",children:["Instagram handle",te("instagram_handle")]}),e.jsx(pe,{id:"instagram_handle",placeholder:"@yourhandle",value:V.instagram_handle||"",onChange:ze=>X("instagram_handle",ze.target.value)})]}),ne("city")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{htmlFor:"city",children:["Primary city / market",te("city")]}),e.jsx(pe,{id:"city",value:V.city||"",onChange:ze=>X("city",ze.target.value)})]})]}),ne("service_areas")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{htmlFor:"service_areas",children:["Neighborhoods or areas you serve",te("service_areas")]}),e.jsx(Ls,{id:"service_areas",rows:2,value:V.service_areas||"",onChange:ze=>X("service_areas",ze.target.value)})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[ne("years_experience")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{children:["Years in real estate",te("years_experience")]}),e.jsxs(ms,{value:V.years_experience||"",onValueChange:ze=>X("years_experience",ze),children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Select"})}),e.jsx(hs,{children:["Less than 1","1-3","4-7","8-15","15+"].map(ze=>e.jsx(Ge,{value:ze,children:ze},ze))})]})]}),ne("specialty")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{htmlFor:"specialty",children:["Specialty or niche",te("specialty")]}),e.jsx(pe,{id:"specialty",value:V.specialty||"",onChange:ze=>X("specialty",ze.target.value)})]})]}),_e(0)]}),x===1&&e.jsxs(e.Fragment,{children:[ne("target_audience")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{htmlFor:"target_audience",children:["Who are you trying to reach?",te("target_audience")]}),e.jsx(Ls,{id:"target_audience",rows:2,placeholder:"First-time buyers, move-up sellers, investors…",value:V.target_audience||"",onChange:ze=>X("target_audience",ze.target.value)})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[ne("video_comfort")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{children:["How comfortable are you on camera?",te("video_comfort")]}),e.jsxs(ms,{value:V.video_comfort||"",onValueChange:ze=>X("video_comfort",ze),children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Select"})}),e.jsx(hs,{children:["Terrified","Nervous but willing","Getting comfortable","Very comfortable"].map(ze=>e.jsx(Ge,{value:ze,children:ze},ze))})]})]}),ne("posting_frequency")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{children:["How often do you post today?",te("posting_frequency")]}),e.jsxs(ms,{value:V.posting_frequency||"",onValueChange:ze=>X("posting_frequency",ze),children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Select"})}),e.jsx(hs,{children:["Never","Rarely","Weekly","A few times a week","Daily"].map(ze=>e.jsx(Ge,{value:ze,children:ze},ze))})]})]})]}),ne("content_style")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{htmlFor:"content_style",children:["What content style feels like you?",te("content_style")]}),e.jsx(Ls,{id:"content_style",rows:2,placeholder:"Educational, funny, behind-the-scenes, luxury-polished…",value:V.content_style||"",onChange:ze=>X("content_style",ze.target.value)})]}),ne("personal_interests")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{htmlFor:"personal_interests",children:["Interests or hobbies we can weave in",te("personal_interests")]}),e.jsx(Ls,{id:"personal_interests",rows:2,value:V.personal_interests||"",onChange:ze=>X("personal_interests",ze.target.value)})]}),_e(1)]}),x===2&&e.jsxs(e.Fragment,{children:[ne("primary_goal")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{htmlFor:"primary_goal",children:["Your #1 goal for this program",te("primary_goal")]}),e.jsx(Ls,{id:"primary_goal",rows:3,value:V.primary_goal||"",onChange:ze=>X("primary_goal",ze.target.value)})]}),ne("topics_to_avoid")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{htmlFor:"topics_to_avoid",children:["Anything you don't want to talk about",te("topics_to_avoid")]}),e.jsx(Ls,{id:"topics_to_avoid",rows:2,value:V.topics_to_avoid||"",onChange:ze=>X("topics_to_avoid",ze.target.value)})]}),ne("timezone")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{children:["Your time zone",te("timezone")]}),e.jsxs(ms,{value:V.timezone||i.timezone,onValueChange:ze=>X("timezone",ze),children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Select"})}),e.jsx(hs,{children:["America/New_York","America/Chicago","America/Denver","America/Phoenix","America/Los_Angeles","Pacific/Honolulu"].map(ze=>e.jsx(Ge,{value:ze,children:ze.replace("America/","").replace("_"," ")},ze))})]})]}),_e(2),ne("consent_public_profile")&&e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border border-border/60 p-4",children:[e.jsx(ai,{id:"consent_public_profile",checked:!!V.consent_public_profile,onCheckedChange:ze=>X("consent_public_profile",!!ze)}),e.jsx(ee,{htmlFor:"consent_public_profile",className:"text-sm font-normal leading-relaxed",children:"I'm okay with my content being reviewed and shared as an example inside the cohort."})]})]}),x===3&&e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"rounded-lg border border-border/60 p-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:i.name}),e.jsx("span",{className:"font-semibold",children:i.payment_mode==="free"?"Included":O?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-normal text-muted-foreground line-through",children:Sg(O.original_cents,i.currency)}),Sg(ae,i.currency)]}):Sg(i.price_cents,i.currency)})]}),i.payment_mode!=="free"&&e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:UGe(ae,i.currency,i.duration_weeks)}),i.payment_mode!=="free"&&e.jsx("div",{className:"mt-3 border-t border-border/60 pt-3",children:O?e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 rounded-md bg-primary/5 px-3 py-2 text-sm",children:[e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(Ap,{className:"h-3.5 w-3.5 text-primary"}),"Code ",e.jsx("span",{className:"font-mono font-semibold",children:O.code})," applied — you save ",Sg(O.discount_cents,i.currency)]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:Ee,disabled:g.isPending,children:[e.jsx(pr,{className:"mr-1 h-3.5 w-3.5"})," Remove"]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"discount_code",className:"text-xs text-muted-foreground",children:"Have a discount code?"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{id:"discount_code",placeholder:"Enter code",className:"font-mono uppercase",value:R,onChange:ze=>D(ze.target.value.toUpperCase()),onKeyDown:ze=>{ze.key==="Enter"&&(ze.preventDefault(),ve())}}),e.jsx($,{variant:"outline",onClick:ve,disabled:!R.trim()||f.isPending||m.isPending,children:f.isPending||m.isPending?e.jsx(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(Nv,{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 — ${Sg(ae,i.currency)} for the ${ose(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 — ${Sg(ae,i.currency)} for the ${ose(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:()=>y(ze=>Math.max(0,ze-1)),disabled:x===0||v,children:[e.jsx(Va,{className:"mr-1.5 h-4 w-4"})," Back"]}),xString(s).padStart(2,"0"),ABe=s=>s.toISOString().replace(/[-:]/g,"").split(".")[0]+"Z",qnn=({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:${ABe(new Date)}`,`DTSTART:${ABe(d)}`,`DTEND:${ABe(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:CBe(i.hours)},{label:"Minutes",value:CBe(i.minutes)},{label:"Seconds",value:CBe(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(Ie,{className:"relative space-y-6 p-6 md:p-9",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs($e,{className:"gap-1.5",children:[e.jsx(Nn,{className:"h-3.5 w-3.5"})," Your seat is confirmed"]}),e.jsxs($e,{variant:"outline",className:"gap-1.5",children:[e.jsx(da,{className:"h-3.5 w-3.5"})," ",l]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("h2",{className:"text-2xl font-bold tracking-tight md:text-3xl",children:i.done?"We're live — let's go":`${s.name} kicks off soon`}),e.jsx("p",{className:"max-w-2xl text-sm text-muted-foreground md:text-base",children:i.done?"The kickoff call is starting. Head to your sessions below to join.":"Everything unlocks on kickoff day. Until then, get your setup dialed in so week one is pure momentum."})]}),e.jsx("div",{className:"grid max-w-xl grid-cols-4 gap-2 md:gap-3",children:c.map(d=>e.jsxs("div",{className:"rounded-xl border bg-background/80 px-2 py-4 text-center backdrop-blur-sm",children:[e.jsx("div",{className:"text-2xl font-bold tabular-nums tracking-tight md:text-4xl",children:d.value}),e.jsx("div",{className:"mt-1 text-[10px] uppercase tracking-widest text-muted-foreground md:text-xs",children:d.label})]},d.label))}),e.jsx("div",{className:"flex flex-wrap gap-3",children:e.jsxs($,{onClick:o,size:"lg",children:[e.jsx(bv,{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))})]})]})},EBe=s=>s.toISOString().replace(/[-:]/g,"").split(".")[0]+"Z",Vnn=(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:${EBe(new Date)}`,`DTSTART:${EBe(n)}`,`DTEND:${EBe(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)},Hnn={pdf:Jr,document:YN,checklist:Cv,template_link:c2,video:nf,external:Wd},Gnn=()=>{var ce;const{slug:s}=Wi(),[t]=gc(),{isAdmin:n}=bs(),r=n?t.get("as"):null,a=t.get("name")||"this member",i=n&&(t.get("preview")==="1"||!!r),{data:l,isLoading:o}=nnt(s),{data:c}=ant(l==null?void 0:l.id),{data:d,isLoading:u}=TGs(l==null?void 0:l.id,r),h=MGs(l==null?void 0:l.id),m=PGs(l==null?void 0:l.id),f=IGs(l==null?void 0:l.id),g=LGs(l==null?void 0:l.id),{data:x}=$Ut(l==null?void 0:l.id),y=!!(l!=null&&l.kickoff_at)&&new Date(l.kickoff_at).getTime()>Date.now(),[v,b]=j.useState(!1),[w,S]=j.useState({title:"",instagram_url:""}),[A,E]=j.useState({}),[I,P]=j.useState(null),R=j.useMemo(()=>{if(!(l!=null&&l.kickoff_at))return 1;const _e=Math.floor((Date.now()-new Date(l.kickoff_at).getTime())/864e5);return Math.min(Math.max(Math.floor(_e/7)+1,1),l.duration_weeks)},[l]),D=new Set(((d==null?void 0:d.completions)||[]).map(_e=>_e.lesson_id)),O=(d==null?void 0:d.lessons)||[],U=O.length?Math.round(D.size/O.length*100):0,W=((d==null?void 0:d.videoLogs)||[]).filter(_e=>_e.week_number===R).length,V=((d==null?void 0:d.videoLogs)||[]).length,G=(l==null?void 0:l.weekly_video_goal)||3,Y=j.useMemo(()=>{const _e=new Map;((d==null?void 0:d.videoLogs)||[]).forEach(ue=>_e.set(ue.week_number,(_e.get(ue.week_number)||0)+1));let he=0;for(let ue=R;ue>=1;ue--)if((_e.get(ue)||0)>=G)he++;else if(ue!==R)break;return he},[d==null?void 0:d.videoLogs,R,G]);if(o||u)return e.jsx(Vs,{children:e.jsxs("div",{className:"mx-auto max-w-6xl space-y-6 p-8",children:[e.jsx(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(wr,{to:"/programs",children:"Back to Programs"})})]})});if(!TG(c)&&!i)return e.jsx(Vs,{children:e.jsxs("div",{className:"mx-auto max-w-xl space-y-4 p-12 text-center",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"You're not enrolled yet"}),e.jsxs("p",{className:"text-muted-foreground",children:["Reserve your seat in ",l.name," to unlock the roadmap, lessons and mastermind sessions."]}),e.jsx($,{asChild:!0,size:"lg",children:e.jsx(wr,{to:`/programs/${l.slug}`,children:"View the program"})})]})});const X=((d==null?void 0:d.events)||[]).filter(_e=>new Date(_e.starts_at)>=new Date),ae=((d==null?void 0:d.events)||[]).filter(_e=>new Date(_e.starts_at)_e.is_pinned),te=[...(d==null?void 0:d.myResources)||[],...(d==null?void 0:d.resources)||[]].reduce((_e,he)=>{const ue=he.user_id?`Just for you · ${he.category}`:he.category;return(_e[ue]||(_e[ue]=[])).push(he),_e},{}),J=((d==null?void 0:d.progress)||[]).find(_e=>_e.week_number===R)||{};return e.jsx(Vs,{children:e.jsx("div",{className:"program-theme-neon relative min-h-screen",children:e.jsxs("div",{className:"relative mx-auto w-full max-w-6xl space-y-8 p-4 md:p-8",children:[i&&(r||!TG(c))&&e.jsx(je,{className:"border-primary/40 bg-primary/5",children:e.jsxs(Ie,{className:"flex flex-wrap items-center justify-between gap-3 p-4 text-sm",children:[e.jsx("span",{children:r?e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:"Admin view"})," — you're seeing ",a,"'s dashboard exactly as they see it (progress, check-ins, videos and personal resources). It's read-only: avoid logging videos or check-ins here."]}):e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:"Admin preview"})," — this is exactly what an enrollee sees. Your own progress, check-ins and video logs are empty because you're not enrolled."]})}),e.jsx($,{variant:"outline",size:"sm",asChild:!0,children:e.jsx(wr,{to:"/admin/programs",children:"Back to Programs admin"})})]})}),e.jsxs("header",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs($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})]}),y&&e.jsx(qnn,{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(Ie,{className:"space-y-1.5 p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs uppercase tracking-[0.16em] text-muted-foreground",children:[e.jsx(nh,{className:"h-3.5 w-3.5 text-primary"})," 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(Ie,{className:"space-y-1.5 p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs uppercase tracking-[0.16em] text-muted-foreground",children:[e.jsx(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(Ie,{className:"space-y-1.5 p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs uppercase tracking-[0.16em] text-muted-foreground",children:[e.jsx(sh,{className:"h-3.5 w-3.5 text-primary"})," Streak"]}),e.jsxs("p",{className:"neon-stat text-3xl font-black",children:[Y," wk"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"hitting your goal"})]})}),e.jsx(je,{className:"neon-topline",children:e.jsxs(Ie,{className:"space-y-1.5 p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs uppercase tracking-[0.16em] text-muted-foreground",children:[e.jsx(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(zs,{open:v,onOpenChange:b,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{children:[e.jsx(dn,{className:"mr-1.5 h-4 w-4"})," Log a video"]})}),e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Log a posted video"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"v-title",children:"What was it about?"}),e.jsx(pe,{id:"v-title",value:w.title,onChange:_e=>S(he=>({...he,title:_e.target.value}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"v-url",children:"Instagram link (optional)"}),e.jsx(pe,{id:"v-url",placeholder:"https://instagram.com/reel/…",value:w.instagram_url,onChange:_e=>S(he=>({...he,instagram_url:_e.target.value}))})]})]}),e.jsx(Sr,{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(Ie,{className:"space-y-3 p-5",children:le.map(_e=>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:_e.title}),_e.body&&e.jsx("p",{className:"text-sm text-muted-foreground",children:_e.body})]})]},_e.id))})}),e.jsxs(ha,{defaultValue:"roadmap",children:[e.jsxs(ma,{className:"flex w-full flex-wrap justify-start",children:[e.jsx(Zt,{value:"roadmap",children:"Roadmap"}),e.jsx(Zt,{value:"lessons",children:"Lessons"}),e.jsx(Zt,{value:"checkin",children:"Weekly check-in"}),e.jsx(Zt,{value:"events",children:"Sessions"}),e.jsx(Zt,{value:"resources",children:"Resources"}),e.jsx(Zt,{value:"profile",children:"Profile review"})]}),e.jsxs(Xt,{value:"roadmap",className:"mt-6 space-y-4",children:[((d==null?void 0:d.weeks)||[]).length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"The roadmap will appear here before kickoff."}),((d==null?void 0:d.weeks)||[]).map(_e=>{const he=_e.release_at&&new Date(_e.release_at)>new Date;return e.jsx(je,{className:he?"opacity-60":_e.week_number===R?"border-primary/50":"",children:e.jsxs(Ie,{className:"space-y-2 p-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs($e,{variant:"outline",children:["Week ",_e.week_number]}),e.jsx("span",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:_e.phase}),_e.week_number===R&&e.jsx($e,{children:"Current"}),he&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(da,{className:"h-3 w-3"})," Unlocks ",th(_e.release_at)]})]}),e.jsx("h3",{className:"font-semibold",children:_e.title}),_e.learning_goal&&e.jsx("p",{className:"text-sm text-muted-foreground",children:_e.learning_goal}),!he&&Array.isArray(_e.tasks)&&_e.tasks.length>0&&e.jsx("ul",{className:"mt-2 space-y-1.5",children:_e.tasks.map((ue,ve)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(Vr,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-primary"}),typeof ue=="string"?ue:ue.label]},ve))})]})},_e.id)})]}),e.jsxs(Xt,{value:"lessons",className:"mt-6 space-y-3",children:[O.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Lessons unlock as the program progresses."}),O.map(_e=>{const he=UUt(_e.video_url),ue=I===_e.id;return e.jsx(je,{children:e.jsxs(Ie,{className:"space-y-4 p-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[e.jsx(ai,{checked:D.has(_e.id),onCheckedChange:ve=>h.mutate({lessonId:_e.id,done:!!ve}),"aria-label":`Mark ${_e.title} complete`}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-medium",children:_e.title}),_e.summary&&e.jsx("p",{className:"text-sm text-muted-foreground",children:_e.summary}),_e.action_assignment&&e.jsxs("p",{className:"mt-1 text-xs text-primary",children:["Action: ",_e.action_assignment]})]}),_e.duration_minutes&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(da,{className:"h-3 w-3"})," ",_e.duration_minutes," min"]}),e.jsxs("div",{className:"flex gap-2",children:[_e.video_url&&(he||jee(_e.video_url))&&e.jsxs($,{size:"sm",variant:"outline",onClick:()=>P(ue?null:_e.id),children:[e.jsx(ef,{className:"mr-1.5 h-3.5 w-3.5"})," ",ue?"Close":"Watch"]}),_e.video_url&&!he&&!jee(_e.video_url)&&e.jsx($,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:_e.video_url,target:"_blank",rel:"noreferrer",children:[e.jsx(ef,{className:"mr-1.5 h-3.5 w-3.5"})," Watch"]})}),_e.worksheet_url&&e.jsx($,{size:"sm",variant:"ghost",asChild:!0,children:e.jsxs("a",{href:_e.worksheet_url,target:"_blank",rel:"noreferrer",children:[e.jsx(xi,{className:"mr-1.5 h-3.5 w-3.5"})," Worksheet"]})})]})]}),ue&&he&&e.jsx("div",{className:"overflow-hidden rounded-lg border border-border/60",children:e.jsx("iframe",{src:he,title:_e.title,className:"aspect-video w-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; picture-in-picture",allowFullScreen:!0})}),ue&&!he&&jee(_e.video_url)&&e.jsx("div",{className:"overflow-hidden rounded-lg border border-border/60 bg-black",children:e.jsx("video",{src:_e.video_url,controls:!0,autoPlay:!0,className:"aspect-video w-full"})})]})},_e.id)})]}),e.jsx(Xt,{value:"checkin",className:"mt-6",children:e.jsx(je,{children:e.jsxs(Ie,{className:"space-y-5 p-6",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"font-semibold",children:["Week ",R," check-in"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Two minutes of honesty here is what makes the next week better."})]}),e.jsx("div",{className:"grid gap-4 sm:grid-cols-3",children:[["videos_planned","Videos planned"],["videos_recorded","Videos recorded"],["videos_posted","Videos posted"]].map(([_e,he])=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:_e,children:he}),e.jsx(pe,{id:_e,type:"number",min:0,defaultValue:J[_e]??"",onChange:ue=>E(ve=>({...ve,[_e]:Number(ue.target.value)}))})]},_e))}),[["biggest_win","Biggest win"],["biggest_challenge","Biggest challenge"],["what_to_improve","What you’ll change next week"]].map(([_e,he])=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:_e,children:he}),e.jsx(Ls,{id:_e,rows:2,defaultValue:J[_e]??"",onChange:ue=>E(ve=>({...ve,[_e]:ue.target.value}))})]},_e)),e.jsx($,{onClick:()=>f.mutate({week_number:R,goal_videos:G,...A}),children:"Save check-in"})]})})}),e.jsxs(Xt,{value:"events",className:"mt-6 space-y-4",children:[X.length===0&&ae.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Sessions will be scheduled before kickoff."}),X.map(_e=>e.jsx(je,{className:"border-primary/30",children:e.jsxs(Ie,{className:"flex flex-wrap items-center gap-4 p-5",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx($e,{variant:"secondary",className:"capitalize",children:String(_e.event_kind).replace("_"," ")}),e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(Wc,{className:"h-3 w-3"})," ",th(_e.starts_at,!0)]})]}),e.jsx("p",{className:"mt-1.5 font-medium",children:_e.title}),_e.speaker&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:["with ",_e.speaker]}),_e.description&&e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:_e.description})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx($,{size:"sm",variant:"outline",onClick:()=>g.mutate({eventId:_e.id,optIn:!0}),children:"Remind me"}),e.jsxs($,{size:"sm",variant:"ghost",onClick:()=>Vnn(_e,l.name),children:[e.jsx(Wc,{className:"mr-1.5 h-3.5 w-3.5"})," Add to calendar"]}),_e.meeting_link&&e.jsx($,{size:"sm",asChild:!0,children:e.jsxs("a",{href:_e.meeting_link,target:"_blank",rel:"noreferrer",children:["Join ",e.jsx(Fr,{className:"ml-1.5 h-3.5 w-3.5"})]})})]})]})},_e.id)),ae.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"pt-2 text-sm font-semibold uppercase tracking-wider text-muted-foreground",children:"Replays"}),ae.map(_e=>e.jsx(je,{children:e.jsxs(Ie,{className:"flex flex-wrap items-center gap-4 p-5",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-medium",children:_e.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:th(_e.starts_at,!0)})]}),_e.replay_url?e.jsx($,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:_e.replay_url,target:"_blank",rel:"noreferrer",children:[e.jsx(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"})]})},_e.id))]})]}),e.jsxs(Xt,{value:"resources",className:"mt-6 space-y-8",children:[Object.keys(te).length===0&&e.jsx(je,{className:"border-dashed",children:e.jsxs(Ie,{className:"flex flex-col items-center gap-2 p-12 text-center",children:[e.jsx(Jr,{className:"h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"font-medium",children:"Your resource library is being built"}),e.jsx("p",{className:"max-w-md text-sm text-muted-foreground",children:"Worksheets, scripts and swipe files will appear here as the program unlocks."})]})}),Object.entries(te).map(([_e,he])=>e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h3",{className:"text-sm font-semibold uppercase tracking-[0.18em] text-muted-foreground",children:_e}),e.jsx("span",{className:"h-px flex-1 bg-border"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[he.length," item",he.length===1?"":"s"]})]}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2 xl:grid-cols-3",children:he.map(ue=>{const ve=nie(ue),Ee=Hnn[ue.resource_kind]||Jr;return e.jsxs("div",{role:"button",tabIndex:0,onClick:()=>ve&&Nee(ue),onKeyDown:Se=>{ve&&(Se.key==="Enter"||Se.key===" ")&&(Se.preventDefault(),Nee(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(Fr,{className:"h-3.5 w-3.5"})," Open"]}),ue.file_path&&e.jsxs("button",{type:"button",onClick:Se=>{Se.stopPropagation(),Nee(ue,"download")},className:"inline-flex items-center gap-1.5 text-sm font-medium text-muted-foreground hover:text-primary",children:[e.jsx(xi,{className:"h-3.5 w-3.5"})," Download"]})]})]},ue.id)})})]},_e))]}),e.jsx(Xt,{value:"profile",className:"mt-6",children:e.jsx(je,{children:e.jsxs(Ie,{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(([_e,he])=>e.jsxs("div",{className:"space-y-1 rounded-lg border border-border/60 p-3",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"capitalize",children:_e.replace(/_/g," ")}),e.jsxs("span",{className:"font-semibold",children:[he,"/10"]})]}),e.jsx(Yi,{value:Number(he)*10,className:"h-1.5"})]},_e))}),Array.isArray(d.analysis.top_priorities)&&d.analysis.top_priorities.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:"Top priorities"}),e.jsx("ul",{className:"space-y-1.5",children:d.analysis.top_priorities.map((_e,he)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(Im,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-primary"}),typeof _e=="string"?_e:_e.label]},he))})]}),d.analysis.member_notes&&e.jsx("div",{className:"rounded-lg border border-border/60 bg-muted/30 p-4 text-sm leading-relaxed whitespace-pre-line",children:d.analysis.member_notes}),d.analysis.report_url&&e.jsx($,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:d.analysis.report_url,target:"_blank",rel:"noreferrer",children:[e.jsx(xi,{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 Wnn=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}));Wnn.displayName="TableFooter";const En=j.forwardRef(({className:s,...t},n)=>e.jsx("tr",{ref:n,className:Pt("border-b transition-colors data-[state=selected]:bg-muted hover:bg-muted/50",s),...t}));En.displayName="TableRow";const Dt=j.forwardRef(({className:s,...t},n)=>e.jsx("th",{ref:n,className:Pt("h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",s),...t}));Dt.displayName="TableHead";const _t=j.forwardRef(({className:s,...t},n)=>e.jsx("td",{ref:n,className:Pt("p-4 align-middle [&:has([role=checkbox])]:pr-0",s),...t}));_t.displayName="TableCell";const Knn=j.forwardRef(({className:s,...t},n)=>e.jsx("caption",{ref:n,className:Pt("mt-4 text-sm text-muted-foreground",s),...t}));Knn.displayName="TableCaption";const _de=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())}`},wde=s=>s?new Date(s).toISOString():null,TBe=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:_de(s.enrollment_open_at),enrollment_close_at:_de(s.enrollment_close_at),kickoff_at:_de(s.kickoff_at),charge_at:_de(s.charge_at),status:s.status||"draft",is_public:!!s.is_public,is_featured:!!s.is_featured,sort_order:s.sort_order??0}),Ynn=({program:s,onSaved:t})=>{const[n,r]=j.useState(()=>TBe(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(TBe(s)),i(!1)},[s.id,s.updated_at]);const m=(y,v)=>{r(b=>({...b,[y]:v})),i(!0)},f=async(y,v)=>{if(!y.type.startsWith("image/")){re.error("Please choose an image file");return}if(y.size>8*1024*1024){re.error("Image must be under 8MB");return}d(v);try{const b=y.name.split(".").pop()||"jpg",w=`programs/${s.id}/${v}-${Date.now()}.${b}`,{error:S}=await q.storage.from("event-images").upload(w,y,{cacheControl:"31536000",upsert:!0});if(S)throw S;const{data:A}=q.storage.from("event-images").getPublicUrl(w);m(v==="cover"?"cover_image_url":"hero_image_url",A.publicUrl),re.success(`${v==="cover"?"Cover":"Hero"} image uploaded — remember to save`)}catch(b){re.error(b.message||"Upload failed")}finally{d(null)}},g=async()=>{if(!n.name.trim())return re.error("Program name is required");if(!n.slug.trim())return re.error("Slug is required");o(!0);try{const y={name:n.name.trim(),slug:n.slug.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""),subtitle:n.subtitle||null,tagline:n.tagline||null,short_description:n.short_description||null,description:n.description||null,price_cents:Math.max(0,Math.round(n.price_cents)),currency:n.currency||"usd",capacity:Math.max(0,Math.round(n.capacity)),duration_weeks:Math.max(1,Math.round(n.duration_weeks)),weekly_video_goal:Math.max(0,Math.round(n.weekly_video_goal)),payment_mode:n.payment_mode,payment_grace_days:Math.max(0,Math.round(n.payment_grace_days)),timezone:n.timezone||"America/New_York",accent_color:n.accent_color||null,cover_image_url:n.cover_image_url||null,hero_image_url:n.hero_image_url||null,promo_video_url:n.promo_video_url.trim()||null,promo_video_headline:n.promo_video_headline.trim()||null,enrollment_open_at:wde(n.enrollment_open_at),enrollment_close_at:wde(n.enrollment_close_at),kickoff_at:wde(n.kickoff_at),charge_at:wde(n.charge_at),status:n.status,is_public:n.is_public,is_featured:n.is_featured,sort_order:Math.round(n.sort_order)},{error:v}=await q.from("programs").update(y).eq("id",s.id);if(v)throw v;re.success("Program saved"),i(!1),t()}catch(y){re.error(y.message||"Could not save the program")}finally{o(!1)}},x=({kind:y,label:v,hint:b})=>{const w=y==="cover"?n.cover_image_url:n.hero_image_url,S=y==="cover"?u:h;return e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:v}),e.jsxs("div",{className:"flex flex-wrap items-start gap-4",children:[e.jsx("div",{className:"relative h-28 w-48 shrink-0 overflow-hidden rounded-lg border border-border bg-muted/40",children:w?e.jsxs(e.Fragment,{children:[e.jsx("img",{src:w,alt:`${v} preview`,className:"h-full w-full object-cover"}),e.jsx("button",{type:"button",onClick:()=>m(y==="cover"?"cover_image_url":"hero_image_url",""),className:"absolute right-1.5 top-1.5 rounded-full bg-background/90 p-1 text-foreground shadow","aria-label":`Remove ${v}`,children:e.jsx(pr,{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(Sv,{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,y),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===y,children:[c===y?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(y==="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(TBe(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(Ie,{className:"space-y-5 p-6",children:[e.jsx("h3",{className:"text-sm font-semibold uppercase tracking-wide text-muted-foreground",children:"Basics"}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Program name"}),e.jsx(pe,{value:n.name,onChange:y=>m("name",y.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Slug (public URL)"}),e.jsx(pe,{value:n.slug,onChange:y=>m("slug",y.target.value)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["/programs/",n.slug||"slug"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Subtitle"}),e.jsx(pe,{value:n.subtitle,onChange:y=>m("subtitle",y.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Tagline"}),e.jsx(pe,{value:n.tagline,onChange:y=>m("tagline",y.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Short description (cards & previews)"}),e.jsx(Ls,{rows:2,value:n.short_description,onChange:y=>m("short_description",y.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Full program description (sales page)"}),e.jsx(Ls,{rows:8,value:n.description,onChange:y=>m("description",y.target.value)})]})]})}),e.jsx(je,{children:e.jsxs(Ie,{className:"space-y-6 p-6",children:[e.jsx("h3",{className:"text-sm font-semibold uppercase tracking-wide text-muted-foreground",children:"Imagery & branding"}),e.jsx(x,{kind:"cover",label:"Program cover image",hint:"Shown on the Programs list and enrollment cards. 1200×630 works great."}),e.jsx(x,{kind:"hero",label:"Hero banner (optional)",hint:"Wide banner used at the top of the program sales page."}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Promo video URL (optional)"}),e.jsx(pe,{placeholder:"https://youtu.be/… , Vimeo, or a direct .mp4 link",value:n.promo_video_url,onChange:y=>m("promo_video_url",y.target.value)}),e.jsx(pe,{placeholder:"Video headline (e.g. Watch: what 90 days inside Reel Estate looks like)",value:n.promo_video_headline,onChange:y=>m("promo_video_headline",y.target.value)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Plays in a cinematic player near the top of the program signup page."})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Accent color"}),e.jsx(pe,{placeholder:"#406E71",value:n.accent_color,onChange:y=>m("accent_color",y.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Sort order"}),e.jsx(pe,{type:"number",value:n.sort_order,onChange:y=>m("sort_order",Number(y.target.value))})]})]})]})}),e.jsx(je,{children:e.jsxs(Ie,{className:"space-y-5 p-6",children:[e.jsx("h3",{className:"text-sm font-semibold uppercase tracking-wide text-muted-foreground",children:"Pricing & seats"}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"One-time price (USD)"}),e.jsx(pe,{type:"number",min:0,step:"1",value:n.price_cents/100,onChange:y=>m("price_cents",Math.round(Number(y.target.value)*100))}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Charged one time for the full program — never recurring."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Seats (capacity)"}),e.jsx(pe,{type:"number",min:0,value:n.capacity,onChange:y=>m("capacity",Number(y.target.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Billing mode"}),e.jsxs(ms,{value:n.payment_mode,onValueChange:y=>m("payment_mode",y),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"delayed",children:"Save card, charge once later"}),e.jsx(Ge,{value:"immediate",children:"Charge once at checkout"}),e.jsx(Ge,{value:"free",children:"Free / included"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Charge date (one-time)"}),e.jsx(pe,{type:"datetime-local",value:n.charge_at,onChange:y=>m("charge_at",y.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Payment grace days"}),e.jsx(pe,{type:"number",min:0,value:n.payment_grace_days,onChange:y=>m("payment_grace_days",Number(y.target.value))}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Days of access kept after a failed charge before access is paused."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Currency"}),e.jsx(pe,{value:n.currency,onChange:y=>m("currency",y.target.value)})]})]})]})}),e.jsx(je,{children:e.jsxs(Ie,{className:"space-y-5 p-6",children:[e.jsx("h3",{className:"text-sm font-semibold uppercase tracking-wide text-muted-foreground",children:"Schedule & structure"}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Enrollment opens"}),e.jsx(pe,{type:"datetime-local",value:n.enrollment_open_at,onChange:y=>m("enrollment_open_at",y.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Enrollment closes"}),e.jsx(pe,{type:"datetime-local",value:n.enrollment_close_at,onChange:y=>m("enrollment_close_at",y.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Kickoff"}),e.jsx(pe,{type:"datetime-local",value:n.kickoff_at,onChange:y=>m("kickoff_at",y.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Length (weeks)"}),e.jsx(pe,{type:"number",min:1,value:n.duration_weeks,onChange:y=>m("duration_weeks",Number(y.target.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Videos per week goal"}),e.jsx(pe,{type:"number",min:0,value:n.weekly_video_goal,onChange:y=>m("weekly_video_goal",Number(y.target.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Timezone"}),e.jsx(pe,{value:n.timezone,onChange:y=>m("timezone",y.target.value)})]})]})]})}),e.jsx(je,{children:e.jsxs(Ie,{className:"space-y-5 p-6",children:[e.jsx("h3",{className:"text-sm font-semibold uppercase tracking-wide text-muted-foreground",children:"Visibility"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Status"}),e.jsxs(ms,{value:n.status,onValueChange:y=>m("status",y),children:[e.jsx(us,{className:"sm:max-w-xs",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"draft",children:"Draft (hidden)"}),e.jsx(Ge,{value:"published",children:"Published (members can enroll)"}),e.jsx(Ge,{value:"archived",children:"Archived"})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-4 border-t border-border/60 pt-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Featured"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Pin this program to the top."})]}),e.jsx(Sn,{checked:n.is_featured,onCheckedChange:y=>m("is_featured",y)})]}),e.jsxs("div",{className:"flex items-center justify-between gap-4 border-t border-border/60 pt-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Visible to all members"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Turn off to keep it invite-only via a direct link."})]}),e.jsx(Sn,{checked:n.is_public,onCheckedChange:y=>m("is_public",y)})]})]})}),e.jsx("div",{className:"flex justify-end pb-4",children:e.jsxs($,{onClick:g,disabled:l||!a,size:"lg",children:[l?e.jsx(Ct,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(tl,{className:"mr-1.5 h-4 w-4"}),"Save changes"]})})]})},c_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}=KGs(s,t),i=YGs(s,t),l=ZGs(),[o,c]=j.useState(!1),[d,u]=j.useState({...c_t}),[h,m]=j.useState(!1),f=j.useRef(null),g=()=>{u({...c_t,sort_order:r.length}),c(!0)},x=b=>{u({id:b.id,title:b.title,description:b.description||"",category:b.category||"Personal",resource_kind:b.resource_kind,url:b.url||"",file_path:b.file_path||"",status:b.status,sort_order:b.sort_order}),c(!0)},y=async b=>{if(!(!b||!s||!t)){if(b.size>50*1024*1024)return re.error("File must be under 50MB");m(!0);try{const w=b.name.split(".").pop()||"pdf",S=`programs/${s}/members/${t}/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${w}`,{error:A}=await q.storage.from(mK).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})),re.success("File uploaded")}catch(w){re.error(w.message||"Upload failed")}finally{m(!1),f.current&&(f.current.value="")}}},v=async()=>{if(!d.title.trim())return re.error("Give the resource a title");if(!d.file_path&&!d.url.trim())return re.error("Upload a file or paste a link");await i.mutateAsync({...d,sort_order:Number(d.sort_order)||0}),c(!1)};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("p",{className:"flex items-center gap-1.5 font-medium",children:[e.jsx(pc,{className:"h-4 w-4 text-primary"})," Personal resources"]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Only ",n||"this member"," can see these — they appear in a “Just for you” section on their program dashboard."]})]}),e.jsxs($,{size:"sm",onClick:g,disabled:!t,children:[e.jsx(dn,{className:"mr-1.5 h-4 w-4"})," Add for this member"]})]}),a?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading…"}):r.length===0?e.jsx(je,{className:"border-dashed",children:e.jsx(Ie,{className:"p-6 text-center text-sm text-muted-foreground",children:"No personal resources yet. Upload their custom plan, feedback doc or scripts."})}):e.jsx("div",{className:"space-y-2",children:r.map(b=>e.jsx(je,{className:"border-border/60",children:e.jsxs(Ie,{className:"flex flex-wrap items-start justify-between gap-3 p-4",children:[e.jsxs("div",{className:"min-w-0 space-y-1.5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"font-medium",children:b.title}),e.jsx($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}),nie(b)&&e.jsxs("button",{type:"button",onClick:()=>Nee(b),className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(Fr,{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 fo(`Remove "${b.title}"?`)&&l.mutate(b)},children:e.jsx(Hn,{className:"h-4 w-4 text-destructive"})})]})]})},b.id))}),e.jsx(zs,{open:o,onOpenChange:c,children:e.jsxs(Os,{className:"max-w-lg",children:[e.jsx(Us,{children:e.jsx(Bs,{children:d.id?"Edit personal resource":"New personal resource"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Title"}),e.jsx(pe,{value:d.title,onChange:b=>u({...d,title:b.target.value}),placeholder:"Your 90-day content plan"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Description"}),e.jsx(Ls,{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:qUt.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 y((w=b.target.files)==null?void 0:w[0])}})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"…or link"}),e.jsx(pe,{value:d.url,onChange:b=>u({...d,url:b.target.value,file_path:""}),placeholder:"https://…"})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Status"}),e.jsxs(ms,{value:d.status,onValueChange:b=>u({...d,status:b}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"published",children:"Published"}),e.jsx(Ge,{value:"draft",children:"Draft"}),e.jsx(Ge,{value:"archived",children:"Archived"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Sort order"}),e.jsx(pe,{type:"number",value:d.sort_order,onChange:b=>u({...d,sort_order:b.target.value})})]})]})]}),e.jsxs(Sr,{children:[e.jsx($,{variant:"ghost",onClick:()=>c(!1),children:"Cancel"}),e.jsxs($,{onClick:v,disabled:i.isPending||h,children:[i.isPending&&e.jsx(Ct,{className:"mr-1.5 h-4 w-4 animate-spin"})," Save"]})]})]})})]})},Xnn=({program:s,enrollment:t,open:n,onOpenChange:r,onUpdated:a})=>{var G,Y,X,ae,le,ne,te,J,ce,_e;const i=t==null?void 0:t.user_id,[l,o]=j.useState((t==null?void 0:t.admin_notes)||""),[c,d]=j.useState(!1),[u,h]=j.useState(""),[m,f]=j.useState(!1),[g,x]=j.useState(!1),y=j.useRef(null),{data:v,isLoading:b,refetch:w}=st({queryKey:["admin-program-agent",s.id,i],enabled:n&&!!i,queryFn:async()=>{const[he,ue,ve,Ee,Se,Le,Fe,ke]=await Promise.all([q.from("program_weekly_progress").select("*").eq("program_id",s.id).eq("user_id",i).order("week_number"),q.from("program_video_logs").select("*").eq("program_id",s.id).eq("user_id",i).order("posted_at",{ascending:!1}),q.from("program_lesson_completions").select("*").eq("program_id",s.id).eq("user_id",i),q.from("program_badge_awards").select("*").eq("program_id",s.id).eq("user_id",i),q.from("program_intake_responses").select("*").eq("program_id",s.id).eq("user_id",i).maybeSingle(),q.from("program_event_attendance").select("*").eq("program_id",s.id).eq("user_id",i),q.from("program_lessons").select("id").eq("program_id",s.id),q.from("program_profile_analyses").select("*").eq("program_id",s.id).eq("user_id",i).maybeSingle()]);return{weekly:he.data||[],videos:ue.data||[],completions:ve.data||[],badges:Ee.data||[],intake:Se.data,attendance:Le.data||[],lessonCount:(Fe.data||[]).length,analysis:ke.data}}});j.useEffect(()=>{var he;h(((he=v==null?void 0:v.analysis)==null?void 0:he.member_notes)||"")},[(G=v==null?void 0:v.analysis)==null?void 0:G.id]);const S=j.useMemo(()=>{var ve;const he=lse(s),ue=((ve=v==null?void 0:v.intake)==null?void 0:ve.extra)||{};return he.custom.map(Ee=>({label:Ee.label,value:typeof ue[Ee.id]=="boolean"?ue[Ee.id]?"Yes":"No":ue[Ee.id]||""})).filter(Ee=>!!Ee.value)},[s,v==null?void 0:v.intake]),A=async he=>i?q.from("program_profile_analyses").upsert({program_id:s.id,user_id:i,enrollment_id:(t==null?void 0:t.id)||null,...he},{onConflict:"program_id,user_id"}):{error:{message:"Missing agent"}},E=async he=>{if(he.type!=="application/pdf")return re.error("Please choose a PDF file");if(he.size>25*1024*1024)return re.error("PDF must be under 25MB");x(!0);try{const ue=`programs/${s.id}/reviews/${i}-${Date.now()}.pdf`,{error:ve}=await q.storage.from("event-images").upload(ue,he,{contentType:"application/pdf",upsert:!0});if(ve)throw ve;const{data:Ee}=q.storage.from("event-images").getPublicUrl(ue),{error:Se}=await A({report_url:Ee.publicUrl,status:"ready",reviewed_at:new Date().toISOString()});if(Se)throw Se;re.success("Profile review uploaded"),await w()}catch(ue){re.error(ue.message||"Upload failed")}finally{x(!1)}},I=async()=>{const{error:he}=await A({report_url:null,status:"in_review"});if(he)return re.error(he.message);re.success("Review removed"),await w()},P=async()=>{f(!0);const{error:he}=await A({member_notes:u});if(f(!1),he)return re.error(he.message);re.success("Review notes saved"),await w()},R=async()=>{if(!t)return;d(!0);const{error:he}=await q.from("program_enrollments").update({admin_notes:l}).eq("id",t.id);if(d(!1),he)return re.error(he.message);re.success("Notes saved"),a()},D=((v==null?void 0:v.videos)||[]).filter(he=>he.posted).length,O=(s.weekly_video_goal||0)*(s.duration_weeks||0),U=v!=null&&v.lessonCount?Math.round(((v==null?void 0:v.completions.length)||0)/v.lessonCount*100):0,W=O?Math.min(100,Math.round(D/O*100)):0,V=((v==null?void 0:v.attendance)||[]).filter(he=>he.attended).length;return e.jsx(Gy,{open:n,onOpenChange:r,children:e.jsxs(my,{className:"w-full overflow-y-auto sm:max-w-2xl",children:[e.jsxs(L0,{className:"mb-4",children:[e.jsxs(R0,{children:[((Y=t==null?void 0:t.profile)==null?void 0:Y.name)||"Agent"," · ",s.name]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(X=t==null?void 0:t.profile)==null?void 0:X.email}),i&&e.jsx($,{variant:"outline",size:"sm",className:"mt-3 w-fit",asChild:!0,children:e.jsxs("a",{href:`/programs/${s.slug}/workspace?preview=1&as=${i}&name=${encodeURIComponent(((ae=t==null?void 0:t.profile)==null?void 0:ae.name)||((le=t==null?void 0:t.profile)==null?void 0:le.email)||"this member")}`,target:"_blank",rel:"noreferrer",children:[e.jsx(Fr,{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(Ie,{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:[Sg(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(Ie,{className:"p-4",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Last activity"}),e.jsx("p",{className:"mt-1 text-sm font-medium",children: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(Ie,{className:"space-y-4 p-5",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"mb-1 flex items-center justify-between text-sm",children:[e.jsx("span",{className:"font-medium",children:"Videos posted"}),e.jsxs("span",{className:"text-muted-foreground",children:[D," / ",O||"—"]})]}),e.jsx(Yi,{value:W})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"mb-1 flex items-center justify-between text-sm",children:[e.jsx("span",{className:"font-medium",children:"Curriculum completed"}),e.jsxs("span",{className:"text-muted-foreground",children:[(v==null?void 0:v.completions.length)||0," / ",(v==null?void 0:v.lessonCount)||0]})]}),e.jsx(Yi,{value:U})]}),e.jsxs("div",{className:"flex flex-wrap gap-4 border-t border-border/60 pt-4 text-sm",children:[e.jsxs("span",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Live sessions attended: "}),V]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Badges: "}),(v==null?void 0:v.badges.length)||0]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Weeks reported: "}),(v==null?void 0:v.weekly.length)||0]})]})]})}),e.jsx(je,{children:e.jsxs(Ie,{className:"p-5",children:[e.jsx("p",{className:"mb-3 text-sm font-semibold",children:"Weekly progress"}),((v==null?void 0:v.weekly.length)||0)===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No weekly check-ins yet."}):e.jsx("div",{className:"space-y-3",children:v.weekly.map(he=>e.jsxs("div",{className:"rounded-lg border border-border/60 p-3 text-sm",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"font-medium",children:["Week ",he.week_number]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[he.videos_posted,"/",he.goal_videos||s.weekly_video_goal," posted ·"," ",he.stories_posted," stories"]})]}),he.biggest_win&&e.jsxs("p",{className:"mt-1 text-muted-foreground",children:["Win: ",he.biggest_win]}),he.biggest_challenge&&e.jsxs("p",{className:"text-muted-foreground",children:["Challenge: ",he.biggest_challenge]})]},he.id))})]})}),e.jsx(je,{children:e.jsxs(Ie,{className:"p-5",children:[e.jsx("p",{className:"mb-3 text-sm font-semibold",children:"Video log"}),((v==null?void 0:v.videos.length)||0)===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No videos logged yet."}):e.jsx("div",{className:"space-y-2",children:v.videos.slice(0,25).map(he=>e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(ua,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:he.title||"Untitled video"}),e.jsxs("span",{className:"ml-auto shrink-0 text-xs text-muted-foreground",children:["Wk ",he.week_number," · ",th(he.posted_at)]}),he.instagram_url&&e.jsx("a",{href:he.instagram_url,target:"_blank",rel:"noreferrer",className:"shrink-0 text-muted-foreground hover:text-foreground","aria-label":"Open post",children:e.jsx(Fr,{className:"h-3.5 w-3.5"})})]},he.id))})]})}),(v==null?void 0:v.intake)&&e.jsx(je,{children:e.jsxs(Ie,{className:"space-y-1 p-5 text-sm",children:[e.jsx("p",{className:"mb-2 text-sm font-semibold",children:"Intake answers"}),[["Full name",v.intake.full_name],["Email",v.intake.email],["Phone",v.intake.phone],["Instagram",v.intake.instagram_handle],["City / market",v.intake.city],["Areas served",v.intake.service_areas],["Years in real estate",v.intake.years_experience],["Specialty",v.intake.specialty],["Target audience",v.intake.target_audience],["On camera",v.intake.video_comfort],["Posts today",v.intake.posting_frequency],["Content style",v.intake.content_style],["Interests",v.intake.personal_interests],["#1 goal",v.intake.primary_goal],["Topics to avoid",v.intake.topics_to_avoid],["Time zone",v.intake.timezone]].filter(([,he])=>!!he).map(([he,ue])=>e.jsxs("p",{children:[e.jsxs("span",{className:"text-muted-foreground",children:[he,": "]}),ue]},he)),S.map(({label:he,value:ue})=>e.jsxs("p",{children:[e.jsxs("span",{className:"text-muted-foreground",children:[he,": "]}),ue]},he)),e.jsxs("p",{className:"pt-1 text-xs text-muted-foreground",children:["Content-sharing consent: ",v.intake.consent_public_profile?"Yes":"No"]})]})}),e.jsx(je,{children:e.jsx(Ie,{className:"p-5",children:e.jsx(Znn,{programId:s.id,userId:i,memberName:(ne=t==null?void 0:t.profile)==null?void 0:ne.name})})}),e.jsx(je,{children:e.jsxs(Ie,{className:"space-y-3 p-5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold",children:"Profile review PDF"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Upload this agent's personalized profile review. They see it in their workspace."})]}),((te=v==null?void 0:v.analysis)==null?void 0:te.status)&&e.jsx($e,{variant:"secondary",className:"capitalize",children:String(v.analysis.status).replace(/_/g," ")})]}),(J=v==null?void 0:v.analysis)!=null&&J.report_url?e.jsxs("div",{className:"flex flex-wrap items-center gap-2 rounded-lg border border-border/60 p-3 text-sm",children:[e.jsx(Jr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:"Review uploaded"}),e.jsxs("a",{href:v.analysis.report_url,target:"_blank",rel:"noreferrer",className:"ml-auto inline-flex items-center gap-1 text-primary hover:underline",children:["View ",e.jsx(Fr,{className:"h-3.5 w-3.5"})]})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"No review uploaded yet."}),e.jsx("input",{ref:y,type:"file",accept:"application/pdf",className:"hidden",onChange:he=>{var ve;const ue=(ve=he.target.files)==null?void 0:ve[0];ue&&E(ue),he.target.value=""}}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs($,{size:"sm",variant:"outline",onClick:()=>{var he;return(he=y.current)==null?void 0:he.click()},disabled:g,children:[e.jsx(ni,{className:"mr-1.5 h-3.5 w-3.5"}),g?"Uploading…":(ce=v==null?void 0:v.analysis)!=null&&ce.report_url?"Replace PDF":"Upload PDF"]}),((_e=v==null?void 0:v.analysis)==null?void 0:_e.report_url)&&e.jsx($,{size:"sm",variant:"ghost",onClick:I,children:"Remove"})]}),e.jsxs("div",{className:"space-y-2 pt-1",children:[e.jsx(ee,{children:"Review summary shown to the agent (optional)"}),e.jsx(Ls,{rows:3,value:u,onChange:he=>h(he.target.value),placeholder:"Top 3 priorities, quick wins, what to fix first…"}),e.jsx("div",{className:"flex justify-end",children:e.jsx($,{size:"sm",variant:"outline",onClick:P,disabled:m,children:"Save review notes"})})]})]})}),e.jsx(je,{children:e.jsxs(Ie,{className:"space-y-3 p-5",children:[e.jsx(ee,{children:"Coach notes (internal)"}),e.jsx(Ls,{rows:4,value:l,onChange:he=>o(he.target.value)}),e.jsx("div",{className:"flex justify-end",children:e.jsx($,{size:"sm",onClick:R,disabled:c,children:"Save notes"})})]})})]}):null]})})},d_t={code:"",label:"",kind:"percent",percent_off:"20",amount_off:"",max_redemptions:"",starts_at:"",expires_at:"",is_active:!0},u_t=s=>{if(!s)return"";const t=new Date(s),n=t.getTimezoneOffset();return new Date(t.getTime()-n*6e4).toISOString().slice(0,16)},Qnn=({program:s})=>{const{data:t=[],isLoading:n}=RGs(s.id),r=DGs(s.id),a=FGs(),[i,l]=j.useState(!1),[o,c]=j.useState({...d_t}),d=()=>{c({...d_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:u_t(g.starts_at),expires_at:u_t(g.expires_at),is_active:g.is_active}),l(!0)},h=j.useMemo(()=>{const g=o.kind==="percent"?Math.floor(s.price_cents*Number(o.percent_off||0)/100):Math.round(Number(o.amount_off||0)*100),x=Math.min(Math.max(g,0),s.price_cents);return{discount:x,final:s.price_cents-x}},[o,s.price_cents]),m=async()=>{if(!o.code.trim())return re.error("Give the code a name, e.g. FOUNDER50");await r.mutateAsync({id:o.id,code:o.code,label:o.label||null,percent_off:o.kind==="percent"?Number(o.percent_off)||0:null,amount_off_cents:o.kind==="amount"?Math.round(Number(o.amount_off||0)*100):null,max_redemptions:o.max_redemptions?Number(o.max_redemptions):null,starts_at:o.starts_at?new Date(o.starts_at).toISOString():null,expires_at:o.expires_at?new Date(o.expires_at).toISOString():null,is_active:o.is_active}),l(!1)},f=g=>{const x=g.percent_off!=null?Math.floor(s.price_cents*Number(g.percent_off)/100):g.amount_off_cents||0,y=Math.max(s.price_cents-Math.min(x,s.price_cents),0);return{off:g.percent_off!=null?`${Number(g.percent_off)}% off`:`${Sg(g.amount_off_cents||0,s.currency)} off`,final:Sg(y,s.currency)}};return e.jsxs("div",{className:"space-y-4",children:[e.jsx(je,{children:e.jsxs(Ie,{className:"flex flex-wrap items-center justify-between gap-4 p-5",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Discount codes"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Enrollees can enter a code on the final enrollment step. The discount is applied to the one-time ",Sg(s.price_cents,s.currency)," charge."]})]}),e.jsxs(zs,{open:i,onOpenChange:l,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{onClick:d,children:[e.jsx(dn,{className:"mr-1.5 h-4 w-4"})," New code"]})}),e.jsxs(Os,{className:"max-h-[85vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(Bs,{children:o.id?"Edit discount code":"Create a discount code"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Code"}),e.jsx(pe,{placeholder:"FOUNDER50",value:o.code,onChange:g=>c({...o,code:g.target.value.toUpperCase()})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Internal label (optional)"}),e.jsx(pe,{placeholder:"Founding cohort",value:o.label,onChange:g=>c({...o,label:g.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Discount type"}),e.jsxs(ms,{value:o.kind,onValueChange:g=>c({...o,kind:g}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"percent",children:"Percent off"}),e.jsx(Ge,{value:"amount",children:"Dollar amount off"})]})]})]}),o.kind==="percent"?e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Percent off"}),e.jsx(pe,{type:"number",min:1,max:100,value:o.percent_off,onChange:g=>c({...o,percent_off:g.target.value})})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Amount off (USD)"}),e.jsx(pe,{type:"number",min:0,value:o.amount_off,onChange:g=>c({...o,amount_off:g.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Max redemptions (blank = unlimited)"}),e.jsx(pe,{type:"number",min:1,value:o.max_redemptions,onChange:g=>c({...o,max_redemptions:g.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Active from (optional)"}),e.jsx(pe,{type:"datetime-local",value:o.starts_at,onChange:g=>c({...o,starts_at:g.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Expires (optional)"}),e.jsx(pe,{type:"datetime-local",value:o.expires_at,onChange:g=>c({...o,expires_at:g.target.value})})]})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border border-border/60 p-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Code is active"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Turn off to stop new redemptions instantly."})]}),e.jsx(Sn,{checked:o.is_active,onCheckedChange:g=>c({...o,is_active:g})})]}),e.jsxs("div",{className:"rounded-lg border border-primary/30 bg-primary/5 p-4 text-sm",children:[e.jsx("p",{className:"font-medium",children:"Enrollee sees"}),e.jsxs("p",{className:"mt-1 text-muted-foreground",children:[Sg(s.price_cents,s.currency)," →"," ",e.jsx("span",{className:"font-semibold text-foreground",children:Sg(h.final,s.currency)})," ","(",Sg(h.discount,s.currency)," off) — charged one time."]})]})]}),e.jsx(Sr,{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(Ie,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(Ap,{className:"h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"font-medium",children:"No discount codes yet"}),e.jsx("p",{className:"max-w-md text-sm text-muted-foreground",children:"Create a code for early birds, brokerage partners or a founding cohort. Codes are entered by the enrollee at checkout and change the one-time price."})]})}):e.jsx(je,{children:e.jsx(Ie,{className:"overflow-x-auto p-0",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Code"}),e.jsx(Dt,{children:"Discount"}),e.jsx(Dt,{children:"Price after"}),e.jsx(Dt,{children:"Used"}),e.jsx(Dt,{children:"Window"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(fi,{children:t.map(g=>{const x=f(g);return e.jsxs(En,{children:[e.jsxs(_t,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-mono font-semibold",children:g.code}),e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>{navigator.clipboard.writeText(g.code),re.success("Code copied")},children:e.jsx(Ha,{className:"h-3.5 w-3.5"})})]}),g.label&&e.jsx("p",{className:"text-xs text-muted-foreground",children:g.label})]}),e.jsx(_t,{className:"whitespace-nowrap",children:e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(Ew,{className:"h-3.5 w-3.5 text-muted-foreground"}),x.off]})}),e.jsx(_t,{className:"font-medium",children:x.final}),e.jsxs(_t,{children:[g.times_redeemed,g.max_redemptions?` / ${g.max_redemptions}`:""]}),e.jsxs(_t,{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(_t,{children:e.jsx($e,{variant:g.is_active?"default":"secondary",children:g.is_active?"Active":"Paused"})}),e.jsx(_t,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[e.jsx($,{variant:"outline",size:"sm",onClick:()=>u(g),children:"Edit"}),e.jsx($,{variant:"ghost",size:"icon",onClick:async()=>{await fo(`Delete ${g.code}?`)&&a.mutate(g.id)},children:e.jsx(Hn,{className:"h-4 w-4 text-destructive"})})]})})]},g.id)})})]})})})]})},s5=({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})]})]}),Jnn=({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}=k6e(s),l=`/programs/${s.slug}`,o=[{icon:Nn,title:"1 · Sales page",body:`${s.name} — hero image, ${s.subtitle?"subtitle":"no subtitle"}, description, price, dates, seats left and FAQ.`,href:l,cta:"Preview sales page"},{icon:Xq,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:Nv,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 ${Sg(s.price_cents,s.currency)} charge runs on ${th(s.charge_at||s.kickoff_at)||"the charge date (not set)"}.`:`Stripe charges ${Sg(s.price_cents,s.currency)} once at checkout.`},{icon:mn,title:"4 · Emails",body:"Confirmation right after enrollment, then payment receipt (or a payment-failed action email) when the one-time charge runs."},{icon:Vq,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(Ie,{className:"flex flex-wrap items-center justify-between gap-4 p-5",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"What enrollees see"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Walk the exact member journey end to end. Workspace preview opens in read-only admin mode — it does not create an enrollment."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx($,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:l,target:"_blank",rel:"noreferrer",children:["Sales page ",e.jsx(Fr,{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(Fr,{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(Ie,{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(Ie,{className:"space-y-3 p-5",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"The enrollee journey"}),e.jsx("div",{className:"space-y-4",children:o.map(u=>e.jsxs("div",{className:"flex gap-3",children:[e.jsx("div",{className:"mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-primary/10",children:e.jsx(u.icon,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"min-w-0 space-y-1",children:[e.jsx("p",{className:"text-sm font-medium",children:u.title}),e.jsx("p",{className:"text-sm text-muted-foreground",children:u.body}),u.href&&e.jsx($,{variant:"link",size:"sm",className:"h-auto p-0",asChild:!0,children:e.jsxs("a",{href:u.href,target:"_blank",rel:"noreferrer",children:[u.cta," ",e.jsx(Fr,{className:"ml-1 h-3 w-3"})]})})]})]},u.title))})]})}),e.jsx(je,{children:e.jsxs(Ie,{className:"p-5",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Premium-experience checklist"}),n?e.jsx(xn,{className:"mt-4 h-64 w-full rounded-lg"}):e.jsxs("div",{className:"mt-2",children:[e.jsx(s5,{ok:!!s.cover_image_url,label:"Cover image",detail:s.cover_image_url?"Set":"Missing — cards look empty on the Programs page"}),e.jsx(s5,{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(s5,{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(s5,{ok:s.payment_mode==="free"||s.price_cents>0,label:"One-time price",detail:s.payment_mode==="free"?"Free / included":Sg(s.price_cents,s.currency)}),e.jsx(s5,{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(s5,{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(s5,{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(s5,{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(s5,{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(s5,{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(Ie,{className:"grid gap-4 p-5 sm:grid-cols-2 lg:grid-cols-5",children:[{icon:Wc,label:"Weeks",value:t.weeks.length},{icon:Jr,label:"Lessons",value:t.lessons.length},{icon:Jr,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."})]})},ern=["Step 1 · Your business","Step 2 · Your content","Step 3 · Your goals"],trn={short_text:"Short answer",long_text:"Paragraph",select:"Dropdown",checkbox:"Yes / no checkbox"},srn=({program:s,onSaved:t})=>{const[n,r]=j.useState(()=>lse(s)),[a,i]=j.useState(!1),[l,o]=j.useState(!1);j.useEffect(()=>{r(lse(s)),i(!1)},[s.id,s.updated_at]);const c=y=>{r(v=>({...v,...y})),i(!0)},d=(y,v)=>{const b=v?n.hidden.filter(S=>S!==y):[...new Set([...n.hidden,y])],w=v?n.required:n.required.filter(S=>S!==y);c({hidden:b,required:w})},u=(y,v)=>{c({required:v?[...new Set([...n.required,y])]:n.required.filter(b=>b!==y)})},h=()=>{const y={id:`q_${Date.now().toString(36)}`,label:"",type:"short_text",required:!1,options:[]};c({custom:[...n.custom,y]})},m=(y,v)=>c({custom:n.custom.map(b=>b.id===y?{...b,...v}:b)}),f=y=>c({custom:n.custom.filter(v=>v.id!==y)}),g=(y,v)=>{const b=[...n.custom],w=y+v;w<0||w>=b.length||([b[y],b[w]]=[b[w],b[y]],c({custom:b}))},x=async()=>{if(n.custom.find(w=>!w.label.trim()))return re.error("Every custom question needs a label");o(!0);const v={...s.sales_copy||{},intake:n},{error:b}=await q.from("programs").update({sales_copy:v}).eq("id",s.id);if(o(!1),b)return re.error(b.message);i(!1),re.success("Intake form saved"),t==null||t()};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold",children:"Intake form"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Controls the questions each agent answers during enrollment."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:`/programs/${s.slug}/enroll`,target:"_blank",rel:"noreferrer",children:[e.jsx(Fr,{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(Ie,{children:e.jsx(Ls,{rows:3,placeholder:"Shown at the top of the intake — e.g. “Answer a few questions so we can personalize your 90 days.”",value:n.intro||"",onChange:y=>c({intro:y.target.value})})})]}),[0,1,2].map(y=>e.jsxs(je,{children:[e.jsx(St,{className:"pb-3",children:e.jsx(Et,{className:"text-sm",children:ern[y]})}),e.jsxs(Ie,{className:"space-y-2",children:[e.jsxs("div",{className:"hidden grid-cols-[1fr,auto,auto] gap-4 pb-1 text-xs uppercase tracking-wide text-muted-foreground sm:grid",children:[e.jsx("span",{children:"Question"}),e.jsx("span",{className:"w-16 text-center",children:"Show"}),e.jsx("span",{className:"w-16 text-center",children:"Required"})]}),snt.filter(v=>v.step===y).map(v=>{const b=!n.hidden.includes(v.key);return e.jsxs("div",{className:"grid grid-cols-[1fr,auto,auto] items-center gap-4 rounded-lg border border-border/60 px-3 py-2",children:[e.jsx("span",{className:"text-sm",children:v.label}),e.jsx("div",{className:"flex w-16 justify-center",children:e.jsx(Sn,{checked:b,onCheckedChange:w=>d(v.key,w),"aria-label":`Show ${v.label}`})}),e.jsx("div",{className:"flex w-16 justify-center",children:e.jsx(Sn,{checked:n.required.includes(v.key),disabled:!b,onCheckedChange:w=>u(v.key,w),"aria-label":`Require ${v.label}`})})]},v.key)})]})]},y)),e.jsxs(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(dn,{className:"mr-1.5 h-3.5 w-3.5"})," Add question"]})]}),e.jsxs(Ie,{className:"space-y-3",children:[n.custom.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No custom questions yet. Add program-specific questions here — answers appear on each agent's dashboard."}),n.custom.map((y,v)=>e.jsxs("div",{className:"space-y-3 rounded-lg border border-border/60 p-4",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("div",{className:"flex flex-col pt-1.5",children:e.jsx("button",{type:"button",className:"text-muted-foreground hover:text-foreground",onClick:()=>g(v,-1),"aria-label":"Move up",children:e.jsx(Ug,{className:"h-4 w-4"})})}),e.jsxs("div",{className:"grid flex-1 gap-3 sm:grid-cols-[2fr,1fr]",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Question"}),e.jsx(pe,{value:y.label,placeholder:"What is your biggest content roadblock?",onChange:b=>m(y.id,{label:b.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Answer type"}),e.jsxs(ms,{value:y.type,onValueChange:b=>m(y.id,{type:b}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:Object.entries(trn).map(([b,w])=>e.jsx(Ge,{value:b,children:w},b))})]})]})]}),e.jsx($,{size:"icon",variant:"ghost",onClick:()=>f(y.id),"aria-label":"Delete question",children:e.jsx(Hn,{className:"h-4 w-4 text-destructive"})})]}),y.type==="select"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Options (one per line)"}),e.jsx(Ls,{rows:3,value:(y.options||[]).join(` `),onChange:b=>m(y.id,{options:b.target.value.split(` `).map(w=>w.trim()).filter(Boolean)})})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-[1fr,auto]",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Helper text (optional)"}),e.jsx(pe,{value:y.help||"",onChange:b=>m(y.id,{help:b.target.value})})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-6",children:[e.jsx(Sn,{checked:!!y.required,onCheckedChange:b=>m(y.id,{required:b}),"aria-label":"Required"}),e.jsx("span",{className:"text-sm",children:"Required"})]})]})]},y.id))]})]})]})},v1=SHt,b1=jHt,_1=kHt,nrn=[kx,Jr,nh],rrn=["Business profile","Content style","Goals & consent"],arn=({fieldKey:s})=>s.includes("phone")?e.jsx(Da,{className:"h-3.5 w-3.5"}):s.includes("email")?e.jsx(mn,{className:"h-3.5 w-3.5"}):s.includes("instagram")?e.jsx(Ef,{className:"h-3.5 w-3.5"}):s.includes("city")||s.includes("area")?e.jsx(ci,{className:"h-3.5 w-3.5"}):s.includes("timezone")?e.jsx(da,{className:"h-3.5 w-3.5"}):s.includes("consent")?s.includes("true")?e.jsx(Vr,{className:"h-3.5 w-3.5"}):e.jsx(Nu,{className:"h-3.5 w-3.5"}):e.jsx(sl,{className:"h-3.5 w-3.5"}),h_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(Nu,{className:"h-3.5 w-3.5"})," No"]}):String(s),irn=({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=lse(s),c=snt.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(Ie,{className:"p-12 text-center text-sm text-muted-foreground",children:[e.jsx(Jr,{className:"mx-auto mb-3 h-6 w-6"}),e.jsx("p",{children:"No intake responses yet."}),e.jsx("p",{className:"mt-1 text-xs",children:"Responses appear here once members complete the enrollment intake form."})]})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold",children:"Intake responses"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[d.length," of ",i.length," response",i.length===1?"":"s"," · every field from the enrollment intake form"]})]}),e.jsxs("div",{className:"relative w-full sm:w-64",children:[e.jsx(Zr,{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(v1,{open:m,onOpenChange:()=>u(h.id),children:[e.jsx(b1,{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(_1,{children:e.jsxs(Ie,{className:"space-y-5 p-5",children:[[0,1,2].map(g=>{const x=c.filter(v=>v.step===g),y=nrn[g];return x.length===0?null:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 border-b border-border/40 pb-2",children:[e.jsx("div",{className:"flex h-6 w-6 items-center justify-center rounded-md bg-primary/10",children:e.jsx(y,{className:"h-3.5 w-3.5 text-primary"})}),e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:rrn[g]})]}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:x.map(v=>{const b=h[v.key];return b==null||b===""?null:e.jsxs("div",{className:"rounded-lg border border-border/50 p-3",children:[e.jsxs("div",{className:"mb-1 flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(arn,{fieldKey:v.key}),v.label]}),e.jsx("p",{className:"text-sm font-medium",children:h_t(b,v.key)})]},v.key)})})]},g)}),o.custom&&o.custom.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 border-b border-border/40 pb-2",children:[e.jsx("div",{className:"flex h-6 w-6 items-center justify-center rounded-md bg-primary/10",children:e.jsx(Jr,{className:"h-3.5 w-3.5 text-primary"})}),e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Custom questions"})]}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:o.custom.map(g=>{var y;const x=(y=h.extra)==null?void 0:y[g.id];return x==null||x===""?null:e.jsxs("div",{className:"rounded-lg border border-border/50 p-3",children:[e.jsx("p",{className:"mb-1 text-xs text-muted-foreground",children:g.label}),e.jsx("p",{className:"text-sm font-medium",children:h_t(x,g.id)})]},g.id)})})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 pt-2 text-xs text-muted-foreground",children:[e.jsx(Ta,{className:"h-3.5 w-3.5"}),"Submitted ",f,h.timezone&&e.jsxs("span",{className:"ml-2",children:["· Timezone: ",h.timezone]})]})]})})]})},h.id)})})]})},orn=[{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"}],lrn=s=>{if(!s)return"";const t=new Date(s),n=t.getTimezoneOffset();return new Date(t.getTime()-n*6e4).toISOString().slice(0,16)},m_t={title:"",description:"",event_kind:"mastermind",starts_at:"",duration_minutes:60,speaker:"",meeting_link:"",replay_url:"",is_published:!0},crn=({programId:s})=>{const{data:t=[],isLoading:n}=BGs(s),r=$Gs(s),a=UGs(),[i,l]=j.useState(!1),[o,c]=j.useState({...m_t}),d=()=>{c({...m_t}),l(!0)},u=y=>{c({id:y.id,title:y.title,description:y.description||"",event_kind:y.event_kind,starts_at:lrn(y.starts_at),duration_minutes:y.duration_minutes,speaker:y.speaker||"",meeting_link:y.meeting_link||"",replay_url:y.replay_url||"",is_published:y.is_published}),l(!0)},h=async()=>{if(!o.title.trim())return re.error("Give the session a title");if(!o.starts_at)return re.error("Pick a date and time");await r.mutateAsync({...o,starts_at:new Date(o.starts_at).toISOString(),duration_minutes:Number(o.duration_minutes)||60}),l(!1)},m=Date.now(),f=t.filter(y=>new Date(y.starts_at).getTime()>=m),g=t.filter(y=>new Date(y.starts_at).getTime()e.jsx(je,{className:"border-border/60",children:e.jsxs(Ie,{className:"flex flex-wrap items-start justify-between gap-4 p-5",children:[e.jsxs("div",{className:"min-w-0 space-y-1.5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"font-medium",children:y.title}),e.jsx($e,{variant:"secondary",className:"capitalize",children:y.event_kind.replace("_"," ")}),!y.is_published&&e.jsx($e,{variant:"outline",children:"Hidden"})]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[th(y.starts_at,!0)," · ",y.duration_minutes," min",y.speaker?` · ${y.speaker}`:""]}),y.description&&e.jsx("p",{className:"max-w-2xl text-sm text-muted-foreground",children:y.description}),e.jsxs("div",{className:"flex flex-wrap gap-3 pt-1 text-xs",children:[y.meeting_link?e.jsxs(e.Fragment,{children:[e.jsxs("a",{className:"inline-flex items-center gap-1 text-primary hover:underline",href:y.meeting_link,target:"_blank",rel:"noreferrer",children:[e.jsx(Fr,{className:"h-3 w-3"})," Join link"]}),e.jsxs("button",{className:"inline-flex items-center gap-1 text-muted-foreground hover:text-foreground",onClick:()=>{navigator.clipboard.writeText(y.meeting_link),re.success("Join link copied")},children:[e.jsx(Ha,{className:"h-3 w-3"})," Copy"]})]}):e.jsx("span",{className:"text-muted-foreground",children:"No meeting link yet"}),y.replay_url&&e.jsxs("a",{className:"inline-flex items-center gap-1 text-primary hover:underline",href:y.replay_url,target:"_blank",rel:"noreferrer",children:[e.jsx(ua,{className:"h-3 w-3"})," Replay"]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",size:"sm",onClick:()=>u(y),children:e.jsx(pi,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"outline",size:"sm",onClick:async()=>{await fo(`Remove "${y.title}"?`)&&a.mutate(y.id)},children:e.jsx(Hn,{className:"h-3.5 w-3.5"})})]})]})});return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Live sessions"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Add your Zoom (or Meet / Teams) sessions here. Enrolled members see them in the Sessions tab with the join button, RSVP reminders and an add-to-calendar link."})]}),e.jsxs($,{onClick:d,children:[e.jsx(dn,{className:"mr-1.5 h-4 w-4"})," Add session"]})]}),n?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading sessions…"}):t.length===0?e.jsx(je,{className:"border-dashed",children:e.jsxs(Ie,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(Cu,{className:"h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"font-medium",children:"No live sessions scheduled"}),e.jsx("p",{className:"max-w-md text-sm text-muted-foreground",children:"Paste your recurring Zoom link once for each call — kickoff, weekly masterminds, workshops and office hours."})]})}):e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"space-y-3",children:[e.jsxs("h3",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:["Upcoming (",f.length,")"]}),f.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nothing upcoming."}):f.map(y=>e.jsx(x,{e:y},y.id))]}),g.length>0&&e.jsxs("section",{className:"space-y-3",children:[e.jsxs("h3",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:["Past (",g.length,") — add replay links so members can catch up"]}),g.map(y=>e.jsx(x,{e:y},y.id))]})]}),e.jsx(zs,{open:i,onOpenChange:l,children:e.jsxs(Os,{className:"max-h-[85vh] max-w-2xl overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(Bs,{children:o.id?"Edit session":"Add a live session"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Title"}),e.jsx(pe,{placeholder:"Week 1 Mastermind — Content that converts",value:o.title,onChange:y=>c({...o,title:y.target.value})})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Type"}),e.jsxs(ms,{value:o.event_kind,onValueChange:y=>c({...o,event_kind:y}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:orn.map(y=>e.jsx(Ge,{value:y.value,children:y.label},y.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Host / speaker"}),e.jsx(pe,{value:o.speaker,onChange:y=>c({...o,speaker:y.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Starts (your local time)"}),e.jsx(pe,{type:"datetime-local",value:o.starts_at,onChange:y=>c({...o,starts_at:y.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Length (minutes)"}),e.jsx(pe,{type:"number",value:o.duration_minutes,onChange:y=>c({...o,duration_minutes:y.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Zoom / meeting link"}),e.jsx(pe,{placeholder:"https://us02web.zoom.us/j/1234567890?pwd=…",value:o.meeting_link,onChange:y=>c({...o,meeting_link:y.target.value})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Members only see this after they're enrolled. A recurring Zoom link can be reused on every session."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Replay link (after the call)"}),e.jsx(pe,{placeholder:"YouTube, Vimeo, Loom or Zoom cloud recording URL",value:o.replay_url,onChange:y=>c({...o,replay_url:y.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"What we'll cover"}),e.jsx(Ls,{rows:3,value:o.description,onChange:y=>c({...o,description:y.target.value})})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border border-border/60 p-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Visible to members"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Turn off to draft a session privately."})]}),e.jsx(Sn,{checked:o.is_published,onCheckedChange:y=>c({...o,is_published:y})})]})]}),e.jsx(Sr,{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"]})})]})})]})},f_t={title:"",summary:"",week_id:"none",duration_minutes:"",video_url:"",worksheet_url:"",action_assignment:"",status:"published",sort_order:0},drn=({programId:s})=>{const{data:t,isLoading:n}=qGs(s),r=(t==null?void 0:t.lessons)||[],a=(t==null?void 0:t.weeks)||[],{data:i=[]}=VUt(s),l=VGs(s),o=HGs(),[c,d]=j.useState(!1),[u,h]=j.useState({...f_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 re.error("Please choose a video file");if(A.size>500*1024*1024)return re.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})),re.success("Video uploaded")}catch(E){re.error((E==null?void 0:E.message)||"Upload failed")}finally{f(!1)}}},y=()=>{h({...f_t,sort_order:r.length}),d(!0)},v=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 re.error("Give the video a title");await l.mutateAsync({...u,week_id:u.week_id==="none"?null:u.week_id,duration_minutes:u.duration_minutes===""?null:Number(u.duration_minutes),sort_order:Number(u.sort_order)||0}),d(!1)},w=A=>{const E=a.find(I=>I.id===A);return E?`Week ${E.week_number}`:"Unassigned"},S=UUt(u.video_url);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"On-demand videos"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Your program's video library. Paste a YouTube, Vimeo or Loom link and it plays inline in the member workspace, grouped by week, with completion tracking."})]}),e.jsxs($,{onClick:y,children:[e.jsx(dn,{className:"mr-1.5 h-4 w-4"})," Add video"]})]}),n?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading library…"}):r.length===0?e.jsx(je,{className:"border-dashed",children:e.jsxs(Ie,{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(Ie,{className:"flex flex-wrap items-start justify-between gap-4 p-5",children:[e.jsxs("div",{className:"min-w-0 space-y-1.5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"font-medium",children: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(Fr,{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(Fr,{className:"h-3 w-3"})," Worksheet"]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",size:"sm",onClick:()=>v(A),children:e.jsx(pi,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"outline",size:"sm",onClick:async()=>{await fo(`Remove "${A.title}"?`)&&o.mutate(A.id)},children:e.jsx(Hn,{className:"h-3.5 w-3.5"})})]})]})},A.id))}),e.jsx(zs,{open:c,onOpenChange:d,children:e.jsxs(Os,{className:"max-h-[85vh] max-w-2xl overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(Bs,{children:u.id?"Edit video":"Add an on-demand video"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Title"}),e.jsx(pe,{placeholder:"How to script a 30-second listing reel",value:u.title,onChange: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&&!jee(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&&jee(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(Ls,{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?nie(E):null;I?h({...u,worksheet_url:I}):re.error("That resource has no file or link yet")},children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Choose an uploaded program resource…"})}),e.jsx(hs,{children:i.map(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(Fr,{className:"h-3 w-3"})," Preview worksheet"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Action assignment"}),e.jsx(Ls,{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(Sr,{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"]})})]})})]})},p_t={title:"",description:"",category:"Resources",resource_kind:"pdf",url:"",file_path:"",status:"published",sort_order:0},urn=({programId:s})=>{const{data:t=[],isLoading:n}=VUt(s),r=GGs(s),a=WGs(),[i,l]=j.useState(!1),[o,c]=j.useState({...p_t}),[d,u]=j.useState(!1),h=j.useRef(null),m=Array.from(new Set(t.map(v=>v.category))).filter(Boolean),f=()=>{c({...p_t,sort_order:t.length}),l(!0)},g=v=>{c({id:v.id,title:v.title,description:v.description||"",category:v.category||"Resources",resource_kind:v.resource_kind,url:v.url||"",file_path:v.file_path||"",status:v.status,sort_order:v.sort_order}),l(!0)},x=async v=>{if(!(!v||!s)){if(v.size>50*1024*1024)return re.error("File must be under 50MB");u(!0);try{const b=v.name.split(".").pop()||"pdf",w=`programs/${s}/resources/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${b}`,{error:S}=await q.storage.from(mK).upload(w,v,{contentType:v.type||"application/pdf",upsert:!1});if(S)throw S;c(A=>({...A,file_path:w,url:"",title:A.title||v.name.replace(/\.[^.]+$/,""),resource_kind:v.type==="application/pdf"?"pdf":A.resource_kind})),re.success("File uploaded")}catch(b){re.error(b.message||"Upload failed")}finally{u(!1),h.current&&(h.current.value="")}}},y=async()=>{if(!o.title.trim())return re.error("Give the resource a title");if(!o.file_path&&!o.url.trim())return re.error("Upload a file or paste a link");await r.mutateAsync({...o,sort_order:Number(o.sort_order)||0}),l(!1)};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Resources"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Upload PDFs, worksheets and checklists — or link to Canva/Google templates. Enrollees see them grouped by category in their program dashboard."})]}),e.jsxs($,{onClick:f,children:[e.jsx(dn,{className:"mr-1.5 h-4 w-4"})," Add resource"]})]}),n?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading resources…"}):t.length===0?e.jsx(je,{className:"border-dashed",children:e.jsxs(Ie,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(Jr,{className:"h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"font-medium",children:"No resources yet"}),e.jsx("p",{className:"max-w-md text-sm text-muted-foreground",children:"Add the swipe files, scripts and worksheets that make this program feel premium."})]})}):e.jsx("div",{className:"space-y-3",children:t.map(v=>{const b=nie(v);return e.jsx(je,{className:"border-border/60",children:e.jsxs(Ie,{className:"flex flex-wrap items-start justify-between gap-4 p-5",children:[e.jsxs("div",{className:"min-w-0 space-y-1.5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"font-medium",children:v.title}),e.jsx($e,{variant:"secondary",children:v.category}),e.jsx($e,{variant:"outline",className:"capitalize",children:v.resource_kind.replace("_"," ")}),v.status!=="published"&&e.jsx($e,{variant:"outline",className:"capitalize",children:v.status})]}),v.description&&e.jsx("p",{className:"max-w-2xl text-sm text-muted-foreground",children:v.description}),b&&e.jsxs("button",{type:"button",onClick:()=>Nee(v),className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(Fr,{className:"h-3 w-3"})," Open"]})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>g(v),children:e.jsx(pi,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:async()=>{await fo(`Remove "${v.title}"?`)&&a.mutate(v)},children:e.jsx(Hn,{className:"h-4 w-4 text-destructive"})})]})]})},v.id)})}),e.jsx(zs,{open:i,onOpenChange:l,children:e.jsxs(Os,{className:"max-w-lg",children:[e.jsx(Us,{children:e.jsx(Bs,{children:o.id?"Edit resource":"Add resource"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Title"}),e.jsx(pe,{value:o.title,onChange:v=>c({...o,title:v.target.value}),placeholder:"90-Day Content Calendar"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Description"}),e.jsx(Ls,{rows:2,value:o.description,onChange:v=>c({...o,description:v.target.value}),placeholder:"What this is and how to use it"})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Category"}),e.jsx(pe,{value:o.category,onChange:v=>c({...o,category:v.target.value}),placeholder:"Getting started",list:"program-resource-categories"}),e.jsx("datalist",{id:"program-resource-categories",children:m.map(v=>e.jsx("option",{value:v},v))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Type"}),e.jsxs(ms,{value:o.resource_kind,onValueChange:v=>c({...o,resource_kind:v}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:qUt.map(v=>e.jsx(Ge,{value:v.value,children:v.label},v.value))})]})]})]}),e.jsxs("div",{className:"space-y-2 rounded-lg border p-3",children:[e.jsx(ee,{children:"File"}),e.jsx("input",{ref:h,type:"file",className:"hidden",accept:".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.csv,.zip,image/*",onChange:v=>{var b;return x((b=v.target.files)==null?void 0:b[0])}}),o.file_path?e.jsxs("div",{className:"flex items-center justify-between gap-2 text-sm",children:[e.jsx("span",{className:"truncate",children:o.file_path.split("/").pop()}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>c({...o,file_path:""}),children:"Remove"})]}):e.jsxs($,{variant:"outline",size:"sm",onClick:()=>{var v;return(v=h.current)==null?void 0:v.click()},disabled:d,children:[d?e.jsx(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:v=>c({...o,url:v.target.value,file_path:""}),placeholder:"https://…",disabled:!!o.file_path})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Status"}),e.jsxs(ms,{value:o.status,onValueChange:v=>c({...o,status:v}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"published",children:"Published (visible)"}),e.jsx(Ge,{value:"draft",children:"Draft (hidden)"}),e.jsx(Ge,{value:"archived",children:"Archived"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Sort order"}),e.jsx(pe,{type:"number",value:o.sort_order,onChange:v=>c({...o,sort_order:v.target.value})})]})]})]}),e.jsxs(Sr,{children:[e.jsx($,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsxs($,{onClick:y,disabled:r.isPending||d,children:[r.isPending&&e.jsx(Ct,{className:"mr-1.5 h-4 w-4 animate-spin"})," Save resource"]})]})]})})]})},hrn=({programId:s})=>{const{data:t=[],isLoading:n}=JGs(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(Ie,{className:"flex items-center gap-3 p-4",children:[e.jsx(ZS,{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(Ie,{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(Ie,{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),re.success("Emails copied")},children:[e.jsx(Ha,{className:"mr-2 h-4 w-4"})," Copy emails"]}),e.jsxs($,{variant:"outline",size:"sm",disabled:!t.length,onClick:i,children:[e.jsx(xi,{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(En,{children:[e.jsx(Dt,{children:"Member"}),e.jsx(Dt,{children:"Email"}),e.jsx(Dt,{children:"Phone"}),e.jsx(Dt,{children:"Brokerage"}),e.jsx(Dt,{children:"Joined"})]})}),e.jsx(fi,{children:t.map(l=>e.jsxs(En,{children:[e.jsx(_t,{className:"font-medium",children:l.full_name||"—"}),e.jsx(_t,{children:l.email||"—"}),e.jsx(_t,{children:l.phone||"—"}),e.jsx(_t,{children:l.brokerage||"—"}),e.jsx(_t,{className:"text-muted-foreground",children:th(l.created_at)})]},l.id))})]})})]})},g_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:""},mrn=()=>{const s=Wt(),[t,n]=j.useState(null),[r,a]=j.useState(!1),[i,l]=j.useState({...g_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:y=[]}=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:v=[]}=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;re.success("Program created"),a(!1),l({...g_t}),s.invalidateQueries({queryKey:["admin-programs"]})}catch(P){re.error(P.message||"Could not create the program")}finally{c(!1)}},S=async P=>{if(!x)return;const{error:R}=await q.from("programs").update(P).eq("id",x.id);if(R)return re.error(R.message);s.invalidateQueries({queryKey:["admin-programs"]})},A=async(P,R)=>{const{error:D}=await q.from("program_enrollments").update(R).eq("id",P);if(D)return re.error(D.message);re.success("Enrollment updated"),s.invalidateQueries({queryKey:["admin-program-enrollments"]})},E=async P=>{u(!0);const{data:R,error:D}=await q.functions.invoke("program-charge-due",{body:P?{enrollment_id:P}:{}});if(u(!1),D||R!=null&&R.error)return re.error((R==null?void 0:R.error)||(D==null?void 0:D.message));re.success(`Processed ${(R==null?void 0:R.processed)??0} charge(s)`),s.invalidateQueries({queryKey:["admin-program-enrollments"]})},I=P=>P==="paid"||P==="completed"?"default":P==="payment_failed"?"destructive":"secondary";return e.jsx(Vs,{children:e.jsxs("div",{className:"mx-auto w-full max-w-7xl space-y-6 p-4 md:p-8",children:[e.jsxs("header",{className:"flex flex-wrap items-end justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Programs"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Manage cohorts, enrollments, delayed billing and program content."})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{variant:"outline",onClick:()=>E(),disabled:d,children:[d?e.jsx(Ct,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(Nv,{className:"mr-1.5 h-4 w-4"}),"Run due charges"]}),e.jsxs(zs,{open:r,onOpenChange:a,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{children:[e.jsx(dn,{className:"mr-1.5 h-4 w-4"})," New program"]})}),e.jsxs(Os,{className:"max-h-[85vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Create a program"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Name"}),e.jsx(pe,{value:i.name,onChange:P=>l({...i,name:P.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Slug (URL)"}),e.jsx(pe,{placeholder:"reel-estate-90",value:i.slug,onChange:P=>l({...i,slug:P.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Subtitle"}),e.jsx(pe,{value:i.subtitle,onChange:P=>l({...i,subtitle:P.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Description"}),e.jsx(Ls,{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(Sr,{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(Ie,{className:"p-12 text-center text-sm text-muted-foreground",children:"No programs yet. Create your first cohort to get started."})}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex flex-wrap gap-2",children:f.map(P=>e.jsxs($,{variant:(x==null?void 0:x.id)===P.id?"default":"outline",size:"sm",onClick:()=>n(P.id),children:[P.name,e.jsx($e,{variant:"secondary",className:"ml-2 capitalize",children:P.status})]},P.id))}),x&&e.jsxs(ha,{defaultValue:"overview",children:[e.jsxs(ma,{className:"flex w-full flex-wrap justify-start",children:[e.jsx(Zt,{value:"overview",children:"Overview"}),e.jsx(Zt,{value:"details",children:"Details & pricing"}),e.jsx(Zt,{value:"sessions",children:"Live sessions"}),e.jsx(Zt,{value:"videos",children:"On-demand videos"}),e.jsx(Zt,{value:"resources",children:"Resources"}),e.jsx(Zt,{value:"intake-form",children:"Intake form"}),e.jsx(Zt,{value:"discounts",children:"Discount codes"}),e.jsx(Zt,{value:"experience",children:"Enrollee experience"}),e.jsx(Zt,{value:"interest",children:"Interest list"}),e.jsxs(Zt,{value:"enrollments",children:["Enrollments (",y.length,")"]}),e.jsxs(Zt,{value:"intake",children:["Intake (",v.length,")"]}),e.jsx(Zt,{value:"audit",children:"Audit"})]}),e.jsxs(Xt,{value:"overview",className:"mt-6 space-y-4",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsx(je,{children:e.jsxs(Ie,{className:"p-5",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Seats filled"}),e.jsxs("p",{className:"mt-1 text-2xl font-bold",children:[y.filter(P=>["reserved","scheduled_for_charge","paid","completed"].includes(P.status)).length,e.jsxs("span",{className:"text-base font-normal text-muted-foreground",children:[" / ",x.capacity]})]})]})}),e.jsx(je,{children:e.jsxs(Ie,{className:"p-5",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Paid"}),e.jsx("p",{className:"mt-1 text-2xl font-bold",children:y.filter(P=>P.status==="paid").length})]})}),e.jsx(je,{children:e.jsxs(Ie,{className:"p-5",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Failed payments"}),e.jsx("p",{className:"mt-1 text-2xl font-bold",children:y.filter(P=>P.status==="payment_failed").length})]})}),e.jsx(je,{children:e.jsxs(Ie,{className:"p-5",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Projected revenue (one-time)"}),e.jsx("p",{className:"mt-1 text-2xl font-bold",children:Sg(y.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(Ie,{className:"space-y-5 p-6",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Publish this program"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Published programs appear on the member Programs page."})]}),e.jsx(Sn,{checked:x.status==="published",onCheckedChange:P=>S({status:P?"published":"draft"})})]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4 border-t border-border/60 pt-5",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Feature it"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Pins the program to the top."})]}),e.jsx(Sn,{checked:x.is_featured,onCheckedChange:P=>S({is_featured:P})})]}),e.jsxs("div",{className:"grid gap-4 border-t border-border/60 pt-5 sm:grid-cols-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"One-time price"}),e.jsx("p",{className:"font-medium",children:Sg(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(Xt,{value:"details",className:"mt-6",children:e.jsx(Ynn,{program:x,onSaved:()=>s.invalidateQueries({queryKey:["admin-programs"]})})}),e.jsx(Xt,{value:"sessions",className:"mt-6",children:e.jsx(crn,{programId:x.id})}),e.jsx(Xt,{value:"videos",className:"mt-6",children:e.jsx(drn,{programId:x.id})}),e.jsx(Xt,{value:"resources",className:"mt-6",children:e.jsx(urn,{programId:x.id})}),e.jsx(Xt,{value:"discounts",className:"mt-6",children:e.jsx(Qnn,{program:x})}),e.jsx(Xt,{value:"intake-form",className:"mt-6",children:e.jsx(srn,{program:x,onSaved:()=>s.invalidateQueries({queryKey:["admin-programs"]})})}),e.jsx(Xt,{value:"experience",className:"mt-6",children:e.jsx(Jnn,{program:x})}),e.jsx(Xt,{value:"interest",className:"mt-6",children:e.jsx(hrn,{programId:x.id})}),e.jsx(Xt,{value:"enrollments",className:"mt-6",children:e.jsx(je,{children:e.jsx(Ie,{className:"overflow-x-auto p-0",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Member"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{children:"Charge date"}),e.jsx(Dt,{children:"Amount"}),e.jsx(Dt,{children:"Access"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsxs(fi,{children:[y.length===0&&e.jsx(En,{children:e.jsxs(_t,{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"]})}),y.map(P=>{var R,D;return e.jsxs(En,{children:[e.jsx(_t,{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(_t,{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(_t,{className:"text-sm",children:th(P.charge_scheduled_at)||"—"}),e.jsx(_t,{className:"text-sm",children:Sg(P.amount_cents,P.currency)}),e.jsx(_t,{children:e.jsx(Sn,{checked:P.access_override,onCheckedChange:O=>A(P.id,{access_override:O})})}),e.jsxs(_t,{className:"space-x-2 text-right",children:[["scheduled_for_charge","payment_failed"].includes(P.status)&&e.jsxs($,{size:"sm",variant:"outline",onClick:()=>E(P.id),disabled:d,children:[e.jsx(ro,{className:"mr-1.5 h-3.5 w-3.5"})," Charge now"]}),!["canceled","refunded"].includes(P.status)&&e.jsx($,{size:"sm",variant:"ghost",onClick:()=>A(P.id,{status:"canceled",canceled_at:new Date().toISOString()}),children:"Cancel"})]})]},P.id)})]})]})})})}),e.jsx(Xt,{value:"intake",className:"mt-6",children:e.jsx(irn,{program:x})}),e.jsx(Xt,{value:"audit",className:"mt-6",children:e.jsx(je,{children:e.jsxs(Ie,{className:"space-y-2 p-5 text-sm",children:[b.length===0&&e.jsx("p",{className:"text-muted-foreground",children:"No activity yet."}),b.map(P=>e.jsxs("div",{className:"flex flex-wrap items-center gap-2 border-b border-border/40 py-2 last:border-0",children:[e.jsx($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(Xnn,{program:x,enrollment:h,open:!!h,onOpenChange:P=>!P&&m(null),onUpdated:()=>s.invalidateQueries({queryKey:["admin-program-enrollments"]})})]})]})})},frn=()=>{const{user:s}=bs(),[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(v=>({...v,resources:(g==null?void 0:g.filter(b=>b.video_id===v.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(Zr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search videos...",value:t,onChange:m=>n(m.target.value),className:"pl-10"})]})}),e.jsx(ha,{value:r,onValueChange:a,children:e.jsxs(ma,{className:"w-full justify-start flex-wrap h-auto gap-2 bg-transparent p-0",children:[e.jsx(Zt,{value:"all",className:"data-[state=active]:bg-primary data-[state=active]:text-primary-foreground",children:"All Videos"}),i.map(m=>e.jsx(Zt,{value:m.id,className:"data-[state=active]:bg-primary data-[state=active]:text-primary-foreground",children:m.name},m.id))]})}),o?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):d.length===0?e.jsx(je,{children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(ua,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold",children:"No videos found"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:t?"Try adjusting your search terms":"Check back soon for new content"})]})}):e.jsx("div",{className:"grid gap-6 sm:grid-cols-2 lg:grid-cols-3",children:d.map(m=>e.jsx(wr,{to:`/academy/${m.id}`,children:e.jsxs(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(ua,{className:"h-12 w-12 text-muted-foreground"})}),e.jsx("div",{className:"absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center",children:e.jsx("div",{className:"w-16 h-16 rounded-full bg-primary/90 flex items-center justify-center",children:e.jsx(zu,{className:"h-8 w-8 text-primary-foreground ml-1"})})}),m.duration&&e.jsxs("div",{className:"absolute bottom-2 right-2 bg-black/70 text-white text-xs px-2 py-1 rounded flex items-center gap-1",children:[e.jsx(da,{className:"h-3 w-3"}),m.duration]})]}),e.jsxs(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(Ie,{className:"pt-0",children:[m.description&&e.jsx(Gn,{className:"line-clamp-2",children:m.description.replace(/<[^>]*>/g,"")}),e.jsxs("div",{className:"flex items-center gap-4 mt-3 text-sm text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(qy,{className:`h-4 w-4 ${h(m.id)?"fill-primary text-primary":""}`}),u(m.id)]}),m.resources&&m.resources.length>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Jr,{className:"h-4 w-4"}),m.resources.length]})]})]})]})},m.id))})]})})};function PHt({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(wr,{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 prn=(s,t)=>{if(t==="bunny_stream"){let n=s.replace("iframe.mediadelivery.net","player.mediadelivery.net");return n.includes("?")||(n+="?autoplay=false&loop=false&muted=false&preload=true&responsive=true"),n}if(t==="youtube"){const n=/(?: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},grn=()=>{const{videoId:s}=Wi();Xn();const{user:t,isAdmin:n}=bs(),{toast:r}=Bi(),a=Wt(),{trackEngagement:i}=hK(),[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)),y=w=>{switch(w==null?void 0:w.toLowerCase()){case"pdf":return"📄";case"pptx":case"ppt":return"📊";case"xlsx":case"xls":return"📈";case"docx":case"doc":return"📝";case"zip":return"📦";default:return"📁"}},v=w=>w.split(" ").map(S=>S[0]).join("").toUpperCase().slice(0,2),b=w=>{w.preventDefault(),!(!l.trim()||!t)&&m.mutate(l.trim())};return d?e.jsx(Vs,{title:"Academy",children:e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):c?e.jsx(Vs,{title:c.title,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx($,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(wr,{to:"/academy",children:[e.jsx(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:prn(c.video_url,c.video_type),loading:"lazy",style:{border:0,position:"absolute",top:0,left:0,height:"100%",width:"100%"},allow:"accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture",allowFullScreen:!0}):e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center text-white gap-4",children:[e.jsx(ua,{className:"h-16 w-16 opacity-50"}),e.jsx($,{variant:"secondary",asChild:!0,children:e.jsxs("a",{href:c.video_url,target:"_blank",rel:"noopener noreferrer",className:"gap-2",children:[e.jsx(Fr,{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(wr,{to:`/admin/academy?edit=${c.id}`,children:[e.jsx(pi,{className:"h-4 w-4"}),e.jsx("span",{children:"Edit"})]})}),e.jsx(pK,{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(qy,{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(Ie,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Jr,{className:"h-4 w-4"}),"Resources"]}),e.jsx("div",{className:"grid gap-2",children:c.resources.map(w=>e.jsxs("a",{href:w.file_url,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-3 p-3 rounded-lg border hover:bg-muted transition-colors",children:[e.jsx("span",{className:"text-2xl",children:y(w.file_type)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:w.title}),e.jsx("p",{className:"text-xs text-muted-foreground uppercase",children:w.file_type})]}),e.jsx(xi,{className:"h-4 w-4 text-muted-foreground"})]},w.id))})]})}),e.jsx(PHt,{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(Ls,{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(Kr,{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(Ie,{className:"py-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No comments yet. Be the first to share your thoughts!"})})}):h.map(w=>e.jsx(je,{children:e.jsx(Ie,{className:"pt-4 pb-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Oa,{className:"h-10 w-10 flex-shrink-0",children:e.jsx(za,{className:"text-sm",children:v(w.user_name||"U")})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-medium",children:w.user_name}),e.jsx("span",{className:"text-sm text-muted-foreground",children: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(Hn,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:w.content})]})]})})},w.id))})]})]})}):e.jsx(Vs,{title:"Academy",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(ua,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold",children:"Video not found"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"This video may have been removed or is not available."}),e.jsx($,{asChild:!0,className:"mt-4",children:e.jsx(wr,{to:"/academy",children:"Back to Academy"})})]})})},S$="https://dashboard.relevelup.com",xrn=(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},yrn=[{icon:ef,title:"100+ Training Videos",desc:"On-demand LevelUp Academy content covering lead gen, listings, buyer conversion, marketing, and more."},{icon:eg,title:"Marketing Studio & Tools",desc:"AI-powered marketing tools, listing videos, landing pages, and social content — done for you."},{icon: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 vrn(){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?xrn(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:S$,children:e.jsx($,{className:"bg-[#406E71] hover:bg-[#4d8285] text-white",children:"Go to LevelUp"})})]}):e.jsxs("div",{className:"min-h-screen bg-[#0a1520] text-[#e8ecf1] overflow-x-hidden",children:[e.jsxs("div",{className:"pointer-events-none fixed inset-0 z-0",children:[e.jsx("div",{className:"absolute -top-40 -left-40 w-[600px] h-[600px] rounded-full bg-[#406E71]/20 blur-3xl"}),e.jsx("div",{className:"absolute top-1/2 -right-40 w-[500px] h-[500px] rounded-full bg-[#2a4c64]/30 blur-3xl"}),e.jsx("div",{className:"absolute bottom-0 left-1/3 w-[400px] h-[400px] rounded-full bg-[#406E71]/10 blur-3xl"})]}),e.jsx("header",{className:"relative z-10 border-b border-white/5 backdrop-blur-sm bg-[#0a1520]/70",children:e.jsxs("div",{className:"max-w-7xl mx-auto px-6 py-5 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-gradient-to-br from-[#406E71] to-[#2a4c64] flex items-center justify-center",children:e.jsx(Nn,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-lg tracking-tight",children:"LevelUp"}),e.jsx("div",{className:"text-[10px] uppercase tracking-widest text-[#5a9ea1] -mt-1",children:"Academy"})]})]}),e.jsx("a",{href:S$,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(qg,{className:"w-10 h-10 mx-auto mb-4 text-[#7ec0c3]"}),e.jsxs("h2",{className:"text-3xl md:text-4xl font-bold mb-3",children:["This is just ",e.jsx("span",{className:"text-[#7ec0c3]",children:"one"})," of hundreds."]}),e.jsx("p",{className:"text-[#c5d3de] text-lg mb-8 max-w-2xl mx-auto",children:"LevelUp members get unlimited access to the full Academy, AI marketing tools, coaching, and everything you need to grow your real estate business."}),e.jsxs("div",{className:"flex flex-col sm:flex-row items-center justify-center gap-3",children:[e.jsx("a",{href:S$,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:S$,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:yrn.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:S$,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:S$,className:"hover:text-[#7ec0c3]",children:"dashboard.relevelup.com"})]})]})}function brn(){const s=Xn(),[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(Zr,{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(Ie,{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),y=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(Ie,{className:"p-4",children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 mb-1",children:f.name}),f.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3",children:zte(f.description)}),e.jsxs("div",{className:"flex items-center justify-between text-sm text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Jr,{className:"h-4 w-4"}),g," file",g!==1?"s":""]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(qy,{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"}),y]})]})]})]})]},f.id)})})]})})}const _rn=()=>{const{kitId:s}=Wi(),{user:t,isAdmin:n}=bs(),{toast:r}=Bi(),a=Wt(),{trackEngagement:i}=hK(),[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)),y=w=>w.split(" ").map(S=>S[0]).join("").toUpperCase().slice(0,2),v=w=>w?w<1024?w+" B":w<1024*1024?(w/1024).toFixed(1)+" KB":(w/(1024*1024)).toFixed(1)+" MB":"",b=w=>{w.preventDefault(),!(!l.trim()||!t)&&m.mutate(l.trim())};return d?e.jsx(Vs,{title:"Toolbox",children:e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):c?e.jsx(Vs,{title:c.name,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx($,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(wr,{to:"/toolbox",children:[e.jsx(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(wr,{to:`/admin/toolbox?edit=${c.id}`,children:[e.jsx(pi,{className:"h-4 w-4"}),e.jsx("span",{children:"Edit"})]})}),e.jsx(pK,{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(qy,{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(Ie,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Jr,{className:"h-4 w-4"}),"Included Resources (",c.files.length,")"]}),e.jsx("div",{className:"grid gap-2",children:c.files.map(w=>e.jsxs("a",{href:w.file_url,target:"_blank",rel:"noopener noreferrer",onClick:()=>i("toolbox",c.id,c.name,"click_pdf"),className:"flex items-center justify-between p-3 rounded-lg border hover:bg-muted transition-colors group",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-md bg-primary/10",children:e.jsx(Jr,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:w.name}),w.file_size&&e.jsx("div",{className:"text-xs text-muted-foreground",children:v(w.file_size)})]})]}),e.jsx(xi,{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(Ie,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Fr,{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(Fr,{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(PHt,{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(Ls,{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(Kr,{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(Ie,{className:"py-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No comments yet. Be the first to share your thoughts!"})})}):h.map(w=>e.jsx(je,{children:e.jsx(Ie,{className:"pt-4 pb-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Oa,{className:"h-10 w-10 flex-shrink-0",children:e.jsx(za,{className:"text-sm",children:y(w.user_name||"U")})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-medium",children:w.user_name}),e.jsx("span",{className:"text-sm text-muted-foreground",children: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(Hn,{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(wr,{to:"/toolbox",children:"Back to Toolbox"})})]})})},wrn=()=>{const s=Xn(),[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 y=new Map;return g==null||g.forEach(b=>{y.set(b.swag_id,(y.get(b.swag_id)||0)+1)}),(d||[]).map(b=>({...b,links:(h||[]).filter(w=>w.swag_id===b.id)||[],likesCount:x.get(b.id)||0,commentsCount:y.get(b.id)||0}))}}),o=i.filter(d=>{var h;return d.title.toLowerCase().includes(t.toLowerCase())||((h=d.description)==null?void 0:h.toLowerCase().includes(t.toLowerCase()))}),c=d=>{s(`/social-swag/${d}`)};return e.jsx(Vs,{title:"Social Swag",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Social Swag"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Browse our collection of social media content and graphics"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(Zr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search social swag...",value:t,onChange:d=>n(d.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex gap-2",children:[t&&e.jsx($,{variant:"outline",size:"sm",onClick:()=>n(""),children:"Clear"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{variant:r==="grid"?"secondary":"outline",size:"icon",onClick:()=>a("grid"),className:"rounded-full",children:e.jsx(Qf,{className:"h-4 w-4"})}),e.jsx($,{variant:r==="list"?"secondary":"outline",size:"icon",onClick:()=>a("list"),className:"rounded-full",children:e.jsx(T0,{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(Ie,{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(Ie,{className:`p-4 flex flex-col ${r==="list"?"flex-1":""}`,children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 mb-1",children:d.title}),d.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3 flex-1",children:d.description.replace(/<[^>]*>/g,"")}),e.jsxs("div",{className:"flex items-center gap-4 text-sm text-muted-foreground mb-3",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(qy,{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(Fr,{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(tan,{displayMonth:s.displayMonth,hideNext:u,hidePrevious:h,nextMonth:a,previousMonth:r,onPreviousClick:m,onNextClick:f})}function san(s){var t,n=sp(),r=n.classNames,a=n.disableNavigation,i=n.styles,l=n.captionLayout,o=n.components,c=(t=o==null?void 0:o.CaptionLabel)!==null&&t!==void 0?t:RHt,d;return a?d=e.jsx(c,{id:s.id,displayMonth:s.displayMonth}):l==="dropdown"?d=e.jsx(x_t,{displayMonth:s.displayMonth,id:s.id}):l==="dropdown-buttons"?d=e.jsxs(e.Fragment,{children:[e.jsx(x_t,{displayMonth:s.displayMonth,displayIndex:s.displayIndex,id:s.id}),e.jsx(y_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(y_t,{displayMonth:s.displayMonth,id:s.id})]}),e.jsx("div",{className:r.caption,style:i.caption,children:d})}function nan(s){var t=sp(),n=t.footer,r=t.styles,a=t.classNames.tfoot;return n?e.jsx("tfoot",{className:a,style:r.tfoot,children:e.jsx("tr",{children:e.jsx("td",{colSpan:8,children:n})})}):e.jsx(e.Fragment,{})}function ran(s,t,n){for(var r=n?uT(new Date):j1(new Date,{locale:s,weekStartsOn:t}),a=[],i=0;i<7;i++){var l=Am(r,i);a.push(l)}return a}function aan(){var s=sp(),t=s.classNames,n=s.styles,r=s.showWeekNumber,a=s.locale,i=s.weekStartsOn,l=s.ISOWeek,o=s.formatters.formatWeekdayName,c=s.labels.labelWeekday,d=ran(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 ian(){var s,t=sp(),n=t.classNames,r=t.styles,a=t.components,i=(s=a==null?void 0:a.HeadRow)!==null&&s!==void 0?s:aan;return e.jsx("thead",{style:r.head,className:n.head,children:e.jsx(i,{})})}function oan(s){var t=sp(),n=t.locale,r=t.formatters.formatDay;return e.jsx(e.Fragment,{children:r(s.date,{locale:n})})}var art=j.createContext(void 0);function lan(s){if(!hie(s.initialProps)){var t={selected:void 0,modifiers:{disabled:[]}};return e.jsx(art.Provider,{value:t,children:s.children})}return e.jsx(can,{initialProps:s.initialProps,children:s.children})}function can(s){var t=s.initialProps,n=s.children,r=t.selected,a=t.min,i=t.max,l=function(d,u,h){var m,f;(m=t.onDayClick)===null||m===void 0||m.call(t,d,u,h);var g=!!(u.selected&&a&&(r==null?void 0:r.length)===a);if(!g){var x=!!(!u.selected&&i&&(r==null?void 0:r.length)===i);if(!x){var y=r?IHt([],r):[];if(u.selected){var v=y.findIndex(function(b){return sf(d,b)});y.splice(v,1)}else y.push(d);(f=t.onSelect)===null||f===void 0||f.call(t,y,d,u,h)}}},o={disabled:[]};r&&o.disabled.push(function(d){var u=i&&r.length>i-1,h=r.some(function(m){return sf(m,d)});return!!(u&&!h)});var c={selected:r,onDayClick:l,modifiers:o};return e.jsx(art.Provider,{value:c,children:n})}function irt(){var s=j.useContext(art);if(!s)throw new Error("useSelectMultiple must be used within a SelectMultipleProvider");return s}function dan(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:R4(r,s)?{from:s,to:a}:{from:r,to:s}:a?R4(s,a)?{from:a,to:s}:{from:s,to:a}:r?rC(s,r)?{from:s,to:r}:{from:r,to:s}:{from:s,to:void 0}}var ort=j.createContext(void 0);function uan(s){if(!mie(s.initialProps)){var t={selected:void 0,modifiers:{range_start:[],range_end:[],range_middle:[],disabled:[]}};return e.jsx(ort.Provider,{value:t,children:s.children})}return e.jsx(han,{initialProps:s.initialProps,children:s.children})}function han(s){var t=s.initialProps,n=s.children,r=t.selected,a=r||{},i=a.from,l=a.to,o=t.min,c=t.max,d=function(f,g,x){var y,v;(y=t.onDayClick)===null||y===void 0||y.call(t,f,g,x);var b=dan(f,r);(v=t.onSelect)===null||v===void 0||v.call(t,b,f,g,x)},u={range_start:[],range_end:[],range_middle:[],disabled:[]};if(i?(u.range_start=[i],l?(u.range_end=[l],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:Y4e(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:Y4e(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=ub(l,i)+1,m=c-h;u.disabled.push({before:Y4e(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(ort.Provider,{value:{selected:r,onDayClick:d,modifiers:u},children:n})}function lrt(){var s=j.useContext(ort);if(!s)throw new Error("useSelectRange must be used within a SelectRangeProvider");return s}function x3e(s){return Array.isArray(s)?IHt([],s):s!==void 0?[s]:[]}function man(s){var t={};return Object.entries(s).forEach(function(n){var r=n[0],a=n[1];t[r]=x3e(a)}),t}var gC;(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"})(gC||(gC={}));var fan=gC.Selected,eA=gC.Disabled,pan=gC.Hidden,gan=gC.Today,MBe=gC.RangeEnd,PBe=gC.RangeMiddle,IBe=gC.RangeStart,xan=gC.Outside;function yan(s,t,n){var r,a=(r={},r[fan]=x3e(s.selected),r[eA]=x3e(s.disabled),r[pan]=x3e(s.hidden),r[gan]=[s.today],r[MBe]=[],r[PBe]=[],r[IBe]=[],r[xan]=[],r);return s.fromDate&&a[eA].push({before:s.fromDate}),s.toDate&&a[eA].push({after:s.toDate}),hie(s)?a[eA]=a[eA].concat(t.modifiers[eA]):mie(s)&&(a[eA]=a[eA].concat(n.modifiers[eA]),a[IBe]=n.modifiers[IBe],a[PBe]=n.modifiers[PBe],a[MBe]=n.modifiers[MBe]),a}var OHt=j.createContext(void 0);function van(s){var t=sp(),n=irt(),r=lrt(),a=yan(t,n,r),i=man(t.modifiers),l=Cc(Cc({},a),i);return e.jsx(OHt.Provider,{value:l,children:s.children})}function zHt(){var s=j.useContext(OHt);if(!s)throw new Error("useModifiers must be used within a ModifiersProvider");return s}function ban(s){return!!(s&&typeof s=="object"&&"before"in s&&"after"in s)}function _an(s){return!!(s&&typeof s=="object"&&"from"in s)}function wan(s){return!!(s&&typeof s=="object"&&"after"in s)}function jan(s){return!!(s&&typeof s=="object"&&"before"in s)}function Nan(s){return!!(s&&typeof s=="object"&&"dayOfWeek"in s)}function kan(s,t){var n,r=t.from,a=t.to;if(r&&a){var i=ub(a,r)<0;i&&(n=[a,r],r=n[0],a=n[1]);var l=ub(s,r)>=0&&ub(a,s)>=0;return l}return a?sf(a,s):r?sf(r,s):!1}function San(s){return btt(s)}function Can(s){return Array.isArray(s)&&s.every(btt)}function Aan(s,t){return t.some(function(n){if(typeof n=="boolean")return n;if(San(n))return sf(s,n);if(Can(n))return n.includes(s);if(_an(n))return kan(s,n);if(Nan(n))return n.dayOfWeek.includes(s.getDay());if(ban(n)){var r=ub(n.before,s),a=ub(n.after,s),i=r>0,l=a<0,o=R4(n.before,n.after);return o?l&&i:i||l}return wan(n)?ub(s,n.after)>0:jan(n)?ub(n.before,s)>0:typeof n=="function"?n(s):!1})}function crt(s,t,n){var r=Object.keys(t).reduce(function(i,l){var o=t[l];return Aan(s,o)&&i.push(l),i},[]),a={};return r.forEach(function(i){return a[i]=!0}),n&&!Oae(s,n)&&(a.outside=!0),a}function Ean(s,t){for(var n=Zm(s[0]),r=hw(s[s.length-1]),a,i,l=n;l<=r;){var o=crt(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 Tan=365;function BHt(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:a8,month:Ev,year:JMs,startOfWeek:function(y){return a.ISOWeek?uT(y):j1(y,{locale:h,weekStartsOn:c})},endOfWeek:function(y){return a.ISOWeek?Nzt(y):PLe(y,{locale:h,weekStartsOn:c})}},f=m[n](s,r==="after"?1:-1);r==="before"&&d?f=ePs([d,f]):r==="after"&&u&&(f=tPs([u,f]));var g=!0;if(i){var x=crt(f,i);g=!x.disabled&&!x.hidden}return g?f:o.count>Tan?o.lastFocused:BHt(f,{moveBy:n,direction:r,context:a,modifiers:i,retry:Cc(Cc({},o),{count:o.count+1})})}var $Ht=j.createContext(void 0);function Man(s){var t=fie(),n=zHt(),r=j.useState(),a=r[0],i=r[1],l=j.useState(),o=l[0],c=l[1],d=Ean(t.displayMonths,n),u=a??(o&&t.isDateDisplayed(o))?o:d,h=function(){c(a),i(void 0)},m=function(y){i(y)},f=sp(),g=function(y,v){if(a){var b=BHt(a,{moveBy:y,direction:v,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($Ht.Provider,{value:x,children:s.children})}function drt(){var s=j.useContext($Ht);if(!s)throw new Error("useFocusContext must be used within a FocusProvider");return s}function Pan(s,t){var n=zHt(),r=crt(s,n,t);return r}var urt=j.createContext(void 0);function Ian(s){if(!Q6e(s.initialProps)){var t={selected:void 0};return e.jsx(urt.Provider,{value:t,children:s.children})}return e.jsx(Lan,{initialProps:s.initialProps,children:s.children})}function Lan(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(urt.Provider,{value:a,children:n})}function UHt(){var s=j.useContext(urt);if(!s)throw new Error("useSelectSingle must be used within a SelectSingleProvider");return s}function Ran(s,t){var n=sp(),r=UHt(),a=irt(),i=lrt(),l=drt(),o=l.focusDayAfter,c=l.focusDayBefore,d=l.focusWeekAfter,u=l.focusWeekBefore,h=l.blur,m=l.focus,f=l.focusMonthBefore,g=l.focusMonthAfter,x=l.focusYearBefore,y=l.focusYearAfter,v=l.focusStartOfWeek,b=l.focusEndOfWeek,w=function(X){var ae,le,ne,te;Q6e(n)?(ae=r.onDayClick)===null||ae===void 0||ae.call(r,s,t,X):hie(n)?(le=a.onDayClick)===null||le===void 0||le.call(a,s,t,X):mie(n)?(ne=i.onDayClick)===null||ne===void 0||ne.call(i,s,t,X):(te=n.onDayClick)===null||te===void 0||te.call(n,s,t,X)},S=function(X){var ae;m(s),(ae=n.onDayFocus)===null||ae===void 0||ae.call(n,s,t,X)},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?y():g();break;case"Home":X.preventDefault(),X.stopPropagation(),v();break;case"End":X.preventDefault(),X.stopPropagation(),b();break}(ae=n.onDayKeyDown)===null||ae===void 0||ae.call(n,s,t,X)},Y={onClick:w,onFocus:S,onBlur:A,onKeyDown:G,onKeyUp:V,onMouseEnter:E,onMouseLeave:I,onPointerEnter:P,onPointerLeave:R,onTouchCancel:D,onTouchEnd:O,onTouchMove:U,onTouchStart:W};return Y}function Dan(){var s=sp(),t=UHt(),n=irt(),r=lrt(),a=Q6e(s)?t.selected:hie(s)?n.selected:mie(s)?r.selected:void 0;return a}function Fan(s){return Object.values(gC).includes(s)}function Oan(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(Fan(r)){var i=s.classNames["day_".concat(r)];i&&n.push(i)}}),n}function zan(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 Ban(s,t,n){var r,a,i,l=sp(),o=drt(),c=Pan(s,t),d=Ran(s,c),u=Dan(),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=Oan(l,c).join(" "),f=zan(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:oan,y=e.jsx(x,{date:s,displayMonth:t,activeModifiers:c}),v={style:f,className:m,children:y,role:"gridcell"},b=o.focusTarget&&sf(o.focusTarget,s)&&!c.outside,w=o.focusedDay&&sf(o.focusedDay,s),S=Cc(Cc(Cc({},v),(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:v};return A}function $an(s){var t=j.useRef(null),n=Ban(s.date,s.displayMonth,t);return n.isHidden?e.jsx("div",{role:"gridcell"}):n.isButton?e.jsx(FTe,Cc({name:"day",ref:t},n.buttonProps)):e.jsx("div",Cc({},n.divProps))}function Uan(s){var t=s.number,n=s.dates,r=sp(),a=r.onWeekNumberClick,i=r.styles,l=r.classNames,o=r.locale,c=r.labels.labelWeekNumber,d=r.formatters.formatWeekNumber,u=d(Number(t),{locale:o});if(!a)return e.jsx("span",{className:l.weeknumber,style:i.weeknumber,children:u});var h=c(Number(t),{locale:o}),m=function(f){a(t,n,f)};return e.jsx(FTe,{name:"week-number","aria-label":h,className:l.weeknumber,style:i.weeknumber,onClick:m,children:u})}function qan(s){var t,n,r=sp(),a=r.styles,i=r.classNames,l=r.showWeekNumber,o=r.components,c=(t=o==null?void 0:o.Day)!==null&&t!==void 0?t:$an,d=(n=o==null?void 0:o.WeekNumber)!==null&&n!==void 0?n:Uan,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})},iIs(h))})]})}function v_t(s,t,n){for(var r=n!=null&&n.ISOWeek?Nzt(t):PLe(t,n),a=n!=null&&n.ISOWeek?uT(s):j1(s,n),i=ub(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?wtt(u):Ntt(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 Van(s,t){var n=v_t(Zm(s),hw(s),t);if(t!=null&&t.useFixedWeeks){var r=lIs(s,t);if(r<6){var a=n[n.length-1],i=a.dates[a.dates.length-1],l=a8(i,6-r),o=v_t(a8(i,1),l,t);n.push.apply(n,o)}}return n}function Han(s){var t,n,r,a=sp(),i=a.locale,l=a.classNames,o=a.styles,c=a.hideHead,d=a.fixedWeeks,u=a.components,h=a.weekStartsOn,m=a.firstWeekContainsDate,f=a.ISOWeek,g=Van(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:ian,y=(n=u==null?void 0:u.Row)!==null&&n!==void 0?n:qan,v=(r=u==null?void 0:u.Footer)!==null&&r!==void 0?r:nan;return e.jsxs("table",{id:s.id,className:l.table,style:o.table,role:"grid","aria-labelledby":s["aria-labelledby"],children:[!c&&e.jsx(x,{}),e.jsx("tbody",{className:l.tbody,style:o.tbody,children:g.map(function(b){return e.jsx(y,{displayMonth:s.displayMonth,dates:b.dates,weekNumber:b.weekNumber},b.weekNumber)})}),e.jsx(v,{displayMonth:s.displayMonth})]})}function Gan(){return!!(typeof window<"u"&&window.document&&window.document.createElement)}var Wan=Gan()?j.useLayoutEffect:j.useEffect,LBe=!1,Kan=0;function b_t(){return"react-day-picker-".concat(++Kan)}function Yan(s){var t,n=s??(LBe?b_t():null),r=j.useState(n),a=r[0],i=r[1];return Wan(function(){a===null&&i(b_t())},[]),j.useEffect(function(){LBe===!1&&(LBe=!0)},[]),(t=s??a)!==null&&t!==void 0?t:void 0}function Zan(s){var t,n,r=sp(),a=r.dir,i=r.classNames,l=r.styles,o=r.components,c=fie().displayMonths,d=Yan(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 y=(n=o==null?void 0:o.Caption)!==null&&n!==void 0?n:san;return e.jsxs("div",{className:h.join(" "),style:m,children:[e.jsx(y,{id:d,displayMonth:s.displayMonth,displayIndex:s.displayIndex}),e.jsx(Han,{id:u,"aria-labelledby":d,displayMonth:s.displayMonth})]},s.displayIndex)}function Xan(s){var t=sp(),n=t.classNames,r=t.styles;return e.jsx("div",{className:n.months,style:r.months,children:s.children})}function Qan(s){var t,n,r=s.initialProps,a=sp(),i=drt(),l=fie(),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 y;return Cc(Cc({},g),(y={},y[x]=r[x],y))},{}),f=(n=(t=r.components)===null||t===void 0?void 0:t.Months)!==null&&n!==void 0?n:Xan;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 Jan(s){var t=s.children,n=jrn(s,["children"]);return e.jsx(Urn,{initialProps:n,children:e.jsx(Qrn,{children:e.jsx(Ian,{initialProps:n,children:e.jsx(lan,{initialProps:n,children:e.jsx(uan,{initialProps:n,children:e.jsx(van,{children:e.jsx(Man,{children:t})})})})})})})}function ein(s){return e.jsx(Jan,Cc({},s,{children:e.jsx(Qan,{initialProps:s})}))}function T2({className:s,classNames:t,showOutsideDays:n=!0,...r}){return e.jsx(ein,{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(hG({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(hG({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})}T2.displayName="Calendar";var tin=Object.defineProperty,p6=(s,t)=>tin(s,"name",{value:t,configurable:!0}),hrt="Popover",[qHt,mSr]=tp(hrt,[r3]),mrt=r3(),[sin,gK]=qHt(hrt),nin=p6(s=>{const{__scopePopover:t,children:n,open:r,defaultOpen:a,onOpenChange:i,modal:l=!1}=s,o=mrt(t),c=j.useRef(null),[d,u]=j.useState(!1),[h,m]=hy({prop:r,defaultProp:a??!1,onChange:i,caller:hrt});return e.jsx(wae,{...o,children:e.jsx(sin,{scope:t,contentId:uy(),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"),rin="PopoverTrigger",ain=j.forwardRef(p6(function(t,n){const{__scopePopover:r,...a}=t,i=gK(rin,r),l=mrt(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":frt(i.open),...a,ref:o,onClick:Ra(t.onClick,i.onOpenToggle)});return i.hasCustomAnchor?c:e.jsx(jae,{asChild:!0,...l,children:c})},"PopoverTrigger")),VHt="PopoverPortal",[iin,oin]=qHt(VHt,{forceMount:void 0}),lin=p6(s=>{const{__scopePopover:t,forceMount:n,children:r,container:a}=s,i=gK(VHt,t);return e.jsx(iin,{scope:t,forceMount:n,children:e.jsx(py,{present:n||i.open,children:e.jsx(gae,{asChild:!0,container:a,children:r})})})},"PopoverPortal"),Nse="PopoverContent",cin=j.forwardRef(p6(function(t,n){const r=oin(Nse,t.__scopePopover),{forceMount:a=r.forceMount,...i}=t,l=gK(Nse,t.__scopePopover);return e.jsx(py,{present:a||l.open,children:l.modal?e.jsx(uin,{...i,ref:n}):e.jsx(hin,{...i,ref:n})})},"PopoverContent")),din=mC("PopoverContent.RemoveScroll"),uin=j.forwardRef(p6(function(t,n){const r=gK(Nse,t.__scopePopover),a=j.useRef(null),i=Vo(n,a),l=j.useRef(!1);return j.useEffect(()=>{const o=a.current;if(o)return VIe(o)},[]),e.jsx(yae,{as:din,allowPinchZoom:!0,children:e.jsx(HHt,{...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")),hin=j.forwardRef(p6(function(t,n){const r=gK(Nse,t.__scopePopover),a=j.useRef(!1),i=j.useRef(!1);return e.jsx(HHt,{...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")),HHt=j.forwardRef(p6(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=gK(Nse,r),g=mrt(r);return UW(),e.jsx(UIe,{asChild:!0,loop:!0,trapped:a,onMountAutoFocus:i,onUnmountAutoFocus:l,children:e.jsx(TB,{asChild:!0,disableOutsidePointerEvents:o,onInteractOutside:h,onEscapeKeyDown:c,onPointerDownOutside:d,onFocusOutside:u,onDismiss:()=>f.onOpenChange(!1),deferPointerDownOutside:!0,children:e.jsx(Nae,{"data-state":frt(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 frt(s){return s?"open":"closed"}p6(frt,"getState");var min=nin,fin=ain,pin=lin,GHt=cin;const Kd=min,Yd=fin,Od=j.forwardRef(({className:s,align:t="center",sideOffset:n=4,...r},a)=>e.jsx(pin,{children:e.jsx(GHt,{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})}));Od.displayName=GHt.displayName;async function kse(s){if(s instanceof kae)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 gin=MB("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"}}),Sse=j.forwardRef(({className:s,variant:t,...n},r)=>e.jsx("div",{ref:r,role:"alert",className:Pt(gin({variant:t}),s),...n}));Sse.displayName="Alert";const xin=j.forwardRef(({className:s,...t},n)=>e.jsx("h5",{ref:n,className:Pt("mb-1 font-medium leading-none tracking-tight",s),...t}));xin.displayName="AlertTitle";const Cse=j.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:Pt("text-sm [&_p]:leading-relaxed",s),...t}));Cse.displayName="AlertDescription";function yin({open:s,onOpenChange:t,imageUrl:n,imageId:r,defaultCaption:a="",swagItemId:i,reelId:l}){const o=Wt(),{user:c}=bs(),d=(c==null?void 0:c.id)??null,[u,h]=j.useState(a),[m,f]=j.useState([]),[g,x]=j.useState(null),[y,v]=j.useState("now"),[b,w]=j.useState(jyt(Tyt(new Date),1)),[S,A]=j.useState("12"),[E,I]=j.useState("00"),[P,R]=j.useState("PM");j.useEffect(()=>{if(s){h(a),v("now"),f([]);const he=jyt(Tyt(new Date),1);w(he);const ue=he.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 he=parseInt(S);const ue=parseInt(E);return P==="PM"&&he!==12&&(he+=12),P==="AM"&&he===12&&(he=0),Lzt(Izt(b,he),ue)},{data:O,isLoading:U}=st({queryKey:["social-accounts-for-post",d],queryFn:async()=>{const{data:{user:he}}=await q.auth.getUser();if(!he)return[];const{data:ue,error:ve}=await q.from("social_accounts").select("*").eq("user_id",he.id).eq("is_active",!0).order("platform",{ascending:!0});if(ve)throw ve;return console.log("Fetched social accounts for posting:",ue),ue},enabled:s,staleTime:0}),W=mt({mutationFn:async({accountId:he,platform:ue})=>{x(he);const{data:ve,error:Ee}=await q.functions.invoke("social-post",{body:{platform:ue,accountId:he,imageUrl:n,caption:u}});if(Ee)throw new Error(await kse(Ee));if(ve!=null&&ve.error)throw new Error(ve.error);return ve},onSuccess:he=>{const ue=he.platform==="facebook"?"Facebook":he.platform==="instagram"?"Instagram":he.platform==="linkedin"?"LinkedIn":"Google Business";re.success(`Posted to ${ue}!`)},onError:he=>{re.error(`Failed to post: ${he.message}`)},onSettled:()=>{x(null)}}),V=mt({mutationFn:async({accountId:he,platform:ue,scheduledFor:ve})=>{const{data:{user:Ee}}=await q.auth.getUser();if(!Ee)throw new Error("Not authenticated");const{error:Se}=await q.from("scheduled_posts").insert({user_id:Ee.id,social_account_id:he,platform:ue,image_url:n,caption:u,swag_item_id:i||null,reel_id:l||null,scheduled_for:ve.toISOString(),status:"scheduled"});if(Se)throw Se;return{platform:ue}},onSuccess:he=>{const ue=he.platform==="facebook"?"Facebook":he.platform==="instagram"?"Instagram":"LinkedIn";re.success(`Post scheduled for ${ue}!`)},onError:he=>{re.error(`Failed to schedule: ${he.message}`)}}),G=async()=>{if(m.length===0){re.error("Please select at least one account");return}if(y==="schedule"){const he=D();if(!he||he<=new Date){re.error("Please select a future date and time");return}for(const ue of m){const ve=O==null?void 0:O.find(Ee=>Ee.id===ue);ve&&await V.mutateAsync({accountId:ue,platform:ve.platform,scheduledFor:he})}o.invalidateQueries({queryKey:["scheduled-posts",d]}),re.success(`${m.length} post(s) scheduled for ${en(he,"PPp")}`)}else for(const he of m){const ue=O==null?void 0:O.find(ve=>ve.id===he);ue&&await W.mutateAsync({accountId:he,platform:ue.platform})}o.invalidateQueries({queryKey:["scheduled-posts",d]}),h(""),f([]),t(!1)},Y=he=>{f(ue=>ue.includes(he)?ue.filter(ve=>ve!==he):[...ue,he])},X=(O==null?void 0:O.filter(he=>he.platform==="facebook"))||[],ae=(O==null?void 0:O.filter(he=>he.platform==="instagram"))||[],le=(O==null?void 0:O.filter(he=>he.platform==="linkedin"))||[],ne=(O==null?void 0:O.filter(he=>he.platform==="google_business"))||[],te=((O==null?void 0:O.length)||0)>0,J=W.isPending||V.isPending,ce=Array.from({length:12},(he,ue)=>String(ue+1)),_e=["00","15","30","45"];return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Create Social Post"}),e.jsx(Pr,{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(Ls,{id:"caption",placeholder:"Write a caption for your post...",value:u,onChange:he=>h(he.target.value),rows:3}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[u.length,"/2200 characters"]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(ee,{children:"Publish Time"}),e.jsxs("div",{className:"flex items-center gap-1 p-1 bg-muted rounded-lg",children:[e.jsx("button",{type:"button",onClick:()=>v("now"),className:Pt("flex-1 px-4 py-2 rounded-md text-sm font-medium transition-all",y==="now"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:"Post Now"}),e.jsx("button",{type:"button",onClick:()=>v("schedule"),className:Pt("flex-1 px-4 py-2 rounded-md text-sm font-medium transition-all",y==="schedule"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:"Schedule"})]})]}),y==="schedule"&&e.jsxs("div",{className:"space-y-3 p-4 border rounded-lg bg-muted/30",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(da,{className:"h-4 w-4"}),"Schedule for"]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs(Kd,{children:[e.jsx(Yd,{asChild:!0,children:e.jsxs($,{variant:"outline",className:Pt("justify-start text-left font-normal flex-1",!b&&"text-muted-foreground"),children:[e.jsx(Ta,{className:"mr-2 h-4 w-4"}),b?en(b,"PPP"):e.jsx("span",{children:"Pick a date"})]})}),e.jsx(Od,{className:"w-auto p-0",align:"start",children:e.jsx(T2,{mode:"single",selected:b,onSelect:w,disabled:he=>hee.jsx(Ge,{value:he,children:he},he))})]}),e.jsx("span",{className:"text-muted-foreground",children:":"}),e.jsxs(ms,{value:E,onValueChange:I,children:[e.jsx(us,{className:"w-[70px]",children:e.jsx(fs,{})}),e.jsx(hs,{children:_e.map(he=>e.jsx(Ge,{value:he,children:he},he))})]}),e.jsxs(ms,{value:P,onValueChange:he=>R(he),children:[e.jsx(us,{className:"w-[70px]",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"AM",children:"AM"}),e.jsx(Ge,{value:"PM",children:"PM"})]})]})]})]}),b&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Post will be published on ",en(D()||new Date,"PPP 'at' p")]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(ee,{children:"Post to"}),U&&e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin"})}),!U&&!te&&e.jsxs(Sse,{children:[e.jsx(ll,{className:"h-4 w-4"}),e.jsxs(Cse,{className:"flex flex-col gap-2",children:[e.jsx("span",{children:"No social accounts connected yet."}),e.jsxs(wr,{to:"/social-connections",className:"inline-flex items-center gap-1.5 text-primary hover:underline font-medium",children:[e.jsx(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(Qp,{className:"h-4 w-4 text-blue-600"})," Facebook"]}),X.map(he=>e.jsxs("label",{className:"flex items-center gap-3 rounded-lg border p-3 cursor-pointer hover:bg-muted/50 transition-colors",children:[e.jsx(ai,{checked:m.includes(he.id),onCheckedChange:()=>Y(he.id),disabled:g===he.id}),e.jsxs(Oa,{className:"h-8 w-8",children:[e.jsx(Ii,{src:he.profile_picture_url||""}),e.jsx(za,{children:e.jsx(Qp,{className:"h-4 w-4"})})]}),e.jsx("span",{className:"flex-1 text-sm font-medium",children:he.page_name||he.platform_username}),g===he.id&&e.jsx(Ct,{className:"h-4 w-4 animate-spin"})]},he.id))]}),ae.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(Ef,{className:"h-4 w-4 text-pink-600"})," Instagram"]}),ae.map(he=>e.jsxs("label",{className:"flex items-center gap-3 rounded-lg border p-3 cursor-pointer hover:bg-muted/50 transition-colors",children:[e.jsx(ai,{checked:m.includes(he.id),onCheckedChange:()=>Y(he.id),disabled:g===he.id}),e.jsxs(Oa,{className:"h-8 w-8",children:[e.jsx(Ii,{src:he.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:["@",he.platform_username]}),g===he.id&&e.jsx(Ct,{className:"h-4 w-4 animate-spin"})]},he.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(dy,{className:"h-4 w-4 text-blue-700"})," LinkedIn"]}),le.map(he=>e.jsxs("label",{className:"flex items-center gap-3 rounded-lg border p-3 cursor-pointer hover:bg-muted/50 transition-colors",children:[e.jsx(ai,{checked:m.includes(he.id),onCheckedChange:()=>Y(he.id),disabled:g===he.id}),e.jsxs(Oa,{className:"h-8 w-8",children:[e.jsx(Ii,{src:he.profile_picture_url||""}),e.jsx(za,{children:e.jsx(dy,{className:"h-4 w-4"})})]}),e.jsx("span",{className:"flex-1 text-sm font-medium",children:he.platform_username}),g===he.id&&e.jsx(Ct,{className:"h-4 w-4 animate-spin"})]},he.id))]}),ne.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(ci,{className:"h-4 w-4 text-red-600"})," Google Business"]}),ne.map(he=>e.jsxs("label",{className:"flex items-center gap-3 rounded-lg border p-3 cursor-pointer hover:bg-muted/50 transition-colors",children:[e.jsx(ai,{checked:m.includes(he.id),onCheckedChange:()=>Y(he.id),disabled:g===he.id}),e.jsxs(Oa,{className:"h-8 w-8",children:[e.jsx(Ii,{src:he.profile_picture_url||""}),e.jsx(za,{children:e.jsx(ci,{className:"h-4 w-4"})})]}),e.jsx("span",{className:"flex-1 text-sm font-medium",children:he.page_name||he.platform_username}),g===he.id&&e.jsx(Ct,{className:"h-4 w-4 animate-spin"})]},he.id))]})]})]}),e.jsxs(Sr,{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"}):y==="schedule"?e.jsx(Ta,{className:"h-4 w-4"}):e.jsx(Kr,{className:"h-4 w-4"}),y==="schedule"?`Schedule ${m.length} post${m.length!==1?"s":""}`:`Post to ${m.length} account${m.length!==1?"s":""}`]})]})]})})}function vin(){const{user:s}=bs(),t=(s==null?void 0:s.id)??null,n=Wt(),[r,a]=j.useState(void 0),[i,l]=j.useState("all"),[o,c]=j.useState(null),[d,u]=j.useState(""),[h,m]=j.useState(void 0),[f,g]=j.useState("12"),[x,y]=j.useState("00"),[v,b]=j.useState("PM"),{data:w=[],isLoading:S}=st({queryKey:["scheduled-posts",t],enabled:!!t,queryFn:async()=>{const{data:ne,error:te}=await q.from("scheduled_posts").select(` *, social_accounts ( page_name, platform_username, profile_picture_url ) `).eq("user_id",t).order("scheduled_for",{ascending:!1});if(te)throw te;return ne}}),A=w.filter(ne=>{if(i!=="all"&&ne.status!==i)return!1;if(r&&ne.scheduled_for){const te=new Date(ne.scheduled_for);if(!sf(te,r))return!1}return!0}),E=w.filter(ne=>ne.scheduled_for).map(ne=>Mg(new Date(ne.scheduled_for))),I=mt({mutationFn:async ne=>{const{error:te}=await q.from("scheduled_posts").update({caption:ne.caption,scheduled_for:ne.scheduled_for}).eq("id",ne.id);if(te)throw te},onSuccess:()=>{re.success("Post updated!"),n.invalidateQueries({queryKey:["scheduled-posts",t]}),c(null)},onError:ne=>{re.error(`Failed to update: ${ne.message}`)}}),P=mt({mutationFn:async ne=>{const{error:te}=await q.from("scheduled_posts").update({status:"cancelled"}).eq("id",ne);if(te)throw te},onSuccess:()=>{re.success("Post cancelled"),n.invalidateQueries({queryKey:["scheduled-posts",t]})},onError:ne=>{re.error(`Failed to cancel: ${ne.message}`)}}),R=mt({mutationFn:async ne=>{const{error:te}=await q.from("scheduled_posts").delete().eq("id",ne);if(te)throw te},onSuccess:()=>{re.success("Post deleted"),n.invalidateQueries({queryKey:["scheduled-posts",t]})},onError:ne=>{re.error(`Failed to delete: ${ne.message}`)}}),D=mt({mutationFn:async ne=>{const{data:te,error:J}=await q.functions.invoke("social-post",{body:{platform:ne.platform,accountId:ne.social_account_id,imageUrl:ne.image_url,caption:ne.caption}});if(J)throw new Error(await kse(J));if(te!=null&&te.error)throw new Error(te.error);return await q.from("scheduled_posts").update({status:"posted",posted_at:new Date().toISOString(),post_id:te.postId}).eq("id",ne.id),te},onSuccess:ne=>{const te=ne.platform==="facebook"?"Facebook":ne.platform==="instagram"?"Instagram":"LinkedIn";re.success(`Posted to ${te}!`),n.invalidateQueries({queryKey:["scheduled-posts",t]})},onError:ne=>{re.error(`Failed to post: ${ne.message}`)}}),O=ne=>{if(c(ne),u(ne.caption||""),ne.scheduled_for){const te=new Date(ne.scheduled_for);m(te);const J=te.getHours();g(String(J>12?J-12:J===0?12:J)),y(String(te.getMinutes()).padStart(2,"0")),b(J>=12?"PM":"AM")}},U=()=>{if(!o||!h)return;let ne=parseInt(f);const te=parseInt(x);v==="PM"&&ne!==12&&(ne+=12),v==="AM"&&ne===12&&(ne=0);const J=Lzt(Izt(h,ne),te);I.mutate({id:o.id,caption:d,scheduled_for:J.toISOString()})},W=ne=>{switch(ne){case"facebook":return e.jsx(Qp,{className:"h-4 w-4 text-blue-600"});case"instagram":return e.jsx(Ef,{className:"h-4 w-4 text-pink-600"});case"linkedin":return e.jsx(dy,{className:"h-4 w-4 text-blue-700"});default:return null}},V=ne=>{switch(ne){case"scheduled":return e.jsxs($e,{variant:"secondary",className:"gap-1",children:[e.jsx(da,{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(Nu,{className:"h-3 w-3"}),"Failed"]});case"cancelled":return e.jsxs($e,{variant:"outline",className:"gap-1 text-muted-foreground",children:[e.jsx(ll,{className:"h-3 w-3"}),"Cancelled"]});default:return e.jsx($e,{variant:"outline",children:ne})}},G=Array.from({length:12},(ne,te)=>String(te+1)),Y=["00","15","30","45"],X=w.filter(ne=>ne.status==="scheduled").length,ae=w.filter(ne=>ne.status==="posted").length,le=w.filter(ne=>ne.status==="scheduled"&&ne.scheduled_for&&cIs(new Date(ne.scheduled_for))).length;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs(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(T2,{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(Cw,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("div",{className:"flex flex-wrap gap-1",children:["all","scheduled","posted","failed","cancelled"].map(ne=>e.jsx($,{variant:i===ne?"default":"outline",size:"sm",onClick:()=>l(ne),className:"capitalize",children:ne},ne))})]}),S&&e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(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(Ta,{className:"h-12 w-12 mx-auto text-muted-foreground/50 mb-4"}),e.jsx("h3",{className:"font-medium mb-2",children:"No posts found"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:r?`No posts scheduled for ${en(r,"PPP")}`:"Schedule a post from Social Swag to get started!"})]}),e.jsx("div",{className:"space-y-4",children:A.map(ne=>{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:ne.image_url,alt:"Post preview",className:"w-full h-full object-cover"})}),e.jsxs(Ie,{className:"flex-1 p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-2 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[W(ne.platform),e.jsx("span",{className:"font-medium",children:((te=ne.social_accounts)==null?void 0:te.page_name)||((J=ne.social_accounts)==null?void 0:J.platform_username)||"Unknown"}),V(ne.status)]}),e.jsxs("div",{className:"flex items-center gap-1",children:[ne.status==="scheduled"&&e.jsxs(bk,{children:[e.jsxs(iy,{children:[e.jsx(oy,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",onClick:()=>O(ne),children:e.jsx(pi,{className:"h-4 w-4"})})}),e.jsx(jx,{children:"Edit post"})]}),e.jsxs(iy,{children:[e.jsx(oy,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",onClick:()=>D.mutate(ne),disabled:D.isPending,children:D.isPending?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Kr,{className:"h-4 w-4"})})}),e.jsx(jx,{children:"Post now"})]}),e.jsxs(fc,{children:[e.jsx(Tg,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive",children:e.jsx(Hn,{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(ne.id),className:"bg-amber-600 hover:bg-amber-700",children:"Cancel Post"}),e.jsx(Yl,{onClick:()=>R.mutate(ne.id),className:"bg-destructive hover:bg-destructive/90",children:"Delete"})]})]})]})]}),(ne.status==="posted"||ne.status==="cancelled"||ne.status==="failed")&&e.jsxs(fc,{children:[e.jsx(Tg,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive",children:e.jsx(Hn,{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(ne.id),className:"bg-destructive hover:bg-destructive/90",children:"Delete"})]})]})]})]})]}),ne.caption&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-2",children:ne.caption}),e.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(da,{className:"h-3 w-3"}),ne.status==="posted"&&ne.posted_at?`Posted ${en(new Date(ne.posted_at),"PPp")}`:ne.scheduled_for?`Scheduled for ${en(new Date(ne.scheduled_for),"PPp")}`:"Not scheduled"]}),ne.status==="failed"&&ne.error_message&&e.jsxs("p",{className:"text-xs text-destructive mt-2",children:["Error: ",ne.error_message]})]})]})},ne.id)})})]})]}),e.jsx(zs,{open:!!o,onOpenChange:ne=>!ne&&c(null),children:e.jsxs(Os,{className:"max-w-lg",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Edit Scheduled Post"}),e.jsx(Pr,{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(Ls,{value:d,onChange:ne=>u(ne.target.value),rows:3})]}),e.jsxs("div",{className:"space-y-3 p-4 border rounded-lg",children:[e.jsx(ee,{children:"Schedule for"}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs(Kd,{children:[e.jsx(Yd,{asChild:!0,children:e.jsxs($,{variant:"outline",className:Pt("justify-start text-left font-normal flex-1",!h&&"text-muted-foreground"),children:[e.jsx(Ta,{className:"mr-2 h-4 w-4"}),h?en(h,"PPP"):"Pick a date"]})}),e.jsx(Od,{className:"w-auto p-0",align:"start",children:e.jsx(T2,{mode:"single",selected:h,onSelect:m,disabled:ne=>nee.jsx(Ge,{value:ne,children:ne},ne))})]}),e.jsx("span",{className:"text-muted-foreground",children:":"}),e.jsxs(ms,{value:x,onValueChange:y,children:[e.jsx(us,{className:"w-[70px]",children:e.jsx(fs,{})}),e.jsx(hs,{children:Y.map(ne=>e.jsx(Ge,{value:ne,children:ne},ne))})]}),e.jsxs(ms,{value:v,onValueChange:ne=>b(ne),children:[e.jsx(us,{className:"w-[70px]",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"AM",children:"AM"}),e.jsx(Ge,{value:"PM",children:"PM"})]})]})]})]})]})]}),e.jsxs(Sr,{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 jde(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 WHt={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 jde=="function"&&jde;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 jde=="function"&&jde,c=0;c>2,f=(3&d)<<4|u>>4,g=1>6:64,x=2>4,u=(15&m)<<4|(f=o.indexOf(c.charAt(x++)))>>2,h=(3&f)<<6|(g=o.indexOf(c.charAt(x++))),b[y++]=d,f!==64&&(b[y++]=u),g!==64&&(b[y++]=h);return b}},{"./support":30,"./utils":32}],2:[function(n,r,a){var i=n("./external"),l=n("./stream/DataWorker"),o=n("./stream/Crc32Probe"),c=n("./stream/DataLengthProbe");function d(u,h,m,f,g){this.compressedSize=u,this.uncompressedSize=h,this.crc32=m,this.compression=f,this.compressedContent=g}d.prototype={getContentWorker:function(){var u=new l(i.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new c("data_length")),h=this;return u.on("end",function(){if(this.streamInfo.data_length!==h.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),u},getCompressedWorker:function(){return new l(i.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},d.createWorkerFrom=function(u,h,m){return u.pipe(new o).pipe(new c("uncompressedSize")).pipe(h.compressWorker(m)).pipe(new c("compressedSize")).withStreamInfo("compression",h)},r.exports=d},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(n,r,a){var i=n("./stream/GenericWorker");a.STORE={magic:"\0\0",compressWorker:function(){return new i("STORE compression")},uncompressWorker:function(){return new i("STORE decompression")}},a.DEFLATE=n("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(n,r,a){var i=n("./utils"),l=function(){for(var o,c=[],d=0;d<256;d++){o=d;for(var u=0;u<8;u++)o=1&o?3988292384^o>>>1:o>>>1;c[d]=o}return c}();r.exports=function(o,c){return o!==void 0&&o.length?i.getTypeOf(o)!=="string"?function(d,u,h,m){var f=l,g=m+h;d^=-1;for(var x=m;x>>8^f[255&(d^u[x])];return-1^d}(0|c,o,o.length,0):function(d,u,h,m){var f=l,g=m+h;d^=-1;for(var x=m;x>>8^f[255&(d^u.charCodeAt(x))];return-1^d}(0|c,o,o.length,0):0}},{"./utils":32}],5:[function(n,r,a){a.base64=!1,a.binary=!1,a.dir=!1,a.createFolders=!0,a.date=null,a.compression=null,a.compressionOptions=null,a.comment=null,a.unixPermissions=null,a.dosPermissions=null},{}],6:[function(n,r,a){var i=null;i=typeof Promise<"u"?Promise:n("lie"),r.exports={Promise:i}},{lie:37}],7:[function(n,r,a){var i=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Uint32Array<"u",l=n("pako"),o=n("./utils"),c=n("./stream/GenericWorker"),d=i?"uint8array":"array";function u(h,m){c.call(this,"FlateWorker/"+h),this._pako=null,this._pakoAction=h,this._pakoOptions=m,this.meta={}}a.magic="\b\0",o.inherits(u,c),u.prototype.processChunk=function(h){this.meta=h.meta,this._pako===null&&this._createPako(),this._pako.push(o.transformTo(d,h.data),!1)},u.prototype.flush=function(){c.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)},u.prototype.cleanUp=function(){c.prototype.cleanUp.call(this),this._pako=null},u.prototype._createPako=function(){this._pako=new l[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var h=this;this._pako.onData=function(m){h.push({data:m,meta:h.meta})}},a.compressWorker=function(h){return new u("Deflate",h)},a.uncompressWorker=function(){return new u("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(n,r,a){function i(f,g){var x,y="";for(x=0;x>>=8;return y}function l(f,g,x,y,v,b){var w,S,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="",Y="",X="",ae=A.dir,le=A.date,ne={crc32:0,compressedSize:0,uncompressedSize:0};g&&!x||(ne.crc32=f.crc32,ne.compressedSize=f.compressedSize,ne.uncompressedSize=f.uncompressedSize);var te=0;g&&(te|=8),I||!W&&!V||(te|=2048);var J=0,ce=0;ae&&(J|=16),v==="UNIX"?(ce=798,J|=function(he,ue){var ve=he;return he||(ve=ue?16893:33204),(65535&ve)<<16}(A.unixPermissions,ae)):(ce=20,J|=function(he){return 63&(he||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&&(Y=i(1,1)+i(u(P),4)+R,G+="up"+i(Y.length,2)+Y),V&&(X=i(1,1)+i(u(O),4)+U,G+="uc"+i(X.length,2)+X);var _e="";return _e+=` \0`,_e+=i(te,2),_e+=E.magic,_e+=i(w,2),_e+=i(S,2),_e+=i(ne.crc32,4),_e+=i(ne.compressedSize,4),_e+=i(ne.uncompressedSize,4),_e+=i(P.length,2),_e+=i(G.length,2),{fileRecord:h.LOCAL_FILE_HEADER+_e+P+G,dirRecord:h.CENTRAL_FILE_HEADER+i(ce,2)+_e+i(O.length,2)+"\0\0\0\0"+i(J,4)+i(y,4)+P+G+O}}var o=n("../utils"),c=n("../stream/GenericWorker"),d=n("../utf8"),u=n("../crc32"),h=n("../signature");function m(f,g,x,y){c.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=g,this.zipPlatform=x,this.encodeFileName=y,this.streamFiles=f,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}o.inherits(m,c),m.prototype.push=function(f){var g=f.meta.percent||0,x=this.entriesCount,y=this._sources.length;this.accumulate?this.contentBuffer.push(f):(this.bytesWritten+=f.data.length,c.prototype.push.call(this,{data:f.data,meta:{currentFile:this.currentFile,percent:x?(g+100*(x-y-1))/x:100}}))},m.prototype.openedSource=function(f){this.currentSourceOffset=this.bytesWritten,this.currentFile=f.file.name;var g=this.streamFiles&&!f.file.dir;if(g){var x=l(f,g,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:x.fileRecord,meta:{percent:0}})}else this.accumulate=!0},m.prototype.closedSource=function(f){this.accumulate=!1;var g=this.streamFiles&&!f.file.dir,x=l(f,g,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(x.dirRecord),g)this.push({data:function(y){return h.DATA_DESCRIPTOR+i(y.crc32,4)+i(y.compressedSize,4)+i(y.uncompressedSize,4)}(f),meta:{percent:100}});else for(this.push({data:x.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},m.prototype.flush=function(){for(var f=this.bytesWritten,g=0;g=this.index;c--)d=(d<<8)+this.byteAt(c);return this.index+=o,d},readString:function(o){return i.transformTo("string",this.readData(o))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var o=this.readInt(4);return new Date(Date.UTC(1980+(o>>25&127),(o>>21&15)-1,o>>16&31,o>>11&31,o>>5&63,(31&o)<<1))}},r.exports=l},{"../utils":32}],19:[function(n,r,a){var i=n("./Uint8ArrayReader");function l(o){i.call(this,o)}n("../utils").inherits(l,i),l.prototype.readData=function(o){this.checkOffset(o);var c=this.data.slice(this.zero+this.index,this.zero+this.index+o);return this.index+=o,c},r.exports=l},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(n,r,a){var i=n("./DataReader");function l(o){i.call(this,o)}n("../utils").inherits(l,i),l.prototype.byteAt=function(o){return this.data.charCodeAt(this.zero+o)},l.prototype.lastIndexOfSignature=function(o){return this.data.lastIndexOf(o)-this.zero},l.prototype.readAndCheckSignature=function(o){return o===this.readData(4)},l.prototype.readData=function(o){this.checkOffset(o);var c=this.data.slice(this.zero+this.index,this.zero+this.index+o);return this.index+=o,c},r.exports=l},{"../utils":32,"./DataReader":18}],21:[function(n,r,a){var i=n("./ArrayReader");function l(o){i.call(this,o)}n("../utils").inherits(l,i),l.prototype.readData=function(o){if(this.checkOffset(o),o===0)return new Uint8Array(0);var c=this.data.subarray(this.zero+this.index,this.zero+this.index+o);return this.index+=o,c},r.exports=l},{"../utils":32,"./ArrayReader":17}],22:[function(n,r,a){var i=n("../utils"),l=n("../support"),o=n("./ArrayReader"),c=n("./StringReader"),d=n("./NodeBufferReader"),u=n("./Uint8ArrayReader");r.exports=function(h){var m=i.getTypeOf(h);return i.checkSupport(m),m!=="string"||l.uint8array?m==="nodebuffer"?new d(h):l.uint8array?new u(i.transformTo("uint8array",h)):new o(i.transformTo("array",h)):new c(h)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(n,r,a){a.LOCAL_FILE_HEADER="PK",a.CENTRAL_FILE_HEADER="PK",a.CENTRAL_DIRECTORY_END="PK",a.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK\x07",a.ZIP64_CENTRAL_DIRECTORY_END="PK",a.DATA_DESCRIPTOR="PK\x07\b"},{}],24:[function(n,r,a){var i=n("./GenericWorker"),l=n("../utils");function o(c){i.call(this,"ConvertWorker to "+c),this.destType=c}l.inherits(o,i),o.prototype.processChunk=function(c){this.push({data:l.transformTo(this.destType,c.data),meta:c.meta})},r.exports=o},{"../utils":32,"./GenericWorker":28}],25:[function(n,r,a){var i=n("./GenericWorker"),l=n("../crc32");function o(){i.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}n("../utils").inherits(o,i),o.prototype.processChunk=function(c){this.streamInfo.crc32=l(c.data,this.streamInfo.crc32||0),this.push(c)},r.exports=o},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(n,r,a){var i=n("../utils"),l=n("./GenericWorker");function o(c){l.call(this,"DataLengthProbe for "+c),this.propName=c,this.withStreamInfo(c,0)}i.inherits(o,l),o.prototype.processChunk=function(c){if(c){var d=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=d+c.data.length}l.prototype.processChunk.call(this,c)},r.exports=o},{"../utils":32,"./GenericWorker":28}],27:[function(n,r,a){var i=n("../utils"),l=n("./GenericWorker");function o(c){l.call(this,"DataWorker");var d=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,c.then(function(u){d.dataIsReady=!0,d.data=u,d.max=u&&u.length||0,d.type=i.getTypeOf(u),d.isPaused||d._tickAndRepeat()},function(u){d.error(u)})}i.inherits(o,l),o.prototype.cleanUp=function(){l.prototype.cleanUp.call(this),this.data=null},o.prototype.resume=function(){return!!l.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,i.delay(this._tickAndRepeat,[],this)),!0)},o.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(i.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},o.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var c=null,d=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":c=this.data.substring(this.index,d);break;case"uint8array":c=this.data.subarray(this.index,d);break;case"array":case"nodebuffer":c=this.data.slice(this.index,d)}return this.index=d,this.push({data:c,meta:{percent:this.max?this.index/this.max*100:0}})},r.exports=o},{"../utils":32,"./GenericWorker":28}],28:[function(n,r,a){function i(l){this.name=l||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}i.prototype={push:function(l){this.emit("data",l)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(l){this.emit("error",l)}return!0},error:function(l){return!this.isFinished&&(this.isPaused?this.generatedError=l:(this.isFinished=!0,this.emit("error",l),this.previous&&this.previous.error(l),this.cleanUp()),!0)},on:function(l,o){return this._listeners[l].push(o),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(l,o){if(this._listeners[l])for(var c=0;c "+l:l}},r.exports=i},{}],29:[function(n,r,a){var i=n("../utils"),l=n("./ConvertWorker"),o=n("./GenericWorker"),c=n("../base64"),d=n("../support"),u=n("../external"),h=null;if(d.nodestream)try{h=n("../nodejs/NodejsStreamOutputAdapter")}catch{}function m(g,x){return new u.Promise(function(y,v){var b=[],w=g._internalType,S=g._outputType,A=g._mimeType;g.on("data",function(E,I){b.push(E),x&&x(I)}).on("error",function(E){b=[],v(E)}).on("end",function(){try{var E=function(I,P,R){switch(I){case"blob":return i.newBlob(i.transformTo("arraybuffer",P),R);case"base64":return c.encode(P);default:return i.transformTo(I,P)}}(S,function(I,P){var R,D=0,O=null,U=0;for(R=0;R"u")a.blob=!1;else{var i=new ArrayBuffer(0);try{a.blob=new Blob([i],{type:"application/zip"}).size===0}catch{try{var l=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);l.append(i),a.blob=l.getBlob("application/zip").size===0}catch{a.blob=!1}}}try{a.nodestream=!!n("readable-stream").Readable}catch{a.nodestream=!1}},{"readable-stream":16}],31:[function(n,r,a){for(var i=n("./utils"),l=n("./support"),o=n("./nodejsUtils"),c=n("./stream/GenericWorker"),d=new Array(256),u=0;u<256;u++)d[u]=252<=u?6:248<=u?5:240<=u?4:224<=u?3:192<=u?2:1;d[254]=d[254]=1;function h(){c.call(this,"utf-8 decode"),this.leftOver=null}function m(){c.call(this,"utf-8 encode")}a.utf8encode=function(f){return l.nodebuffer?o.newBufferFrom(f,"utf-8"):function(g){var x,y,v,b,w,S=g.length,A=0;for(b=0;b>>6:(y<65536?x[w++]=224|y>>>12:(x[w++]=240|y>>>18,x[w++]=128|y>>>12&63),x[w++]=128|y>>>6&63),x[w++]=128|63&y);return x}(f)},a.utf8decode=function(f){return l.nodebuffer?i.transformTo("nodebuffer",f).toString("utf-8"):function(g){var x,y,v,b,w=g.length,S=new Array(2*w);for(x=y=0;x>10&1023,S[y++]=56320|1023&v)}return S.length!==y&&(S.subarray?S=S.subarray(0,y):S.length=y),i.applyFromCharCode(S)}(f=i.transformTo(l.uint8array?"uint8array":"array",f))},i.inherits(h,c),h.prototype.processChunk=function(f){var g=i.transformTo(l.uint8array?"uint8array":"array",f.data);if(this.leftOver&&this.leftOver.length){if(l.uint8array){var x=g;(g=new Uint8Array(x.length+this.leftOver.length)).set(this.leftOver,0),g.set(x,this.leftOver.length)}else g=this.leftOver.concat(g);this.leftOver=null}var y=function(b,w){var S;for((w=w||b.length)>b.length&&(w=b.length),S=w-1;0<=S&&(192&b[S])==128;)S--;return S<0||S===0?w:S+d[b[S]]>w?S:w}(g),v=g;y!==g.length&&(l.uint8array?(v=g.subarray(0,y),this.leftOver=g.subarray(y,g.length)):(v=g.slice(0,y),this.leftOver=g.slice(y,g.length))),this.push({data:a.utf8decode(v),meta:f.meta})},h.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:a.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},a.Utf8DecodeWorker=h,i.inherits(m,c),m.prototype.processChunk=function(f){this.push({data:a.utf8encode(f.data),meta:f.meta})},a.Utf8EncodeWorker=m},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(n,r,a){var i=n("./support"),l=n("./base64"),o=n("./nodejsUtils"),c=n("./external");function d(x){return x}function u(x,y){for(var v=0;v>8;this.dir=!!(16&this.externalFileAttributes),f==0&&(this.dosPermissions=63&this.externalFileAttributes),f==3&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||this.fileNameStr.slice(-1)!=="/"||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var f=i(this.extraFields[1].value);this.uncompressedSize===l.MAX_VALUE_32BITS&&(this.uncompressedSize=f.readInt(8)),this.compressedSize===l.MAX_VALUE_32BITS&&(this.compressedSize=f.readInt(8)),this.localHeaderOffset===l.MAX_VALUE_32BITS&&(this.localHeaderOffset=f.readInt(8)),this.diskNumberStart===l.MAX_VALUE_32BITS&&(this.diskNumberStart=f.readInt(4))}},readExtraFields:function(f){var g,x,y,v=f.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});f.index+4>>6:(f<65536?m[y++]=224|f>>>12:(m[y++]=240|f>>>18,m[y++]=128|f>>>12&63),m[y++]=128|f>>>6&63),m[y++]=128|63&f);return m},a.buf2binstring=function(h){return u(h,h.length)},a.binstring2buf=function(h){for(var m=new i.Buf8(h.length),f=0,g=m.length;f>10&1023,b[g++]=56320|1023&x)}return u(b,g)},a.utf8border=function(h,m){var f;for((m=m||h.length)>h.length&&(m=h.length),f=m-1;0<=f&&(192&h[f])==128;)f--;return f<0||f===0?m:f+c[h[f]]>m?f:m}},{"./common":41}],43:[function(n,r,a){r.exports=function(i,l,o,c){for(var d=65535&i|0,u=i>>>16&65535|0,h=0;o!==0;){for(o-=h=2e3>>1:l>>>1;o[c]=l}return o}();r.exports=function(l,o,c,d){var u=i,h=d+c;l^=-1;for(var m=d;m>>8^u[255&(l^o[m])];return-1^l}},{}],46:[function(n,r,a){var i,l=n("../utils/common"),o=n("./trees"),c=n("./adler32"),d=n("./crc32"),u=n("./messages"),h=0,m=4,f=0,g=-2,x=-1,y=4,v=2,b=8,w=9,S=286,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,Y=3,X=4;function ae(Ne,Ae){return Ne.msg=u[Ae],Ae}function le(Ne){return(Ne<<1)-(4Ne.avail_out&&(Ce=Ne.avail_out),Ce!==0&&(l.arraySet(Ne.output,Ae.pending_buf,Ae.pending_out,Ce,Ne.next_out),Ne.next_out+=Ce,Ae.pending_out+=Ce,Ne.total_out+=Ce,Ne.avail_out-=Ce,Ae.pending-=Ce,Ae.pending===0&&(Ae.pending_out=0))}function J(Ne,Ae){o._tr_flush_block(Ne,0<=Ne.block_start?Ne.block_start:-1,Ne.strstart-Ne.block_start,Ae),Ne.block_start=Ne.strstart,te(Ne.strm)}function ce(Ne,Ae){Ne.pending_buf[Ne.pending++]=Ae}function _e(Ne,Ae){Ne.pending_buf[Ne.pending++]=Ae>>>8&255,Ne.pending_buf[Ne.pending++]=255&Ae}function he(Ne,Ae){var Ce,Ve,ze=Ne.max_chain_length,qe=Ne.strstart,dt=Ne.prev_length,Xe=Ne.nice_match,at=Ne.strstart>Ne.w_size-O?Ne.strstart-(Ne.w_size-O):0,rt=Ne.window,Ke=Ne.w_mask,Je=Ne.prev,pt=Ne.strstart+D,gt=rt[qe+dt-1],ss=rt[qe+dt];Ne.prev_length>=Ne.good_match&&(ze>>=2),Xe>Ne.lookahead&&(Xe=Ne.lookahead);do if(rt[(Ce=Ae)+dt]===ss&&rt[Ce+dt-1]===gt&&rt[Ce]===rt[qe]&&rt[++Ce]===rt[qe+1]){qe+=2,Ce++;do;while(rt[++qe]===rt[++Ce]&&rt[++qe]===rt[++Ce]&&rt[++qe]===rt[++Ce]&&rt[++qe]===rt[++Ce]&&rt[++qe]===rt[++Ce]&&rt[++qe]===rt[++Ce]&&rt[++qe]===rt[++Ce]&&rt[++qe]===rt[++Ce]&&qeat&&--ze!=0);return dt<=Ne.lookahead?dt:Ne.lookahead}function ue(Ne){var Ae,Ce,Ve,ze,qe,dt,Xe,at,rt,Ke,Je=Ne.w_size;do{if(ze=Ne.window_size-Ne.lookahead-Ne.strstart,Ne.strstart>=Je+(Je-O)){for(l.arraySet(Ne.window,Ne.window,Je,Je,0),Ne.match_start-=Je,Ne.strstart-=Je,Ne.block_start-=Je,Ae=Ce=Ne.hash_size;Ve=Ne.head[--Ae],Ne.head[Ae]=Je<=Ve?Ve-Je:0,--Ce;);for(Ae=Ce=Je;Ve=Ne.prev[--Ae],Ne.prev[Ae]=Je<=Ve?Ve-Je:0,--Ce;);ze+=Je}if(Ne.strm.avail_in===0)break;if(dt=Ne.strm,Xe=Ne.window,at=Ne.strstart+Ne.lookahead,rt=ze,Ke=void 0,Ke=dt.avail_in,rt=R)for(qe=Ne.strstart-Ne.insert,Ne.ins_h=Ne.window[qe],Ne.ins_h=(Ne.ins_h<=R&&(Ne.ins_h=(Ne.ins_h<=R)if(Ve=o._tr_tally(Ne,Ne.strstart-Ne.match_start,Ne.match_length-R),Ne.lookahead-=Ne.match_length,Ne.match_length<=Ne.max_lazy_match&&Ne.lookahead>=R){for(Ne.match_length--;Ne.strstart++,Ne.ins_h=(Ne.ins_h<=R&&(Ne.ins_h=(Ne.ins_h<=R&&Ne.match_length<=Ne.prev_length){for(ze=Ne.strstart+Ne.lookahead-R,Ve=o._tr_tally(Ne,Ne.strstart-1-Ne.prev_match,Ne.prev_length-R),Ne.lookahead-=Ne.prev_length-1,Ne.prev_length-=2;++Ne.strstart<=ze&&(Ne.ins_h=(Ne.ins_h<Ne.pending_buf_size-5&&(Ce=Ne.pending_buf_size-5);;){if(Ne.lookahead<=1){if(ue(Ne),Ne.lookahead===0&&Ae===h)return V;if(Ne.lookahead===0)break}Ne.strstart+=Ne.lookahead,Ne.lookahead=0;var Ve=Ne.block_start+Ce;if((Ne.strstart===0||Ne.strstart>=Ve)&&(Ne.lookahead=Ne.strstart-Ve,Ne.strstart=Ve,J(Ne,!1),Ne.strm.avail_out===0)||Ne.strstart-Ne.block_start>=Ne.w_size-O&&(J(Ne,!1),Ne.strm.avail_out===0))return V}return Ne.insert=0,Ae===m?(J(Ne,!0),Ne.strm.avail_out===0?Y:X):(Ne.strstart>Ne.block_start&&(J(Ne,!1),Ne.strm.avail_out),V)}),new Se(4,4,8,4,ve),new Se(4,5,16,8,ve),new Se(4,6,32,32,ve),new Se(4,4,16,16,Ee),new Se(8,16,32,32,Ee),new Se(8,16,128,128,Ee),new Se(8,32,128,256,Ee),new Se(32,128,258,1024,Ee),new Se(32,258,258,4096,Ee)],a.deflateInit=function(Ne,Ae){return Be(Ne,Ae,b,15,8,0)},a.deflateInit2=Be,a.deflateReset=ke,a.deflateResetKeep=Fe,a.deflateSetHeader=function(Ne,Ae){return Ne&&Ne.state?Ne.state.wrap!==2?g:(Ne.state.gzhead=Ae,f):g},a.deflate=function(Ne,Ae){var Ce,Ve,ze,qe;if(!Ne||!Ne.state||5>8&255),ce(Ve,Ve.gzhead.time>>16&255),ce(Ve,Ve.gzhead.time>>24&255),ce(Ve,Ve.level===9?2:2<=Ve.strategy||Ve.level<2?4:0),ce(Ve,255&Ve.gzhead.os),Ve.gzhead.extra&&Ve.gzhead.extra.length&&(ce(Ve,255&Ve.gzhead.extra.length),ce(Ve,Ve.gzhead.extra.length>>8&255)),Ve.gzhead.hcrc&&(Ne.adler=d(Ne.adler,Ve.pending_buf,Ve.pending,0)),Ve.gzindex=0,Ve.status=69):(ce(Ve,0),ce(Ve,0),ce(Ve,0),ce(Ve,0),ce(Ve,0),ce(Ve,Ve.level===9?2:2<=Ve.strategy||Ve.level<2?4:0),ce(Ve,3),Ve.status=W);else{var dt=b+(Ve.w_bits-8<<4)<<8;dt|=(2<=Ve.strategy||Ve.level<2?0:Ve.level<6?1:Ve.level===6?2:3)<<6,Ve.strstart!==0&&(dt|=32),dt+=31-dt%31,Ve.status=W,_e(Ve,dt),Ve.strstart!==0&&(_e(Ve,Ne.adler>>>16),_e(Ve,65535&Ne.adler)),Ne.adler=1}if(Ve.status===69)if(Ve.gzhead.extra){for(ze=Ve.pending;Ve.gzindex<(65535&Ve.gzhead.extra.length)&&(Ve.pending!==Ve.pending_buf_size||(Ve.gzhead.hcrc&&Ve.pending>ze&&(Ne.adler=d(Ne.adler,Ve.pending_buf,Ve.pending-ze,ze)),te(Ne),ze=Ve.pending,Ve.pending!==Ve.pending_buf_size));)ce(Ve,255&Ve.gzhead.extra[Ve.gzindex]),Ve.gzindex++;Ve.gzhead.hcrc&&Ve.pending>ze&&(Ne.adler=d(Ne.adler,Ve.pending_buf,Ve.pending-ze,ze)),Ve.gzindex===Ve.gzhead.extra.length&&(Ve.gzindex=0,Ve.status=73)}else Ve.status=73;if(Ve.status===73)if(Ve.gzhead.name){ze=Ve.pending;do{if(Ve.pending===Ve.pending_buf_size&&(Ve.gzhead.hcrc&&Ve.pending>ze&&(Ne.adler=d(Ne.adler,Ve.pending_buf,Ve.pending-ze,ze)),te(Ne),ze=Ve.pending,Ve.pending===Ve.pending_buf_size)){qe=1;break}qe=Ve.gzindexze&&(Ne.adler=d(Ne.adler,Ve.pending_buf,Ve.pending-ze,ze)),qe===0&&(Ve.gzindex=0,Ve.status=91)}else Ve.status=91;if(Ve.status===91)if(Ve.gzhead.comment){ze=Ve.pending;do{if(Ve.pending===Ve.pending_buf_size&&(Ve.gzhead.hcrc&&Ve.pending>ze&&(Ne.adler=d(Ne.adler,Ve.pending_buf,Ve.pending-ze,ze)),te(Ne),ze=Ve.pending,Ve.pending===Ve.pending_buf_size)){qe=1;break}qe=Ve.gzindexze&&(Ne.adler=d(Ne.adler,Ve.pending_buf,Ve.pending-ze,ze)),qe===0&&(Ve.status=103)}else Ve.status=103;if(Ve.status===103&&(Ve.gzhead.hcrc?(Ve.pending+2>Ve.pending_buf_size&&te(Ne),Ve.pending+2<=Ve.pending_buf_size&&(ce(Ve,255&Ne.adler),ce(Ve,Ne.adler>>8&255),Ne.adler=0,Ve.status=W)):Ve.status=W),Ve.pending!==0){if(te(Ne),Ne.avail_out===0)return Ve.last_flush=-1,f}else if(Ne.avail_in===0&&le(Ae)<=le(Ce)&&Ae!==m)return ae(Ne,-5);if(Ve.status===666&&Ne.avail_in!==0)return ae(Ne,-5);if(Ne.avail_in!==0||Ve.lookahead!==0||Ae!==h&&Ve.status!==666){var Xe=Ve.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?Y:X):at.last_lit&&(J(at,!1),at.strm.avail_out===0)?V:G}(Ve,Ae):Ve.strategy===3?function(at,rt){for(var Ke,Je,pt,gt,ss=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?Y:X):at.last_lit&&(J(at,!1),at.strm.avail_out===0)?V:G}(Ve,Ae):i[Ve.level].func(Ve,Ae);if(Xe!==Y&&Xe!==X||(Ve.status=666),Xe===V||Xe===Y)return Ne.avail_out===0&&(Ve.last_flush=-1),f;if(Xe===G&&(Ae===1?o._tr_align(Ve):Ae!==5&&(o._tr_stored_block(Ve,0,0,!1),Ae===3&&(ne(Ve.head),Ve.lookahead===0&&(Ve.strstart=0,Ve.block_start=0,Ve.insert=0))),te(Ne),Ne.avail_out===0))return Ve.last_flush=-1,f}return Ae!==m?f:Ve.wrap<=0?1:(Ve.wrap===2?(ce(Ve,255&Ne.adler),ce(Ve,Ne.adler>>8&255),ce(Ve,Ne.adler>>16&255),ce(Ve,Ne.adler>>24&255),ce(Ve,255&Ne.total_in),ce(Ve,Ne.total_in>>8&255),ce(Ve,Ne.total_in>>16&255),ce(Ve,Ne.total_in>>24&255)):(_e(Ve,Ne.adler>>>16),_e(Ve,65535&Ne.adler)),te(Ne),0=Ce.w_size&&(qe===0&&(ne(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),dt=Ne.avail_in,Xe=Ne.next_in,at=Ne.input,Ne.avail_in=Ke,Ne.next_in=0,Ne.input=Ae,ue(Ce);Ce.lookahead>=R;){for(Ve=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(y),W.sane=1,W.back=-1,m):f}function S(U){var W;return U&&U.state?((W=U.state).wsize=0,W.whave=0,W.wnext=0,w(U)):f}function 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<(Y=X.wsize-X.wnext)&&(Y=G),i.arraySet(X.window,W,V-G,Y,X.wnext),(G-=Y)?(i.arraySet(X.window,W,V-G,G,0),X.wnext=G,X.whave=X.wsize):(X.wnext+=Y,X.wnext===X.wsize&&(X.wnext=0),X.whave>>8&255,V.check=o(V.check,qe,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,Ne=8+(15&(te>>>=4)),V.wbits===0)V.wbits=Ne;else if(Ne>V.wbits){U.msg="invalid window size",V.mode=30;break}V.dmax=1<>8&1),512&V.flags&&(qe[0]=255&te,qe[1]=te>>>8&255,V.check=o(V.check,qe,2,0)),J=te=0,V.mode=3;case 3:for(;J<32;){if(le===0)break e;le--,te+=G[X++]<>>8&255,qe[2]=te>>>16&255,qe[3]=te>>>24&255,V.check=o(V.check,qe,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&&(qe[0]=255&te,qe[1]=te>>>8&255,V.check=o(V.check,qe,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,qe,2,0)),J=te=0}else V.head&&(V.head.extra=null);V.mode=6;case 6:if(1024&V.flags&&(le<(he=V.length)&&(he=le),he&&(V.head&&(Ne=V.head.extra_len-V.length,V.head.extra||(V.head.extra=new Array(V.head.extra_len)),i.arraySet(V.head.extra,G,X,he,Ne)),512&V.flags&&(V.check=o(V.check,G,he,X)),le-=he,X+=he,V.length-=he),V.length))break e;V.length=0,V.mode=7;case 7:if(2048&V.flags){if(le===0)break e;for(he=0;Ne=G[X+he++],V.head&&Ne&&V.length<65536&&(V.head.name+=String.fromCharCode(Ne)),Ne&&he>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(he=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[dt[V.have++]]=0;if(V.lencode=V.lendyn,V.lenbits=7,Ce={bits:V.lenbits},Ae=d(0,V.lens,0,19,V.lencode,0,V.work,Ce),V.lenbits=Ce.bits,Ae){U.msg="invalid code lengths set",V.mode=30;break}V.have=0,V.mode=19;case 19:for(;V.have>>16&255,Le=65535&ze,!((Ee=ze>>>24)<=J);){if(le===0)break e;le--,te+=G[X++]<>>=Ee,J-=Ee,V.lens[V.have++]=Le;else{if(Le===16){for(Ve=Ee+2;J>>=Ee,J-=Ee,V.have===0){U.msg="invalid bit length repeat",V.mode=30;break}Ne=V.lens[V.have-1],he=3+(3&te),te>>>=2,J-=2}else if(Le===17){for(Ve=Ee+3;J>>=Ee)),te>>>=3,J-=3}else{for(Ve=Ee+7;J>>=Ee)),te>>>=7,J-=7}if(V.have+he>V.nlen+V.ndist){U.msg="invalid bit length repeat",V.mode=30;break}for(;he--;)V.lens[V.have++]=Ne}}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<=ne){U.next_out=ae,U.avail_out=ne,U.next_in=X,U.avail_in=le,V.hold=te,V.bits=J,c(U,_e),ae=U.next_out,Y=U.output,ne=U.avail_out,X=U.next_in,G=U.input,le=U.avail_in,te=V.hold,J=V.bits,V.mode===12&&(V.back=-1);break}for(V.back=0;Se=(ze=V.lencode[te&(1<>>16&255,Le=65535&ze,!((Ee=ze>>>24)<=J);){if(le===0)break e;le--,te+=G[X++]<>Fe)])>>>16&255,Le=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=Le,Se===0){V.mode=26;break}if(32&Se){V.back=-1,V.mode=12;break}if(64&Se){U.msg="invalid literal/length code",V.mode=30;break}V.extra=15&Se,V.mode=22;case 22:if(V.extra){for(Ve=V.extra;J>>=V.extra,J-=V.extra,V.back+=V.extra}V.was=V.length,V.mode=23;case 23:for(;Se=(ze=V.distcode[te&(1<>>16&255,Le=65535&ze,!((Ee=ze>>>24)<=J);){if(le===0)break e;le--,te+=G[X++]<>Fe)])>>>16&255,Le=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&Se){U.msg="invalid distance code",V.mode=30;break}V.offset=Le,V.extra=15&Se,V.mode=24;case 24:if(V.extra){for(Ve=V.extra;J>>=V.extra,J-=V.extra,V.back+=V.extra}if(V.offset>V.dmax){U.msg="invalid distance too far back",V.mode=30;break}V.mode=25;case 25:if(ne===0)break e;if(he=_e-ne,V.offset>he){if((he=V.offset-he)>V.whave&&V.sane){U.msg="invalid distance too far back",V.mode=30;break}ue=he>V.wnext?(he-=V.wnext,V.wsize-he):V.wnext-he,he>V.length&&(he=V.length),ve=V.window}else ve=Y,ue=ae-V.offset,he=V.length;for(neI?(R=ue[ve+y[W]],J[ce+y[W]]):(R=96,0),b=1<>ae)+(w-=b)]=P<<24|R<<16|D|0,w!==0;);for(b=1<>=1;if(b!==0?(te&=b-1,te+=b):te=0,W++,--_e[U]==0){if(U===G)break;U=h[m+y[W]]}if(Y>>7)]}function ce(ze,qe){ze.pending_buf[ze.pending++]=255&qe,ze.pending_buf[ze.pending++]=qe>>>8&255}function _e(ze,qe,dt){ze.bi_valid>v-dt?(ze.bi_buf|=qe<>v-ze.bi_valid,ze.bi_valid+=dt-v):(ze.bi_buf|=qe<>>=1,dt<<=1,0<--qe;);return dt>>>1}function ve(ze,qe,dt){var Xe,at,rt=new Array(y+1),Ke=0;for(Xe=1;Xe<=y;Xe++)rt[Xe]=Ke=Ke+dt[Xe-1]<<1;for(at=0;at<=qe;at++){var Je=ze[2*at+1];Je!==0&&(ze[2*at]=ue(rt[Je]++,Je))}}function Ee(ze){var qe;for(qe=0;qe>1;1<=dt;dt--)Fe(ze,rt,dt);for(at=pt;dt=ze.heap[1],ze.heap[1]=ze.heap[ze.heap_len--],Fe(ze,rt,1),Xe=ze.heap[1],ze.heap[--ze.heap_max]=dt,ze.heap[--ze.heap_max]=Xe,rt[2*at]=rt[2*dt]+rt[2*Xe],ze.depth[at]=(ze.depth[dt]>=ze.depth[Xe]?ze.depth[dt]:ze.depth[Xe])+1,rt[2*dt+1]=rt[2*Xe+1]=at,ze.heap[1]=at++,Fe(ze,rt,1),2<=ze.heap_len;);ze.heap[--ze.heap_max]=ze.heap[1],function(ss,Yt){var ts,ys,Bt,Ft,as,kt,Ks=Yt.dyn_tree,wt=Yt.max_code,gs=Yt.stat_desc.static_tree,ks=Yt.stat_desc.has_stree,Is=Yt.stat_desc.extra_bits,Xs=Yt.stat_desc.extra_base,ds=Yt.stat_desc.max_length,Ss=0;for(Ft=0;Ft<=y;Ft++)ss.bl_count[Ft]=0;for(Ks[2*ss.heap[ss.heap_max]+1]=0,ts=ss.heap_max+1;ts>=7;at>>=1)if(1>&&Je.dyn_ltree[2*pt]!==0)return l;if(Je.dyn_ltree[18]!==0||Je.dyn_ltree[20]!==0||Je.dyn_ltree[26]!==0)return o;for(pt=32;pt>>3,(rt=ze.static_len+3+7>>>3)<=at&&(at=rt)):at=rt=dt+5,dt+4<=at&&qe!==-1?Ve(ze,qe,dt,Xe):ze.strategy===4||rt===at?(_e(ze,2+(Xe?1:0),3),ke(ze,O,U)):(_e(ze,4+(Xe?1:0),3),function(Je,pt,gt,ss){var Yt;for(_e(Je,pt-257,5),_e(Je,gt-1,5),_e(Je,ss-4,4),Yt=0;Yt>>8&255,ze.pending_buf[ze.d_buf+2*ze.last_lit+1]=255&qe,ze.pending_buf[ze.l_buf+ze.last_lit]=255&dt,ze.last_lit++,qe===0?ze.dyn_ltree[2*dt]++:(ze.matches++,qe--,ze.dyn_ltree[2*(V[dt]+h+1)]++,ze.dyn_dtree[2*J(qe)]++),ze.last_lit===ze.lit_bufsize-1},a._tr_align=function(ze){_e(ze,2,3),he(ze,w,O),function(qe){qe.bi_valid===16?(ce(qe,qe.bi_buf),qe.bi_buf=0,qe.bi_valid=0):8<=qe.bi_valid&&(qe.pending_buf[qe.pending++]=255&qe.bi_buf,qe.bi_buf>>=8,qe.bi_valid-=8)}(ze)}},{"../utils/common":41}],53:[function(n,r,a){r.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(n,r,a){(function(i){(function(l,o){if(!l.setImmediate){var c,d,u,h,m=1,f={},g=!1,x=l.document,y=Object.getPrototypeOf&&Object.getPrototypeOf(l);y=y&&y.setTimeout?y:l,c={}.toString.call(l.process)==="[object process]"?function(S){process.nextTick(function(){b(S)})}:function(){if(l.postMessage&&!l.importScripts){var S=!0,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)},y.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 Sp<"u"?Sp:typeof self<"u"?self:typeof window<"u"?window:{})},{}]},{},[10])(10)})})(WHt);var bin=WHt.exports;const KHt=ru(bin);function RBe(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 YHt=({embedded:s=!1,onCompose:t}={})=>{const{isAdmin:n}=bs(),[r,a]=j.useState(null),[i,l]=j.useState(null),[o,c]=j.useState("all"),[d,u]=j.useState(new Set),[h,m]=j.useState(!1),[f,g]=j.useState(!1),[x,y]=j.useState("images"),[v,b]=j.useState(null),{data:w=[],isLoading:S}=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,_e)=>_e.localeCompare(ce)),[w]);j.useEffect(()=>{D.length>0&&o==="all"&&c(D[0])},[D,o]);const O=J=>{try{const ce=Ctt(J,"yyyy-MM",new Date);return en(ce,"MMMM yyyy")}catch{return J}},U=j.useMemo(()=>o==="all"?w:w.filter(J=>J.month===o),[o,w]),W=j.useMemo(()=>{var J;return o==="all"?null:((J=A.find(ce=>ce.month===o))==null?void 0:J.canva_link)||null},[o,A]),V=async J=>{try{await navigator.clipboard.writeText(J),re.success("Caption copied to clipboard!")}catch{re.error("Failed to copy caption")}},G=async(J,ce)=>{try{const he=await(await fetch(J)).blob(),ue=/iPhone|iPad|iPod|Android/i.test(navigator.userAgent),ve=navigator.canShare&&navigator.canShare({files:[new File([he],"test.jpg",{type:"image/jpeg"})]});if(ue&&ve){const Ee=new File([he],`social-swag-${ce}.jpg`,{type:"image/jpeg"});await navigator.share({files:[Ee],title:"Social Swag Image"}),re.success("Image ready to save!")}else{const Ee=window.URL.createObjectURL(he),Se=document.createElement("a");Se.href=Ee,Se.download=`social-swag-${ce}.jpg`,document.body.appendChild(Se),Se.click(),document.body.removeChild(Se),window.URL.revokeObjectURL(Ee),re.success("Image downloaded!")}}catch(_e){_e.name!=="AbortError"&&re.error("Failed to download image")}},Y=J=>{u(ce=>{const _e=new Set(ce);return _e.has(J)?_e.delete(J):_e.add(J),_e})},X=()=>{u(new Set(U.map(J=>J.id)))},ae=()=>{u(new Set),m(!1)},le=async()=>{const J=U.filter(ce=>d.has(ce.id));if(J.length===0){re.error("No images selected");return}g(!0),re.info(`Preparing ${J.length} images for download...`);try{const ce=new KHt,_e=[...J].sort((Se,Le)=>Se.sort_order-Le.sort_order);for(let Se=0;Se<_e.length;Se++){const Le=_e[Se];try{const Fe=await fetch(Le.image_url),ke=await Fe.blob(),Be=Fe.headers.get("content-type")||"image/jpeg",Ne=Be.includes("png")?"png":Be.includes("webp")?"webp":"jpg",Ae=`${Se+1}.${Ne}`;ce.file(Ae,ke)}catch{console.error("Failed to fetch image:",Le.id)}}const he=o!=="all"?O(o):"Social Swag",ue=await ce.generateAsync({type:"blob"}),ve=window.URL.createObjectURL(ue),Ee=document.createElement("a");Ee.href=ve,Ee.download=`${he}.zip`,document.body.appendChild(Ee),Ee.click(),document.body.removeChild(Ee),window.URL.revokeObjectURL(ve),re.success(`Downloaded ${_e.length} images as "${he}.zip"!`)}catch(ce){console.error("Failed to create ZIP:",ce),re.error("Failed to create download package")}g(!1),ae()},ne=J=>{h?Y(J.id):a(J)},te=({children:J})=>s?e.jsx(e.Fragment,{children:J}):e.jsx(Vs,{title:"Social Swag 2.0",children:J});return e.jsx(te,{children:e.jsxs("div",{className:"space-y-8",children:[!s&&e.jsxs("div",{className:"relative overflow-hidden rounded-2xl bg-gradient-to-br from-primary via-primary/80 to-info p-8 text-primary-foreground",children:[e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmYiIGZpbGwtb3BhY2l0eT0iMC4xIj48cGF0aCBkPSJNMzYgMzRjMC0yIDItNCAyLTRzMiAyIDIgNC0yIDQtMiA0LTItMi0yLTR6Ii8+PC9nPjwvZz48L3N2Zz4=')] opacity-30"}),e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3 mb-4",children:[e.jsxs($e,{variant:"secondary",className:"bg-white/20 text-white border-0 backdrop-blur-sm",children:[e.jsx(Nn,{className:"h-3 w-3 mr-1"}),"New content monthly"]}),e.jsxs($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(ha,{defaultValue:"gallery",className:"space-y-6",children:[!s&&e.jsxs(ma,{className:"grid w-full max-w-md grid-cols-2",children:[e.jsxs(Zt,{value:"gallery",className:"gap-2",children:[e.jsx(Hc,{className:"h-4 w-4"}),"Gallery"]}),e.jsxs(Zt,{value:"scheduled",className:"gap-2",children:[e.jsx(Wc,{className:"h-4 w-4"}),"Scheduled"]})]}),e.jsxs(Xt,{value:"gallery",className:"space-y-6",children:[P?e.jsx(je,{className:"border rounded-xl",children:e.jsx(Ie,{className:"p-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"p-3 rounded-full bg-muted text-2xl",children:"📸"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-semibold text-foreground mb-1",children:"Ready to post!"}),e.jsx("p",{className:"text-muted-foreground",children:'Click any image and use "Create Post" to share directly to your connected accounts.'})]}),e.jsx($,{variant:"outline",size:"sm",asChild:!0,className:"gap-2",children:e.jsx(wr,{to:"/mission-control/integrations",children:"Manage Accounts"})})]})})}):e.jsx(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(Ie,{className:"p-6",children:e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"p-2 rounded-full bg-blue-500/10",children:e.jsx(Qp,{className:"h-5 w-5 text-blue-600"})}),e.jsx("div",{className:"p-2 rounded-full bg-pink-500/10",children:e.jsx(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(wr,{to:"/social-connections",children:[e.jsx(Wd,{className:"h-4 w-4"}),"Connect Accounts"]})})]})})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"flex flex-wrap gap-2",children:D.map(J=>e.jsx("button",{onClick:()=>c(J),className:Pt("px-4 py-2 rounded-full text-sm font-medium transition-all",o===J?"bg-primary text-primary-foreground shadow-sm":"bg-muted text-muted-foreground hover:text-foreground"),children:O(J)},J))}),o!=="all"&&(W?e.jsxs("a",{href:W,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx("span",{className:"text-base",children:"🎨"}),"Edit ",O(o)," Images in Canva"]}):e.jsxs("span",{className:"inline-flex items-center gap-2 text-sm text-muted-foreground/50",children:[e.jsx("span",{className:"text-base",children:"🎨"}),"Edit ",O(o)," Images in Canva"]}))]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-1 p-1 bg-muted rounded-full",children:[e.jsxs("button",{onClick:()=>{y("images"),ae()},className:Pt("flex items-center gap-2 px-4 py-2 rounded-full text-sm font-medium transition-all",x==="images"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:[e.jsx(Hc,{className:"h-4 w-4"}),"Images"]}),e.jsxs("button",{onClick:()=>{y("reels"),ae()},className:Pt("flex items-center gap-2 px-4 py-2 rounded-full text-sm font-medium transition-all",x==="reels"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:[e.jsx(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(pr,{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(xi,{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(ca,{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:()=>ne(J),children:e.jsxs("div",{className:"relative aspect-[4/5] overflow-hidden",children:[e.jsx("img",{src:RBe(J.image_url,400,75),alt:"Social swag",className:"w-full h-full object-cover transition-transform duration-300 group-hover:scale-110",loading:"lazy",decoding:"async"}),J.post_date&&!h&&e.jsx("div",{className:"absolute top-0 left-0 w-24 h-24 overflow-hidden pointer-events-none",children:e.jsx("div",{className:"absolute flex items-center justify-center text-white font-bold text-[10px] tracking-wider uppercase",style:{top:"20px",left:"-34px",width:"136px",transform:"rotate(-45deg)",backgroundColor:"#2d5052",padding:"5px 0",boxShadow:"0 2px 4px rgba(0,0,0,0.25)"},children:en(new Date(J.post_date+"T00:00:00"),"MMM d")})}),h&&e.jsx("div",{className:Pt("absolute top-2 right-2 w-6 h-6 rounded-full border-2 flex items-center justify-center transition-all",ce?"bg-primary border-primary text-primary-foreground":"bg-white/80 border-muted-foreground/50"),children:ce&&e.jsx(ca,{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:RBe(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(zs,{open:!!r,onOpenChange:()=>a(null),children:e.jsx(Os,{className:"max-w-4xl max-h-[90vh] overflow-hidden p-0",children:e.jsx("div",{className:"max-h-[90vh] overflow-y-auto touch-pan-y",style:{WebkitOverflowScrolling:"touch"},children:r&&e.jsxs("div",{className:"flex flex-col md:flex-row",children:[e.jsx("div",{className:"md:w-1/2 bg-muted",children:e.jsx("div",{className:"aspect-[4/5]",children:e.jsx("img",{src:RBe(r.image_url,900,85),alt:"Social swag",className:"w-full h-full object-cover",decoding:"async"})})}),e.jsxs("div",{className:"md:w-1/2 p-6 flex flex-col",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-sm text-muted-foreground mb-4",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Ta,{className:"h-4 w-4"}),en(new Date(r.created_at),"MMMM d, yyyy")]}),r.post_date&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 font-medium rounded-full px-3 py-1 text-xs text-white",style:{background:"#406E71"},children:[e.jsx(Ta,{className:"h-3.5 w-3.5"}),"Post on ",en(new Date(r.post_date+"T00:00:00"),"MMMM d, yyyy")]})]}),e.jsxs("div",{className:"flex-1 min-h-0",children:[e.jsx("h4",{className:"text-sm font-medium text-foreground mb-2",children:"Caption"}),e.jsx("div",{className:"bg-muted/50 rounded-lg p-4 max-h-64 overflow-y-auto",children:e.jsx("p",{className:"text-sm text-foreground whitespace-pre-wrap",children:r.caption})})]}),e.jsxs("div",{className:"flex flex-col gap-3 mt-6",children:[e.jsxs($,{onClick:()=>{if(t){t({mediaUrl:r.image_url,mediaType:"image",caption:r.caption,swagItemId:r.id}),a(null);return}b({imageUrl:r.image_url,imageId:r.id,caption:r.caption})},className:"w-full gap-2 bg-gradient-to-r from-pink-500 via-purple-500 to-blue-500 hover:from-pink-600 hover:via-purple-600 hover:to-blue-600 text-white",children:[e.jsx(Kr,{className:"h-4 w-4"}),"Create Post"]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs($,{variant:"outline",onClick:()=>V(r.caption),className:"flex-1 gap-2",children:[e.jsx(Ha,{className:"h-4 w-4"}),"Copy Caption"]}),e.jsxs($,{variant:"outline",onClick:()=>G(r.image_url,r.id),className:"flex-1 gap-2",children:[e.jsx(xi,{className:"h-4 w-4"}),"Download"]})]})]})]})]})})})}),e.jsx(zs,{open:!!i,onOpenChange:()=>l(null),children:e.jsx(Os,{className:"max-w-4xl max-h-[90vh] overflow-hidden p-0",children:e.jsx("div",{className:"max-h-[90vh] overflow-y-auto touch-pan-y",style:{WebkitOverflowScrolling:"touch"},children:i&&e.jsxs("div",{className:"flex flex-col md:flex-row",children:[e.jsx("div",{className:"md:w-1/2 bg-black flex items-center justify-center",children:e.jsx("div",{className:"aspect-[9/16] max-h-[70vh]",children:e.jsx("img",{src:i.image_url,alt:"Reel preview",className:"w-full h-full object-contain"})})}),e.jsxs("div",{className:"md:w-1/2 p-6 flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-4",children:[e.jsx(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(Ha,{className:"h-4 w-4"}),"Copy Caption"]}),i.canva_link&&e.jsxs($,{variant:"outline",onClick:()=>window.open(i.canva_link,"_blank"),className:"flex-1 gap-2",children:[e.jsx(Fr,{className:"h-4 w-4"}),"Open in Canva"]})]})]})]})})})}),e.jsx(yin,{open:!!v,onOpenChange:J=>!J&&b(null),imageUrl:(v==null?void 0:v.imageUrl)||"",imageId:(v==null?void 0:v.imageId)||"",defaultCaption:(v==null?void 0:v.caption)||"",swagItemId:v==null?void 0:v.imageId})]}),e.jsx(Xt,{value:"scheduled",children:e.jsx(vin,{})})]})]})})},__t={facebook:{id:"facebook",label:"Facebook Page",icon:Qp,dot:"bg-blue-500",chip:"bg-blue-500/10 text-blue-600 border-blue-500/20",captionLimit:63206,supportsVideo:!0,requiresMedia:!1},instagram:{id:"instagram",label:"Instagram",icon: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:dy,dot:"bg-sky-600",chip:"bg-sky-600/10 text-sky-700 border-sky-600/20",captionLimit:3e3,supportsVideo:!1,requiresMedia:!1},google_business:{id:"google_business",label:"Google Business",icon:ci,dot:"bg-emerald-600",chip:"bg-emerald-600/10 text-emerald-700 border-emerald-600/20",captionLimit:1500,supportsVideo:!1,requiresMedia:!1}},O4=s=>__t[s]??__t.facebook,_in=[{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}],w_t="agent-uploads",win="social-studio",jin=200*1024*1024,j_t=s=>typeof s=="number"?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s):"";function Nin({onSelect:s}){const{user:t}=bs(),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>jin){re.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=`${win}/${t.id}/${crypto.randomUUID()}.${h}`,{error:f}=await q.storage.from(w_t).upload(m,d,{cacheControl:"3600",upsert:!1,contentType:d.type});if(f)throw f;const{data:g}=q.storage.from(w_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"}),re.success("Media uploaded")}catch(h){console.error(h),re.error("Upload failed. Please try again.")}finally{a(!1),n.current&&(n.current.value="")}};return e.jsxs(ha,{defaultValue:"upload",className:"space-y-4",children:[e.jsxs(ma,{className:"grid grid-cols-3 w-full",children:[e.jsxs(Zt,{value:"upload",className:"gap-2",children:[e.jsx(ni,{className:"h-4 w-4"}),"Upload"]}),e.jsxs(Zt,{value:"swag",className:"gap-2",children:[e.jsx(Nn,{className:"h-4 w-4"}),"Gallery"]}),e.jsxs(Zt,{value:"listings",className:"gap-2",children:[e.jsx(va,{className:"h-4 w-4"}),"Listings"]})]}),e.jsxs(Xt,{value:"upload",className:"space-y-4",children:[e.jsx("input",{ref:n,type:"file",accept:"image/*,video/*",className:"hidden",onChange: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(Ie,{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(uo,{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(Xt,{value:"swag",children:e.jsx(uo,{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(Xt,{value:"listings",children:e.jsx(uo,{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}`,j_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(Ie,{className:"p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:d.property_address||`${d.city}, ${d.state}`}),e.jsx("p",{className:"text-xs text-muted-foreground",children:j_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 kin({platform:s,accountName:t,avatarUrl:n,caption:r,mediaUrl:a,mediaType:i}){const l=O4(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(Kr,{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(qy,{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(YJ,{className:"h-4 w-4"})," Share"]})]})]})]})}function prt(){const{user:s}=bs();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 Sin(s){const{user:t}=bs();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 ZHt(){const s=Wt();return()=>{s.invalidateQueries({queryKey:["studio-posts"]}),s.invalidateQueries({queryKey:["studio-accounts"]})}}const Cin="America/New_York",XHt="levelup.calendar.timezone";function p7(s){if(!s)return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:s}),!0}catch{return!1}}function Ain(){try{const s=localStorage.getItem(XHt);if(p7(s))return s}catch{}return null}let y3e=Ain();function MT(){return y3e||pie()}function N_t(s){y3e=p7(s)?s:pie();try{localStorage.setItem(XHt,y3e)}catch{}return y3e}function pie(){const s=Intl.DateTimeFormat().resolvedOptions().timeZone;return p7(s)?s:Cin}function dL(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 DBe(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 Ein(){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 Tin(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 xK(){const{user:s}=bs(),t=Wt(),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&&p7(n.data)&&N_t(n.data)},[n.data]);const r=p7(n.data)?n.data:MT()||pie(),a=mt({mutationFn:async i=>{if(!p7(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:Tin(s.email,s.id),timezone:i,is_active:!1});if(c)throw c}return N_t(i),i},onSuccess:i=>{t.setQueryData(["calendar-timezone",s==null?void 0:s.id],i),t.invalidateQueries({queryKey:["booking-settings"]}),t.invalidateQueries({queryKey:["my-calendar"]}),re.success("Calendar timezone updated")},onError:i=>re.error(i.message||"Could not update timezone")});return{timezone:r,isLoading:n.isLoading,update:a}}function JHt({open:s,onOpenChange:t}){const{timezone:n,update:r}=xK(),[a,i]=j.useState(n),[l,o]=j.useState("");j.useEffect(()=>{s&&(i(n),o(""))},[s,n]);const c=pie(),d=j.useMemo(()=>{const h=l.trim().toLowerCase();return h?Ein().filter(m=>m.toLowerCase().includes(h.replace(/\s+/g,"_"))).slice(0,40):[]},[l]),u=()=>{r.mutate(a,{onSuccess:()=>t(!1)})};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-lg max-h-[85vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(CN,{className:"h-4 w-4 text-primary"}),"Calendar settings"]}),e.jsx(Pr,{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:["· ",DBe(a)," ",dL(a)]})]})]}),c!==a&&e.jsxs($,{type:"button",variant:"outline",size:"sm",className:"w-full justify-start gap-2",onClick:()=>i(c),children:[e.jsx(ci,{className:"h-4 w-4"}),"Use my device timezone (",c.replace(/_/g," "),")"]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-sm font-medium",children:"Common timezones"}),e.jsx("div",{className:"grid gap-1.5",children: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:DBe(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:DBe(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 r4=s=>String(s).padStart(2,"0");function gie(s){return p7(s)?s:MT()}function grt(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 k_t(s,t){const n=grt(s,t);return Date.UTC(n.year,n.month-1,n.day,n.hour,n.minute,n.second)-s.getTime()}function OTe(s,t){const n=gie(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-k_t(new Date(u),n));return h=new Date(u-k_t(h,n)),h}function eGt(s,t){const n=gie(t),r=typeof s=="string"?new Date(s):s,a=grt(r,n);return`${a.year}-${r4(a.month)}-${r4(a.day)}T${r4(a.hour)}:${r4(a.minute)}`}function Min(s,t){const n=gie(t),r=typeof s=="string"?new Date(s):s,a=grt(r,n);return`${a.year}-${a.month-1}-${a.day}`}function tGt(s,t,n){const r=typeof s=="string"?new Date(s):s;return new Intl.DateTimeFormat("en-US",{timeZone:gie(t),...n}).format(r)}function sGt(s,t){return tGt(s,t,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZoneName:"short"})}function Pin(s,t){return tGt(s,t,{hour:"numeric",minute:"2-digit"})}function Iin(s,t,n,r){const a=gie(n),i=r&&r.includes("T")?r.split("T")[0]:eGt(new Date,a).split("T")[0];let l=`${i}T${r4(s)}:${r4(t)}`;if(OTe(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()}-${r4(u.getUTCMonth()+1)}-${r4(u.getUTCDate())}T${r4(s)}:${r4(t)}`}return l}const Nde=s=>s.page_name||s.platform_username||O4(s.platform).label;function Lin({seed:s,editingPost:t,onSaved:n,onCancelEdit:r}){const{user:a}=bs(),{data:i=[],isLoading:l}=prt(),{timezone:o}=xK(),[c,d]=j.useState(!1),u=ue=>eGt(ue,o),[h,m]=j.useState(""),[f,g]=j.useState(null),[x,y]=j.useState("text"),[v,b]=j.useState("manual"),[w,S]=j.useState([]),[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),y(s.mediaType??"image")),s.caption!==void 0&&m(s.caption),s.source&&b(s.source),s.scheduledFor&&(D(!0),U(u(s.scheduledFor))))},[s]),j.useEffect(()=>{var ve;if(!t)return;m(t.caption??""),g(((ve=t.media_urls)==null?void 0:ve[0])??null),y(t.media_type),b(t.source??"manual"),S(t.social_post_targets.map(Ee=>Ee.social_account_id));const ue={};t.social_post_targets.forEach(Ee=>{Ee.caption_override&&(ue[Ee.social_account_id]=Ee.caption_override)}),E(ue),P(Object.keys(ue).length>0),t.scheduled_for&&(D(!0),U(u(new Date(t.scheduled_for))))},[t]);const G=j.useMemo(()=>i.filter(ue=>w.includes(ue.id)),[i,w]),Y=ue=>{var ve;return I&&((ve=A[ue])!=null&&ve.trim())?A[ue]:h},X=j.useMemo(()=>{const ue=[];return G.forEach(ve=>{const Ee=O4(ve.platform),Se=Y(ve.id);Ee.requiresMedia&&!f&&ue.push(`${Ee.label} requires a photo or video.`),!Ee.supportsVideo&&x==="video"&&ue.push(`${Ee.label} can't publish video from LevelUp yet.`),Se.length>Ee.captionLimit&&ue.push(`${Ee.label} caption is over the ${Ee.captionLimit.toLocaleString()} character limit.`)}),Array.from(new Set(ue))},[G,f,x,h,A,I]),ae=()=>{m(""),g(null),y("text"),b("manual"),S([]),E({}),P(!1),D(!1),U("")},le=ue=>{g(ue.mediaUrl),y(ue.mediaType),b(ue.source),ue.caption&&!h.trim()&&m(ue.caption)},ne=ue=>S(ve=>ve.includes(ue)?ve.filter(Ee=>Ee!==ue):[...ve,ue]),te=async ue=>{if(a!=null&&a.id){if(ue!=="draft"&&w.length===0){re.error("Choose at least one account to post to.");return}if(ue!=="draft"&&!h.trim()&&!f){re.error("Add a caption or media before publishing.");return}if(ue==="schedule"&&!O){re.error("Pick a date and time to schedule.");return}if(ue!=="draft"&&X.length>0){re.error(X[0]);return}V(ue);try{const ve={user_id:a.id,caption:h.trim()||null,media_type:x,media_urls:f?[f]:[],source:v,status:ue==="draft"?"draft":ue==="schedule"?"scheduled":"publishing",scheduled_for:ue==="schedule"?OTe(O,o).toISOString():null,timezone:o};let Ee=(t==null?void 0:t.id)??null;if(Ee){const{error:Se}=await q.from("social_posts").update(ve).eq("id",Ee);if(Se)throw Se;await q.from("social_post_targets").delete().eq("post_id",Ee)}else{const{data:Se,error:Le}=await q.from("social_posts").insert(ve).select("id").single();if(Le)throw Le;Ee=Se.id}if(w.length>0){const Se=G.map(Fe=>{var ke;return{post_id:Ee,user_id:a.id,social_account_id:Fe.id,platform:Fe.platform,caption_override:I&&((ke=A[Fe.id])!=null&&ke.trim())?A[Fe.id].trim():null,status:"pending"}}),{error:Le}=await q.from("social_post_targets").insert(Se);if(Le)throw Le}if(ue==="now"){const{data:Se,error:Le}=await q.functions.invoke("social-publish-post",{body:{post_id:Ee}});if(Le)throw Le;const Fe=Se==null?void 0:Se.status;Fe==="failed"?re.error("Publishing failed. Check the Queue tab for details."):Fe==="partial"?re.warning("Some accounts failed. Check the Queue tab to retry."):re.success("Posted to your accounts.")}else re.success(ue==="draft"?"Draft saved":"Post scheduled");t||ae(),n==null||n()}catch(ve){console.error(ve),re.error((ve==null?void 0:ve.message)??"Something went wrong saving your post.")}finally{V(null)}}},J=(ue,ve)=>{D(!0),U(Iin(ue,ve,o,O))},ce=dL(o),_e=pie(),he=_e!==o;return e.jsxs("div",{className:"grid gap-6 lg:grid-cols-[minmax(0,1fr)_380px]",children:[e.jsxs("div",{className:"space-y-6",children:[t&&e.jsx(Sse,{children:e.jsxs(Cse,{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(pr,{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(Ie,{className:"space-y-4",children:[f&&e.jsxs("div",{className:"relative w-full max-w-xs overflow-hidden rounded-lg border",children:[x==="video"?e.jsx("video",{src:f,className:"w-full",controls:!0,playsInline:!0}):e.jsx("img",{src:f,alt:"Selected media",className:"w-full object-cover"}),e.jsx($,{variant:"secondary",size:"icon",className:"absolute top-2 right-2 h-8 w-8",onClick:()=>{g(null),y("text")},children:e.jsx(Hn,{className:"h-4 w-4"})})]}),e.jsx(Nin,{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(Ie,{className:"space-y-4",children:[e.jsx(Ls,{value:h,onChange:ue=>m(ue.target.value),rows:6,placeholder:"What do you want to share with your audience?"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-xs text-muted-foreground",children:[h.length," characters"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ee,{htmlFor:"per-platform",className:"text-xs",children:"Customize per platform"}),e.jsx(Sn,{id:"per-platform",checked:I,onCheckedChange:P})]})]}),I&&G.length>0&&e.jsxs(ha,{defaultValue:G[0].id,className:"pt-2",children:[e.jsx(ma,{className:"flex-wrap h-auto",children:G.map(ue=>e.jsx(Zt,{value:ue.id,className:"text-xs",children:Nde(ue)},ue.id))}),G.map(ue=>e.jsx(Xt,{value:ue.id,className:"pt-3",children:e.jsx(Ls,{rows:5,value:A[ue.id]??"",placeholder:`Leave blank to use the main caption for ${O4(ue.platform).label}`,onChange:ve=>E(Ee=>({...Ee,[ue.id]:ve.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(Ie,{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 ve=O4(ue.platform),Ee=ve.icon,Se=w.includes(ue.id);return e.jsxs("button",{type:"button",onClick:()=>ne(ue.id),className:`flex items-center gap-3 rounded-lg border p-3 text-left transition ${Se?"border-primary bg-primary/5":"hover:bg-muted/50"}`,children:[e.jsxs(Oa,{className:"h-9 w-9",children:[e.jsx(Ii,{src:ue.profile_picture_url??void 0}),e.jsx(za,{children:Nde(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:Nde(ue)}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Ee,{className:"h-3 w-3"})," ",ve.label]})]}),Se&&e.jsx(ca,{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(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"schedule-toggle",children:"Schedule for later"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Otherwise it goes out right away."})]}),e.jsx(Sn,{id:"schedule-toggle",checked:R,onCheckedChange:D})]}),R&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(pe,{type:"datetime-local",value:O,onChange:ue=>U(ue.target.value)}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(CN,{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:sGt(OTe(O,o),o)})]}),he&&e.jsxs("p",{className:"text-xs text-amber-600",children:["Your device is set to ",_e.replace(/_/g," ")," — posts still go out on your ",ce||"saved"," schedule."]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:_in.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(Sse,{variant:"destructive",children:[e.jsx(Al,{className:"h-4 w-4"}),e.jsx(Cse,{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(Cu,{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(Kr,{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(Ie,{className:"p-6 text-sm text-muted-foreground",children:"Select an account to see exactly how your post will look."})}):e.jsx("div",{className:"space-y-4",children:G.map(ue=>e.jsx(kin,{platform:ue.platform,accountName:Nde(ue),avatarUrl:ue.profile_picture_url,caption:Y(ue.id),mediaUrl:f,mediaType:x},ue.id))})]}),e.jsx(JHt,{open:c,onOpenChange:d})]})}const Rin=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],S_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 Din({posts:s,onCreateAt:t,onOpenPost:n}){const{timezone:r}=xK(),a=dL(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=Min(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(Ie,{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold",children:i.toLocaleDateString("en-US",{month:"long",year:"numeric"})}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["All times ",a||r.replace(/_/g," ")]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($,{variant:"outline",size:"sm",onClick:()=>l(new Date(d.getFullYear(),d.getMonth(),1)),children:"Today"}),e.jsx($,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>l(new Date(i.getFullYear(),i.getMonth()-1,1)),children:e.jsx(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:Rin.map(h=>e.jsx("div",{className:"py-1",children:h},h))}),e.jsx("div",{className:"grid grid-cols-7 gap-px bg-border rounded-lg overflow-hidden",children:o.map(h=>{const m=`${h.getFullYear()}-${h.getMonth()}-${h.getDate()}`,f=c.get(m)??[],g=h.getMonth()!==i.getMonth();return e.jsxs("div",{className:`group relative min-h-[104px] bg-background p-1.5 ${g?"opacity-50":""}`,children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:`text-xs ${u(h)?"flex h-5 w-5 items-center justify-center rounded-full bg-primary text-primary-foreground":"text-muted-foreground"}`,children:h.getDate()}),e.jsx("button",{type:"button","aria-label":"Create post",onClick:()=>{const x=new Date(h);x.setHours(9,0,0,0),t(x)},className:"opacity-0 group-hover:opacity-100 transition text-muted-foreground hover:text-foreground",children:e.jsx(dn,{className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"mt-1 space-y-1",children:[f.slice(0,3).map(x=>{var v;const y=x.scheduled_for??x.published_at;return e.jsxs("button",{type:"button",onClick:()=>n(x),className:`w-full rounded border px-1.5 py-1 text-left text-[10px] leading-tight ${S_t[x.status]??S_t.draft}`,children:[e.jsx("span",{className:"font-medium",children:Pin(y,r)})," ",e.jsx("span",{className:"truncate",children:((v=x.caption)==null?void 0:v.slice(0,24))||"Media post"}),e.jsx("span",{className:"mt-1 flex gap-1",children:x.social_post_targets.slice(0,4).map(b=>e.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${O4(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 Fin=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:Cu};default:return{label:"Draft",variant:"outline",icon:pi}}};function C_t({posts:s,accounts:t,onEdit:n,onChanged:r,emptyLabel:a}){const[i,l]=j.useState(null),{timezone:o}=xK(),c=h=>t.find(m=>m.id===h),d=async h=>{l(h.id);try{await q.from("social_posts").update({status:"publishing",scheduled_for:null,error_message:null}).eq("id",h.id),await q.from("social_post_targets").update({status:"pending"}).eq("post_id",h.id).in("status",["cancelled","failed"]);const{data:m,error:f}=await q.functions.invoke("social-publish-post",{body:{post_id:h.id}});if(f)throw f;const g=m==null?void 0:m.status;g==="failed"?re.error("Publishing failed. See the error details below."):g==="partial"?re.warning("Some accounts failed."):re.success("Published."),r()}catch(m){re.error((m==null?void 0:m.message)??"Could not publish this post.")}finally{l(null)}},u=async h=>{l(h.id);try{const{error:m}=await q.from("social_posts").delete().eq("id",h.id);if(m)throw m;re.success("Post deleted"),r()}catch(m){re.error((m==null?void 0:m.message)??"Could not delete this post.")}finally{l(null)}};return s.length===0?e.jsx(je,{children:e.jsx(Ie,{className:"p-8 text-center text-sm text-muted-foreground",children:a??"Nothing here yet."})}):e.jsx("div",{className:"space-y-3",children:s.map(h=>{var y,v;const f=h.status==="failed"&&!!((y=h.error_message)!=null&&y.startsWith("Missed its scheduled time"))?{label:"Didn't send",variant:"destructive",icon:Al}:Fin(h.status),g=f.icon,x=h.scheduled_for??h.published_at??h.created_at;return e.jsx(je,{children:e.jsx(Ie,{className:"p-4",children:e.jsxs("div",{className:"flex gap-4",children:[((v=h.media_urls)==null?void 0:v[0])&&(h.media_type==="video"?e.jsx("video",{src:h.media_urls[0],className:"h-20 w-20 rounded-lg object-cover shrink-0"}):e.jsx("img",{src:h.media_urls[0],alt:"",loading:"lazy",className:"h-20 w-20 rounded-lg object-cover shrink-0"})),e.jsxs("div",{className:"min-w-0 flex-1 space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs($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:sGt(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=O4(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(Fr,{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:[O4(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(ro,{className:"h-3.5 w-3.5"}):e.jsx(Kr,{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(Hn,{className:"h-3.5 w-3.5"})," Delete"]})]})]})})},h.id)})})}const Oin=()=>{const[s,t]=j.useState("compose"),[n,r]=j.useState(null),[a,i]=j.useState(null);j.useEffect(()=>{const x=sessionStorage.getItem("social-studio-seed");if(x){sessionStorage.removeItem("social-studio-seed");try{const y=JSON.parse(x);(y!=null&&y.mediaUrl||y!=null&&y.caption)&&(r(y),t("compose"))}catch{}}},[]);const{data:l=[]}=prt(),{data:o=[],isLoading:c}=Sin(),d=ZHt(),u=j.useMemo(()=>o.filter(x=>x.status==="scheduled"||x.status==="draft"||x.status==="publishing").sort((x,y)=>new Date(x.scheduled_for??x.created_at).getTime()-new Date(y.scheduled_for??y.created_at).getTime()),[o]),h=j.useMemo(()=>o.filter(x=>["published","partial","failed","cancelled"].includes(x.status)),[o]),m=h.filter(x=>x.status==="failed"||x.status==="partial").length,f=(x,y=null)=>{r(x),i(y),t("compose")},g=x=>{f({mediaUrl:x.mediaUrl,mediaType:x.mediaType,caption:x.caption,source:"swag",sourceRef:x.swagItemId??x.reelId})};return e.jsx(Vs,{title:"Social Studio",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(je,{className:"overflow-hidden border-none bg-gradient-to-br from-primary/10 via-background to-background",children:e.jsxs(Ie,{className:"p-6 flex flex-col gap-5 md:flex-row md:items-center md:justify-between",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs($e,{variant:"secondary",className:"gap-1",children:[e.jsx(Nn,{className:"h-3 w-3"})," Social Studio"]}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Post everywhere, from one place"}),e.jsx("p",{className:"text-sm text-muted-foreground max-w-xl",children:"Write once, preview each network, and publish or schedule to every connected account."})]}),e.jsxs("div",{className:"flex flex-col items-start gap-3 md:items-end",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[l.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No accounts connected yet"}):e.jsx("div",{className:"flex -space-x-2",children:l.slice(0,6).map(x=>e.jsxs(Oa,{className:"h-8 w-8 border-2 border-background",title:x.page_name??x.platform,children:[e.jsx(Ii,{src:x.profile_picture_url??void 0}),e.jsx(za,{className:"text-[10px]",children:O4(x.platform).label.slice(0,2)})]},x.id))}),e.jsx($,{variant:"outline",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(wr,{to:"/social-connections",children:[e.jsx(eC,{className:"h-4 w-4"})," Manage accounts"]})})]}),e.jsxs($,{className:"gap-2",onClick:()=>f(null),children:[e.jsx(_p,{className:"h-4 w-4"})," New post"]})]})]})}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-3",children:[{label:"Connected accounts",value:l.length,icon:M4},{label:"Scheduled & drafts",value:u.length,icon:Wc},{label:"Published",value:h.filter(x=>x.status==="published").length,icon:Vr}].map(({label:x,value:y,icon:v})=>e.jsx(je,{children:e.jsxs(Ie,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"rounded-lg bg-primary/10 p-2",children:e.jsx(v,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xl font-semibold leading-none",children:y}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:x})]})]})},x))}),e.jsxs(ha,{value:s,onValueChange:t,className:"space-y-6",children:[e.jsxs(ma,{className:"flex-wrap h-auto",children:[e.jsxs(Zt,{value:"compose",className:"gap-2",children:[e.jsx(_p,{className:"h-4 w-4"}),"Compose"]}),e.jsxs(Zt,{value:"calendar",className:"gap-2",children:[e.jsx(Wc,{className:"h-4 w-4"}),"Calendar"]}),e.jsxs(Zt,{value:"queue",className:"gap-2",children:[e.jsx(Kr,{className:"h-4 w-4"}),"Queue",u.length>0&&e.jsx($e,{variant:"secondary",className:"ml-1",children:u.length})]}),e.jsxs(Zt,{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(Zt,{value:"gallery",className:"gap-2",children:[e.jsx(Nn,{className:"h-4 w-4"}),"Swag gallery"]})]}),e.jsx(Xt,{value:"compose",children:e.jsx(Lin,{seed:n,editingPost:a,onSaved:()=>{d(),i(null),r(null)},onCancelEdit:()=>{i(null),r(null)}})}),e.jsx(Xt,{value:"calendar",children:e.jsx(Din,{posts:o,onCreateAt:x=>f({scheduledFor:x}),onOpenPost:x=>f(null,x)})}),e.jsx(Xt,{value:"queue",children:e.jsx(C_t,{posts:u,accounts:l,onEdit:x=>f(null,x),onChanged:d,emptyLabel:c?"Loading your posts…":"Nothing scheduled yet. Compose a post to get started."})}),e.jsx(Xt,{value:"history",children:e.jsx(C_t,{posts:h,accounts:l,onEdit:x=>f(null,x),onChanged:d,emptyLabel:"Your published posts will show up here."})}),e.jsx(Xt,{value:"gallery",children:e.jsx(YHt,{embedded:!0,onCompose:g})})]})]})})},zin=[{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:Fg,comingSoon:!0,color:"from-pink-500 to-rose-500"},{id:"holiday",title:"Holiday & Seasonal",description:"Pre-designed templates for every holiday, restyled to your brand.",icon:Xj,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:PE,comingSoon:!0,color:"from-amber-500 to-yellow-500"}];function Bin(){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(Nn,{className:"h-3 w-3"})," New"]}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold tracking-tight",children:"Marketing Studio"}),e.jsx("p",{className:"text-muted-foreground max-w-2xl mt-1",children:"Your one-stop creative hub. Drop in any photo or video, and walk away with a fully branded export — no design skills, no AI credits."})]}),e.jsx($,{variant:"outline",asChild:!0,children:e.jsxs(wr,{to:"/marketing-studio/brand-kit",children:[e.jsx(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:zin.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(Ie,{className:"p-5 space-y-3",children:[e.jsx("div",{className:`inline-flex h-10 w-10 items-center justify-center rounded-lg bg-gradient-to-br ${s.color} text-white shadow-md`,children:e.jsx(t,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold",children:s.title}),s.comingSoon&&e.jsx($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(wr,{to:s.to,className:"block",children:n},s.id):e.jsx("div",{children:n},s.id)})})]})})}function xie(){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 $in(){const{data:s,...t}=xie();return{data:(s==null?void 0:s.find(n=>n.is_default))??(s==null?void 0:s[0])??null,...t}}function Uin(){const s=Sa(),t=Wt();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 qin(){const s=Sa(),t=Wt();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 Vin(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 Hin({preset:s,onSaved:t,onCancel:n}){var x;const r=Sa(),a=Uin(),i=qin(),l=j.useRef(null),o=j.useRef(null),[c,d]=j.useState(null),[u,h]=j.useState({name:(s==null?void 0:s.name)??"My Brand",is_default:(s==null?void 0:s.is_default)??!0,display_name:(s==null?void 0:s.display_name)??"",phone:(s==null?void 0:s.phone)??"",email:(s==null?void 0:s.email)??"",license_number:(s==null?void 0:s.license_number)??"",tagline:(s==null?void 0:s.tagline)??"",website_url:(s==null?void 0:s.website_url)??"",headshot_url:(s==null?void 0:s.headshot_url)??"",brokerage_logo_url:(s==null?void 0:s.brokerage_logo_url)??"",brand_color:(s==null?void 0:s.brand_color)??"#0f172a",accent_color:(s==null?void 0:s.accent_color)??"#3b82f6"});j.useEffect(()=>{s||(async()=>{if(!r)return;const{supabase:y}=await ri(async()=>{const{supabase:b}=await Promise.resolve().then(()=>Mks);return{supabase:b}},void 0),{data:v}=await y.from("profiles").select("name, email, phone, avatar_url, website_url, title, brokerage_id").eq("id",r).maybeSingle();v&&h(b=>({...b,display_name:b.display_name||(v.name??""),email:b.email||(v.email??""),phone:b.phone||(v.phone??""),headshot_url:b.headshot_url||(v.avatar_url??""),website_url:b.website_url||(v.website_url??""),tagline:b.tagline||(v.title??"")}))})()},[r]);const m=async(y,v)=>{if(r){d(y);try{const b=await Vin(r,v,y);h(w=>({...w,[y==="headshot"?"headshot_url":"brokerage_logo_url"]:b}))}catch(b){re.error(b.message||"Upload failed")}finally{d(null)}}},f=async()=>{try{const y=await a.mutateAsync({id:s==null?void 0:s.id,...u});re.success("Brand preset saved"),t==null||t(y)}catch(y){re.error(y.message||"Save failed")}},g=async()=>{s!=null&&s.id&&await fo("Delete this brand preset?")&&(await i.mutateAsync(s.id),re.success("Preset deleted"),n==null||n())};return e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Preset name"}),e.jsx(pe,{value:u.name,onChange:y=>h({...u,name:y.target.value}),placeholder:"Personal, Team, Luxury..."})]}),e.jsxs("div",{className:"flex items-end gap-3 pb-1",children:[e.jsx(Sn,{checked:u.is_default,onCheckedChange:y=>h({...u,is_default:y})}),e.jsx(ee,{children:"Use as default"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Display name"}),e.jsx(pe,{value:u.display_name,onChange:y=>h({...u,display_name:y.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Phone"}),e.jsx(pe,{value:u.phone,onChange:y=>h({...u,phone:y.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Email"}),e.jsx(pe,{value:u.email,onChange:y=>h({...u,email:y.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"License #"}),e.jsx(pe,{value:u.license_number,onChange:y=>h({...u,license_number:y.target.value})})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(ee,{children:"Tagline"}),e.jsx(pe,{value:u.tagline,onChange:y=>h({...u,tagline:y.target.value}),placeholder:"Helping families find home"})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(ee,{children:"Website"}),e.jsx(pe,{value:u.website_url,onChange:y=>h({...u,website_url:y.target.value})})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Headshot"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(Oa,{className:"h-16 w-16",children:[e.jsx(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 y;return(y=l.current)==null?void 0:y.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:y=>{var v;return((v=y.target.files)==null?void 0:v[0])&&m("headshot",y.target.files[0])}})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Brokerage logo"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-16 w-24 bg-muted rounded flex items-center justify-center overflow-hidden border",children:u.brokerage_logo_url?e.jsx("img",{src:u.brokerage_logo_url,alt:"logo",className:"max-h-full max-w-full object-contain"}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"No logo"})}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:()=>{var y;return(y=o.current)==null?void 0:y.click()},disabled:c==="logo",children:[c==="logo"?e.jsx(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:y=>{var v;return((v=y.target.files)==null?void 0:v[0])&&m("logo",y.target.files[0])}})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Brand color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:u.brand_color,onChange:y=>h({...u,brand_color:y.target.value}),className:"h-10 w-14 rounded cursor-pointer border"}),e.jsx(pe,{value:u.brand_color,onChange:y=>h({...u,brand_color:y.target.value})})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Accent color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:u.accent_color,onChange:y=>h({...u,accent_color:y.target.value}),className:"h-10 w-14 rounded cursor-pointer border"}),e.jsx(pe,{value:u.accent_color,onChange:y=>h({...u,accent_color:y.target.value})})]})]})]}),e.jsxs("div",{className:"flex justify-between pt-2",children:[e.jsx("div",{children:(s==null?void 0:s.id)&&e.jsxs($,{variant:"ghost",size:"sm",onClick:g,className:"text-destructive",children:[e.jsx(Hn,{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 Gin(){const{data:s,isLoading:t}=xie(),[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(wr,{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(dn,{className:"h-4 w-4 mr-1"})," New preset"]})]}),t&&e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading..."}),!t&&s&&s.length===0&&e.jsx(je,{className:"border-dashed",children:e.jsxs(Ie,{className:"py-12 text-center space-y-3",children:[e.jsx("h3",{className:"font-semibold",children:"Create your first brand preset"}),e.jsx("p",{className:"text-sm text-muted-foreground max-w-md mx-auto",children:"We'll pre-fill from your profile. You can have multiple presets — Personal, Team, Luxury division — and switch between them."}),e.jsxs($,{onClick:()=>r("new"),children:[e.jsx(dn,{className:"h-4 w-4 mr-1"})," Create preset"]})]})}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2",children:s==null?void 0:s.map(a=>e.jsxs(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(Gn,{children:a.display_name})]}),e.jsxs(Ie,{className:"text-sm text-muted-foreground space-y-1",children:[a.tagline&&e.jsxs("div",{className:"italic",children:['"',a.tagline,'"']}),a.phone&&e.jsx("div",{children:a.phone}),a.email&&e.jsx("div",{children:a.email})]})]},a.id))}),e.jsx(zs,{open:n!==null,onOpenChange:a=>!a&&r(null),children:e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto w-[calc(100vw-2rem)] sm:w-full",children:[e.jsx(Us,{children:e.jsx(Bs,{children:n==="new"?"New brand preset":"Edit brand preset"})}),e.jsx(Hin,{preset:n==="new"?null:n,onSaved:()=>r(null),onCancel:()=>r(null)})]})})]})})}const AWe=[{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"}],Win=s=>AWe.find(t=>t.id===s)??AWe[0];function Kin(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 Yin({value:s,onChange:t,mediaType:n}){const r=AWe.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 Xin=Math.PI/180;function Qin(){return typeof window<"u"&&({}.toString.call(window)==="[object Window]"||{}.toString.call(window)==="[object global]")}const eq=typeof global<"u"?global:typeof window<"u"?window:typeof WorkerGlobalScope<"u"?self:{},Qo={_global:eq,version:"10.7.0",isBrowser:Qin(),isUnminified:/param/.test((function(s){}).toString()),dblClickWindow:400,getAngle(s){return Qo.angleDeg?s*Xin: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:eq.document,_injectGlobal(s){typeof eq.Konva<"u"&&console.error("Several Konva instances detected. It is not recommended to use multiple Konva instances in the same environment."),eq.Konva=s}},nGt=new Set,Yg=(s,t=!1)=>{Qo[s.prototype.getClassName()]=s,t&&nGt.add(s)};Qo._injectGlobal(Qo);const Jin=`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"; `,A_t=()=>{if(typeof document>"u")throw new Error(Jin)};class b0{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 b0(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=Jn._getRotation(c.rotation),c}}const eon="[object Array]",ton="[object Number]",son="[object String]",non="[object Boolean]",ron=Math.PI/180,rGt=180/Math.PI,FBe="#",aon="",ion="0",oon="Konva warning: ",E_t="Konva error: ",lon={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 RZ=null;const con=typeof window<"u"?window:{},OBe=new WeakMap,don=(s,t)=>{typeof s.requestAnimationFrame=="function"?s.requestAnimationFrame(t):typeof requestAnimationFrame<"u"?requestAnimationFrame(t):setTimeout(t,16)},T_t=new Map,aGt=Object.getPrototypeOf(Int8Array),M_t=s=>{const t=s.trim();return t.indexOf(",")===-1?t.split(/\s*\/\s*|\s+/):t.split(/\s*,\s*/)},iGt="[+-]?(?:\\d+\\.?\\d*|\\.\\d+)(?:e[+-]?\\d+)?",uon=new RegExp(`^(${iGt})(%?)$`,"i"),pR=(s,t)=>{const n=uon.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)},kde=/^#[0-9a-f]+$/i,hon=new RegExp(`^(${iGt})(deg|grad|rad|turn)?$`,"i"),mon={deg:1,grad:.9,rad:rGt,turn:360};function DZ(s,t){return Math.min(Math.max(s||0,0),t)}const Jn={_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)===eon},_isNumber(s){return Object.prototype.toString.call(s)===ton&&!isNaN(s)&&isFinite(s)},_isString(s){return Object.prototype.toString.call(s)===son},_isBoolean(s){return Object.prototype.toString.call(s)===non},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||con;let r=OBe.get(n);r||(r=[],OBe.set(n,r),don(n,function(){OBe.delete(n),r.forEach(function(a){a()})})),r.push(s)},createCanvasElement(){A_t();const s=document.createElement("canvas");try{s.style=s.style||{}}catch{}return s},createImageElement(){return A_t(),document.createElement("img")},_urlToImage(s,t,n){const r=Jn.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(FBe,aon);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=ion+s;return FBe+s},isCanvasFarblingActive(){if(RZ!==null)return RZ;if(typeof document>"u")return RZ=!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 RZ=r,this.releaseCanvas(s),RZ},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 FBe+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=Jn.colorToRGBA(s))!==null&&t!==void 0?t:{};return{r:n,g:r,b:a}},colorToRGBA(s){s=(s||"").trim()||"black";const t=Jn._namedColorToRBA(s)||Jn._hex3ColorToRGBA(s)||Jn._hex4ColorToRGBA(s)||Jn._hex6ColorToRGBA(s)||Jn._hex8ColorToRGBA(s)||Jn._rgbColorToRGBA(s)||Jn._hslColorToRGBA(s);if(t&&[t.r,t.g,t.b,t.a].every(Jn._isNumber))return t},_namedColorToRBA(s){const t=lon[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=M_t(t[1]);if(!(n.length<3||n.length>4))return{r:pR(n[0],255),g:pR(n[1],255),b:pR(n[2],255),a:n.length>3?pR(n[3],1):1}},_hex8ColorToRGBA(s){if(s.length===9&&kde.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&&kde.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&&kde.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&&kde.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=M_t(t[1]);if(n.length<3||n.length>4)return;const r=hon.exec(n[0]);if(!r)return;const a=r[2],i=Number(r[1])*(a?mon[a.toLowerCase()]:1);if(!isFinite(i))return;const l=(i%360+360)%360/360,o=pR(n[1],100)/100,c=pR(n[2],100)/100,d=n.length>3?pR(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(Jn._cloneValue):s.slice():Jn._isPlainObject(s)?Jn.cloneObject(s):s instanceof aGt?s.slice():s},cloneArray(s){return s.slice(0)},degToRad(s){return s*ron},radToDeg(s){return s*rGt},_getRotation(s){return Qo.angleDeg?Jn.radToDeg(s):s},_capitalize(s){const t=T_t.get(s);if(t!==void 0)return t;const n=s.charAt(0).toUpperCase()+s.slice(1);return T_t.set(s,n),n},throw(s){throw new Error(E_t+s)},error(s){console.error(E_t+s)},warn(s){Qo.showWarnings&&console.warn(oon+s)},_batchEvents(s,t){if(!s)return t();let n=!1,r=!0;try{s(()=>{if(n||!r){Jn.warn("eventBatchFunc must call its argument exactly once, synchronously.");return}n=!0,t()})}finally{r=!1,n||Jn.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=Jn.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=Jn._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=DZ(s,r);return[a,a,a,a]}return[DZ(s[0],r),DZ(s[1],r),DZ(s[2],r),DZ(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]=Jn._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+=gon+d.join(pon)+xon)):(i+=o.property,t||(i+=bon+o.val)),i+=yon;return i}clearTrace(){this.traceArr=[]}_trace(t){let n=this.traceArr,r;n.push(t),r=n.length,r>=won&&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=P_t.length,r=this.setAttr,a,i;const l=function(o){let c=t[o],d;t[o]=function(){return i=fon(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 g7({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(),Jn.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 Non(this,{willReadFrequently:t.willReadFrequently}),this.setSize(t.width,t.height)}}class yrt extends xrt{constructor(t={width:0,height:0}){super(t),this.hitCanvas=!0,this.context=new kon(this),this.context.imageSmoothingEnabled=!1,this.setSize(t.width,t.height)}}const fh={get isDragging(){let s=!1;return fh._dragElements.forEach(t=>{t.dragStatus==="dragging"&&(s=!0)}),s},get node(){let s;for(const t of fh._dragElements.values()){if(t.dragStatus==="dragging")return t.node;s=t.node}return s},_dragElements:new Map,_listenToWindow(s){const t=a=>fh._endDragBefore(a,s),n=a=>fh._batchEvents(()=>fh._drag(a,s),s),r=a=>fh._batchEvents(()=>fh._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(!fh._dragElements.size)return;const n=new Set;for(const{node:a}of fh._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=()=>Jn._batchEvents(a,i)}r()},_drag(s,t){const n=[],r=new Set;fh._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=Jn._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;fh._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!==Jn._getEventType(s.type)||!(i.pointerId===void 0||c._changedPointerPositions.some(u=>u.id===i.pointerId)))))if(i.dragStatus==="ready")fh._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){fh._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"&&fh._dragElements.delete(r))})}},DG=new Map,oGt=Qo._global.PointerEvent!==void 0;function Sde(s,t){const n=DG.get(s);return n&&(!t||n.stage===t)?n.shape:void 0}function lGt(s,t,n){s._fire(t,{evt:new PointerEvent(t,{pointerId:n}),pointerId:n})}function cGt(s,t){var n;return((n=DG.get(s))===null||n===void 0?void 0:n.shape)===t}function dGt(s,t){var n;NV(s);const r=t.getStage();if(r&&(DG.set(s,{shape:t,stage:r}),oGt)){try{(n=r.content)===null||n===void 0||n.setPointerCapture(s)}catch{}lGt(t,"gotpointercapture",s)}}function Son(s){DG.forEach(({shape:t,stage:n},r)=>{(t===s||n===s)&&NV(r)})}function NV(s,t){var n;const r=DG.get(s);if(!r||t&&r.shape!==t)return;const{shape:a,stage:i}=r;if(DG.delete(s),oGt){try{(n=i.content)===null||n===void 0||n.releasePointerCapture(s)}catch{}lGt(a,"lostpointercapture",s)}}function g6(s){return Jn._isString(s)?'"'+s+'"':Object.prototype.toString.call(s)==="[object Number]"||Jn._isBoolean(s)?s:Object.prototype.toString.call(s)}function vrt(s){return s>255?255:s<0?0:Math.round(s)}function Ti(){if(Qo.isUnminified)return function(s,t){return Jn._isNumber(s)||Jn.warn(g6(s)+' is a not valid value for "'+t+'" attribute. The value should be a number.'),s}}function eRe(s){if(Qo.isUnminified)return function(t,n){let r=Jn._isNumber(t),a=Jn._isArray(t)&&t.length==s;return!r&&!a&&Jn.warn(g6(t)+' is a not valid value for "'+n+'" attribute. The value should be a number or Array('+s+")"),t}}function brt(){if(Qo.isUnminified)return function(s,t){return Jn._isNumber(s)||s==="auto"||Jn.warn(g6(s)+' is a not valid value for "'+t+'" attribute. The value should be a number or "auto".'),s}}function qB(){if(Qo.isUnminified)return function(s,t){return Jn._isString(s)||Jn.warn(g6(s)+' is a not valid value for "'+t+'" attribute. The value should be a string.'),s}}function uGt(){if(Qo.isUnminified)return function(s,t){const n=Jn._isString(s),r=Object.prototype.toString.call(s)==="[object CanvasGradient]"||s&&s.addColorStop;return n||r||Jn.warn(g6(s)+' is a not valid value for "'+t+'" attribute. The value should be a string or a native gradient.'),s}}function Con(){if(Qo.isUnminified)return function(s,t){return s instanceof aGt||(Jn._isArray(s)?s.forEach(function(n){Jn._isNumber(n)||Jn.warn('"'+t+'" attribute has non numeric element '+n+". Make sure that all elements are numbers.")}):Jn.warn(g6(s)+' is a not valid value for "'+t+'" attribute. The value should be a array of numbers.')),s}}function jC(){if(Qo.isUnminified)return function(s,t){return s===!0||s===!1||Jn.warn(g6(s)+' is a not valid value for "'+t+'" attribute. The value should be a boolean.'),s}}function Aon(s){if(Qo.isUnminified)return function(t,n){return t==null||Jn.isObject(t)||Jn.warn(g6(t)+' is a not valid value for "'+n+'" attribute. The value should be an object with properties '+s),t}}const OZ="get",zZ="set",Tn={addGetterSetter(s,t,n,r,a){Tn.addGetter(s,t,n),Tn.addSetter(s,t,r,a),Tn.addOverloadedGetterSetter(s,t)},addGetter(s,t,n){const r=OZ+Jn._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=zZ+Jn._capitalize(t);s.prototype[a]||Tn.overWriteSetter(s,t,n,r)},overWriteSetter(s,t,n,r){const a=zZ+Jn._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=Jn._capitalize,o=OZ+l(t),c=zZ+l(t),d=n.map(m=>t+l(m)),u=d.map(m=>OZ+l(m));s.prototype[o]=function(){const m={};for(let f=0;f{this._setAttr(t+l(g),void 0)}),this._fireChangeEvent(t,f,m),a&&a.call(this),this},Tn.addOverloadedGetterSetter(s,t)},addOverloadedGetterSetter(s,t){const n=Jn._capitalize(t),r=zZ+n,a=OZ+n,i=function(){return arguments.length?(this[r](arguments[0]),this):this[a]()};s.prototype[t]=i},backCompat(s,t){Jn.each(t,function(n,r){const a=s.prototype[r],i=OZ+Jn._capitalize(n),l=zZ+Jn._capitalize(n);function o(){return Jn.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 Eon(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)){Jn.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?KM._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 Jn.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 g7({pixelRatio:c,width:l,height:o}),f=new g7({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(mQ);try{this.drawScene(m,this)}catch(x){throw Jn.releaseCanvas(m._canvas),x}finally{this._isUnderCache=!1,this._clearSelfAndDescendantCache(mQ),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 yrt(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)&&fh._dragElements.delete(n)}),this._remove(),this}_clearCaches(){this._clearSelfAndDescendantCache(bA),this._clearSelfAndDescendantCache(mQ),this._clearSelfAndDescendantCache(R_t),this._clearSelfAndDescendantCache(MWe),this._clearSelfAndDescendantCache(EWe)}_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}),Son(this),this.remove(),this.clearCache(),this}getAttr(t){const n="get"+Jn._capitalize(t);return Jn._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!==Mon&&(r=I_t+Jn._capitalize(n),Jn._isFunction(this[r])?this[r](t[n]):this._setAttr(n,t[n]))}),this}isListening(){return this._getCache(EWe,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(MWe,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!==Bon&&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(WM),this._clearSelfAndDescendantCache(bA))}}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 b0,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(WM);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}):Jn.warn("Cannot set the absolute position: the absolute transform is not invertible (an ancestor has a zero scale)."),this._clearCache(WM),this._clearSelfAndDescendantCache(bA),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 Jn.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 Jn.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 Jn.warn("Node has no parent. zIndex parameter is ignored."),this;(t<0||t>=this.parent.children.length)&&Jn.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(mQ,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=Jn.isObject(a)&&!Jn._isPlainObject(a)&&!Jn._isArray(a),!i&&(((t=this["get"+Jn._capitalize(r)])===null||t===void 0?void 0:t._def)!==a||r==="brightness"||r==="threshold")&&(l.attrs[r]=r==="filters"&&Jn._isArray(a)?a.filter(o=>typeof o=="string"):Jn.isObject(a)?Jn._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||{};Jn._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)||fh._dragElements.has(this._id))return;let a=!1;fh._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=fh._dragElements.get(this._id),r=n&&n.dragStatus==="dragging",a=n&&n.dragStatus==="ready";r?this.stopDrag():a&&fh._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 Jn.haveIntersection(r,this.getClientRect())}static create(t,n){return Jn._isString(t)&&(t=JSON.parse(t)),this._createNode(t,n)}static _createNode(t,n){let r=KM.prototype.getClassName.call(t),a=t.children,i,l,o;if(n&&(t.attrs.container=n),!Qo[r]){const d=a?"Group":"Shape";Jn.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=Jn._getEventType(s);if(t==="pointer")return Qo.pointerEventsEnabled&&zBe.pointer;if(t==="touch")return zBe.touch;if(t==="mouse")return zBe.mouse};function F_t(s={}){return(s.clipFunc||s.clipWidth||s.clipHeight)&&Jn.warn("Stage does not support clipping. Please use clip for Layers or Groups."),s}const Yon="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);",Dee=[],O_t=new WeakSet,z_t=s=>{!s||O_t.has(s)||(O_t.add(s),fh._listenToWindow(s),s.document.addEventListener("visibilitychange",()=>{Dee.forEach(t=>{t.batchDraw()})}))};let yie=class extends x2{constructor(t){super(F_t(t)),this._pointerPositions=[],this._changedPointerPositions=[],this._pointerStates=new Map,this._lastClicks={},this._buildDOM(),this._bindContentEvents(),Dee.push(this),this.on("widthChange.konva heightChange.konva",this._resizeDOM),this.on("visibleChange.konva",this._checkVisibility),this.on("clipWidthChange.konva clipHeightChange.konva clipFuncChange.konva",()=>{F_t(this.attrs)}),this._checkVisibility()}_validateAdd(t){const n=t.getType()==="Layer",r=t.getType()==="FastLayer";n||r||Jn.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===Von){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),z_t(this._getOwnerWindow())),this}shouldDrawHit(){return!0}clear(){const t=this.children,n=t.length;for(let r=0;r-1&&Dee.splice(r,1),Jn.releaseCanvas(this.bufferHitCanvas._canvas),this}getPointerPosition(){const t=this._pointerPositions[0]||this._changedPointerPositions[0];return t?{x:t.x,y:t.y}:(Jn.warn(Yon),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 g7({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()),Jn.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+D_t,this.content.style.height=n+D_t),this.children.forEach(r=>{r._setSize({width:t,height:n}),r.draw()})}add(t,...n){if(arguments.length>1){for(let a=0;aWon&&Jn.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 cGt(t,this)}setPointerCapture(t){dGt(t,this)}releaseCapture(t){NV(t,this)}getLayers(){return this.getChildren()}_bindContentEvents(){Qo.isBrowser&&Kon.forEach(([t,n])=>{this.content.addEventListener(t,r=>{this._batchEvents(()=>this[n](r))},{passive:!1})})}_batchEvents(t){Jn._batchEvents(this.eventBatchFunc(),t)}_pointerenter(t){this.setPointersPositions(t);const n=gR(t.type);n&&this._fire(n.pointerenter,{evt:t,target:this,currentTarget:this})}_pointerover(t){this.setPointersPositions(t);const n=gR(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 fh._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=gR(t.type),i=Jn._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=gR(t.type),r=Jn._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 fh._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=gR(t.type),r=Jn._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 fh._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=Sde(c.id)||this.getIntersection(c),f=h.targetShape===m||((d=h.targetShape)===null||d===void 0?void 0:d.getStage())===this?h.targetShape:void 0,g=c.id,x={evt:t,pointerId:g},y=f!==m;h.targetShape=m&&m.isListening()?m:void 0,y&&f&&(f._fireAndBubble(n.pointerout,{...x},m),f._fireAndBubble(n.pointerleave,{...x},m)),m&&m.isListening()?(o=!0,y&&(m._fireAndBubble(n.pointerover,{...x},f),m._fireAndBubble(n.pointerenter,{...x},f)),l[m._id]||(l[m._id]=!0,m._fireAndBubble(n.pointermove,{...x}))):f&&this._fire(n.pointerover,{evt:t,target:this,currentTarget:this,pointerId:g})}),o||this._fire(n.pointermove,{evt:t,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id})}_pointerup(t){const n=gR(t.type),r=Jn._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=Sde(l.id)||this.getIntersection(l),f=m&&a[m._id];m&&(m.releaseCapture(l.id),a[m._id]=!0);const g=l.id,x={evt:t,pointerId:g},y=m&&m.isListening()?m:null,v=this._lastClicks[r],b=u&&(!y||h===y),w=b&&v&&(d==null?void 0:d.lastClick)===v&&v.shape===y&&Date.now()-v.time{var a;const i=Jn._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=Sde(r.id)||this.getIntersection(r),d={evt:t,pointerId:r.id};c?(n&&c._fireAndBubble(n.pointercancel,{...d}),c._fireAndBubble(tq,{...d})):n&&this._fire(n.pointercancel,{...d,target:this,currentTarget:this}),NV(r.id),n&&i==="touch"&&(o==null?void 0:o.getStage())===this&&(o._fireAndBubble(n.pointerout,{...d}),o._fireAndBubble(n.pointerleave,{...d}))})}_lostpointercapture(t){Sde(t.pointerId,this)&&NV(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:Jn._getFirstPointerId(t)}],this._changedPointerPositions=[{x:r,y:a,id:Jn._getFirstPointerId(t)}])}_setPointerPosition(t){Jn.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 yrt({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),z_t(this._getOwnerWindow()),this._resizeDOM()}cache(){return Jn.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}};yie.prototype.nodeType=qon;Yg(yie);Tn.addGetterSetter(yie,"container");Tn.addGetterSetter(yie,"eventBatchFunc");const wGt="hasShadow",jGt="hasFill",NGt="hasStroke",kGt="shadowRGBA",SGt="patternImage",CGt="linearGradient",AGt="radialGradient";let Tde;function BBe(){return Tde||(Tde=Jn.createCanvasElement().getContext("2d"),Tde)}const Fee={};function EGt(s){const t=this.attrs.fillRule;t?s.fill(t):s.fill()}function TGt(s){s.stroke()}function Zon(){this._clearCache(wGt)}function Xon(){this._clearCache(jGt)}function Qon(){this._clearCache(NGt)}function Jon(){this._clearCache(kGt)}function eln(){this._clearCache(SGt)}function tln(){this._clearCache(CGt)}function sln(){this._clearCache(AGt)}let li=class MGt extends zi{constructor(t){super(t);let n,r=0;for(;n=Jn.getHitColor(),!(n&&!(n in Fee));)if(r++,r>=1e4){Jn.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=Jn.getRandomColor();break}this.colorKey=n,Fee[n]=this}getContext(){return Jn.warn("shape.getContext() method is deprecated. Please do not use it."),this.getLayer().getContext()}getCanvas(){return Jn.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(wGt,this._hasShadow)}_hasShadow(){return this.shadowEnabled()&&this.shadowOpacity()!==0&&!!(this.shadowColor()||this.shadowBlur()||this.shadowOffsetX()||this.shadowOffsetY())}_getFillPattern(){return this._getCache(SGt,this.__getFillPattern)}__getFillPattern(){if(this.fillPatternImage()){const n=BBe().createPattern(this.fillPatternImage(),this.fillPatternRepeat()||"repeat");if(n&&n.setTransform){const r=new b0;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(CGt,this.__getLinearGradient)}__getLinearGradient(){const t=this.fillLinearGradientColorStops();if(t){const n=BBe(),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 Fee[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){Jn.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 b0()._getTransformedRect(this._getSelfRectForDrawing()):this._transformedRect(this._getSelfRectForDrawing(),a):this.getSelfRect(),c=!t.skipStroke&&this.hasStroke()?i?this._getStrokePadding()*2:this.strokeWidth():0;let d=c,u=c,h;if(!i&&c&&!this.strokeScaleEnabled()){let f=this;for(;f&&!f.isCached()&&!f._isUnderCache;)f=f.parent;const[g,x,y,v]=this.getAbsoluteTransform(f).getMatrix(),b=Math.abs(g*v-x*y);if(b)d*=Math.hypot(y,v)/b,u*=Math.hypot(g,x)/b;else if(!r&&(d=u=0,h=f?f.getAbsoluteTransform().copy():new b0,a)){const w=a.getAbsoluteTransform(),[S,A,E,I]=w.getMatrix();h=S*I-A*E?w.copy().invert().multiply(h):new b0}}let m={x:l.x-d/2,y:l.y-u/2,width:l.width+d,height:l.height+u};if(i&&this.strokeScaleEnabled()&&(m=this._transformedRect(m,a)),!t.skipShadow&&this.hasShadow()){const f=i?this.getAbsoluteScale():{x:1,y:1},g=this.shadowOffsetX()*f.x,x=this.shadowOffsetY()*f.y,y=this.shadowBlur()*(i?2*Math.min(Math.abs(f.x),Math.abs(f.y)):1);m.x+=Math.min(0,g)-y,m.y+=Math.min(0,x)-y,m.width+=Math.abs(g)+y*2,m.height+=Math.abs(x)+y*2}if(i)return m;if(!r){const f=this._transformedRect(m,a);if(h){const[g,x,y,v]=h.getMatrix(),b=c*Math.hypot(g,y)/2,w=c*Math.hypot(x,v)/2;f.x-=b,f.y-=w,f.width+=b*2,f.height+=w*2}return f}return m}_getStrokePadding(t=this.miterLimit()||10){return this.attrs.sceneFunc&&(t=this.miterLimit()||10),Math.abs(this.strokeWidth())/2*Math.max(this.lineCap()==="square"?Math.SQRT2:1,(this.lineJoin()||"miter")==="miter"?t:1)}drawScene(t,n){const r=this.getLayer(),a=t||r.getCanvas(),i=a.getContext(),l=this._getCanvasCache(),o=this.getSceneFunc(),c=this.hasShadow(),d=n===this;if(!(n?this._isVisible(n):this.isVisible())&&!d)return this;if(l){i.save();const u=this.getAbsoluteTransform(n).getMatrix();return i.transform(u[0],u[1],u[2],u[3],u[4],u[5]),this._drawCachedSceneCanvas(i),i.restore(),this}if(!o)return this;i.save();try{if(a.width&&a.height&&this._useBufferCanvas(void 0,i._getOpacity(this))){const u=!!i._opacityRoot||!!this.attrs.selfRectFunc&&this.getSelfRect===MGt.prototype.getSelfRect||!this.attrs.sceneFunc&&!this.attrs.charRenderFunc&&nGt.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||Jn.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=Jn._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){Jn.error("Unable to draw hit graph from cached scene canvas. "+o.message)}return this}hasPointerCapture(t){return cGt(t,this)}setPointerCapture(t){dGt(t,this)}releaseCapture(t){NV(t,this)}};li.prototype._fillFunc=EGt;li.prototype._strokeFunc=TGt;li.prototype._fillFuncHit=EGt;li.prototype._strokeFuncHit=TGt;li.prototype._centroid=!1;li.prototype.nodeType="Shape";Yg(li);li.prototype.on("shadowColorChange.konva shadowBlurChange.konva shadowOffsetXChange.konva shadowOffsetYChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",Zon);li.prototype.on("shadowColorChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",Jon);li.prototype.on("fillEnabledChange.konva fillChange.konva fillPatternImageChange.konva fillLinearGradientColorStopsChange.konva fillRadialGradientColorStopsChange.konva",Xon);li.prototype.on("strokeEnabledChange.konva strokeWidthChange.konva strokeChange.konva strokeLinearGradientColorStopsChange.konva",Qon);li.prototype.on("fillPriorityChange.konva fillPatternImageChange.konva fillPatternRepeatChange.konva fillPatternScaleXChange.konva fillPatternScaleYChange.konva fillPatternOffsetXChange.konva fillPatternOffsetYChange.konva fillPatternXChange.konva fillPatternYChange.konva fillPatternRotationChange.konva",eln);li.prototype.on("fillPriorityChange.konva fillLinearGradientColorStopsChange.konva fillLinearGradientStartPointXChange.konva fillLinearGradientStartPointYChange.konva fillLinearGradientEndPointXChange.konva fillLinearGradientEndPointYChange.konva",tln);li.prototype.on("fillPriorityChange.konva fillRadialGradientColorStopsChange.konva fillRadialGradientStartPointXChange.konva fillRadialGradientStartPointYChange.konva fillRadialGradientEndPointXChange.konva fillRadialGradientEndPointYChange.konva fillRadialGradientStartRadiusChange.konva fillRadialGradientEndRadiusChange.konva",sln);Tn.addGetterSetter(li,"stroke",void 0,uGt());Tn.addGetterSetter(li,"strokeWidth",2,Ti());Tn.addGetterSetter(li,"fillAfterStrokeEnabled",!1);Tn.addGetterSetter(li,"hitStrokeWidth","auto",brt());Tn.addGetterSetter(li,"strokeHitEnabled",!0,jC());Tn.addGetterSetter(li,"perfectDrawEnabled",!0,jC());Tn.addGetterSetter(li,"shadowForStrokeEnabled",!0,jC());Tn.addGetterSetter(li,"lineJoin");Tn.addGetterSetter(li,"lineCap");Tn.addGetterSetter(li,"miterLimit");Tn.addGetterSetter(li,"sceneFunc");Tn.addGetterSetter(li,"hitFunc");Tn.addGetterSetter(li,"selfRectFunc");Tn.addGetterSetter(li,"dash");Tn.addGetterSetter(li,"dashOffset",0,Ti());Tn.addGetterSetter(li,"shadowColor",void 0,qB());Tn.addGetterSetter(li,"shadowBlur",0,Ti());Tn.addGetterSetter(li,"shadowOpacity",1,Ti());Tn.addComponentsGetterSetter(li,"shadowOffset",["x","y"]);Tn.addGetterSetter(li,"shadowOffsetX",0,Ti());Tn.addGetterSetter(li,"shadowOffsetY",0,Ti());Tn.addGetterSetter(li,"fillPatternImage");Tn.addGetterSetter(li,"fill",void 0,uGt());Tn.addGetterSetter(li,"fillPatternX",0,Ti());Tn.addGetterSetter(li,"fillPatternY",0,Ti());Tn.addGetterSetter(li,"fillLinearGradientColorStops");Tn.addGetterSetter(li,"strokeLinearGradientColorStops");Tn.addGetterSetter(li,"fillRadialGradientStartRadius",0);Tn.addGetterSetter(li,"fillRadialGradientEndRadius",0);Tn.addGetterSetter(li,"fillRadialGradientColorStops");Tn.addGetterSetter(li,"fillPatternRepeat","repeat");Tn.addGetterSetter(li,"fillEnabled",!0);Tn.addGetterSetter(li,"strokeEnabled",!0);Tn.addGetterSetter(li,"shadowEnabled",!0);Tn.addGetterSetter(li,"dashEnabled",!0);Tn.addGetterSetter(li,"strokeScaleEnabled",!0);Tn.addGetterSetter(li,"fillPriority","color");Tn.addComponentsGetterSetter(li,"fillPatternOffset",["x","y"]);Tn.addGetterSetter(li,"fillPatternOffsetX",0,Ti());Tn.addGetterSetter(li,"fillPatternOffsetY",0,Ti());Tn.addComponentsGetterSetter(li,"fillPatternScale",["x","y"]);Tn.addGetterSetter(li,"fillPatternScaleX",1,Ti());Tn.addGetterSetter(li,"fillPatternScaleY",1,Ti());Tn.addComponentsGetterSetter(li,"fillLinearGradientStartPoint",["x","y"]);Tn.addComponentsGetterSetter(li,"strokeLinearGradientStartPoint",["x","y"]);Tn.addGetterSetter(li,"fillLinearGradientStartPointX",0);Tn.addGetterSetter(li,"strokeLinearGradientStartPointX",0);Tn.addGetterSetter(li,"fillLinearGradientStartPointY",0);Tn.addGetterSetter(li,"strokeLinearGradientStartPointY",0);Tn.addComponentsGetterSetter(li,"fillLinearGradientEndPoint",["x","y"]);Tn.addComponentsGetterSetter(li,"strokeLinearGradientEndPoint",["x","y"]);Tn.addGetterSetter(li,"fillLinearGradientEndPointX",0);Tn.addGetterSetter(li,"strokeLinearGradientEndPointX",0);Tn.addGetterSetter(li,"fillLinearGradientEndPointY",0);Tn.addGetterSetter(li,"strokeLinearGradientEndPointY",0);Tn.addComponentsGetterSetter(li,"fillRadialGradientStartPoint",["x","y"]);Tn.addGetterSetter(li,"fillRadialGradientStartPointX",0);Tn.addGetterSetter(li,"fillRadialGradientStartPointY",0);Tn.addComponentsGetterSetter(li,"fillRadialGradientEndPoint",["x","y"]);Tn.addGetterSetter(li,"fillRadialGradientEndPointX",0);Tn.addGetterSetter(li,"fillRadialGradientEndPointY",0);Tn.addGetterSetter(li,"fillPatternRotation",0);Tn.addGetterSetter(li,"fillRule",void 0,qB());Tn.backCompat(li,{dashArray:"dash",getDashArray:"getDash",setDashArray:"setDash",drawFunc:"sceneFunc",getDrawFunc:"getSceneFunc",setDrawFunc:"setSceneFunc",drawHitFunc:"hitFunc",getDrawHitFunc:"getHitFunc",setDrawHitFunc:"setHitFunc"});const nln="beforeDraw",rln="draw",aln=10,B_t=256;function $_t(s,t){return s[t+3]>=128?Fee[Jn.getHitColorKey(s[t],s[t+1],s[t+2])]:void 0}let VB=class extends x2{constructor(t){super(t),this.canvas=new g7,this.hitCanvas=new yrt({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=aln,c=o*2+1,d=l(o),u=d[(o*c+o)*4+3];for(let h=1;h<=B_t;h++){h>o&&(o=Math.min(B_t,o*2),c=o*2+1,d=l(o));let m=0;for(let f=-h;f<=h;f++){const g=Math.abs(f)===h?1:h*2;for(let x=-h;x<=h;x+=g){const y=((f+o)*c+x+o)*4,v=$_t(d,y);if(v)return v;m=Math.max(m,d[y+3])}}if(m<=u&&m!==255)return null;u=m}return null}_getIntersection(t){if(!this.hitCanvas.width||!this.hitCanvas.height)return{};const n=this.hitCanvas.pixelRatio,r=this.hitCanvas.context.getImageData(Math.floor(t.x*n),Math.floor(t.y*n),1,1).data,a=$_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(nln,{node:this}),this.clearBeforeDraw()&&a.getContext().clear(),x2.prototype.drawScene.call(this,a,n),a._trimIsolationCanvas(),this._fire(rln,{node:this}),this}shouldDrawHit(t){var n;if(!super.shouldDrawHit(t))return!1;if(t||Qo.hitOnDragEnabled)return!0;let r=!1;return fh._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()),x2.prototype.drawHit.call(this,a,n),this}enableHitGraph(){return this.hitGraphEnabled(!0),this}disableHitGraph(){return this.hitGraphEnabled(!1),this}setHitGraphEnabled(t){Jn.warn("hitGraphEnabled method is deprecated. Please use layer.listening() instead."),this.listening(t)}getHitGraphEnabled(t){return Jn.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(),Jn.releaseCanvas(this.getNativeCanvasElement(),this.getHitCanvas()._canvas),super.destroy()}};VB.prototype.nodeType="Layer";Yg(VB);Tn.addGetterSetter(VB,"imageSmoothingEnabled",!0);Tn.addGetterSetter(VB,"clearBeforeDraw",!0);Tn.addOverloadedGetterSetter(VB,"hitGraphEnabled");class _rt extends VB{constructor(t){super(t),this.listening(!1),Jn.warn('Konva.FastLayer is deprecated. Please use "new Konva.Layer({ listening: false })" instead.')}}_rt.prototype.nodeType="FastLayer";Yg(_rt);let J7=class extends x2{_validateAdd(t){const n=t.getType();n!=="Group"&&n!=="Shape"&&Jn.throw("You may only add groups and shapes to groups.")}_drawChildNodes(t,n,r){if(t!=="drawScene"||!this.isolated()||r===this)return super._drawChildNodes(t,n,r);if(!n.width||!n.height)return;const a=n.getContext(),i=n._prepareIsolationCanvas(this.getClientRect({_forDrawing:!0,relativeTo:r})),l=i.getContext();l._opacityRoot=this,a.save();try{super._drawChildNodes(t,i,r),a._applyOpacity(this),a._drawDeviceBuffer(i)}catch(o){throw n._releaseIsolationCanvas(),o}finally{a.restore(),l._opacityRoot=void 0}}};Tn.addGetterSetter(J7,"isolated",!1,jC());J7.prototype.nodeType="Group";Yg(J7);var $Be;const UBe=!(($Be=eq.performance)===null||$Be===void 0)&&$Be.now?()=>eq.performance.now():Date.now;class DN{constructor(t,n){this.id=DN.animIdCounter++,this.frame={time:0,timeDiff:0,lastTime:UBe(),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(UBe()),!(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=DN;t.animations.size?(t._runFrames(),Jn.requestAnimFrame(t._animationLoop)):t.animRunning=!1}static _handleAnimation(){this.animRunning||(this.animRunning=!0,Jn.requestAnimFrame(this._animationLoop))}}DN.animations=new Set;DN.animIdCounter=0;DN.animRunning=!1;const iln={node:1,duration:1,easing:1,onFinish:1,onUpdate:1,onReset:1,yoyo:1},oln=1,U_t=2,q_t=3,V_t=["fill","stroke","shadowColor"];let lln=0;function Mde(s){return Jn.colorToRGBA(s)||Jn.throw('can not tween the color "'+s+'", because it is not a valid color.')}function H_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 G_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 cln{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=U_t,this._startTime=this.getTimer()-this._time,this.fire("onPlay"),this.onEnterFrame()}reverse(){this.state=q_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===U_t?this.setTime(t):this.state===q_t&&this.setTime(this.duration-t)}pause(){this.state=oln,this.fire("onPause")}getTimer(){return Date.now()}}class _g{constructor(t){const n=this,r=t.node,a=r._id,i=t.easing||Oee.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=lln++;const d=r.getLayer()||(r instanceof Qo.Stage?r.getLayers():null);d||Jn.error("Tween constructor have `node` that is not in a layer. Please add node into layer first."),this.anim=new DN(function(){n.tween.onEnterFrame()},d),this.tween=new cln(c,function(u){n._tweenFunc(u)},i,0,1,o*1e3,l),this._addListeners(),_g.attrs[a]||(_g.attrs[a]={}),_g.attrs[a][this._id]||(_g.attrs[a][this._id]={}),_g.tweens[a]||(_g.tweens[a]={});for(c in t)iln[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(Jn._isPlainObject(n)){for(const h in n)this._addAttr(t+Jn._capitalize(h),n[h]);return}const r=this.node,a=r._id;let i,l,o,c;const d=_g.tweens[a][t];d!==void 0&&delete _g.attrs[a][d][t];let u=r.getAttr(t);if(Jn._isArray(n)||Jn._isArray(u))if(i=[],c=u,o=n,u=Jn._isArray(u)?u.slice():new Array(n.length).fill(u||0),Jn._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=Jn._prepareArrayForTween(u,n,r.closed()):n=Jn._prepareArrayForTween(n,u,r.closed())),t.endsWith("ColorStops"))for(let h=0;hthis.destroy(),r=()=>{this.node.off(t).on(t,n),this.anim.start()};this.tween.onPlay=r,this.tween.onReverse=r,this.tween.onPause=()=>{this.node.off(t),this.anim.stop()};const a=(i,l)=>{var o;const c=(o=_g.attrs[this.node._id])===null||o===void 0?void 0:o[this._id];if(c){for(const d in c)c[d][i]!==void 0&&this.node.setAttr(d,c[d][i]);l==null||l.call(this)}};this.tween.onFinish=()=>a("trueEnd",this.onFinish),this.tween.onReset=()=>a("trueStart",this.onReset),this.tween.onUpdate=()=>{this.onUpdate&&this.onUpdate.call(this)}}play(){return this.tween.play(),this}reverse(){return this.tween.reverse(),this}reset(){return this.tween.reset(),this}seek(t){return this.tween.seek(t*1e3),this}pause(){return this.tween.pause(),this}finish(){return this.tween.finish(),this}destroy(){var t;const n=this.node._id,r=this._id,a=(t=_g.attrs[n])===null||t===void 0?void 0:t[r],i=_g.tweens[n];if(this.pause(),this.anim&&this.anim.stop(),a){if(i){for(const l in a)delete i[l];Object.keys(i).length===0&&delete _g.tweens[n]}delete _g.attrs[n][r],Object.keys(_g.attrs[n]).length===0&&delete _g.attrs[n]}}}_g.attrs={};_g.tweens={};zi.prototype.to=function(s){const t=s.onFinish,n=new _g({...s,node:this,onFinish(){n.destroy(),t&&t()}});return n.play(),n};const Oee={BackEaseIn(s,t,n,r){return n*(s/=r)*s*((1.70158+1)*s-1.70158)+t},BackEaseOut(s,t,n,r){return n*((s=s/r-1)*s*((1.70158+1)*s+1.70158)+1)+t},BackEaseInOut(s,t,n,r){let a=1.70158;return(s/=r/2)<1?n/2*(s*s*(((a*=1.525)+1)*s-a))+t:n/2*((s-=2)*s*(((a*=1.525)+1)*s+a)+2)+t},ElasticEaseIn(s,t,n,r,a,i){let l=0;return s===0?t:(s/=r)===1?t+n:(i||(i=r*.3),!a||a=o?o:(c%o+o)%o,u=Math.cos(Math.min(d,Math.PI)),h=1,m=Math.sin(Math.min(Math.max(Math.PI,d),3*Math.PI/2)),f=Math.sin(Math.min(d,Math.PI/2)),g=u*(u>0?r:a),x=h*a,y=m*(m>0?r:a),v=f*(f>0?a:r);return{x:g,y:i?-1*v:y,width:x-g,height:v-y}}}PT.prototype._centroid=!0;PT.prototype.className="Arc";PT.prototype._attrsAffectingSize=["innerRadius","outerRadius","angle","clockwise"];Yg(PT,!0);Tn.addGetterSetter(PT,"innerRadius",0,Ti());Tn.addGetterSetter(PT,"outerRadius",0,Ti());Tn.addGetterSetter(PT,"angle",0,Ti());Tn.addGetterSetter(PT,"clockwise",!1,jC());const W_t=[-.07652652113349734,.07652652113349734,-.22778585114164507,.22778585114164507,-.37370608871541955,.37370608871541955,-.5108670019508271,.5108670019508271,-.636053680726515,.636053680726515,-.7463319064601508,.7463319064601508,-.8391169718222188,.8391169718222188,-.912234428251326,.912234428251326,-.9639719272779138,.9639719272779138,-.9931285991850949,.9931285991850949],dln=[.15275338713072584,.15275338713072584,.14917298647260374,.14917298647260374,.14209610931838204,.14209610931838204,.13168863844917664,.13168863844917664,.11819453196151841,.11819453196151841,.10193011981724044,.10193011981724044,.08327674157670475,.08327674157670475,.06267204833410907,.06267204833410907,.04060142980038694,.04060142980038694,.017614007139152118,.017614007139152118],LWe=(s,t,n)=>{const r=n/2;let a=0;for(let i=0;iLWe([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 uln(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 Y_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},Z_t=(s,t,n,r)=>{const a=1-r;return a*a*s+2*a*r*t+r*r*n},PGt=(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(Z_t(s,n,a,c),Z_t(t,r,i,c))}return l},X_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},wrt=(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(X_t(s,n,a,l,x),X_t(t,r,i,o,x))}return c};function RWe(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 Q_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,...PGt(r,a,i,l,o,c)),(r,a,i,l,o,c,d,u)=>n.push(d,u,...wrt(r,a,i,l,o,c,d,u))),t=n}else this.bezier()&&(t=[t[0],t[1],...hln(t)]);return Jn._getPointsRect(t)}};c3.prototype.className="Line";c3.prototype._attrsAffectingSize=["points","bezier","tension","closed"];Yg(c3,!0);Tn.addGetterSetter(c3,"closed",!1);Tn.addGetterSetter(c3,"bezier",!1);Tn.addGetterSetter(c3,"tension",0,Ti());Tn.addGetterSetter(c3,"points",[],Con());const mln={m:2,l:2,h:1,v:1,c:6,s:4,q:4,t:2,a:7,z:0},qBe=Math.PI*2;let HS=class Q1 extends li{constructor(t){super(t),this.dataArray=[],this.pathLength=0,this._readDataAttribute(),this.on("dataChange.konva",function(){this._readDataAttribute()})}_readDataAttribute(){this.dataArray=Q1.parsePathData(this.data()),this.pathLength=Q1.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)%qBe+qBe)%qBe0&&t<=c;)c-=n[--o].pathLength;for(t-=c;on[o].pathLength;){const m=n[o].pathLength;t-=m,c+=m,++o}if(r&&oLWe([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 Q1.getPointOnQuadraticBezier(Y_t(t,u.pathLength,m=>K_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 Q1.getPointOnEllipticalArc(h[0],h[1],h[2],h[3],h[2]===h[3]?h[4]+h[5]*t/u.pathLength:Q1._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");)y.push(+A[0]),v++,A=A.slice(1);const E=parseFloat(A);y.push(isNaN(E)?0:E),v>=0&&(v=(v+1)%7)}let b=0;for(;b=n)return{theta:h+(g-h)*((n-m)/y),length:n};m+=y,u=x,h=g}return{theta:h,length:m}}static calcLength(t,n,r,a){const i=Q1;switch(r){case"L":return i.getLineLength(t,n,a[0],a[1]);case"C":return LWe([t,a[0],a[2],a[4]],[n,a[1],a[3],a[5]],1);case"Q":return K_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,y=g*-c*h/o,v=(t+r)/2+Math.cos(u)*x-Math.sin(u)*y,b=(n+a)/2+Math.sin(u)*x+Math.cos(u)*y,w=function(D){return Math.sqrt(D[0]*D[0]+D[1]*D[1])},S=function(D,O){return(D[0]*O[0]+D[1]*O[1])/(w(D)*w(O))},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),[v,b,o,c,E,R,u,l]}};HS.prototype.className="Path";HS.prototype._attrsAffectingSize=["data"];Yg(HS,!0);Tn.addGetterSetter(HS,"data");class x6 extends c3{_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=HS.calcLength(h,m,"Q",[f,g,l,o]),y=HS.getPointOnQuadraticBezier(x?Math.max(0,1-this.pointerLength()/x):0,h,m,f,g,l,o);c=l-y.x,d=o-y.y}for(let h=t?0:i.length-2;!c&&!d&&h>=0&&h{this._requestDraw()},this.on("imageChange.konva",n=>{this._removeImageLoad(n.oldVal),this._setImageLoad()}),this._setImageLoad()}_setImageLoad(){var t;const n=this.image();n!=null&&n.complete&&n.src||(n==null?void 0:n.readyState)>=2||(t=n==null?void 0:n.addEventListener)===null||t===void 0||t.call(n,"videoWidth"in n?"loadeddata":"load",this._loadListener)}_removeImageLoad(t){var n;(n=t==null?void 0:t.removeEventListener)===null||n===void 0||n.call(t,"videoWidth"in t?"loadeddata":"load",this._loadListener)}destroy(){return this._removeImageLoad(this.image()),super.destroy(),this}_useBufferCanvas(t,n=this.getAbsoluteOpacity()){if(this.attrs.perfectDrawEnabled===!1)return!1;const r=!!this.cornerRadius(),a=this.hasShadow();return r&&a?!0:super._useBufferCanvas(!0,n)}_getStrokePadding(){return super._getStrokePadding(this.strokeScaleEnabled()?1:void 0)}_sceneFunc(t){const n=this.getWidth(),r=this.getHeight(),a=this.cornerRadius(),i=this.attrs.image;if((this.hasFill()||this.hasStroke()||a)&&(t.beginPath(),a?Jn.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?Jn.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=Jn.createImageElement();a.onload=()=>{a.onload=a.onerror=null,n(new IGt({image:a}))},a.onerror=r,a.crossOrigin="Anonymous",a.src=t}};NC.prototype.className="Image";NC.prototype._attrsAffectingSize=["image"];Yg(NC,!0);Tn.addGetterSetter(NC,"cornerRadius",0,eRe(4));Tn.addGetterSetter(NC,"image");Tn.addComponentsGetterSetter(NC,"crop",["x","y","width","height"]);Tn.addGetterSetter(NC,"cropX",0,Ti());Tn.addGetterSetter(NC,"cropY",0,Ti());Tn.addGetterSetter(NC,"cropWidth",0,Ti());Tn.addGetterSetter(NC,"cropHeight",0,Ti());const J_t=typeof Intl<"u"&&Intl.Segmenter?new Intl.Segmenter(void 0,{granularity:"grapheme"}):null;function zee(s){return s/15}function yQ(s){return J_t?Array.from(J_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 C$="auto",ewt="center",LGt="inherit",A$="justify",fln="Change.konva",RGt="2d",pln="-",DGt="left",gln="text",xln="Text",yln="top",vln="bottom",twt="middle",FGt="normal",bln="px ",VBe=" ",swt="right",nwt="rtl",_ln="word",wln="char",rwt="none",HBe="…",OGt=["direction","fontFamily","fontSize","fontStyle","fontVariant","padding","align","verticalAlign","lineHeight","text","width","height","wrap","ellipsis","letterSpacing"];let BZ=null;function jln(){if(BZ!==null)return BZ;BZ=!1;let s;try{s=Jn.createCanvasElement(),s.width=10,s.height=10;const t=s.getContext(RGt);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){BZ=!0;break}}}catch{}finally{s&&Jn.releaseCanvas(s)}return BZ}function Nln(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 Pde;function v3e(){return Pde||(Pde=Jn.createCanvasElement().getContext(RGt),Pde)}function kln(s){this._partialFillStyle&&s.setAttr("fillStyle",this._partialFillStyle),s.fillText(this._partialText,this._partialTextX,this._partialTextY)}function Sln(s){s.setAttr("miterLimit",2),this._partialStrokeStyle&&s.setAttr("strokeStyle",this._partialStrokeStyle),s.strokeText(this._partialText,this._partialTextX,this._partialTextY)}function Cln(s){return s=s||{},s.fill||s.fillLinearGradientColorStops||s.fillRadialGradientColorStops||s.fillPatternImage?s:{...s,fill:"black"}}let lf=class extends li{constructor(t){super(Cln(t)),this._partialTextX=0,this._partialTextY=0,this._baselineShift=0,this._setTextData()}_sceneFunc(t){var n,r;const a=this.textArr,i=a.length;if(!this.text())return;let l=this.padding(),o=this.fontSize(),c=this.lineHeight()*o,d=this.direction(),u=this.align(),h=this.getWidth(),m=this.letterSpacing(),f=this.charRenderFunc(),g=this.textDecoration(),x=g.indexOf("underline")!==-1,y=g.indexOf("line-through")!==-1,v,b=c/2,w=twt;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!==LGt?t.setAttr("direction",d):d=t.direction,t.setAttr("font",this._getContextFont()),t.setAttr("textBaseline",w),t.setAttr("textAlign",DGt),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(v=0;v1&&(b+=c)}}_getTextTop(){const t=this.padding(),n=this.getHeight()-this.textArr.length*this.lineHeight()*this.fontSize()-t*2,r=this.verticalAlign();return r===twt?t+n/2:r===vln?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()+zee(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===swt?i-g:l===ewt?(i-g)/2:0),y=Math.min(0,this.letterSpacing())*f.length;d=Math.min(d,x+y),u=Math.max(u,x+g-y)}const h=this.textDecoration().includes("underline"),m=Math.min(t.y,c+(h?Math.min(0,this._getUnderlineOffset()):0));return{x:d-n,y:m-n,width:u-d+n*2,height:Math.max(t.y+t.height,c+o)-m+n*2}}_hitFunc(t){const n=this.getWidth(),r=this.getHeight();t.beginPath(),t.rect(0,0,n,r),t.closePath(),t.fillStrokeShape(this)}setText(t){const n=Jn._isString(t)?t:t==null?"":t+"";return this._setAttr(gln,n),this}getWidth(){return this.attrs.width===C$||this.attrs.width===void 0?this.getTextWidth()+this.padding()*2:this.attrs.width}getHeight(){return this.attrs.height===C$||this.attrs.height===void 0?this.fontSize()*this.textArr.length*this.lineHeight()+this.padding()*2:this.attrs.height}getTextWidth(){return this.textWidth}getTextHeight(){return Jn.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=v3e(),g=this.fontSize(),x;f.save(),f.font=this._getContextFont(),x=f.measureText(t),f.restore();const y=g/100;return{actualBoundingBoxAscent:(n=x.actualBoundingBoxAscent)!==null&&n!==void 0?n:71.58203125*y,actualBoundingBoxDescent:(r=x.actualBoundingBoxDescent)!==null&&r!==void 0?r:0,actualBoundingBoxLeft:(a=x.actualBoundingBoxLeft)!==null&&a!==void 0?a:-7.421875*y,actualBoundingBoxRight:(i=x.actualBoundingBoxRight)!==null&&i!==void 0?i:75.732421875*y,alphabeticBaseline:(l=x.alphabeticBaseline)!==null&&l!==void 0?l:0,emHeightAscent:(o=x.emHeightAscent)!==null&&o!==void 0?o:100*y,emHeightDescent:(c=x.emHeightDescent)!==null&&c!==void 0?c:-20*y,fontBoundingBoxAscent:(d=x.fontBoundingBoxAscent)!==null&&d!==void 0?d:91*y,fontBoundingBoxDescent:(u=x.fontBoundingBoxDescent)!==null&&u!==void 0?u:21*y,hangingBaseline:(h=x.hangingBaseline)!==null&&h!==void 0?h:72.80000305175781*y,ideographicBaseline:(m=x.ideographicBaseline)!==null&&m!==void 0?m:-21*y,width:x.width,height:g}}_getContextFont(){return this.fontStyle()+VBe+this.fontVariant()+VBe+(this.fontSize()+bln)+Nln(this.fontFamily())}_addTextLine(t){this.align()===A$&&(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??yQ(t).length):0;return v3e().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!==C$&&a!==void 0,o=i!==C$&&i!==void 0,c=this.padding(),d=a-c*2,u=i-c*2,h=0,m=this.wrap(),f=m!==rwt,g=m!==wln&&f,x=this.ellipsis();const y=this.measureSize("M");this._baselineShift=(y.fontBoundingBoxAscent-y.fontBoundingBoxDescent)/2,this.textArr=[];const v=v3e();v.font=this._getContextFont(),v.fontKerning=this.direction()!==nwt&&(this.letterSpacing()!==0||this.align()===A$||this.charRenderFunc())?"none":"auto";const b=x?this._getTextWidth(HBe):0;for(let w=0,S=t.length;wd){const I=yQ(A),P=I.length;let R=0;const D=W=>I.slice(R,W).join(""),O=W=>W===VBe||W===pln,U=Math.max(1,Math.ceil(P*d/E));for(;Ru?b:0,V=X=>!(this._getTextWidth(D(X),X-R)+W>d);let G=R,Y=Math.min(P,R+U);for(;V(Y)&&(G=Y,Y!==P);)Y=Math.min(P,Y+(Y-R));for(;Y-G>1;){const X=G+Y>>>1;V(X)?G=X:Y=X}if(G===R)break;if(G===P){this._addTextLine(D(P)),h+=r,o&&h+r>u&&w=R&&!O(I[X]);)X--;X>=R&&(G=X+1)}if(this._addTextLine(D(G).trimRight()),h+=r,this._shouldHandleEllipsis(h)){this._tryToAddEllipsisToLastLine();break}for(R=G;Ru&&wu)break}this.textHeight=n,this.textWidth=this.textArr.reduce((w,S)=>Math.max(w,S.width),0)}_shouldHandleEllipsis(t){const n=+this.fontSize(),r=this.lineHeight()*n,a=this.attrs.height,i=a!==C$&&a!==void 0,l=this.padding(),o=a-l*2;return!(this.wrap()!==rwt)||i&&t+r>o}_tryToAddEllipsisToLastLine(){const t=this.attrs.width,n=t!==C$&&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+HBe;if(n){const c=yQ(l.text);for(;c.length&&this._getTextWidth(o)>a;)c.pop(),o=c.join("")+HBe;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&&jln()?!0:super._useBufferCanvas(t,n)}};lf.prototype._fillFunc=kln;lf.prototype._strokeFunc=Sln;lf.prototype.className=xln;lf.prototype._attrsAffectingSize=OGt.filter(s=>s!=="width"&&s!=="height").concat(["textDecoration","underlineOffset"]);Yg(lf,!0);lf.prototype.on(OGt.map(s=>s+fln).join(" "),function(){this._setTextData()});Tn.overWriteSetter(lf,"width",brt());Tn.overWriteSetter(lf,"height",brt());Tn.addGetterSetter(lf,"direction",LGt);Tn.addGetterSetter(lf,"fontFamily","Arial");Tn.addGetterSetter(lf,"fontSize",12,Ti());Tn.addGetterSetter(lf,"fontStyle",FGt);Tn.addGetterSetter(lf,"fontVariant",FGt);Tn.addGetterSetter(lf,"padding",0,Ti());Tn.addGetterSetter(lf,"align",DGt);Tn.addGetterSetter(lf,"verticalAlign",yln);Tn.addGetterSetter(lf,"lineHeight",1,Ti());Tn.addGetterSetter(lf,"wrap",_ln);Tn.addGetterSetter(lf,"ellipsis",!1,jC());Tn.addGetterSetter(lf,"letterSpacing",0,Ti());Tn.addGetterSetter(lf,"text","",qB());Tn.addGetterSetter(lf,"textDecoration","");Tn.addGetterSetter(lf,"underlineOffset",void 0,Ti());Tn.addGetterSetter(lf,"charRenderFunc",void 0);const Aln=[...lf.prototype._attrsAffectingSize,"width","height","pointerDirection","pointerWidth","pointerHeight"],awt=Aln.map(s=>s+"Change.konva").join(" "),Eln="none",b3e="up",DWe="right",FWe="down",_3e="left";let jrt=class extends J7{constructor(t){super(t),this._sync=this._sync.bind(this),this.on("add.konva",function(n){n.child.off(awt,this._sync).on(awt,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 b3e:o=r/2,c=-1*d;break;case DWe:o=r+l,c=a/2;break;case FWe:o=r/2,c=a+d;break;case _3e: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})}}};jrt.prototype.className="Label";Yg(jrt);class HB 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]=Jn._cornerRadii(o,n,r);t.beginPath(),t.moveTo(c,0),a===b3e&&(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===DWe&&(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===FWe&&(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===_3e&&(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===b3e||r===FWe?{x:Math.min(0,(a-t)/2),y:r===b3e?-n:0,width:Math.max(a,t),height:i+n}:r===_3e||r===DWe?{x:r===_3e?-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}}}HB.prototype.className="Tag";Yg(HB,!0);Tn.addGetterSetter(HB,"pointerDirection",Eln);Tn.addGetterSetter(HB,"pointerWidth",0,Ti());Tn.addGetterSetter(HB,"pointerHeight",0,Ti());Tn.addGetterSetter(HB,"cornerRadius",0,eRe(4));let vie=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?Jn.drawRoundedRectPath(t,r,a,n):t.rect(0,0,r,a),t.closePath(),t.fillStrokeShape(this)}};vie.prototype.className="Rect";Yg(vie,!0);Tn.addGetterSetter(vie,"cornerRadius",0,eRe(4));class v6 extends li{_sceneFunc(t){const n=this._getPoints(),r=this.radius(),a=this.sides(),i=this.cornerRadius();if(n.length){if(t.beginPath(),i)Jn.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)}}v6.prototype.className="RegularPolygon";v6.prototype._centroid=!0;v6.prototype._attrsAffectingSize=["radius","sides"];Yg(v6,!0);Tn.addGetterSetter(v6,"radius",0,Ti());Tn.addGetterSetter(v6,"sides",0,Ti());Tn.addGetterSetter(v6,"cornerRadius",0,eRe(4));const iwt=Math.PI*2;class GB 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,iwt,!1),t.moveTo(r,0),t.arc(0,0,r,iwt,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)}}GB.prototype.className="Ring";GB.prototype._centroid=!0;GB.prototype._attrsAffectingSize=["innerRadius","outerRadius"];Yg(GB,!0);Tn.addGetterSetter(GB,"innerRadius",0,Ti());Tn.addGetterSetter(GB,"outerRadius",0,Ti());class d3 extends li{constructor(t){super(t),this._updated=!0,this.anim=new DN(()=>{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:HS.getPointAtLengthOfDataArray(t,this.dataArray,n)}_readDataAttribute(){this.dataArray=HS.parsePathData(this.attrs.data),this.pathLength=this._getTextPathLength()}_sceneFunc(t){t.setAttr("font",this._getContextFont()),t.setAttr("textBaseline",this.textBaseline()),t.setAttr("textAlign","left"),t.save();const n=this.textDecoration(),r=this.fill(),a=this.fontSize(),i=this.glyphInfo,l=n.indexOf("underline")!==-1,o=n.indexOf("line-through")!==-1;l&&t.beginPath();for(let c=0;c=1){const r=n[0].p0;t.moveTo(r.x,r.y)}for(let r=0;r0)try{y=n(t[x-1],t[x])*this.fontSize()}catch{}r.push({char:t[x],width:this._getTextSize(t[x]).width,kern:y}),a+=r[x].width+y}const{width:i,height:l}=this._getTextSize(this.attrs.text);if(this.textWidth=a,this.textHeight=l,this.glyphInfo=[],!this.attrs.data)return null;const o=this.letterSpacing(),c=this.align(),d=c==="justify"?this.text().split(" ").length-1:0,u=Math.max(0,a-i),h=Math.max(this.textWidth+(t.length-1)*o,0);let m=0;c==="center"&&(m=Math.max(0,this.pathLength/2-h/2)),c==="right"&&(m=Math.max(0,this.pathLength-h));let f=m;const g=this.dataArray.some((x,y)=>y>0&&x.command==="M")?void 0:{index:0,offset:0};for(let x=0;xthis.pathLength&&w-this.pathLength<=u?this.pathLength:w,g);if(!S)return;const A=HS.getLineLength(y.x,y.y,S.x,S.y),E=Math.atan2(S.y-y.y,S.x-y.x);this.glyphInfo.push({text:t[x],rotation:E,p0:y,p1:S,width: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=Jn._getPointsRect(t),r=this.fontSize();return{x:n.x-r/2,y:n.y-r/2,width:n.width+r,height:n.height+r}}getStrokeScaleEnabled(){return!0}_getSelfRectForDrawing(){const t=this.getSelfRect(),n=this.fontSize();return{x:t.x-n,y:t.y-n,width:t.width+n*2,height:t.height+n*2}}}Wg.prototype._fillFunc=BGt;Wg.prototype._strokeFunc=$Gt;Wg.prototype._fillFuncHit=BGt;Wg.prototype._strokeFuncHit=$Gt;Wg.prototype.className="TextPath";Wg.prototype._attrsAffectingSize=["text","fontSize","data","align","letterSpacing","kerningFunc","fontFamily","fontStyle","fontVariant","direction"];Yg(Wg,!0);Wg.prototype.on("dataChange.konva",function(){this._readDataAttribute(),this._setTextData()});Wg.prototype.on(Wg.prototype._attrsAffectingSize.filter(s=>s!=="data").map(s=>s+"Change.konva").join(" "),function(){this._setTextData()});Tn.addGetterSetter(Wg,"data");Tn.addGetterSetter(Wg,"fontFamily","Arial");Tn.addGetterSetter(Wg,"fontSize",12,Ti());Tn.addGetterSetter(Wg,"fontStyle",zGt);Tn.addGetterSetter(Wg,"align","left");Tn.addGetterSetter(Wg,"letterSpacing",0,Ti());Tn.addGetterSetter(Wg,"textBaseline","middle");Tn.addGetterSetter(Wg,"fontVariant",zGt);Tn.addGetterSetter(Wg,"text",Tln);Tn.addGetterSetter(Wg,"textDecoration","");Tn.addGetterSetter(Wg,"kerningFunc",void 0);Tn.addGetterSetter(Wg,"direction","inherit");const OWe="tr-konva",Mln=["resizeEnabledChange","rotateAnchorOffsetChange","rotateAnchorAngleChange","rotateEnabledChange","enabledAnchorsChange","anchorSizeChange","borderEnabledChange","shouldOverdrawWholeAreaChange","borderStrokeChange","borderStrokeWidthChange","borderDashChange","anchorStrokeChange","anchorStrokeWidthChange","anchorFillChange","anchorCornerRadiusChange","ignoreStrokeChange","anchorStyleFuncChange","paddingChange"].map(s=>s+`.${OWe}`).join(" "),GBe="nodesRect",Pln=["widthChange","heightChange","scaleXChange","scaleYChange","skewXChange","skewYChange","rotationChange","offsetXChange","offsetYChange","transformsEnabledChange","strokeWidthChange","strokeChange","selfRectFuncChange","strokeLinearGradientColorStopsChange","strokeScaleEnabledChange","strokeEnabledChange","draggableChange"],Iln={"top-left":-45,"top-center":0,"top-right":45,"middle-right":-90,"middle-left":90,"bottom-left":-135,"bottom-center":180,"bottom-right":135},Lln="ontouchstart"in Qo._global;function Rln(s,t,n){if(s==="rotater")return n;t+=Jn.degToRad(Iln[s]||0);const r=(Jn.radToDeg(t)%360+360)%360;return Jn._inRange(r,315+22.5,360)||Jn._inRange(r,0,22.5)?"ns-resize":Jn._inRange(r,45-22.5,45+22.5)?"nesw-resize":Jn._inRange(r,90-22.5,90+22.5)?"ew-resize":Jn._inRange(r,135-22.5,135+22.5)?"nwse-resize":Jn._inRange(r,180-22.5,180+22.5)?"ns-resize":Jn._inRange(r,225-22.5,225+22.5)?"nesw-resize":Jn._inRange(r,270-22.5,270+22.5)?"ew-resize":Jn._inRange(r,315-22.5,315+22.5)?"nwse-resize":(Jn.error("Transformer has unknown angle for cursor detection: "+r),"pointer")}const zTe=["top-left","top-center","top-right","middle-right","middle-left","bottom-left","bottom-center","bottom-right"];function Dln(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 Fln(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 Oln(s,t){const n=Dln(s);return Fln(s,t,n)}function zln(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 w3e=new Set;let Vu=class extends J7{static _isLayerTransforming(t){for(const n of w3e)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(Mln,n=>{n.type==="ignoreStrokeChange"&&this._resetTransformCache(),this.update()}),this.on(`rotationChange.${OWe}`,()=>this._clearCache(GBe)),this.getNode()&&this.update()}attachTo(t){return this.setNode(t),this}setNode(t){return Jn.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 OWe+this._id}setNodes(t=[]){this._nodes&&this._nodes.length&&this.detach();const n=new Set(t);for(const a of n)a.isAncestorOf(this)&&(Jn.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(Pln.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(GBe),this._clearCache("transform"),this._clearSelfAndDescendantCache("absoluteTransform")}_getNodeRect(){return this._getCache(GBe,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 b0;i.rotate(-r);const l=this._nodeRectCache||(this._nodeRectCache=new Map);let o=1/0,c=1/0,d=-1/0,u=-1/0;for(const m of this.nodes()){const f=m instanceof li&&m.getSelfRect===li.prototype.getSelfRect&&!m.attrs.selfRectFunc&&!m._hasCachedAncestor(),g=f?m.width():0,x=f?m.height():0;f&&((t=m._attrsVersion)!==null&&t!==void 0||(m._attrsVersion=0));let y=f?l.get(m):void 0;if(!y||y.rotation!==r||y.ignoreStroke!==a||y.version!==m._attrsVersion||y.width!==g||y.height!==x){let v=m.getAbsoluteTransform();const[b,w,S,A]=v.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&&(v=new b0),y={rotation:r,ignoreStroke:a,width:g,height:x,version:m._attrsVersion||0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};for(const R of P){const D=i.point(v.point(R));y.minX=Math.min(y.minX,D.x),y.minY=Math.min(y.minY,D.y),y.maxX=Math.max(y.maxX,D.x),y.maxY=Math.max(y.maxY,D.y)}f&&l.set(m,y)}o=Math.min(o,y.minX),c=Math.min(c,y.minY),d=Math.max(d,y.maxX),u=Math.max(u,y.maxY)}i.invert();const h=i.point({x:o,y:c});return{x:h.x,y:h.y,width:d-o,height:u-c,rotation:Qo.getAngle(this.rotation())}}getX(){return this._getNodeRect().x}getY(){return this._getNodeRect().y}getWidth(){return this._getNodeRect().width}getHeight(){return this._getNodeRect().height}_createElements(){this._createBack(),zTe.forEach(t=>{this._createAnchor(t)}),this._createAnchor("rotater"),this._elementsCreated=!0}_createAnchor(t){const n=new vie({stroke:"rgb(0, 161, 255)",fill:"white",strokeWidth:1,name:t+" _anchor",dragDistance:0,draggable:!0,hitStrokeWidth:Lln?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=Rln(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=owt(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:Jn._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},w3e.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=Jn.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=zln(this.rotationSnaps(),I,P)-w.rotation,O=Oln(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();w3e.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||Jn._inRange(t.width,-this.padding()*2-i,i)||Jn._inRange(t.height,-this.padding()*2-i,i)){this.update();return}const l=new b0;l.rotate(Qo.getAngle(this.rotation()));const o=r?0:this.padding()*2;let c=null,d=null;if(this._movingAnchorName&&t.width<0&&this._movingAnchorName.indexOf("left")>=0){const v=l.point({x:-o,y:0});t.x+=v.x,t.y+=v.y,t.width+=o,c={axis:"width",from:"left",to:"right",offset:v}}else if(this._movingAnchorName&&t.width<0&&this._movingAnchorName.indexOf("right")>=0){const v=l.point({x:o,y:0});t.width+=o,c={axis:"width",from:"right",to:"left",offset:v}}if(this._movingAnchorName&&t.height<0&&this._movingAnchorName.indexOf("top")>=0){const v=l.point({x:0,y:-o});t.x+=v.x,t.y+=v.y,t.height+=o,d={axis:"height",from:"top",to:"bottom",offset:v}}else if(this._movingAnchorName&&t.height<0&&this._movingAnchorName.indexOf("bottom")>=0){const v=l.point({x:0,y:o});t.height+=o,d={axis:"height",from:"bottom",to:"top",offset:v}}if(this.boundBoxFunc()){const v=this.boundBoxFunc()(a,t);v?t=v:Jn.warn("boundBoxFunc returned falsy. You should return new bound rect from it!")}for(const v of[c,d])v&&t[v.axis]<0&&this._movingAnchorName&&(this._movingAnchorName=this._movingAnchorName.replace(v.from,v.to),this._anchorDragOffset.x-=v.offset.x,this._anchorDragOffset.y-=v.offset.y);const u=1e7,h=new b0;h.translate(a.x,a.y),h.rotate(a.rotation),h.scale(a.width/u,a.height/u);const m=new b0,f=t.width/u,g=t.height/u;this.flipEnabled()===!1?(m.translate(t.x,t.y),m.rotate(t.rotation),m.translate(t.width<0?t.width:0,t.height<0?t.height:0),m.scale(Math.abs(f),Math.abs(g))):(m.translate(t.x,t.y),m.rotate(t.rotation),m.scale(f,g));const x=m.multiply(h.invert()),y=new Set;this._nodes.forEach(v=>{if(!v.getStage())return;const b=v.getParent().getAbsoluteTransform(),w=v.getTransform().copy();w.translate(v.offsetX(),v.offsetY());const S=new b0;S.multiply(b.copy().invert()).multiply(x).multiply(b).multiply(w);const A=S.decompose();v.setAttrs(A);const E=v.getLayer();E&&y.add(E)}),this.rotation(Jn._getRotation(t.rotation)),this._nodes.forEach(v=>{this._fire("transform",{evt:n,target:v}),v._fire("transform",{evt:n,target:v})}),this._resetTransformCache(),this.update(),y.add(this.getLayer()),y.forEach(v=>v&&v.batchDraw())}_scheduleUpdate(){this._updateScheduled||(this._updateScheduled=!0,zi._runAfterAbsTransformCascade(()=>{var t;this._updateScheduled=!1,!(!(!((t=this._nodes)===null||t===void 0)&&t.length)||this._fitting||this.isDragging())&&this._update()}))}forceUpdate(){this._resetTransformCache(),this.update()}update(){this._lastNodeRect=void 0,this._update()}_update(){var t;const n=this._getNodeRect();this._updateElements(n);const r=this.nodes().some(i=>i.draggable());this._back.draggable()!==r&&this._back.draggable(r);const a=this.anchorStyleFunc();a&&Object.values(this._anchors).forEach(i=>a(i)),(t=this.getLayer())===null||t===void 0||t.batchDraw()}_updateElements(t){const n=this._lastNodeRect;if(n&&!this.anchorStyleFunc()&&t.x===n.x&&t.y===n.y&&t.width===n.width&&t.height===n.height&&t.rotation===n.rotation)return;this._lastNodeRect={...t};const r=t.width,a=t.height,i=this.enabledAnchors(),l=this.resizeEnabled(),o=this.padding(),c=this.anchorSize();Object.values(this._anchors).forEach(h=>{h.setAttrs({width:c,height:c,offsetX:c/2,offsetY:c/2,stroke:this.anchorStroke(),strokeWidth:this.anchorStrokeWidth(),fill:this.anchorFill(),cornerRadius:this.anchorCornerRadius()})}),this._anchors["top-left"].setAttrs({x:0,y:0,offsetX:c/2+o,offsetY:c/2+o,visible:l&&i.indexOf("top-left")>=0}),this._anchors["top-center"].setAttrs({x:r/2,y:0,offsetY:c/2+o,visible:l&&i.indexOf("top-center")>=0}),this._anchors["top-right"].setAttrs({x:r,y:0,offsetX:c/2-o,offsetY:c/2+o,visible:l&&i.indexOf("top-right")>=0}),this._anchors["middle-left"].setAttrs({x:0,y:a/2,offsetX:c/2+o,visible:l&&i.indexOf("middle-left")>=0}),this._anchors["middle-right"].setAttrs({x:r,y:a/2,offsetX:c/2-o,visible:l&&i.indexOf("middle-right")>=0}),this._anchors["bottom-left"].setAttrs({x:0,y:a,offsetX:c/2+o,offsetY:c/2-o,visible:l&&i.indexOf("bottom-left")>=0}),this._anchors["bottom-center"].setAttrs({x:r/2,y:a,offsetY:c/2-o,visible:l&&i.indexOf("bottom-center")>=0}),this._anchors["bottom-right"].setAttrs({x:r,y:a,offsetX:c/2-o,offsetY:c/2-o,visible:l&&i.indexOf("bottom-right")>=0});const u=owt(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=""),J7.prototype.destroy.call(this),this.detach(),this._removeEvents(),this}add(...t){return this._elementsCreated?(Jn.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=()=>w3e.size>0;function Bln(s){return s instanceof Array||Jn.warn("enabledAnchors value should be an array"),s instanceof Array&&s.forEach(function(t){zTe.indexOf(t)===-1&&Jn.warn("Unknown anchor name: "+t+". Available names are: "+zTe.join(", "))}),s||[]}Vu.prototype.className="Transformer";Yg(Vu);Tn.addGetterSetter(Vu,"enabledAnchors",zTe,Bln);Tn.addGetterSetter(Vu,"flipEnabled",!0,jC());Tn.addGetterSetter(Vu,"resizeEnabled",!0);Tn.addGetterSetter(Vu,"anchorSize",10,Ti());Tn.addGetterSetter(Vu,"rotateEnabled",!0);Tn.addGetterSetter(Vu,"rotateLineVisible",!0);Tn.addGetterSetter(Vu,"rotationSnaps",[]);Tn.addGetterSetter(Vu,"rotateAnchorOffset",50,Ti());Tn.addGetterSetter(Vu,"rotateAnchorAngle",0,Ti());Tn.addGetterSetter(Vu,"rotateAnchorCursor","crosshair");Tn.addGetterSetter(Vu,"rotationSnapTolerance",5,Ti());Tn.addGetterSetter(Vu,"borderEnabled",!0);Tn.addGetterSetter(Vu,"anchorStroke","rgb(0, 161, 255)");Tn.addGetterSetter(Vu,"anchorStrokeWidth",1,Ti());Tn.addGetterSetter(Vu,"anchorFill","white");Tn.addGetterSetter(Vu,"anchorCornerRadius",0,Ti());Tn.addGetterSetter(Vu,"borderStroke","rgb(0, 161, 255)");Tn.addGetterSetter(Vu,"borderStrokeWidth",1,Ti());Tn.addGetterSetter(Vu,"borderDash");Tn.addGetterSetter(Vu,"keepRatio",!0);Tn.addGetterSetter(Vu,"shiftBehavior","default");Tn.addGetterSetter(Vu,"centeredScaling",!1);Tn.addGetterSetter(Vu,"ignoreStroke",!1);Tn.addGetterSetter(Vu,"padding",0,Ti());Tn.addGetterSetter(Vu,"nodes");Tn.addGetterSetter(Vu,"node");Tn.addGetterSetter(Vu,"boundBoxFunc");Tn.addGetterSetter(Vu,"anchorDragBoundFunc");Tn.addGetterSetter(Vu,"anchorStyleFunc");Tn.addGetterSetter(Vu,"shouldOverdrawWholeArea",!1);Tn.addGetterSetter(Vu,"useSingleNodeRotation",!0);Tn.backCompat(Vu,{lineEnabled:"borderEnabled",rotateHandlerOffset:"rotateAnchorOffset",enabledHandlers:"enabledAnchors"});class IT 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)}}IT.prototype.className="Wedge";IT.prototype._centroid=!0;IT.prototype._attrsAffectingSize=["radius"];Yg(IT,!0);Tn.addGetterSetter(IT,"radius",0,Ti());Tn.addGetterSetter(IT,"angle",0,Ti());Tn.addGetterSetter(IT,"clockwise",!1);Tn.backCompat(IT,{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 lwt(){this.r=0,this.g=0,this.b=0,this.a=0,this.next=null}const $ln=[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],Uln=[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 tA(s,t){return t===255?s:s*t/255}const UGt=180;function qln(s,t){const n=s.data,r=s.width,a=s.height;let i,l,o,c,d,u,h,m,f,g,x,y,v,b,w,S,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 lwt,G=t<=UGt?$ln[t]/2**Uln[t]:1/(U*U);let Y=null,X=V,ae=null,le=null;for(let ne=1;ne0?(I=255/I,n[i]=Math.floor(c*G)*I,n[i+1]=Math.floor(d*G)*I,n[i+2]=Math.floor(u*G)*I):n[i]=n[i+1]=n[i+2]=0,c-=m,d-=f,u-=g,h-=x,m-=ae.r,f-=ae.g,g-=ae.b,x-=ae.a,i=ne+((i=J+U)0&&qln(t,r)};Tn.addGetterSetter(zi,"blurRadius",0,Ti(),Tn.afterSetFilter);const Hln=function(s){const t=this.brightness()*255,n=s.data,r=n.length;for(let a=0;a255?255:a,i=i<0?0:i>255?255:i,l=l<0?0:l>255?255:l,n[o]=a,n[o+1]=i,n[o+2]=l};Tn.addGetterSetter(zi,"contrast",0,Ti(),Tn.afterSetFilter);const Kln=function(s){var t,n,r,a,i,l,o,c,d;const u=s.data,h=s.width,m=s.height,f=Math.min(1,Math.max(0,(n=(t=this.embossStrength)===null||t===void 0?void 0:t.call(this))!==null&&n!==void 0?n:.5)),g=Math.min(1,Math.max(0,(a=(r=this.embossWhiteLevel)===null||r===void 0?void 0:r.call(this))!==null&&a!==void 0?a:.5)),y=(o={"top-left":315,top:270,"top-right":225,right:180,"bottom-right":135,bottom:90,"bottom-left":45,left:0}[(l=(i=this.embossDirection)===null||i===void 0?void 0:i.call(this))!==null&&l!==void 0?l:"top-left"])!==null&&o!==void 0?o:315,v=!!((d=(c=this.embossBlend)===null||c===void 0?void 0:c.call(this))!==null&&d!==void 0&&d),b=f*10,w=g*255,S=y*Math.PI/180,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,y,v,b;if(m>0)f=a+m*(255-a),g=r-m*(r-0),x=o+m*(255-o),y=l-m*(l-0),v=u+m*(255-u),b=d-m*(d-0);else{const w=(a+r)*.5;f=a+m*(a-w),g=r+m*(r-w);const S=(o+l)*.5;x=o+m*(o-S),y=l+m*(l-S);const A=(u+d)*.5;v=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 y=0;yd?m:d;const f=l,g=i,x=0;let y,v;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 lcn(s,t,n){const r=[.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111],a=Math.round(Math.sqrt(r.length)),i=Math.floor(a/2),l=[];for(let o=0;o=0&&f=0&&gMath.min(1,Math.max(0,s)),Tn.afterSetFilter);const pcn=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},xcn=function(s){const t=this.threshold()*255,n=s.data,r=n.length;for(let a=0;amr||lt[Ws]!==Ot[mr]){var $r=` `+lt[Ws].replace(" at new "," at ");return ie.displayName&&$r.includes("")&&($r=$r.replace("",ie.displayName)),$r}while(1<=Ws&&0<=mr);break}}}finally{Ho=!1,Error.prepareStackTrace=Oe}return(ie=ie?ie.displayName||ie.name:"")?Nl(ie):""}var Xr=Object.prototype.hasOwnProperty,Eo=[],Th=-1;function ah(ie){return{current:ie}}function ao(ie){0>Th||(ie.current=Eo[Th],Eo[Th]=null,Th--)}function ta(ie,de){Th++,Eo[Th]=ie.current,ie.current=de}var xc={},fl=ah(xc),Co=ah(!1),fu=xc;function cc(ie,de){var Oe=ie.type.contextTypes;if(!Oe)return xc;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 zr(){ao(Co),ao(fl)}function Hi(ie,de,Oe){if(fl.current!==xc)throw Error(l(168));ta(fl,de),ta(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||xc,fu=fl.current,ta(fl,ie),ta(Co,Co.current),!0}function yc(ie,de,Oe){var tt=ie.stateNode;if(!tt)throw Error(l(169));Oe?(ie=zc(ie,de,fu),tt.__reactInternalMemoizedMergedChildContext=ie,ao(Co),ao(fl),ta(fl,ie)):ao(Co),ta(Co,Oe)}var $l=Math.clz32?Math.clz32:Yo,rg=Math.log,Ix=Math.LN2;function Yo(ie){return ie>>>=0,ie===0?32:31-(rg(ie)/Ix|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,Ws=Oe&268435455;if(Ws!==0){var mr=Ws&~lt;mr!==0?tt=lm(mr):(Ot&=Ws,Ot!==0&&(tt=lm(Ot)))}else Ws=Oe&~lt,Ws!==0?tt=lm(Ws):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>=Ws,lt-=Ws,tr=1<<32-$l(de)+lt|Oe<Md?(bh=Sc,Sc=null):bh=Sc.sibling;var Sl=Zi(Ur,Sc,ia[Md],Qi);if(Sl===null){Sc===null&&(Sc=bh);break}ie&&Sc&&Sl.alternate===null&&de(Ur,Sc),Wn=Ot(Sl,Wn,Md),Jc===null?xl=Sl:Jc.sibling=Sl,Jc=Sl,Sc=bh}if(Md===ia.length)return Oe(Ur,Sc),tn&&yr(Ur,Md),xl;if(Sc===null){for(;MdMd?(bh=Sc,Sc=null):bh=Sc.sibling;var gr=Zi(Ur,Sc,Sl.value,Qi);if(gr===null){Sc===null&&(Sc=bh);break}ie&&Sc&&gr.alternate===null&&de(Ur,Sc),Wn=Ot(gr,Wn,Md),Jc===null?xl=gr:Jc.sibling=gr,Jc=gr,Sc=bh}if(Sl.done)return Oe(Ur,Sc),tn&&yr(Ur,Md),xl;if(Sc===null){for(;!Sl.done;Md++,Sl=ia.next())Sl=gl(Ur,Sl.value,Qi),Sl!==null&&(Wn=Ot(Sl,Wn,Md),Jc===null?xl=Sl:Jc.sibling=Sl,Jc=Sl);return tn&&yr(Ur,Md),xl}for(Sc=tt(Ur,Sc);!Sl.done;Md++,Sl=ia.next())Sl=Hh(Sc,Ur,Md,Sl.value,Qi),Sl!==null&&(ie&&Sl.alternate!==null&&Sc.delete(Sl.key===null?Md:Sl.key),Wn=Ot(Sl,Wn,Md),Jc===null?xl=Sl:Jc.sibling=Sl,Jc=Sl);return ie&&Sc.forEach(function(Er){return de(Ur,Er)}),tn&&yr(Ur,Md),xl}function q_(Ur,Wn,ia,Qi){if(typeof ia=="object"&&ia!==null&&ia.type===u&&ia.key===null&&(ia=ia.props.children),typeof ia=="object"&&ia!==null){switch(ia.$$typeof){case c:e:{for(var xl=ia.key,Jc=Wn;Jc!==null;){if(Jc.key===xl){if(xl=ia.type,xl===u){if(Jc.tag===7){Oe(Ur,Jc.sibling),Wn=lt(Jc,ia.props.children),Wn.return=Ur,Ur=Wn;break e}}else if(Jc.elementType===xl||typeof xl=="object"&&xl!==null&&xl.$$typeof===w&&au(xl)===Jc.type){Oe(Ur,Jc.sibling),Wn=lt(Jc,ia.props),Wn.ref=Pl(Ur,Jc,ia),Wn.return=Ur,Ur=Wn;break e}Oe(Ur,Jc);break}else de(Ur,Jc);Jc=Jc.sibling}ia.type===u?(Wn=sj(ia.props.children,Ur.mode,Qi,ia.key),Wn.return=Ur,Ur=Wn):(Qi=qk(ia.type,ia.key,ia.props,null,Ur.mode,Qi),Qi.ref=Pl(Ur,Wn,ia),Qi.return=Ur,Ur=Qi)}return Ws(Ur);case d:e:{for(Jc=ia.key;Wn!==null;){if(Wn.key===Jc)if(Wn.tag===4&&Wn.stateNode.containerInfo===ia.containerInfo&&Wn.stateNode.implementation===ia.implementation){Oe(Ur,Wn.sibling),Wn=lt(Wn,ia.children||[]),Wn.return=Ur,Ur=Wn;break e}else{Oe(Ur,Wn);break}else de(Ur,Wn);Wn=Wn.sibling}Wn=$C(ia,Ur.mode,Qi),Wn.return=Ur,Ur=Wn}return Ws(Ur);case w:return Jc=ia._init,q_(Ur,Wn,Jc(ia._payload),Qi)}if(G(ia))return hh(Ur,Wn,ia,Qi);if(E(ia))return by(Ur,Wn,ia,Qi);Cd(Ur,ia)}return typeof ia=="string"&&ia!==""||typeof ia=="number"?(ia=""+ia,Wn!==null&&Wn.tag===6?(Oe(Ur,Wn.sibling),Wn=lt(Wn,ia),Wn.return=Ur,Ur=Wn):(Oe(Ur,Wn),Wn=BC(ia,Ur.mode,Qi),Wn.return=Ur,Ur=Wn),Ws(Ur)):Oe(Ur,Wn)}return q_}var Cn=qt(!0),rr=qt(!1),ra=ah(null),Yr=null,Aa=null,gi=null;function Ia(){gi=Aa=Yr=null}function el(ie,de,Oe){Le?(ta(ra,de._currentValue),de._currentValue=Oe):(ta(ra,de._currentValue2),de._currentValue2=Oe)}function zo(ie){var de=ra.current;ao(ra),Le?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 Tu(ie,de){Yr=ie,gi=Aa=null,ie=ie.dependencies,ie!==null&&ie.firstContext!==null&&(ie.lanes&de&&(tx=!0),ie.firstContext=null)}function iu(ie){var de=Le?ie._currentValue:ie._currentValue2;if(gi!==ie)if(ie={context:ie,memoizedValue:de,next:null},Aa===null){if(Yr===null)throw Error(l(308));Aa=ie,Yr.dependencies={lanes:0,firstContext:ie}}else Aa=Aa.next=ie;return de}var dm=null;function Ad(ie){dm===null?dm=[ie]:dm.push(ie)}function pu(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 oh(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 Bd(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 Ws={eventTime:Oe.eventTime,lane:Oe.lane,tag:Oe.tag,payload:Oe.payload,callback:Oe.callback,next:null};Ot===null?lt=Ot=Ws:Ot=Ot.next=Ws,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 $d(ie,de,Oe,tt){var lt=ie.updateQueue;rd=!1;var Ot=lt.firstBaseUpdate,Ws=lt.lastBaseUpdate,mr=lt.shared.pending;if(mr!==null){lt.shared.pending=null;var $r=mr,di=$r.next;$r.next=null,Ws===null?Ot=di:Ws.next=di,Ws=$r;var Mi=ie.alternate;Mi!==null&&(Mi=Mi.updateQueue,mr=Mi.lastBaseUpdate,mr!==Ws&&(mr===null?Mi.firstBaseUpdate=di:mr.next=di,Mi.lastBaseUpdate=$r))}if(Ot!==null){var gl=lt.baseState;Ws=0,Mi=di=$r=null,mr=Ot;do{var Zi=mr.lane,Hh=mr.eventTime;if((tt&Zi)===Zi){Mi!==null&&(Mi=Mi.next={eventTime:Hh,lane:0,tag:mr.tag,payload:mr.payload,callback:mr.callback,next:null});e:{var hh=ie,by=mr;switch(Zi=de,Hh=Oe,by.tag){case 1:if(hh=by.payload,typeof hh=="function"){gl=hh.call(Hh,gl,Zi);break e}gl=hh;break e;case 3:hh.flags=hh.flags&-65537|128;case 0:if(hh=by.payload,Zi=typeof hh=="function"?hh.call(Hh,gl,Zi):hh,Zi==null)break e;gl=i({},gl,Zi);break e;case 2:rd=!0}}mr.callback!==null&&mr.lane!==0&&(ie.flags|=64,Zi=lt.effects,Zi===null?lt.effects=[mr]:Zi.push(mr))}else Hh={eventTime:Hh,lane:Zi,tag:mr.tag,payload:mr.payload,callback:mr.callback,next:null},Mi===null?(di=Mi=Hh,$r=gl):Mi=Mi.next=Hh,Ws|=Zi;if(mr=mr.next,mr===null){if(mr=lt.shared.pending,mr===null)break;Zi=mr,mr=Zi.next,Zi.next=null,lt.lastBaseUpdate=Zi,lt.shared.pending=null}}while(!0);if(Mi===null&&($r=gl),lt.baseState=$r,lt.firstBaseUpdate=di,lt.lastBaseUpdate=Mi,de=lt.shared.interleaved,de!==null){lt=de;do Ws|=lt.lane,lt=lt.next;while(lt!==de)}else Ot===null&&(lt.shared.lanes=0);B1|=Ws,ie.lanes=Ws,ie.memoizedState=gl}}function dd(ie,de,Oe){if(ie=de.effects,de.effects=null,ie!==null)for(de=0;deOe?Oe:4,ie(!0);var tt=Rx.transition;Rx.transition={};try{ie(!1),de()}finally{Zo=Oe,Rx.transition=tt}}function Ib(){return df().memoizedState}function zv(ie,de,Oe){var tt=q1(ie);if(Oe={lane:tt,action:Oe,hasEagerState:!1,eagerState:null,next:null},V2(ie))rp(de,Oe);else if(Oe=pu(ie,de,Oe,tt),Oe!==null){var lt=cp();$x(Oe,ie,tt,lt),Ik(Oe,de,tt)}}function k3(ie,de,Oe){var tt=q1(ie),lt={lane:tt,action:Oe,hasEagerState:!1,eagerState:null,next:null};if(V2(ie))rp(de,lt);else{var Ot=ie.alternate;if(ie.lanes===0&&(Ot===null||Ot.lanes===0)&&(Ot=de.lastRenderedReducer,Ot!==null))try{var Ws=de.lastRenderedState,mr=Ot(Ws,Oe);if(lt.hasEagerState=!0,lt.eagerState=mr,jt(mr,Ws)){var $r=de.interleaved;$r===null?(lt.next=lt,Ad(de)):(lt.next=$r.next,$r.next=lt),de.interleaved=lt;return}}catch{}finally{}Oe=pu(ie,de,lt,tt),Oe!==null&&(lt=cp(),$x(Oe,ie,tt,lt),Ik(Oe,de,tt))}}function V2(ie){var de=ie.alternate;return ie===kc||de!==null&&de===kc}function rp(ie,de){fa=gu=!0;var Oe=ie.pending;Oe===null?de.next=de:(de.next=Oe.next,Oe.next=de),ie.pending=de}function Ik(ie,de,Oe){if(Oe&4194240){var tt=de.lanes;tt&=ie.pendingLanes,Oe|=tt,de.lanes=Oe,cm(ie,Oe)}}var D1={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},ex={readContext:iu,useCallback:function(ie,de){return xh().memoizedState=[ie,de===void 0?null:de],ie},useContext:iu,useEffect:Qg,useImperativeHandle:function(ie,de,Oe){return Oe=Oe!=null?Oe.concat([ie]):null,lh(4194308,4,I1.bind(null,de,ie),Oe)},useLayoutEffect:function(ie,de){return lh(4194308,4,ie,de)},useInsertionEffect:function(ie,de){return lh(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=zv.bind(null,kc,ie),[tt.memoizedState,ie]},useRef:function(ie){var de=xh();return ie={current:ie},de.memoizedState=ie},useState:yh,useDebugValue:R1,useDeferredValue:function(ie){return xh().memoizedState=ie},useTransition:function(){var ie=yh(!1),de=ie[0];return ie=Pk.bind(null,ie[1]),xh().memoizedState=ie,[de,ie]},useMutableSource:function(){},useSyncExternalStore:function(ie,de,Oe){var tt=kc,lt=xh();if(tn){if(Oe===void 0)throw Error(l(407));Oe=Oe()}else{if(Oe=de(),Vd===null)throw Error(l(349));Gu&30||Pb(tt,de,Oe)}lt.memoizedState=Oe;var Ot={value:Oe,getSnapshot:de};return lt.queue=Ot,Qg(zm.bind(null,tt,Ot,ie),[ie]),tt.flags|=2048,Ui(9,Kw.bind(null,tt,Ot,Oe,de),void 0,null),Oe},useId:function(){var ie=xh(),de=Vd.identifierPrefix;if(tn){var Oe=vr,tt=tr;Oe=(tt&~(1<<32-$l(tt)-1)).toString(32)+Oe,de=":"+de+"R"+Oe,Oe=Ao++,0zk&&(de.flags|=128,tt=!0,Ar(lt,!1),de.lanes=4194304)}else{if(!tt)if(ie=Yy(Ot),ie!==null){if(de.flags|=128,tt=!0,ie=ie.updateQueue,ie!==null&&(de.updateQueue=ie,de.flags|=4),Ar(lt,!0),lt.tail===null&<.tailMode==="hidden"&&!Ot.alternate&&!tn)return Qs(de),null}else 2*Zd()-lt.renderingStartTime>zk&&Oe!==1073741824&&(de.flags|=128,tt=!0,Ar(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=Zd(),de.sibling=null,ie=ya.current,ta(ya,tt?ie&1|2:ie&1),de):(Qs(de),null);case 22:case 23:return U_(),Oe=de.memoizedState!==null,ie!==null&&ie.memoizedState!==null!==Oe&&(de.flags|=8192),Oe&&de.mode&1?zx&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 br(ie,de){switch(Vt(de),de.tag){case 1:return nd(de.type)&&zr(),ie=de.flags,ie&65536?(de.flags=ie&-65537|128,de):null;case 3:return Ep(),ao(Co),ao(fl),Xg(),ie=de.flags,ie&65536&&!(ie&128)?(de.flags=ie&-65537|128,de):null;case 5:return Lx(de),null;case 13:if(ao(ya),ie=de.memoizedState,ie!==null&&ie.dehydrated!==null){if(de.alternate===null)throw Error(l(340));oo()}return ie=de.flags,ie&65536?(de.flags=ie&-65537|128,de):null;case 19:return ao(ya),null;case 4:return Ep(),null;case 10:return zo(de.type._context),null;case 22:case 23:return U_(),null;case 24:return null;default:return null}}var aa=!1,ur=!1,pa=typeof WeakSet=="function"?WeakSet:Set,cr=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 Ea(ie,de,Oe){try{Oe()}catch(tt){_m(ie,de,tt)}}var _o=!1;function Fi(ie,de){for(le(ie.containerInfo),cr=de;cr!==null;)if(ie=cr,de=ie.child,(ie.subtreeFlags&1028)!==0&&de!==null)de.return=ie,cr=de;else for(;cr!==null;){ie=cr;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,Ws=Ot.getSnapshotBeforeUpdate(ie.elementType===ie.type?tt:qd(ie.type,tt),lt);Ot.__reactInternalSnapshotBeforeUpdate=Ws}break;case 3:Fe&&ds(ie.stateNode.containerInfo);break;case 5:case 6:case 4:case 17:break;default:throw Error(l(163))}}catch(mr){_m(ie,ie.return,mr)}if(de=ie.sibling,de!==null){de.return=ie.return,cr=de;break}cr=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&&Ea(de,Oe,Ot)}lt=lt.next}while(lt!==tt)}}function lo(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=Y(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&&Ve(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 bi(ie,de,Oe){var tt=ie.tag;if(tt===5||tt===6)ie=ie.stateNode,de?as(Oe,ie,de):Yt(Oe,ie);else if(tt!==4&&(ie=ie.child,ie!==null))for(bi(ie,de,Oe),ie=ie.sibling;ie!==null;)bi(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):ss(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:ur||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?Ks(To,Oe.stateNode):kt(To,Oe.stateNode))}else $c(ie,de,Oe);break;case 18:Fe&&To!==null&&(Ql?xa(To,Oe.stateNode):Rn(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):(ke&&(tt=Oe.stateNode.containerInfo,lt=yn(tt),hn(tt,lt)),$c(ie,de,Oe));break;case 0:case 11:case 14:case 15:if(!ur&&(tt=Oe.updateQueue,tt!==null&&(tt=tt.lastEffect,tt!==null))){lt=tt=tt.next;do{var Ot=lt,Ws=Ot.destroy;Ot=Ot.tag,Ws!==void 0&&(Ot&2||Ot&4)&&Ea(Oe,de,Ws),lt=lt.next}while(lt!==tt)}$c(ie,de,Oe);break;case 1:if(!ur&&(Ua(Oe,de),tt=Oe.stateNode,typeof tt.componentWillUnmount=="function"))try{tt.props=Oe.memoizedProps,tt.state=Oe.memoizedState,tt.componentWillUnmount()}catch(mr){_m(Oe,de,mr)}$c(ie,de,Oe);break;case 21:$c(ie,de,Oe);break;case 22:Oe.mode&1?(ur=(tt=ur)||Oe.memoizedState!==null,$c(ie,de,Oe),ur=tt):$c(ie,de,Oe);break;default:$c(ie,de,Oe)}}function ig(ie){var de=ie.updateQueue;if(de!==null){ie.updateQueue=null;var Oe=ie.stateNode;Oe===null&&(Oe=ie.stateNode=new pa),de.forEach(function(tt){var lt=N9.bind(null,ie,tt);Oe.has(tt)||(Oe.add(tt),tt.then(lt,lt))})}}function Xd(ie,de){var Oe=de.deletions;if(Oe!==null)for(var tt=0;tt";case op:return":has("+(Mp(ie)||"")+")";case uh:return'[role="'+ie.value+'"]';case vc:return'"'+ie.value+'"';case vh:return'[data-testname="'+ie.value+'"]';default:throw Error(l(365))}}function nx(ie,de){var Oe=[];ie=[ie,0];for(var tt=0;ttlt&&(lt=Ws),tt&=~Ot}if(tt=lt,tt=Zd()-tt,tt=(120>tt?120:480>tt?480:1080>tt?1080:1920>tt?1920:3e3>tt?3e3:4320>tt?4320:1960*rx(tt/1960))-tt,10ie?16:ie,lp===null)var tt=!1;else{if(ie=lp,lp=null,$_=0,Jl&6)throw Error(l(331));var lt=Jl;for(Jl|=4,cr=ie.current;cr!==null;){var Ot=cr,Ws=Ot.child;if(cr.flags&16){var mr=Ot.deletions;if(mr!==null){for(var $r=0;$rZd()-W2?cg(ie,0):lg|=Oe),dp(ie,de)}function GT(ie,de){de===0&&(ie.mode&1?(de=Mh,Mh<<=1,!(Mh&130023424)&&(Mh=4194304)):de=1);var Oe=cp();ie=Zc(ie,de),ie!==null&&(ko(ie,de,Oe),dp(ie,Oe))}function j9(ie){var de=ie.memoizedState,Oe=0;de!==null&&(Oe=de.retryLane),GT(ie,Oe)}function N9(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),GT(ie,Oe)}var Uk;Uk=function(ie,de,Oe){if(ie!==null)if(ie.memoizedProps!==de.pendingProps||Co.current)tx=!0;else{if(!(ie.lanes&Oe)&&!(de.flags&128))return tx=!1,Tt(ie,de,Oe);tx=!!(ie.flags&131072)}else tx=!1,tn&&de.flags&1048576&&qa(de,vn,de.index);switch(de.lanes=0,de.tag){case 2:var tt=de.type;He(ie,de),ie=de.pendingProps;var lt=cc(de,fl.current);Tu(de,Oe),lt=Wo(null,de,tt,ie,lt,Oe);var Ot=$0();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,oh(de),lt.updater=IC,de.stateNode=lt,lt._reactInternals=de,Lb(de,tt,ie,Oe),de=Fk(null,de,tt,!0,Ot,Oe)):(de.tag=0,tn&&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=M3(tt),ie=qd(tt,ie),lt){case 0:de=H2(null,de,tt,ie,Oe);break e;case 1:de=Dk(null,de,tt,ie,Oe);break e;case 11:de=F1(null,de,tt,ie,Oe);break e;case 14:de=q0(null,de,tt,qd(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:qd(tt,lt),H2(ie,de,tt,lt,Oe);case 1:return tt=de.type,lt=de.pendingProps,lt=de.elementType===tt?lt:qd(tt,lt),Dk(ie,de,tt,lt,Oe);case 3:e:{if(O_(de),ie===null)throw Error(l(387));tt=de.pendingProps,Ot=de.memoizedState,lt=Ot.element,Pf(ie,de),$d(de,tt,null,Oe);var Ws=de.memoizedState;if(tt=Ws.element,Be&&Ot.isDehydrated)if(Ot={element:tt,isDehydrated:!1,cache:Ws.cache,pendingSuspenseBoundaries:Ws.pendingSuspenseBoundaries,transitions:Ws.transitions},de.updateQueue.baseState=Ot,de.memoizedState=Ot,de.flags&256){lt=Tp(Error(l(423)),de),de=Qw(ie,de,tt,Oe,lt);break e}else if(tt!==lt){lt=Tp(Error(l(424)),de),de=Qw(ie,de,tt,Oe,lt);break e}else for(Be&&(ln=la(de.stateNode.containerInfo),Es=de,tn=!0,nr=null,sr=!1),Oe=rr(de,null,tt,Oe),de.child=Oe;Oe;)Oe.flags=Oe.flags&-3|4096,Oe=Oe.sibling;else{if(oo(),tt===lt){de=ft(ie,de,Oe);break e}uf(ie,de,tt,Oe)}de=de.child}return de;case 5:return Fv(de),ie===null&&Na(de),tt=de.type,lt=de.pendingProps,Ot=ie!==null?ie.memoizedProps:null,Ws=lt.children,he(tt,lt)?Ws=null:Ot!==null&&he(tt,Ot)&&(de.flags|=32),Rk(ie,de),uf(ie,de,Ws,Oe),de.child;case 6:return ie===null&&Na(de),null;case 13:return G2(ie,de,Oe);case 4:return vd(de,de.stateNode.containerInfo),tt=de.pendingProps,ie===null?de.child=Cn(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:qd(tt,lt),F1(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,Ws=lt.value,el(de,tt,Ws),Ot!==null)if(jt(Ot.value,Ws)){if(Ot.children===lt.children&&!Co.current){de=ft(ie,de,Oe);break e}}else for(Ot=de.child,Ot!==null&&(Ot.return=de);Ot!==null;){var mr=Ot.dependencies;if(mr!==null){Ws=Ot.child;for(var $r=mr.firstContext;$r!==null;){if($r.context===tt){if(Ot.tag===1){$r=Bd(-1,Oe&-Oe),$r.tag=2;var di=Ot.updateQueue;if(di!==null){di=di.shared;var Mi=di.pending;Mi===null?$r.next=$r:($r.next=Mi.next,Mi.next=$r),di.pending=$r}}Ot.lanes|=Oe,$r=Ot.alternate,$r!==null&&($r.lanes|=Oe),Pc(Ot.return,Oe,de),mr.lanes|=Oe;break}$r=$r.next}}else if(Ot.tag===10)Ws=Ot.type===de.type?null:Ot.child;else if(Ot.tag===18){if(Ws=Ot.return,Ws===null)throw Error(l(341));Ws.lanes|=Oe,mr=Ws.alternate,mr!==null&&(mr.lanes|=Oe),Pc(Ws,Oe,de),Ws=Ot.sibling}else Ws=Ot.child;if(Ws!==null)Ws.return=Ot;else for(Ws=Ot;Ws!==null;){if(Ws===de){Ws=null;break}if(Ot=Ws.sibling,Ot!==null){Ot.return=Ws.return,Ws=Ot;break}Ws=Ws.return}Ot=Ws}uf(ie,de,lt.children,Oe),de=de.child}return de;case 9:return lt=de.type,tt=de.pendingProps.children,Tu(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=qd(tt,de.pendingProps),lt=qd(tt.type,lt),q0(ie,de,tt,lt,Oe);case 15:return V0(ie,de,de.type,de.pendingProps,Oe);case 17:return tt=de.type,lt=de.pendingProps,lt=de.elementType===tt?lt:qd(tt,lt),He(ie,de),de.tag=1,nd(tt)?(ie=!0,Bc(de)):ie=!1,Tu(de,Oe),VT(de,tt,lt),Lb(de,tt,lt,Oe),Fk(null,de,tt,!0,ie,Oe);case 19:return Pe(ie,de,Oe);case 22:return Ox(ie,de,Oe)}throw Error(l(156,de.tag))};function OC(ie,de){return Zg(ie,de)}function zC(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 W0(ie,de,Oe,tt){return new zC(ie,de,Oe,tt)}function WT(ie){return ie=ie.prototype,!(!ie||!ie.isReactComponent)}function M3(ie){if(typeof ie=="function")return WT(ie)?1:0;if(ie!=null){if(ie=ie.$$typeof,ie===x)return 11;if(ie===b)return 14}return 2}function Ob(ie,de){var Oe=ie.alternate;return Oe===null?(Oe=W0(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 qk(ie,de,Oe,tt,lt,Ot){var Ws=2;if(tt=ie,typeof ie=="function")WT(ie)&&(Ws=1);else if(typeof ie=="string")Ws=5;else e:switch(ie){case u:return sj(Oe.children,lt,Ot,de);case h:Ws=8,lt|=8;break;case m:return ie=W0(12,Oe,de,lt|2),ie.elementType=m,ie.lanes=Ot,ie;case y:return ie=W0(13,Oe,de,lt),ie.elementType=y,ie.lanes=Ot,ie;case v:return ie=W0(19,Oe,de,lt),ie.elementType=v,ie.lanes=Ot,ie;case S:return Vk(Oe,lt,Ot,de);default:if(typeof ie=="object"&&ie!==null)switch(ie.$$typeof){case f:Ws=10;break e;case g:Ws=9;break e;case x:Ws=11;break e;case b:Ws=14;break e;case w:Ws=16,tt=null;break e}throw Error(l(130,ie==null?ie:typeof ie,""))}return de=W0(Ws,Oe,de,lt),de.elementType=ie,de.type=tt,de.lanes=Ot,de}function sj(ie,de,Oe,tt){return ie=W0(7,ie,tt,de),ie.lanes=Oe,ie}function Vk(ie,de,Oe,tt){return ie=W0(22,ie,tt,de),ie.elementType=S,ie.lanes=Oe,ie.stateNode={isHidden:!1},ie}function BC(ie,de,Oe){return ie=W0(6,ie,null,de),ie.lanes=Oe,ie}function $C(ie,de,Oe){return de=W0(4,ie.children!==null?ie.children:[],ie.key,de),de.lanes=Oe,de.stateNode={containerInfo:ie.containerInfo,pendingChildren:null,implementation:ie.implementation},de}function D6(ie,de,Oe,tt,lt){this.tag=de,this.containerInfo=ie,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=Se,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=io(0),this.expirationTimes=io(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=io(0),this.identifierPrefix=tt,this.onRecoverableError=lt,Be&&(this.mutableSourceEagerHydrationData=null)}function P3(ie,de,Oe,tt,lt,Ot,Ws,mr,$r){return ie=new D6(ie,de,Oe,mr,$r),de===1?(de=1,Ot===!0&&(de|=8)):de=0,Ot=W0(3,null,null,de),ie.current=Ot,Ot.stateNode=ie,Ot.memoizedState={element:tt,isDehydrated:Oe,cache:null,transitions:null,pendingSuspenseBoundaries:null},oh(Ot),ie}function F6(ie){if(!ie)return xc;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 KT(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 O6(ie,de){if(ie=ie.memoizedState,ie!==null&&ie.dehydrated!==null){var Oe=ie.retryLane;ie.retryLane=Oe!==0&&Oe=di&&Ot>=gl&<<=Mi&&Ws<=Zi){ie.splice(de,1);break}else if(tt!==di||Oe.width!==$r.width||ZiWs){if(!(Ot!==gl||Oe.height!==$r.height||Milt)){di>tt&&($r.width+=di-tt,$r.x=tt),MiOt&&($r.height+=gl-Ot,$r.y=Ot),ZiOe&&(Oe=Ws)),Ws ")+` 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 Y(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:k9,findFiberByHostInstance:ie.findFiberByHostInstance||z6,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(!dt)throw Error(l(363));ie=Pp(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=cp(),Ws=q1(lt);return Oe=F6(Oe),de.context===null?de.context=Oe:de.pendingContext=Oe,de=Bd(Ot,Ws),de.payload={element:ie},tt=tt===void 0?null:tt,tt!==null&&(de.callback=tt),ie=ad(lt,de,Ws),ie!==null&&($x(ie,lt,Ws,Ot),Ph(ie,lt,Ws)),Ws},n};qGt.exports=ycn;var vcn=qGt.exports;const bcn=ru(vcn);var VGt={exports:{}},WB={};/** * @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. */WB.ConcurrentRoot=1;WB.ContinuousEventPriority=4;WB.DefaultEventPriority=16;WB.DiscreteEventPriority=1;WB.IdleEventPriority=536870912;WB.LegacyRoot=0;VGt.exports=WB;var HGt=VGt.exports;const cwt={children:!0,ref:!0,key:!0,style:!0,forwardedRef:!0,unstable_applyCache:!0,unstable_applyDrawHitFromCache:!0};let dwt=!1,uwt=!1;const Nrt=".react-konva-event",_cn=`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 `,wcn=`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 `,jcn={};function tRe(s,t,n=jcn){if(!dwt&&"zIndex"in t&&(console.warn(wcn),dwt=!0),!uwt&&t.draggable){var r=t.x!==void 0||t.y!==void 0,a=t.onDragEnd||t.onDragMove;r&&!a&&(console.warn(_cn),uwt=!0)}for(var i in n)if(!cwt[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(!cwt[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),_6(s));for(var c in f)s.on(c+Nrt,f[c])}function _6(s){if(!Qo.autoDrawEnabled){var t=s.getLayer()||s.getStage();t&&t.batchDraw()}}const GGt={},Ncn={};eB.Node.prototype._applyProps=tRe;function kcn(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),_6(s)}function Scn(s,t,n){let r=eB[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=eB.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 tRe(c,i),c}function Ccn(s,t,n){console.error(`Text components are not supported for now in ReactKonva. Your text is: "${s}"`)}function Acn(s,t,n){return!1}function Ecn(s){return s}function Tcn(){return null}function Mcn(){return null}function Pcn(s,t,n,r){return Ncn}function Icn(){}function Lcn(s){}function Rcn(s,t){return!1}function Dcn(){return GGt}function Fcn(){return GGt}const Ocn=setTimeout,zcn=clearTimeout,Bcn=-1;function $cn(s,t){return!1}const Ucn=!1,qcn=!0,Vcn=!0;function Hcn(s,t){t.parent===s?t.moveToTop():s.add(t),_6(s)}function Gcn(s,t){t.parent===s?t.moveToTop():s.add(t),_6(s)}function WGt(s,t,n){t._remove(),s.add(t),t.setZIndex(n.getZIndex()),_6(s)}function Wcn(s,t,n){WGt(s,t,n)}function Kcn(s,t){t.destroy(),t.off(Nrt),_6(s)}function Ycn(s,t){t.destroy(),t.off(Nrt),_6(s)}function Zcn(s,t,n){console.error(`Text components are not yet supported in ReactKonva. You text is: "${n}"`)}function Xcn(s,t,n){}function Qcn(s,t,n,r,a){tRe(s,a,r)}function Jcn(s){s.hide(),_6(s)}function edn(s){}function tdn(s,t){(t.visible==null||t.visible)&&s.show()}function sdn(s,t){}function ndn(s){}function rdn(){}const adn=()=>HGt.DefaultEventPriority,idn=Object.freeze(Object.defineProperty({__proto__:null,appendChild:Hcn,appendChildToContainer:Gcn,appendInitialChild:kcn,cancelTimeout:zcn,clearContainer:ndn,commitMount:Xcn,commitTextUpdate:Zcn,commitUpdate:Qcn,createInstance:Scn,createTextInstance:Ccn,detachDeletedInstance:rdn,finalizeInitialChildren:Acn,getChildHostContext:Fcn,getCurrentEventPriority:adn,getPublicInstance:Ecn,getRootHostContext:Dcn,hideInstance:Jcn,hideTextInstance:edn,idlePriority:JQ.unstable_IdlePriority,insertBefore:WGt,insertInContainerBefore:Wcn,isPrimaryRenderer:Ucn,noTimeout:Bcn,now:JQ.unstable_now,prepareForCommit:Tcn,preparePortalMount:Mcn,prepareUpdate:Pcn,removeChild:Kcn,removeChildFromContainer:Ycn,resetAfterCommit:Icn,resetTextContent:Lcn,run:JQ.unstable_runWithPriority,scheduleTimeout:Ocn,shouldDeprioritizeSubtree:Rcn,shouldSetTextContent:$cn,supportsMutation:Vcn,unhideInstance:tdn,unhideTextInstance:sdn,warnsIfNotActing:qcn},Symbol.toStringTag,{value:"Module"}));var odn=Object.defineProperty,ldn=Object.defineProperties,cdn=Object.getOwnPropertyDescriptors,hwt=Object.getOwnPropertySymbols,ddn=Object.prototype.hasOwnProperty,udn=Object.prototype.propertyIsEnumerable,mwt=(s,t,n)=>t in s?odn(s,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):s[t]=n,fwt=(s,t)=>{for(var n in t||(t={}))ddn.call(t,n)&&mwt(s,n,t[n]);if(hwt)for(var n of hwt(t))udn.call(t,n)&&mwt(s,n,t[n]);return s},hdn=(s,t)=>ldn(s,cdn(t)),pwt,gwt;typeof window<"u"&&((pwt=window.document)!=null&&pwt.createElement||((gwt=window.navigator)==null?void 0:gwt.product)==="ReactNative")?j.useLayoutEffect:j.useEffect;function KGt(s,t,n){if(!s)return;if(n(s)===!0)return s;let r=s.child;for(;r;){const a=KGt(r,t,n);if(a)return a;r=r.sibling}}function YGt(s){try{return Object.defineProperties(s,{_currentRenderer:{get(){return null},set(){}},_currentRenderer2:{get(){return null},set(){}}})}catch{return s}}const xwt=console.error;console.error=function(){const s=[...arguments].join("");if(s!=null&&s.startsWith("Warning:")&&s.includes("useContext")){console.error=xwt;return}return xwt.apply(this,arguments)};const krt=YGt(j.createContext(null));class ZGt extends j.Component{render(){return j.createElement(krt.Provider,{value:this._reactInternals},this.props.children)}}function mdn(){const s=j.useContext(krt);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=KGt(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 fdn(){const s=mdn(),[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!==krt&&!t.has(a)&&t.set(a,j.useContext(YGt(a)))}n=n.return}return t}function pdn(){const s=fdn();return j.useMemo(()=>Array.from(s.keys()).reduce((t,n)=>r=>j.createElement(t,null,j.createElement(n.Provider,hdn(fwt({},r),{value:s.get(n)}))),t=>j.createElement(ZGt,fwt({},t))),[s])}function gdn(s){const t=Gt.useRef({});return Gt.useLayoutEffect(()=>{t.current=s}),Gt.useLayoutEffect(()=>()=>{t.current={}},[]),t.current}const xdn=s=>{const t=Gt.useRef(null),n=Gt.useRef(null),r=Gt.useRef(null),a=gdn(s),i=pdn(),l=o=>{const{forwardedRef:c}=s;c&&(typeof c=="function"?c(o):c.current=o)};return Gt.useLayoutEffect(()=>(n.current=new eB.Stage({width:s.width,height:s.height,container:t.current}),l(n.current),r.current=vQ.createContainer(n.current,HGt.LegacyRoot,!1,null),vQ.updateContainer(Gt.createElement(i,{},s.children),r.current),()=>{eB.isBrowser&&(l(null),vQ.updateContainer(null,r.current,null),n.current.destroy())}),[]),Gt.useLayoutEffect(()=>{l(n.current),tRe(n.current,s,a),vQ.updateContainer(Gt.createElement(i,{},s.children),r.current,null)}),Gt.createElement("div",{ref:t,id:s.id,accessKey:s.accessKey,className:s.className,role:s.role,style:s.style,tabIndex:s.tabIndex,title:s.title})},ydn="Layer",vI="Group",x5="Rect",wSr="Line",sq="Image",E$="Text",jSr="Transformer",vQ=bcn(idn);vQ.injectIntoDevTools({findHostInstanceByFiber:()=>null,bundleType:0,version:Gt.version,rendererPackageName:"react-konva"});const vdn=Gt.forwardRef((s,t)=>Gt.createElement(ZGt,{},Gt.createElement(xdn,{...s,forwardedRef:t})));function bdn({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=Win(n),y=(o==null?void 0:o.naturalWidth)??1080,v=(o==null?void 0:o.naturalHeight)??1080,b=j.useMemo(()=>Math.min(1,a/y),[y,a]),w=y*b,S=v*b,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(vdn,{ref:W=>{l.current=W,i&&(i.current=W)},width:w,height:S,scaleX:b,scaleY:b,children:e.jsxs(ydn,{children:[o&&e.jsx(sq,{image:o,width:y,height:v,listening:!1}),!o&&e.jsx(x5,{x:0,y:0,width:y,height:v,fill:"#e2e8f0"}),e.jsx(_dn,{style:x,canvasW:y,canvasH:v,brandColor:A,accentColor:E,name:I,phone:P,email:R,tagline:D,headshot:d,logo:h,hidden:O,has:U})]})})})}function _dn({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":Kin(r),x=g==="#ffffff"?"rgba(255,255,255,0.78)":"rgba(15,23,42,0.7)";if(s.position==="bottom"||s.position==="top"){const y=s.position==="bottom"?n-m:0;return e.jsxs(vI,{children:[e.jsx(x5,{x:0,y,width:t,height:m,fill:r}),e.jsx(x5,{x:0,y:s.position==="bottom"?y:m-4,width:t,height:4,fill:a}),e.jsx(Lde,{x:f,y:y+f,width:t-f*2,height:m-f*2,textColor:g,subTextColor:x,name:i,phone:l,email:o,tagline:c,headshot:d,logo:u,has:h,circular:s.circularHeadshot})]})}if(s.position==="corner-br"){const y=t*.42,v=m,b=t-y-n*.025,w=n-v-n*.025;return e.jsxs(vI,{children:[e.jsx(x5,{x:b,y:w,width:y,height:v,fill:r,cornerRadius:v*.12,opacity:.92}),e.jsx(x5,{x:b,y:w+v-4,width:y,height:4,fill:a,cornerRadius:2}),e.jsx(Lde,{x:b+f,y:w+f,width:y-f*2,height:v-f*2,textColor:g,subTextColor:x,name:i,phone:l,email:o,tagline:c,headshot:d,logo:u,has:h,circular:s.circularHeadshot})]})}if(s.position==="side-right"){const y=Math.max(t*.22,Math.min(t*.3,260)),v=y*.12;return e.jsxs(vI,{children:[e.jsx(x5,{x:t-y,y:0,width:y,height:n,fill:r}),e.jsx(x5,{x:t-y,y:0,width:4,height:n,fill:a}),e.jsx(Lde,{x:t-y+v,y:n*.08,width:y-v*2,height:n*.84,textColor:g,subTextColor:x,name:i,phone:l,email:o,tagline:c,headshot:d,logo:u,has:h,circular:s.circularHeadshot,vertical:!0,railWidth:y})]})}return s.position==="letterbox"?e.jsxs(vI,{children:[e.jsx(x5,{x:0,y:0,width:t,height:m,fill:"#0a0a0a"}),e.jsx(x5,{x:0,y:n-m,width:t,height:m,fill:"#0a0a0a"}),e.jsx(x5,{x:0,y:n-m,width:t,height:3,fill:a}),e.jsx(Lde,{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(sq,{image:u,x:t-f-m*.7,y:f,height:m-f*2,width:m*.7})]}):null}function Lde({x:s,y:t,width:n,height:r,textColor:a,subTextColor:i,name:l,phone:o,email:c,tagline:d,headshot:u,logo:h,has:m,circular:f,vertical:g,railWidth:x}){if(g){const W=x??n,V=Math.min(n,W*.7),G=Math.max(14,W*.13),Y=Math.max(11,W*.085),X=W*.08,ae=W*.35;let le=t;const ne=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+=Y*1.3+X*.4);const _e=le;m("email")&&c&&(le+=Y*1.3+X*.4);const he=le+X*.5;return e.jsxs(vI,{children:[m("headshot")&&u&&e.jsx(vI,{clipFunc:f?ue=>{ue.beginPath(),ue.arc(s+n/2,ne+V/2,V/2,0,Math.PI*2),ue.closePath()}:void 0,children:e.jsx(sq,{image:u,x:s+(n-V)/2,y:ne,width:V,height:V})}),m("name")&&l&&e.jsx(E$,{text:l,x:s,y:te,width:n,align:"center",fontSize:G,fontStyle:"bold",fill:a}),m("phone")&&o&&e.jsx(E$,{text:o,x:s,y:ce,width:n,align:"center",fontSize:Y,fill:i}),m("email")&&c&&e.jsx(E$,{text:c,x:s,y:_e,width:n,align:"center",fontSize:Y,fill:i,ellipsis:!0,wrap:"none"}),m("logo")&&h&&e.jsx(sq,{image:h,x:s,y:he,width:n,height:ae})]})}const y=r*.95,v=u&&m("headshot")?s+y+r*.18:s,b=n-(v-s)-(h&&m("logo")?r*1.6:0),w=Math.max(20,r*.34),S=Math.max(13,r*.22),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(vI,{children:[m("headshot")&&u&&e.jsx(vI,{clipFunc:f?W=>{W.beginPath(),W.arc(s+y/2,t+y/2,y/2,0,Math.PI*2),W.closePath()}:void 0,children:e.jsx(sq,{image:u,x:s,y:t+(r-y)/2,width:y,height:y})}),m("name")&&l&&e.jsx(E$,{text:l,x:v,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(E$,{text:d,x:v,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(E$,{text:[o,c].filter(Boolean).join(" • "),x:v,y:U,width:b,fontSize:S,fill:i,ellipsis:!0,wrap:"none"}):null,m("logo")&&h&&e.jsx(sq,{image:h,x:s+n-r*1.4,y:t+(r-r*.8)/2,width:r*1.4,height:r*.8})]})}function wdn(){const{data:s}=xie(),t=(s==null?void 0:s.find(U=>U.is_default))??(s==null?void 0:s[0])??null,[n,r]=j.useState(void 0),a=(s==null?void 0:s.find(U=>U.id===n))??t,[i,l]=j.useState([]),[o,c]=j.useState(0),[d,u]=j.useState("minimal-stripe"),[h,m]=j.useState({}),[f,g]=j.useState(!1),x=j.useRef(null),[y,v]=j.useState(780),b=j.useRef(null),w=U=>{if(b.current&&(b.current.disconnect(),b.current=null),!U)return;const W=()=>{const G=U.clientWidth;G>0&&v(Math.min(780,G-16))};W();const V=new ResizeObserver(W);V.observe(U),b.current=V};j.useEffect(()=>()=>{var U;(U=b.current)==null||U.disconnect()},[]);const S=j.useRef(null),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",Y=atob(V),X=new Uint8Array(Y.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}),Y=`${((U=i[o])==null?void 0:U.name.replace(/\.[^.]+$/,""))||"branded"}-branded.jpg`,X=P(V),ae=URL.createObjectURL(X);if(I)window.open(ae,"_blank")||(window.location.href=ae),re.success('Long-press the image and tap "Save to Photos"');else{const le=document.createElement("a");le.href=ae,le.download=Y,document.body.appendChild(le),le.click(),le.remove(),re.success("Image exported")}setTimeout(()=>URL.revokeObjectURL(ae),6e4)}catch(W){re.error(W.message||"Export failed")}finally{g(!1)}}},D=async()=>{if(i.length){g(!0);try{const U=new KHt,W=i.length,V=o;for(let X=0;XsetTimeout(J,600)),!S.current)continue;const ae=S.current,ne=ae.toDataURL({pixelRatio:1/(ae.scaleX()||1),mimeType:"image/jpeg",quality:.95}).split(",")[1],te=i[X].name.replace(/\.[^.]+$/,"")||`image-${X+1}`;U.file(`${te}-branded.jpg`,ne,{base64:!0})}c(V);const G=await U.generateAsync({type:"blob"}),Y=document.createElement("a");Y.href=URL.createObjectURL(G),Y.download=`branded-images-${Date.now()}.zip`,Y.click(),URL.revokeObjectURL(Y.href),re.success(`${W} images exported`)}catch(U){re.error(U.message||"Batch export failed")}finally{g(!1)}}},O=i[o];return e.jsx(Vs,{title:"Branding Bar Studio",children:e.jsxs("div",{className:"container max-w-7xl py-4 md:py-6 space-y-4 px-3 md:px-6",children:[e.jsx(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(wr,{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(wr,{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(Ie,{className:"py-5 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold",children:"Create your brand kit first"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"We'll pre-fill it from your profile so you can be exporting in seconds."})]}),e.jsx($,{asChild:!0,className:"w-full sm:w-auto",children:e.jsx(wr,{to:"/marketing-studio/brand-kit",children:"Set up brand"})})]})}),e.jsxs("div",{className:"grid gap-6 lg:grid-cols-[1fr_360px]",children:[e.jsxs("div",{className:"space-y-4 min-w-0",children:[e.jsx(je,{className:"overflow-hidden",children:e.jsxs(Ie,{className:"p-4",children:[O?e.jsx("div",{ref:w,className:"flex justify-center bg-muted/30 rounded p-2 overflow-hidden",children:e.jsx(bdn,{imageUrl:O.url,preset:a,barStyleId:d,overrides:h,maxDisplayWidth:y,stageRef:S})}):e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-12 text-center space-y-3 cursor-pointer hover:bg-muted/30 transition-colors",onClick:()=>{var U;return(U=x.current)==null?void 0:U.click()},onDragOver:U=>U.preventDefault(),onDrop:U=>{U.preventDefault(),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(Ie,{className:"p-3",children:e.jsxs("div",{className:"flex gap-2 overflow-x-auto py-1",children:[i.map((U,W)=>e.jsxs("div",{className:"relative group flex-shrink-0",children:[e.jsx("button",{onClick:()=>c(W),className:`block h-16 w-16 rounded overflow-hidden border-2 transition-all ${W===o?"border-primary":"border-transparent hover:border-muted-foreground/30"}`,children:e.jsx("img",{src:U.url,alt:"",className:"h-full w-full object-cover"})}),e.jsx("button",{onClick:()=>E(U.id),className:"absolute -top-1 -right-1 bg-destructive text-destructive-foreground rounded-full p-0.5 opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx(pr,{className:"h-3 w-3"})})]},U.id)),e.jsx("button",{onClick:()=>{var U;return(U=x.current)==null?void 0:U.click()},className:"flex-shrink-0 h-16 w-16 rounded border-2 border-dashed flex items-center justify-center hover:bg-muted/40",children:e.jsx(dn,{className:"h-5 w-5 text-muted-foreground"})})]})})}),i.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-2 justify-end",children:[e.jsx($,{variant:"outline",onClick:()=>{i.forEach(U=>URL.revokeObjectURL(U.url)),l([])},children:"Clear all"}),e.jsxs($,{onClick:R,disabled:f||!O,children:[f?e.jsx(Ct,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(xi,{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(xi,{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(Ie,{children:e.jsxs(ms,{value:(a==null?void 0:a.id)??"",onValueChange:r,children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Choose preset"})}),e.jsx(hs,{children:s==null?void 0:s.map(U=>e.jsxs(Ge,{value:U.id,children:[U.name," ",U.is_default?"(default)":""]},U.id))})]})})]}),e.jsxs(je,{className:"overflow-hidden",children:[e.jsx(St,{className:"pb-2",children:e.jsx(Et,{className:"text-base",children:"Bar style"})}),e.jsx(Ie,{children:e.jsx(Yin,{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(Ie,{children:e.jsxs(ha,{defaultValue:"text",children:[e.jsxs(ma,{className:"grid grid-cols-2 w-full",children:[e.jsx(Zt,{value:"text",children:"Text"}),e.jsx(Zt,{value:"colors",children:"Colors"})]}),e.jsxs(Xt,{value:"text",className:"space-y-3 pt-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Display name"}),e.jsx(pe,{value:h.display_name??(a==null?void 0:a.display_name)??"",onChange:U=>m({...h,display_name:U.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Phone"}),e.jsx(pe,{value:h.phone??(a==null?void 0:a.phone)??"",onChange:U=>m({...h,phone:U.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Email"}),e.jsx(pe,{value:h.email??(a==null?void 0:a.email)??"",onChange:U=>m({...h,email:U.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Tagline"}),e.jsx(pe,{value:h.tagline??(a==null?void 0:a.tagline)??"",onChange:U=>m({...h,tagline:U.target.value})})]})]}),e.jsxs(Xt,{value:"colors",className:"space-y-3 pt-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Bar color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:h.brand_color??(a==null?void 0:a.brand_color)??"#0f172a",onChange:U=>m({...h,brand_color:U.target.value}),className:"h-10 w-14 rounded border cursor-pointer"}),e.jsx(pe,{value:h.brand_color??(a==null?void 0:a.brand_color)??"#0f172a",onChange:U=>m({...h,brand_color:U.target.value})})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Accent line"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:h.accent_color??(a==null?void 0:a.accent_color)??"#3b82f6",onChange:U=>m({...h,accent_color:U.target.value}),className:"h-10 w-14 rounded border cursor-pointer"}),e.jsx(pe,{value:h.accent_color??(a==null?void 0:a.accent_color)??"#3b82f6",onChange:U=>m({...h,accent_color:U.target.value})})]})]}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>m({}),children:"Reset to preset"})]})]})})]})]})]})]})})}function jdn(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 Ndn=(()=>{let s=0;const t=()=>`0000${(Math.random()*36**4<<0).toString(36)}`.slice(-4);return()=>(s+=1,`u${t()}${s}`)})();function uL(s){const t=[];for(let n=0,r=s.length;nmj||s.height>mj)&&(s.width>mj&&s.height>mj?s.width>s.height?(s.height*=mj/s.width,s.width=mj):(s.width*=mj/s.height,s.height=mj):s.width>mj?(s.height*=mj/s.width,s.width=mj):(s.width*=mj/s.height,s.height=mj))}function $Te(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 Edn(s){return Promise.resolve().then(()=>new XMLSerializer().serializeToString(s)).then(encodeURIComponent).then(t=>`data:image/svg+xml;charset=utf-8,${t}`)}async function Tdn(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),Edn(a)}const Pw=(s,t)=>{if(s instanceof t)return!0;const n=Object.getPrototypeOf(s);return n===null?!1:n.constructor.name===t.name||Pw(n,t)};function Mdn(s){const t=s.getPropertyValue("content");return`${s.cssText} content: '${t.replace(/'|"/g,"")}';`}function Pdn(s,t){return XGt(t).map(n=>{const r=s.getPropertyValue(n),a=s.getPropertyPriority(n);return`${n}: ${r}${a?" !important":""};`}).join(" ")}function Idn(s,t,n,r){const a=`.${s}:${t}`,i=n.cssText?Mdn(n):Pdn(n,r);return document.createTextNode(`${a}{${i}}`)}function ywt(s,t,n,r){const a=window.getComputedStyle(s,n),i=a.getPropertyValue("content");if(i===""||i==="none")return;const l=Ndn();try{t.className=`${t.className} ${l}`}catch{return}const o=document.createElement("style");o.appendChild(Idn(l,n,a,r)),t.appendChild(o)}function Ldn(s,t,n){ywt(s,t,":before",n),ywt(s,t,":after",n)}const vwt="application/font-woff",bwt="image/jpeg",Rdn={woff:vwt,woff2:vwt,ttf:"application/font-truetype",eot:"application/vnd.ms-fontobject",png:"image/png",jpg:bwt,jpeg:bwt,gif:"image/gif",tiff:"image/tiff",svg:"image/svg+xml",webp:"image/webp"};function Ddn(s){const t=/\.([^./]*?)$/g.exec(s);return t?t[1]:""}function Srt(s){const t=Ddn(s).toLowerCase();return Rdn[t]||""}function Fdn(s){return s.split(/,/)[1]}function zWe(s){return s.search(/^(data:)/)!==-1}function Odn(s,t){return`data:${t};base64,${s}`}async function JGt(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 KBe={};function zdn(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 Crt(s,t,n){const r=zdn(s,t,n.includeQueryParams);if(KBe[r]!=null)return KBe[r];n.cacheBust&&(s+=(/\?/.test(s)?"&":"?")+new Date().getTime());let a;try{const i=await JGt(s,n.fetchRequestInit,({res:l,result:o})=>(t||(t=l.headers.get("Content-Type")||""),Fdn(o)));a=Odn(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 KBe[r]=a,a}async function Bdn(s){const t=s.toDataURL();return t==="data:,"?s.cloneNode(!1):$Te(t)}async function $dn(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 $Te(o)}const n=s.poster,r=Srt(n),a=await Crt(n,r,t);return $Te(a)}async function Udn(s,t){var n;try{if(!((n=s==null?void 0:s.contentDocument)===null||n===void 0)&&n.body)return await sRe(s.contentDocument.body,t,!0)}catch{}return s.cloneNode(!1)}async function qdn(s,t){return Pw(s,HTMLCanvasElement)?Bdn(s):Pw(s,HTMLVideoElement)?$dn(s,t):Pw(s,HTMLIFrameElement)?Udn(s,t):s.cloneNode(eWt(s))}const Vdn=s=>s.tagName!=null&&s.tagName.toUpperCase()==="SLOT",eWt=s=>s.tagName!=null&&s.tagName.toUpperCase()==="SVG";async function Hdn(s,t,n){var r,a;if(eWt(t))return t;let i=[];return Vdn(s)&&s.assignedNodes?i=uL(s.assignedNodes()):Pw(s,HTMLIFrameElement)&&(!((r=s.contentDocument)===null||r===void 0)&&r.body)?i=uL(s.contentDocument.body.childNodes):i=uL(((a=s.shadowRoot)!==null&&a!==void 0?a:s).childNodes),i.length===0||Pw(s,HTMLVideoElement)||await i.reduce((l,o)=>l.then(()=>sRe(o,n)).then(c=>{c&&t.appendChild(c)}),Promise.resolve()),t}function Gdn(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):XGt(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`),Pw(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 Wdn(s,t){Pw(s,HTMLTextAreaElement)&&(t.innerHTML=s.value),Pw(s,HTMLInputElement)&&t.setAttribute("value",s.value)}function Kdn(s,t){if(Pw(s,HTMLSelectElement)){const n=t,r=Array.from(n.children).find(a=>s.value===a.getAttribute("value"));r&&r.setAttribute("selected","")}}function Ydn(s,t,n){return Pw(t,Element)&&(Gdn(s,t,n),Ldn(s,t,n),Wdn(s,t),Kdn(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;iqdn(r,t)).then(r=>Hdn(s,r,t)).then(r=>Ydn(s,r,t)).then(r=>Zdn(r,t))}const tWt=/url\((['"]?)([^'"]+?)\1\)/g,Xdn=/url\([^)]+\)\s*format\((["']?)([^"']+)\1\)/g,Qdn=/src:\s*(?:url\([^)]+\)\s*format\([^)]+\)[,;]\s*)+/g;function Jdn(s){const t=s.replace(/([.*+?^${}()|\[\]\/\\])/g,"\\$1");return new RegExp(`(url\\(['"]?)(${t})(['"]?\\))`,"g")}function eun(s){const t=[];return s.replace(tWt,(n,r,a)=>(t.push(a),n)),t.filter(n=>!zWe(n))}async function tun(s,t,n,r,a){try{const i=n?jdn(t,n):t,l=Srt(t);let o;return a||(o=await Crt(i,l,r)),s.replace(Jdn(t),`$1${o}$3`)}catch{}return s}function sun(s,{preferredFontFormat:t}){return t?s.replace(Qdn,n=>{for(;;){const[r,,a]=Xdn.exec(n)||[];if(!a)return"";if(a===t)return`src: ${r};`}}):s}function sWt(s){return s.search(tWt)!==-1}async function nWt(s,t,n){if(!sWt(s))return s;const r=sun(s,n);return eun(r).reduce((i,l)=>i.then(o=>tun(o,l,t,n)),Promise.resolve(r))}async function M$(s,t,n){var r;const a=(r=t.style)===null||r===void 0?void 0:r.getPropertyValue(s);if(a){const i=await nWt(a,null,n);return t.style.setProperty(s,i,t.style.getPropertyPriority(s)),!0}return!1}async function nun(s,t){await M$("background",s,t)||await M$("background-image",s,t),await M$("mask",s,t)||await M$("-webkit-mask",s,t)||await M$("mask-image",s,t)||await M$("-webkit-mask-image",s,t)}async function run(s,t){const n=Pw(s,HTMLImageElement);if(!(n&&!zWe(s.src))&&!(Pw(s,SVGImageElement)&&!zWe(s.href.baseVal)))return;const r=n?s.src:s.href.baseVal,a=await Crt(r,Srt(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 aun(s,t){const r=uL(s.childNodes).map(a=>rWt(a,t));await Promise.all(r).then(()=>s)}async function rWt(s,t){Pw(s,Element)&&(await nun(s,t),await run(s,t),await aun(s,t))}function iun(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 _wt={};async function wwt(s){let t=_wt[s];if(t!=null)return t;const r=await(await fetch(s)).text();return t={url:s,cssText:r},_wt[s]=t,t}async function jwt(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),JGt(o,t.fetchRequestInit,({result:c})=>(n=n.replace(l,`url(${c})`),[l,c]))});return Promise.all(i).then(()=>n)}function Nwt(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 oun(s,t){const n=[],r=[];return s.forEach(a=>{if("cssRules"in a)try{uL(a.cssRules||[]).forEach((i,l)=>{if(i.type===CSSRule.IMPORT_RULE){let o=l+1;const c=i.href,d=wwt(c).then(u=>jwt(u,t)).then(u=>Nwt(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(wwt(a.href).then(o=>jwt(o,t)).then(o=>Nwt(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{uL(a.cssRules||[]).forEach(i=>{n.push(i)})}catch(i){console.error(`Error while reading CSS rules from ${a.href}`,i)}}),n))}function lun(s){return s.filter(t=>t.type===CSSRule.FONT_FACE_RULE).filter(t=>sWt(t.style.getPropertyValue("src")))}async function cun(s,t){if(s.ownerDocument==null)throw new Error("Provided element is not within a Document");const n=uL(s.ownerDocument.styleSheets),r=await oun(n,t);return lun(r)}function aWt(s){return s.trim().replace(/["']/g,"")}function dun(s){const t=new Set;function n(r){(r.style.fontFamily||getComputedStyle(r).fontFamily).split(",").forEach(i=>{t.add(aWt(i))}),Array.from(r.children).forEach(i=>{i instanceof HTMLElement&&n(i)})}return n(s),t}async function uun(s,t){const n=await cun(s,t),r=dun(s);return(await Promise.all(n.filter(i=>r.has(aWt(i.style.fontFamily))).map(i=>{const l=i.parentStyleSheet?i.parentStyleSheet.href:null;return nWt(i.cssText,l,t)}))).join(` `)}async function hun(s,t){const n=t.fontEmbedCSS!=null?t.fontEmbedCSS:t.skipFonts?null:await uun(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 iWt(s,t={}){const{width:n,height:r}=QGt(s,t),a=await sRe(s,t,!0);return await hun(a,t),await rWt(a,t),iun(a,t),await Tdn(a,n,r)}async function oWt(s,t={}){const{width:n,height:r}=QGt(s,t),a=await iWt(s,t),i=await $Te(a),l=document.createElement("canvas"),o=l.getContext("2d"),c=t.pixelRatio||Cdn(),d=t.canvasWidth||n,u=t.canvasHeight||r;return l.width=d*c,l.height=u*c,t.skipAutoScale||Adn(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 FG(s,t={}){return(await oWt(s,t)).toDataURL()}const lWt=Object.freeze(Object.defineProperty({__proto__:null,toCanvas:oWt,toPng:FG,toSvg:iWt},Symbol.toStringTag,{value:"Module"})),OG=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),nRe={"just-listed":"JUST LISTED","just-sold":"JUST SOLD","open-house":"OPEN HOUSE","price-drop":"PRICE DROP"},bI={"instagram-square":{width:1080,height:1080},"instagram-story":{width:1080,height:1920},"facebook-post":{width:1200,height:630}},mun=({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})]})]}),Art=Gt.forwardRef(({listing:s,postType:t,format:n,branding:r,selectedPhotoIndex:a},i)=>{var h;const l=n==="instagram-story"?{w:1080,h:1920}:n==="facebook-post"?{w:1200,h:630}:{w:1080,h:1080},o=400/l.w,c=(h=s.photos)==null?void 0:h[a],d=nRe[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:OG(s.price)}),t==="just-sold"&&s.soldPrice&&e.jsxs("div",{style:{fontSize:l.w*.028,color:"#C9A84C",marginBottom:l.w*.01},children:["Sold for ",OG(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(mun,{branding:r,dim:l})]})]})]})});Art.displayName="LuxuryDarkTemplate";const fun=({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})]})]}),Ert=Gt.forwardRef(({listing:s,postType:t,format:n,branding:r,selectedPhotoIndex:a},i)=>{var f;const l=n==="instagram-story"?{w:1080,h:1920}:n==="facebook-post"?{w:1200,h:630}:{w:1080,h:1080},o=400/l.w,c=(f=s.photos)==null?void 0:f[a],d=nRe[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:OG(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(fun,{branding:r,dim:l,accentColor:m})]})]})});Ert.displayName="ModernCleanTemplate";const pun=({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})]})]}),Trt=Gt.forwardRef(({listing:s,postType:t,format:n,branding:r,selectedPhotoIndex:a},i)=>{var m;const l=n==="instagram-story"?{w:1080,h:1920}:n==="facebook-post"?{w:1200,h:630}:{w:1080,h:1080},o=400/l.w,c=(m=s.photos)==null?void 0:m[a],d=nRe[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:OG(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(pun,{branding:r,dim:l})]})]})]})});Trt.displayName="BoldColorfulTemplate";const gun=({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})]})]}),Mrt=Gt.forwardRef(({listing:s,postType:t,format:n,branding:r,selectedPhotoIndex:a},i)=>{var h;const l=n==="instagram-story"?{w:1080,h:1920}:n==="facebook-post"?{w:1200,h:630}:{w:1080,h:1080},o=400/l.w,c=(h=s.photos)==null?void 0:h[a],d=nRe[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:OG(s.price)}),t==="just-sold"&&s.soldPrice&&e.jsxs("div",{style:{fontSize:l.w*.02,color:"#8B7355",marginBottom:l.w*.01},children:["Sold: ",OG(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(gun,{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"}})]})]})})});Mrt.displayName="EditorialTemplate";const xun=[{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:"📉"}],kwt=[{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(Qp,{className:"h-4 w-4"})}],yun=[{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:"📰"}],Swt={"luxury-dark":Art,"modern-clean":Ert,"bold-colorful":Trt,editorial:Mrt},YBe=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s);function vun(s){var l;const[t,n]=s.split(","),r=((l=t.match(/:(.*?);/))==null?void 0:l[1])||"image/png",a=atob(n),i=new Uint8Array(a.length);for(let o=0;oEe.is_default))??(s==null?void 0:s[0])??null,[n,r]=j.useState(void 0),a=(s==null?void 0:s.find(Ee=>Ee.id===n))??t,i=Sa(),[l,o]=j.useState("mine"),[c,d]=j.useState(""),[u,h]=j.useState("address"),[m,f]=j.useState(!1),[g,x]=j.useState([]),[y,v]=j.useState(null),[b,w]=j.useState(0),[S,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([]),[Y,X]=j.useState("search"),ae=j.useRef({}),{data:le=[],isLoading:ne}=st({queryKey:["marketing-studio-my-listings",i],enabled:!!i,queryFn:async()=>{const{data:Ee,error:Se}=await q.from("listings").select("id, property_address, city, state, price, status, bedrooms, bathrooms, square_footage, year_built, property_type, description, created_at, listing_photos(photo_url, sort_order, is_primary)").eq("agent_id",i).order("created_at",{ascending:!1}).limit(60);if(Se)throw Se;return(Ee||[]).map(Le=>{const Fe=(Le.listing_photos||[]).slice().sort((Be,Ne)=>(Ne.is_primary?1:0)-(Be.is_primary?1:0)||(Be.sort_order??0)-(Ne.sort_order??0)).map(Be=>Be.photo_url).filter(Boolean),ke=String(Le.status||"");return{mlsNumber:Le.id,address:Le.property_address||"",city:Le.city||"",state:Le.state||"",zip:"",price:Number(Le.price||0),status:ke,bedrooms:Number(Le.bedrooms||0),bathrooms:Number(Le.bathrooms||0),sqft:Number(Le.square_footage||0),lotSize:"",yearBuilt:Le.year_built??null,propertyType:Le.property_type||"",description:Le.description||"",photos:Fe,listDate:Le.created_at,soldDate:ke.toLowerCase().includes("sold")?Le.created_at:null,soldPrice:null,agent:{name:"",office:""}}})}}),te=j.useMemo(()=>!D||!a?{enabled:!1}:{enabled:!0,agentName:a.display_name||"",brokerage:a.tagline||"",agentPhotoUrl:a.headshot_url||void 0},[D,a]),J=async()=>{if(c.trim()){f(!0),x([]);try{const{data:Ee,error:Se}=await q.functions.invoke("repliers-mls-search",{body:{searchType:u,query:c.trim()}});if(Se)throw Se;if(Ee!=null&&Ee.error)throw new Error(Ee.error);x((Ee==null?void 0:Ee.listings)||[]),((Ee==null?void 0:Ee.listings)||[]).length===0&&re.info("No listings found. Try a different search.")}catch(Ee){re.error(Ee.message||"Search failed")}finally{f(!1)}}},ce=Ee=>{var Se;v(Ee),w(0),X("customize"),Ee.soldDate||(Se=Ee.status)!=null&&Se.toLowerCase().includes("sold")?A("just-sold"):A("just-listed")},_e=Ee=>I(Se=>Se.includes(Ee)?Se.filter(Le=>Le!==Ee):[...Se,Ee]),he=y?{listing:y,postType:S,format:"instagram-square",branding:te,selectedPhotoIndex:b}:null,ue=j.useCallback(async()=>{if(!(!y||E.length===0)){W(!0),G([]),X("generate");try{await new Promise(Se=>setTimeout(Se,600));const Ee=[];for(const Se of E){const Le=`${P}-${Se}`,Fe=ae.current[Le];if(!Fe)continue;const ke=bI[Se],Be=await FG(Fe,{width:ke.width,height:ke.height,pixelRatio:1,cacheBust:!0,style:{transform:"none",transformOrigin:"top left"}});Ee.push({format:Se,url:Be})}G(Ee),re.success(`Generated ${Ee.length} design${Ee.length>1?"s":""}!`)}catch(Ee){re.error(Ee.message||"Generation failed")}finally{W(!1)}}},[y,E,P]),ve=(Ee,Se)=>{const Le=`${((y==null?void 0:y.address)||"listing").replace(/\s+/g,"-")}-${S}-${Se}.png`;try{const Fe=vun(Ee),ke=URL.createObjectURL(Fe);if(bun)window.open(ke,"_blank"),re.message("Long-press the image to save to Photos");else{const Be=document.createElement("a");Be.href=ke,Be.download=Le,document.body.appendChild(Be),Be.click(),document.body.removeChild(Be)}setTimeout(()=>URL.revokeObjectURL(ke),6e4)}catch{const Fe=document.createElement("a");Fe.href=Ee,Fe.download=Le,Fe.click()}};return j.useEffect(()=>{!n&&t&&r(t.id)},[t,n]),e.jsx(Vs,{title:"Listing Templates",children:e.jsxs("div",{className:"container max-w-6xl py-4 md:py-8 px-3 md:px-6 space-y-5",children:[e.jsxs(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(wr,{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(Nn,{className:"h-3 w-3"})," Listing Templates"]}),e.jsx("h1",{className:"text-2xl md:text-3xl font-bold tracking-tight",children:"Just Listed. Just Stunning."}),e.jsx("p",{className:"text-sm md:text-base text-muted-foreground max-w-2xl mt-1",children:"Search any MLS listing and get pixel-perfect, on-brand graphics for Instagram, Stories and Facebook in one click."})]}),s&&s.length>0&&e.jsxs("div",{className:"min-w-0 sm:min-w-[220px]",children:[e.jsx(ee,{className:"text-xs text-muted-foreground",children:"Brand preset"}),e.jsxs(ms,{value:n,onValueChange:r,children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Default"})}),e.jsx(hs,{children:s.map(Ee=>e.jsxs(Ge,{value:Ee.id,children:[Ee.name,Ee.is_default?" (default)":""]},Ee.id))})]})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-xs sm:text-sm overflow-x-auto -mx-1 px-1 pb-1",children:[e.jsxs("button",{onClick:()=>X("search"),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full whitespace-nowrap ${Y==="search"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground"}`,children:[e.jsx(Zr,{className:"h-3.5 w-3.5"})," 1. Find listing"]}),e.jsx(Di,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("button",{onClick:()=>y&&X("customize"),disabled:!y,className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full whitespace-nowrap ${Y==="customize"?"bg-primary text-primary-foreground":y?"bg-muted text-muted-foreground":"bg-muted text-muted-foreground/50"}`,children:[e.jsx(Nn,{className:"h-3.5 w-3.5"})," 2. Customize"]}),e.jsx(Di,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("div",{className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full whitespace-nowrap ${Y==="generate"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground/50"}`,children:[e.jsx(xi,{className:"h-3.5 w-3.5"})," 3. Download"]})]}),Y==="search"&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(ha,{value:l,onValueChange:Ee=>o(Ee),children:e.jsxs(ma,{className:"grid grid-cols-2 w-full sm:w-auto",children:[e.jsxs(Zt,{value:"mine",children:[e.jsx(va,{className:"h-4 w-4 mr-1.5"})," My Listings"]}),e.jsxs(Zt,{value:"mls",children:[e.jsx(Zr,{className:"h-4 w-4 mr-1.5"})," MLS Search"]})]})}),l==="mine"&&e.jsx("div",{className:"space-y-3",children:ne?e.jsx(je,{children:e.jsx(Ie,{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(Ie,{className:"py-10 text-center space-y-2",children:[e.jsx(va,{className:"h-10 w-10 mx-auto text-muted-foreground/40"}),e.jsx("p",{className:"text-sm font-medium",children:"No listings yet"}),e.jsx("p",{className:"text-xs text-muted-foreground max-w-sm mx-auto",children:"Add a listing to your Listing Exchange first, and it'll show up here ready to brand."}),e.jsx($,{variant:"outline",size:"sm",asChild:!0,className:"mt-2",children:e.jsx(wr,{to:"/mission-control/listings",children:"Go to Listings"})})]})}):e.jsxs(e.Fragment,{children:[e.jsxs("h3",{className:"text-sm font-medium text-muted-foreground",children:[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,Se)=>{var Le;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(Ie,{className:"p-0",children:e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-28 h-28 sm:w-32 sm:h-28 flex-shrink-0 bg-muted overflow-hidden",children:(Le=Ee.photos)!=null&&Le[0]?e.jsx("img",{src:Ee.photos[0],alt:Ee.address,className:"w-full h-full object-cover group-hover:scale-105 transition-transform"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(va,{className:"h-8 w-8 text-muted-foreground/40"})})}),e.jsxs("div",{className:"flex-1 p-3 min-w-0",children:[e.jsx("p",{className:"font-bold",children:Ee.price>0?YBe(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(A4,{className:"h-3 w-3"})," ",Ee.bedrooms]}),Ee.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(A0,{className:"h-3 w-3"})," ",Ee.bathrooms]}),Ee.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(Gz,{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||Se)})})]})}),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(Zr,{className:"h-5 w-5 text-primary"})," Search MLS"]}),e.jsxs(Gn,{children:["Search by address or MLS number. Requires an MLS data connection — if your account doesn't have one, use ",e.jsx("button",{type:"button",className:"underline",onClick:()=>o("mine"),children:"My Listings"})," instead."]})]}),e.jsxs(Ie,{className:"space-y-3",children:[e.jsx(ha,{value:u,onValueChange:Ee=>h(Ee),children:e.jsxs(ma,{children:[e.jsxs(Zt,{value:"address",children:[e.jsx(ci,{className:"h-4 w-4 mr-1.5"})," Address"]}),e.jsxs(Zt,{value:"mls",children:[e.jsx(Ap,{className:"h-4 w-4 mr-1.5"})," MLS #"]})]})}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[e.jsx(pe,{value:c,onChange:Ee=>d(Ee.target.value),placeholder:u==="mls"?"Enter MLS number...":"Enter property address...",className:"flex-1",onKeyDown:Ee=>Ee.key==="Enter"&&J()}),e.jsxs($,{onClick:J,disabled:m||!c.trim(),className:"sm:w-auto w-full",children:[m?e.jsx(Ct,{className:"h-4 w-4 animate-spin mr-1.5"}):e.jsx(Zr,{className:"h-4 w-4 mr-1.5"})," Search"]})]})]})]}),g.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h3",{className:"text-sm font-medium text-muted-foreground",children:[g.length," listing",g.length!==1?"s":""," found"]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:g.map((Ee,Se)=>{var Le;return e.jsx(je,{className:"cursor-pointer hover:border-primary/50 hover:shadow-md transition-all group overflow-hidden",onClick:()=>ce(Ee),children:e.jsx(Ie,{className:"p-0",children:e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-28 h-28 sm:w-32 sm:h-28 flex-shrink-0 bg-muted overflow-hidden",children:(Le=Ee.photos)!=null&&Le[0]?e.jsx("img",{src:Ee.photos[0],alt:Ee.address,className:"w-full h-full object-cover group-hover:scale-105 transition-transform"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(va,{className:"h-8 w-8 text-muted-foreground/40"})})}),e.jsxs("div",{className:"flex-1 p-3 min-w-0",children:[e.jsx("p",{className:"font-bold",children:YBe(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(A4,{className:"h-3 w-3"})," ",Ee.bedrooms]}),Ee.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(A0,{className:"h-3 w-3"})," ",Ee.bathrooms]}),Ee.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(Gz,{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||Se)})})]})]})]}),Y==="customize"&&y&&he&&e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4 md:gap-6",children:[e.jsxs(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(Ie,{className:"space-y-3",children:[y.photos.length>0&&e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"aspect-[4/3] rounded-lg overflow-hidden bg-muted",children:e.jsx("img",{src:y.photos[b],alt:"",className:"w-full h-full object-cover"})}),y.photos.length>1&&e.jsxs("div",{className:"flex items-center justify-between mt-2",children:[e.jsx($,{variant:"outline",size:"icon",className:"h-7 w-7",onClick:()=>w(Ee=>Math.max(0,Ee-1)),disabled:b===0,children:e.jsx(kd,{className:"h-4 w-4"})}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[b+1," of ",y.photos.length]}),e.jsx($,{variant:"outline",size:"icon",className:"h-7 w-7",onClick:()=>w(Ee=>Math.min(y.photos.length-1,Ee+1)),disabled:b===y.photos.length-1,children:e.jsx(Di,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-bold text-lg",children:YBe(y.price)}),e.jsx("p",{className:"text-sm text-muted-foreground",children:y.address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[y.city,", ",y.state," ",y.zip]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 text-center",children:[y.bedrooms>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:y.bedrooms}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Beds"})]}),y.bathrooms>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:y.bathrooms}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Baths"})]}),y.sqft>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:y.sqft.toLocaleString()}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Sq Ft"})]})]}),e.jsxs($,{variant:"outline",size:"sm",className:"w-full",onClick:()=>{X("search"),v(null)},children:[e.jsx(Ax,{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(Nn,{className:"h-5 w-5 text-primary"})," Customize"]}),e.jsx(Gn,{children:"Pick a template, post type, and output format."})]}),e.jsxs(Ie,{className:"space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(yd,{className:"h-4 w-4"})," Template style"]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:yun.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:xun.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:kwt.map(Ee=>e.jsxs("button",{onClick:()=>_e(Ee.value),className:`flex items-center gap-2 px-3 py-2.5 rounded-lg border-2 transition-all text-sm ${E.includes(Ee.value)?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[Ee.icon,e.jsxs("div",{className:"text-left min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:Ee.label}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:Ee.dimensions})]})]},Ee.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(ee,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(sl,{className:"h-4 w-4"})," Show my branding"]}),e.jsx(Sn,{checked:D,onCheckedChange:O})]}),D&&!a&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["No brand preset yet. ",e.jsx(wr,{to:"/marketing-studio/brand-kit",className:"underline",children:"Create one"})," to add your headshot and name."]}),D&&a&&e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border bg-muted/30",children:[a.headshot_url&&e.jsx("img",{src:a.headshot_url,alt:"",className:"w-10 h-10 rounded-full object-cover border"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:a.display_name||"Unnamed agent"}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:a.tagline||a.email||""})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-sm font-medium",children:"Preview"}),e.jsx("div",{className:"bg-muted/30 rounded-lg p-3 md:p-4 flex justify-center overflow-hidden",children:e.jsx("div",{style:{width:360,maxWidth:"100%",height:360*(bI[E[0]||"instagram-square"].height/bI[E[0]||"instagram-square"].width)},children:(()=>{const Ee=Swt[P],Se=E[0]||"instagram-square";return e.jsx(Ee,{...he,format:Se})})()})})]}),e.jsx($,{onClick:ue,disabled:E.length===0||U,size:"lg",className:"w-full gap-2",children:U?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"h-5 w-5 animate-spin"})," Generating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Nn,{className:"h-5 w-5"})," Generate ",E.length," design",E.length>1?"s":""]})})]})]})]}),Y==="generate"&&e.jsxs("div",{className:"space-y-4",children:[U&&e.jsx(je,{children:e.jsxs(Ie,{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(Ax,{className:"h-3.5 w-3.5 mr-1.5"})," Tweak & regenerate"]})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:V.map((Ee,Se)=>{const Le=kwt.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(Ie,{className:"p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[Le==null?void 0:Le.icon,e.jsx("span",{className:"text-sm font-medium",children:Le==null?void 0:Le.label})]}),e.jsx($e,{variant:"outline",className:"text-[10px]",children:Le==null?void 0:Le.dimensions})]}),e.jsxs($,{size:"sm",className:"w-full gap-1.5",onClick:()=>ve(Ee.url,Ee.format),children:[e.jsx(xi,{className:"h-3.5 w-3.5"})," Download"]})]})]},Se)})})]})]}),Y==="generate"&&y&&he&&e.jsx("div",{style:{position:"fixed",left:"-99999px",top:0,pointerEvents:"none"},"aria-hidden":!0,children:E.map(Ee=>{const Se=Swt[P],Le=bI[Ee];return e.jsx("div",{style:{width:Le.width,height:Le.height},children:e.jsx(Se,{ref:Fe=>{ae.current[`${P}-${Ee}`]=Fe},...he,format:Ee})},`${P}-${Ee}`)})})]})})}var wun=Object.defineProperty,jun=(s,t)=>wun(s,"name",{value:t,configurable:!0}),Nun="Toggle",cWt=j.forwardRef(jun(function(t,n){const{pressed:r,defaultPressed:a,onPressedChange:i,...l}=t,[o,c]=hy({prop:r,onChange:i,defaultProp:a??!1,caller:Nun});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")),dWt=cWt,kun=Object.defineProperty,LL=(s,t)=>kun(s,"name",{value:t,configurable:!0}),vK="ToggleGroup",[uWt,NSr]=tp(vK,[t6]),hWt=t6(),mWt=j.forwardRef(LL(function(t,n){const{type:r,...a}=t;if(r==="single"){const i=a;return e.jsx(Sun,{role:"radiogroup",...i,ref:n})}if(r==="multiple"){const i=a;return e.jsx(Cun,{role:"toolbar",...i,ref:n})}throw new Error(`Missing prop \`type\` expected on \`${vK}\``)},"ToggleGroup")),[fWt,pWt]=uWt(vK),Sun=j.forwardRef(LL(function(t,n){const{value:r,defaultValue:a,onValueChange:i=LL(()=>{},"onValueChange"),...l}=t,[o,c]=hy({prop:r,defaultProp:a??"",onChange:i,caller:vK});return e.jsx(fWt,{scope:t.__scopeToggleGroup,type:"single",value:j.useMemo(()=>o?[o]:[],[o]),onItemActivate:c,onItemDeactivate:j.useCallback(()=>c(""),[c]),children:e.jsx(gWt,{...l,ref:n})})},"ToggleGroupImplSingle")),Cun=j.forwardRef(LL(function(t,n){const{value:r,defaultValue:a,onValueChange:i=LL(()=>{},"onValueChange"),...l}=t,[o,c]=hy({prop:r,defaultProp:a??[],onChange:i,caller:vK}),d=j.useCallback(h=>c((m=[])=>[...m,h]),[c]),u=j.useCallback(h=>c((m=[])=>m.filter(f=>f!==h)),[c]);return e.jsx(fWt,{scope:t.__scopeToggleGroup,type:"multiple",value:o,onItemActivate:d,onItemDeactivate:u,children:e.jsx(gWt,{...l,ref:n})})},"ToggleGroupImplMultiple")),[Aun,Eun]=uWt(vK),gWt=j.forwardRef(LL(function(t,n){const{__scopeToggleGroup:r,disabled:a=!1,rovingFocus:i=!0,orientation:l,dir:o,loop:c=!0,...d}=t,u=hWt(r),h=i3(o),m={dir:h,...d};return e.jsx(Aun,{scope:r,rovingFocus:i,disabled:a,children:i?e.jsx(mLe,{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")),BWe="ToggleGroupItem",xWt=j.forwardRef(LL(function(t,n){const r=pWt(BWe,t.__scopeToggleGroup),a=Eun(BWe,t.__scopeToggleGroup),i=hWt(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(fLe,{asChild:!0,...i,focusable:!o,active:l,ref:d,children:e.jsx(Cwt,{...c,ref:n})}):e.jsx(Cwt,{...c,ref:n})},"ToggleGroupItem")),Cwt=j.forwardRef(LL(function(t,n){const{__scopeToggleGroup:r,value:a,...i}=t,l=pWt(BWe,r),o={role:"radio","aria-checked":t.pressed,"aria-pressed":void 0},c=l.type==="single"?o:void 0;return e.jsx(cWt,{...c,...i,ref:n,onPressedChange:d=>{d?l.onItemActivate(a):l.onItemDeactivate(a)}})},"ToggleGroupItemImpl"));const yWt=MB("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"}}),Tun=j.forwardRef(({className:s,variant:t,size:n,...r},a)=>e.jsx(dWt,{ref:a,className:Pt(yWt({variant:t,size:n,className:s})),...r}));Tun.displayName=dWt.displayName;const vWt=j.createContext({size:"default",variant:"default"}),kV=j.forwardRef(({className:s,variant:t,size:n,children:r,...a},i)=>e.jsx(mWt,{ref:i,className:Pt("flex items-center justify-center gap-1",s),...a,children:e.jsx(vWt.Provider,{value:{variant:t,size:n},children:r})}));kV.displayName=mWt.displayName;const x7=j.forwardRef(({className:s,children:t,variant:n,size:r,...a},i)=>{const l=j.useContext(vWt);return e.jsx(xWt,{ref:i,className:Pt(yWt({variant:l.variant||n,size:l.size||r}),s),...a,children:t})});x7.displayName=xWt.displayName;const Mun=[{id:"meet",label:"Meet Your Agent",icon:sl,description:"Polished intro card with your headshot, story, and contact."},{id:"testimonial",label:"Testimonial",icon:h2,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:JS,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."}],ZBe={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"}},Pun=[{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."}],Awt={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 Iun(){const{data:s}=$in(),{data:t}=xie(),[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,...Awt.meet}),o=g=>l(x=>({...x,...g})),c=g=>l(x=>({...x,template:g,...Awt[g]})),d=j.useRef(null),[u,h]=j.useState(!1),m=async()=>{if(!d.current)return;h(!0);const g=d.current,x=g.style.transform;try{g.style.transform="none",await new Promise(b=>requestAnimationFrame(()=>b(null)));const y=await FG(g,{cacheBust:!0,pixelRatio:2,width:g.offsetWidth,height:g.offsetHeight,backgroundColor:"#ffffff"}),v=document.createElement("a");v.href=y,v.download=`personal-branding-${i.template}-${Date.now()}.png`,document.body.appendChild(v),v.click(),v.remove(),re.success("Downloaded to your device")}catch(y){re.error((y==null?void 0:y.message)||"Export failed")}finally{g.style.transform=x,h(!1)}},f=ZBe[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(wr,{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(Nn,{className:"h-3 w-3"})," New"]})}),e.jsx("h1",{className:"text-2xl md:text-3xl font-bold tracking-tight mt-1",children:"Personal Branding"}),e.jsx("p",{className:"text-sm md:text-base text-muted-foreground max-w-2xl",children:"Five editorial-grade templates, four distinct aesthetics. Pick one, drop in your story, export in seconds."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($,{variant:"outline",asChild:!0,children:e.jsxs(wr,{to:"/marketing-studio/brand-kit",children:[e.jsx(yd,{className:"h-4 w-4 mr-1"})," Brand Kit"]})}),e.jsxs($,{onClick:m,disabled:u,children:[e.jsx(xi,{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(Ie,{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Template"}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:Mun.map(g=>{const x=g.icon,y=i.template===g.id;return e.jsxs("button",{onClick:()=>c(g.id),className:`text-left rounded-lg border p-3 transition-all ${y?"border-primary bg-primary/5 ring-2 ring-primary/30":"border-border hover:border-primary/50"}`,children:[e.jsx(x,{className:"h-4 w-4 mb-1"}),e.jsx("div",{className:"text-xs font-semibold",children:g.label})]},g.id)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Style"}),e.jsx(kV,{type:"single",value:i.style,onValueChange:g=>g&&o({style:g}),className:"grid grid-cols-2 gap-1",children:Pun.map(g=>e.jsx(x7,{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(kV,{type:"single",value:i.aspect,onValueChange:g=>g&&o({aspect:g}),className:"grid grid-cols-3 gap-1",children:Object.keys(ZBe).map(g=>e.jsx(x7,{value:g,className:"text-xs h-9",children:ZBe[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(Ie,{className:"p-4 space-y-3",children:[e.jsx(ee,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Content"}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"headline",className:"text-xs",children:"Headline"}),e.jsx(Ls,{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(Ls,{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(kV,{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(x7,{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(Lun,{aspect:f,canvasRef:d,children:e.jsx(Run,{form:i,preset:a,width:f.w,height:f.h})})]})]})})}function Lun({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 Run({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(Dun,{...f}):s.style==="bold"?e.jsx(Fun,{...f}):s.style==="luxury"?e.jsx(zun,{...f}):e.jsx(Oun,{...f})}function bWt({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 rRe({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(rRe,{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(bWt,{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 Fun(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%, ${Bun(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(rRe,{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(bWt,{name:l,phone:o,email:c,website:d,color:"#fff"})]})]})}function Oun(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(rRe,{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 zun(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(rRe,{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 Bun(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 $un=()=>{const{swagId:s}=Wi(),{user:t}=bs(),{toast:n}=Bi(),r=Wt(),{trackEngagement:a}=hK(),[i,l]=j.useState(""),{data:o,isLoading:c}=st({queryKey:["social-swag-detail",s],queryFn:async()=>{const{data:v,error:b}=await q.from("social_swag").select("*").eq("id",s).single();if(b)throw b;const{data:w}=await q.from("social_swag_links").select("*").eq("swag_id",s).order("sort_order");return{...v,links:w||[]}},enabled:!!s});j.useEffect(()=>{o&&a("social_swag",o.id,o.title,"view")},[o==null?void 0:o.id]);const{data:d=[]}=st({queryKey:["social-swag-likes",s],queryFn:async()=>{const{data:v,error:b}=await q.from("social_swag_likes").select("*").eq("swag_id",s);if(b)throw b;return v},enabled:!!s}),{data:u=[]}=st({queryKey:["social-swag-comments",s],queryFn:async()=>{const{data:v,error:b}=await q.from("social_swag_comments").select("*").eq("swag_id",s).order("created_at",{ascending:!1});if(b)throw b;const w=[...new Set(v.map(E=>E.user_id))],{data:S}=await q.from("profiles").select("id, name").in("id",w),A=new Map((S==null?void 0:S.map(E=>[E.id,E.name]))||[]);return v.map(E=>({...E,user_name:A.get(E.user_id)||"Unknown User"}))},enabled:!!s}),h=mt({mutationFn:async v=>{const{error:b}=await q.from("social_swag_comments").insert({swag_id:s,user_id:t.id,content:v});if(b)throw b},onSuccess:()=>{r.invalidateQueries({queryKey:["social-swag-comments",s]}),l(""),n({title:"Comment added!"})},onError:v=>{n({title:"Error adding comment",description:v.message,variant:"destructive"})}}),m=mt({mutationFn:async v=>{const{error:b}=await q.from("social_swag_comments").delete().eq("id",v);if(b)throw b},onSuccess:()=>{r.invalidateQueries({queryKey:["social-swag-comments",s]}),n({title:"Comment deleted"})}}),f=mt({mutationFn:async()=>{const v=d.find(b=>b.user_id===(t==null?void 0:t.id));if(v){const{error:b}=await q.from("social_swag_likes").delete().eq("id",v.id);if(b)throw b}else{const{error:b}=await q.from("social_swag_likes").insert({swag_id:s,user_id:t.id});if(b)throw b}},onSuccess:()=>{r.invalidateQueries({queryKey:["social-swag-likes",s]})}}),g=d.some(v=>v.user_id===(t==null?void 0:t.id)),x=v=>v.split(" ").map(b=>b[0]).join("").toUpperCase().slice(0,2),y=v=>{v.preventDefault(),!(!i.trim()||!t)&&h.mutate(i.trim())};return c?e.jsx(Vs,{title:"Social Swag",children:e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):o?e.jsx(Vs,{title:o.title,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx($,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(wr,{to:"/social-swag",children:[e.jsx(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(pK,{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(qy,{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(Ie,{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(v=>e.jsxs($,{variant:"outline",className:"w-full justify-between gap-2 h-auto py-3",onClick:()=>{a("social_swag",o.id,o.title,"click_canva"),window.open(v.canva_share_link,"_blank")},children:[e.jsx("span",{className:"font-medium",children:v.title}),e.jsx(Fr,{className:"h-4 w-4 text-muted-foreground"})]},v.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:y,className:"flex gap-2",children:[e.jsx(Ls,{placeholder:"Add a comment...",value:i,onChange:v=>l(v.target.value),className:"min-h-[80px] resize-none flex-1"}),e.jsx($,{type:"submit",size:"icon",className:"h-10 w-10",disabled:!i.trim()||h.isPending,children:e.jsx(Kr,{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(Ie,{className:"py-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No comments yet. Be the first to share your thoughts!"})})}):u.map(v=>e.jsx(je,{children:e.jsx(Ie,{className:"pt-4 pb-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Oa,{className:"h-10 w-10 flex-shrink-0",children:e.jsx(za,{className:"text-sm",children:x(v.user_name||"U")})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-medium",children:v.user_name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:hu(new Date(v.created_at),{addSuffix:!0})}),v.user_id===(t==null?void 0:t.id)&&e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>m.mutate(v.id),children:e.jsx(Hn,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:v.content})]})]})})},v.id))})]})]})}):e.jsx(Vs,{title:"Social Swag",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(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(wr,{to:"/social-swag",children:"Back to Social Swag"})})]})})},Uun=({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(HI,{className:"h-4 w-4 mr-2"}),"All Posts"]}),e.jsxs(v1,{open:i,onOpenChange:l,children:[e.jsx(b1,{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(_1,{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(v1,{open:o,onOpenChange:c,children:[e.jsx(b1,{asChild:!0,children:e.jsxs($,{variant:"ghost",className:"w-full justify-between text-muted-foreground hover:text-foreground",children:[e.jsxs("span",{className:"text-xs font-semibold uppercase tracking-wider flex items-center gap-1",children:[e.jsx(pc,{className:"h-3 w-3"}),"Your Groups"]}),o?e.jsx(wl,{className:"h-4 w-4"}):e.jsx(Di,{className:"h-4 w-4"})]})}),e.jsx(_1,{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(v1,{open:d,onOpenChange:u,children:[e.jsx(b1,{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(_1,{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(Og,{className:"h-2.5 w-2.5 fill-green-500 text-green-500 absolute -bottom-0.5 -right-0.5"})]}),e.jsx("span",{className:"text-sm truncate",children:m.name})]},m.id))})]})]})})})},qun=({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($u,{children:[e.jsx(Uu,{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(Au,{className:"w-56 bg-background border",children:[e.jsxs(ja,{onClick:()=>r("all"),children:[e.jsx(HI,{className:"h-4 w-4 mr-2"}),"All Posts"]}),e.jsx(I0,{}),e.jsx(jL,{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(I0,{}),e.jsxs(jL,{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(pc,{className:"h-3 w-3"}),"Your Groups"]}),t.map(d=>e.jsxs(ja,{onClick:()=>r(`group:${d.id}`),children:[e.jsx("span",{className:"mr-2",children:d.icon||"🔒"}),d.name]},d.id))]})]})]}),e.jsxs(Gy,{open:i,onOpenChange:l,children:[e.jsx(Pae,{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(my,{children:[e.jsx(L0,{children:e.jsxs(R0,{className:"flex items-center gap-2",children:[e.jsx(Yn,{className:"h-5 w-5"}),"Online Now (",a.length,")"]})}),e.jsx(uo,{className:"h-[calc(100vh-8rem)] mt-4",children:a.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No one else online right now"}):e.jsx("div",{className:"space-y-2",children:a.map(d=>e.jsxs("div",{className:"flex items-center gap-3 py-2 px-3 rounded-lg hover:bg-muted transition-colors",children:[e.jsxs("div",{className:"relative",children:[e.jsxs(Oa,{className:"h-10 w-10",children:[e.jsx(Ii,{src:d.avatarUrl}),e.jsx(za,{children:o(d.name)})]}),e.jsx(Og,{className:"h-3 w-3 fill-green-500 text-green-500 absolute -bottom-0.5 -right-0.5"})]}),e.jsx("span",{className:"font-medium",children:d.name})]},d.id))})})]})]})]})};var Vun=Object.defineProperty,RL=(s,t)=>Vun(s,"name",{value:t,configurable:!0}),XBe,Prt="HoverCard",[_Wt,kSr]=tp(Prt,[r3]),Irt=r3(),[Hun,Lrt]=_Wt(Prt),Gun=RL(s=>{const{__scopeHoverCard:t,children:n,open:r,defaultOpen:a,onOpenChange:i,openDelay:l=700,closeDelay:o=300}=s,c=Irt(t),d=j.useRef(0),u=j.useRef(0),h=j.useRef(!1),m=j.useRef(!1),[f,g]=hy({prop:r,defaultProp:a??!1,onChange:i,caller:Prt}),x=j.useCallback(()=>{clearTimeout(u.current),d.current=window.setTimeout(()=>g(!0),l)},[l,g]),y=j.useCallback(()=>{clearTimeout(d.current),!h.current&&!m.current&&(u.current=window.setTimeout(()=>g(!1),o))},[o,g]),v=j.useCallback(()=>g(!1),[g]);return j.useEffect(()=>()=>{clearTimeout(d.current),clearTimeout(u.current)},[]),e.jsx(Hun,{scope:t,open:f,onOpenChange:g,onOpen:x,onClose:y,onDismiss:v,hasSelectionRef:h,isPointerDownOnContentRef:m,children:e.jsx(wae,{...c,children:n})})},"HoverCard"),Wun="HoverCardTrigger",Kun=j.forwardRef(RL(function(t,n){const{__scopeHoverCard:r,...a}=t,i=Lrt(Wun,r),l=Irt(r);return e.jsx(jae,{asChild:!0,...l,children:e.jsx(Ei.a,{"data-state":i.open?"open":"closed",...a,ref:n,onPointerEnter:Ra(t.onPointerEnter,Ase(i.onOpen)),onPointerLeave:Ra(t.onPointerLeave,Ase(i.onClose)),onFocus:Ra(t.onFocus,i.onOpen),onBlur:Ra(t.onBlur,i.onClose),onTouchStart:Ra(t.onTouchStart,o=>o.preventDefault())})})},"HoverCardTrigger")),Yun="HoverCardPortal",[SSr,Zun]=_Wt(Yun,{forceMount:void 0}),$We="HoverCardContent",Xun=j.forwardRef(RL(function(t,n){const r=Zun($We,t.__scopeHoverCard),{forceMount:a=r.forceMount,...i}=t,l=Lrt($We,t.__scopeHoverCard);return e.jsx(py,{present:a||l.open,children:e.jsx(Qun,{"data-state":l.open?"open":"closed",...i,onPointerEnter:Ra(t.onPointerEnter,Ase(l.onOpen)),onPointerLeave:Ra(t.onPointerLeave,Ase(l.onClose)),ref:n})})},"HoverCardContent")),Qun=j.forwardRef(RL(function(t,n){const{__scopeHoverCard:r,onEscapeKeyDown:a,onPointerDownOutside:i,onFocusOutside:l,onInteractOutside:o,...c}=t,d=Lrt($We,r),u=Irt(r),h=j.useRef(null),m=Vo(n,h),[f,g]=j.useState(!1);return j.useEffect(()=>{if(f){const x=document.body;return XBe=x.style.userSelect||x.style.webkitUserSelect,x.style.userSelect="none",x.style.webkitUserSelect="none",()=>{x.style.userSelect=XBe,x.style.webkitUserSelect=XBe}}},[f]),j.useEffect(()=>{if(h.current){const x=RL(()=>{g(!1),d.isPointerDownOnContentRef.current=!1,setTimeout(()=>{var v;((v=document.getSelection())==null?void 0:v.toString())!==""&&(d.hasSelectionRef.current=!0)})},"handlePointerUp");return document.addEventListener("pointerup",x),()=>{document.removeEventListener("pointerup",x),d.hasSelectionRef.current=!1,d.isPointerDownOnContentRef.current=!1}}},[d.isPointerDownOnContentRef,d.hasSelectionRef]),j.useEffect(()=>{h.current&&wWt(h.current).forEach(y=>y.setAttribute("tabindex","-1"))}),e.jsx(TB,{asChild:!0,disableOutsidePointerEvents:!1,onInteractOutside:o,onEscapeKeyDown:a,onPointerDownOutside:i,onFocusOutside:Ra(l,x=>{x.preventDefault()}),onDismiss:d.onDismiss,children:e.jsx(Nae,{...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 Ase(s){return t=>t.pointerType==="touch"?void 0:s()}RL(Ase,"excludeTouch");function wWt(s){const t=[],n=document.createTreeWalker(s,NodeFilter.SHOW_ELEMENT,{acceptNode:RL(r=>r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP,"acceptNode")});for(;n.nextNode();)t.push(n.currentNode);return t}RL(wWt,"getTabbableNodes");var Jun=Gun,ehn=Kun,jWt=Xun;const thn=Jun,shn=ehn,NWt=j.forwardRef(({className:s,align:t="center",sideOffset:n=4,...r},a)=>e.jsx(jWt,{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}));NWt.displayName=jWt.displayName;const nhn=[{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"}],rhn=s=>s.split(" ").map(t=>t[0]).join("").toUpperCase().slice(0,2),kWt=({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(thn,{openDelay:200,closeDelay:100,children:[e.jsx(shn,{asChild:!0,children:e.jsx("div",{className:"cursor-pointer",children:t})}),e.jsx(NWt,{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=nhn.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:rhn(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 ahn({images:s,initialIndex:t=0,open:n,onOpenChange:r}){const[a,i]=j.useState(t),[l,o]=j.useState(!1);j.useEffect(()=>{n&&(i(t),o(!1))},[n,t]);const c=()=>{i(m=>m>0?m-1:s.length-1),o(!1)},d=()=>{i(m=>m{n&&(m.key==="ArrowLeft"&&c(),m.key==="ArrowRight"&&d(),m.key==="Escape"&&r(!1))},[n,s.length]);j.useEffect(()=>(window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)),[u]);const h=s[a];return e.jsx(zs,{open:n,onOpenChange:r,children:e.jsxs(Os,{className:"max-w-[95vw] max-h-[95vh] w-auto h-auto p-0 border-none bg-black/95 overflow-hidden",children:[e.jsx($,{variant:"ghost",size:"icon",className:"absolute top-2 right-2 z-50 text-white hover:bg-white/20 h-10 w-10",onClick:()=>r(!1),children:e.jsx(pr,{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(fV,{className:"h-5 w-5"}):e.jsx(tL,{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 Rde=[{type:"like",emoji:"👍",label:"Like"},{type:"love",emoji:"❤️",label:"Love"}],ihn=({commentId:s,reactions:t,currentUserId:n})=>{var d,u;const r=Wt(),[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(kWt,{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=Rde.find(f=>f.type===h))==null?void 0:m.emoji},h)})}),e.jsx("span",{children:t.length})]})}),n&&e.jsxs(Kd,{open:a,onOpenChange:i,children:[e.jsx(Yd,{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=Rde.find(h=>h.type===l.reaction_type))==null?void 0:d.emoji," ",(u=Rde.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(Od,{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:Rde.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 Rrt({content:s,className:t}){const n=/([@#])\[([^\]]+)\]\(([^)]+)\)|(https?:\/\/[^\s<>]+)/g,r=[];let a=0,i,l=0;for(;(i=n.exec(s))!==null;){if(i.index>a&&r.push(s.substring(a,i.index)),i[1]){const o=i[1],c=i[2],d=i[3],u=o==="#";r.push(e.jsx(wr,{to:u?`/templates/${d}`:`/profile?user=${d}`,className:Pt("font-medium hover:underline",u?"text-white bg-[#2a4c64] px-1.5 py-0.5 rounded":"text-primary"),onClick:h=>h.stopPropagation(),children:u?c:`@${c}`},`mention-${l++}`))}else if(i[4]){const o=i[4],c=o.replace(/[.,;:!?)]+$/,""),d=o.slice(c.length);let u;try{const h=new URL(c);u=h.hostname+(h.pathname!=="/"?h.pathname.slice(0,20)+(h.pathname.length>20?"...":""):"")}catch{u=c.length>40?c.slice(0,40)+"...":c}r.push(e.jsx("a",{href:c,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline break-all",onClick:h=>h.stopPropagation(),children:u},`url-${l++}`)),d&&r.push(d)}a=i.index+i[0].length}return ae.jsx(j.Fragment,{children:o},c))})}function UTe({value:s,onChange:t,placeholder:n="What's on your mind? Use @ to mention someone",className:r,minHeight:a="80px",onMentionsChange:i,onTemplatesChange:l,onKeyDown:o,mentionFormat:c="encoded",enableTemplateMentions:d=!1}){const u=j.useRef(null),h=j.useRef(null),[m,f]=j.useState(!1),[g,x]=j.useState("user"),[y,v]=j.useState(""),[b,w]=j.useState(null),[S,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,Se)=>{J.includes(`@${Se}`)&&ue.push(Ee)}),[...new Set(ue)]}const ce=/@\[([^\]]+)\]\(([^)]+)\)/g,_e=[];let he;for(;(he=ce.exec(J))!==null;)_e.push(he[2]);return[...new Set(_e)]},O=J=>{if(c==="plain"){const ue=[];return R.current.forEach((Ee,Se)=>{J.includes(`#${Se}`)&&ue.push(Ee)}),[...new Set(ue)]}const ce=/#\[([^\]]+)\]\(([^)]+)\)/g,_e=[];let he;for(;(he=ce.exec(J))!==null;)_e.push(he[2]);return[...new Set(_e)]};j.useEffect(()=>{if(i){const J=D(s);i(J)}if(l){const J=O(s);l(J)}},[s,i,l,c]);const{data:U=[],isLoading:W}=st({queryKey:["mention-users",y],queryFn:async()=>{const J=q.from("profiles").select("id, name").limit(8),ce=y.length>=1?J.ilike("name",`%${y}%`):J.order("name"),{data:_e,error:he}=await ce;if(he)throw he;const ue=_e.map(Ee=>Ee.id),ve=await LOt(ue);return _e.map(Ee=>({id:Ee.id,name:Ee.name||"Unknown",avatar_url:ve.get(Ee.id)}))},enabled:m&&g==="user",staleTime:3e4}),{data:V=[],isLoading:G}=st({queryKey:["mention-templates",y],queryFn:async()=>{let J=q.from("canva_templates").select("id, name, preview_image_url").lte("publish_date",new Date().toISOString()).order("publish_date",{ascending:!1}).limit(8);y.length>=1&&(J=J.ilike("name",`%${y}%`));const{data:ce,error:_e}=await J;if(_e)throw _e;return ce||[]},enabled:m&&g==="template"&&d,staleTime:3e4}),Y=g==="user"?W:G,X=g==="user"?U:V,ae=J=>J.split(" ").map(ce=>ce[0]).join("").toUpperCase().slice(0,2),le=J=>{const ce=J.target.value,_e=J.target.selectionStart;t(ce);const he=ce.substring(0,_e),ue=he.lastIndexOf("@"),ve=d?he.lastIndexOf("#"):-1;let Ee=-1,Se="user";if(ue>ve?(Ee=ue,Se="user"):ve>ue&&d&&(Ee=ve,Se="template"),Ee!==-1){const Le=he.substring(Ee+1),Fe=Le.includes(" "),ke=Le.includes(` `);if(!Fe&&!ke&&Le.length<=30){w(Ee),v(Le),x(Se),f(!0),A(0);return}}f(!1),w(null)},ne=J=>{if(b===null)return;const ce=s.substring(0,b),_e=s.substring(b+y.length+1),he=g==="user"?"@":"#",ue=c==="plain"?`${he}${J.name} `:`${he}[${J.name}](${J.id}) `;c==="plain"&&(g==="user"?P.current.set(J.name,J.id):R.current.set(J.name,J.id));const ve=ce+ue+_e;t(ve),f(!1),w(null),v(""),setTimeout(()=>{if(u.current){const Ee=ce.length+ue.length;u.current.focus(),u.current.setSelectionRange(Ee,Ee)}},0)},te=J=>{if(!(!m||X.length===0))switch(J.key){case"ArrowDown":J.preventDefault(),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(),ne(X[S]));break;case"Escape":J.preventDefault(),f(!1);break;case"Tab":X[S]&&(J.preventDefault(),ne(X[S]));break}};return j.useEffect(()=>{const J=ce=>{h.current&&!h.current.contains(ce.target)&&u.current&&!u.current.contains(ce.target)&&f(!1)};return document.addEventListener("mousedown",J),()=>document.removeEventListener("mousedown",J)},[]),j.useEffect(()=>{if(!m)return;const J=()=>{const ce=u.current;if(!ce)return;const _e=ce.getBoundingClientRect();I({top:_e.bottom+4,left:_e.left,width:_e.width})};return J(),window.addEventListener("resize",J),window.addEventListener("scroll",J,!0),()=>{window.removeEventListener("resize",J),window.removeEventListener("scroll",J,!0)}},[m,s]),e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Ls,{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&&vv.createPortal(e.jsxs("div",{ref:h,className:"fixed z-[1000] max-h-[220px] overflow-hidden rounded-lg border bg-popover shadow-lg",style:{top:E.top,left:E.left,width:E.width,maxWidth:"320px"},children:[e.jsx("div",{className:"px-3 py-1.5 text-xs font-medium text-muted-foreground border-b bg-muted/30",children:g==="user"?"👤 Mention a person":"📋 Link a template"}),Y?e.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:"Searching..."}):X.length===0?e.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:y.length<1?`Type to search ${g==="user"?"people":"templates"}...`:`No ${g==="user"?"users":"templates"} found`}):e.jsx("ul",{className:"py-1 max-h-[180px] overflow-y-auto",children:X.map((J,ce)=>e.jsx("li",{className:Pt("flex items-center gap-2 px-3 py-2 cursor-pointer transition-colors",ce===S?"bg-accent":"hover:bg-accent/50"),onClick:()=>ne(J),onMouseEnter:()=>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 ohn(s){const t=/#\[([^\]]+)\]\(([^)]+)\)/g,n=[];let r;for(;(r=t.exec(s))!==null;)n.push(r[2]);return[...new Set(n)]}const Ewt=s=>s.split(" ").map(t=>t[0]).join("").toUpperCase().slice(0,2);function SWt({comment:s,postId:t,currentUserId:n,currentUserAvatar:r,currentUserEmail:a,canModerate:i,depth:l=0}){const o=Wt(),[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"]})}),y=()=>{u.trim()&&g.mutate({content:u,parentCommentId:s.id})};return e.jsxs("div",{className:l>0?"ml-8 border-l-2 border-muted pl-3":"",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Oa,{className:"h-8 w-8 shrink-0",children:[e.jsx(Ii,{src:s.user_avatar||void 0}),e.jsx(za,{className:"text-xs",children:Ewt(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(Rrt,{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(ihn,{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(Zq,{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:Ewt((a==null?void 0:a.split("@")[0])||"U")})]}),e.jsxs("div",{className:"flex-1 flex gap-2 items-start",children:[e.jsx(UTe,{placeholder:`Reply to ${s.user_name}...`,value:u,onChange:h,onMentionsChange:f,mentionFormat:"plain",className:"text-sm min-h-0 py-1.5",minHeight:"32px"}),e.jsx($,{size:"sm",variant:"ghost",onClick:y,disabled:!u.trim()||g.isPending,className:"h-8 px-2 mt-0.5",children:e.jsx(Kr,{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(SWt,{comment:b,postId:t,currentUserId:n,currentUserAvatar:r,currentUserEmail:a,canModerate:i,depth:l+1},b.id))})]})}const Dde=[{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"}],lhn=()=>{const{user:s,isBrokerageManager:t,managedBrokerages:n,isAdmin:r}=bs(),{avatarUrl:a}=IOt(s==null?void 0:s.id),{onlineUsers:i}=UFt(),{toast:l}=Bi(),o=Wt(),c=j.useRef(null),[d,u]=j.useState("all"),[h,m]=j.useState(""),[f,g]=j.useState(""),[x,y]=j.useState(""),[v,b]=j.useState([]),[w,S]=j.useState([]),[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,Y]=j.useState({}),[X,ae]=j.useState({}),[le,ne]=j.useState([]),[te,J]=j.useState([]),[ce,_e]=j.useState({open:!1,images:[],index:0});j.useEffect(()=>{if(d.startsWith("group:")){const gt=d.replace("group:","");y(gt),g("")}else d!=="all"?(g(d),y("")):(g(""),y(""))},[d]);const{data:he=[]}=st({queryKey:["community-categories"],queryFn:async()=>{const{data:gt,error:ss}=await q.from("community_categories").select("*").order("sort_order");if(ss)throw ss;return gt}}),{data:ue=[]}=st({queryKey:["community-private-groups"],queryFn:async()=>{const{data:gt,error:ss}=await q.from("community_private_groups").select("id, name, description, icon, brokerage_id, sort_order").order("sort_order");if(ss)throw ss;return gt}}),ve=20,{data:Ee,isLoading:Se,hasNextPage:Le,fetchNextPage:Fe,isFetchingNextPage:ke}=Bws({queryKey:["community-posts",d],initialPageParam:0,queryFn:async({pageParam:gt})=>{var Qn;const ss=gt*ve,Yt=ss+ve;let ts=q.from("community_posts").select("*").order("is_pinned",{ascending:!1}).order("pinned_at",{ascending:!1,nullsFirst:!1}).order("created_at",{ascending:!1}).range(ss,Yt);if(d.startsWith("group:")){const Cr=d.replace("group:","");ts=ts.eq("private_group_id",Cr)}else d==="all"||(ts=ts.eq("category_id",d).is("private_group_id",null));const{data:ys,error:Bt}=await ts;if(Bt)throw Bt;const Ft=((ys==null?void 0:ys.length)||0)>ve,as=(ys||[]).slice(0,ve);if(as.length===0)return{posts:[],hasMore:!1,nextPage:gt+1};const kt=as.map(Cr=>Cr.id),Ks=[...new Set(as.filter(Cr=>Cr.category_id).map(Cr=>Cr.category_id))].filter(Boolean),[wt,gs,ks,Is,Xs]=await Promise.all([Ks.length?q.from("community_categories").select("*").in("id",Ks):Promise.resolve({data:[]}),q.from("community_post_media").select("*").in("post_id",kt).order("sort_order"),q.from("community_reactions").select("*").in("post_id",kt),q.from("community_comments").select("*").in("post_id",kt).order("created_at",{ascending:!0}),q.from("community_post_resources").select("*").in("post_id",kt)]),ds=wt==null?void 0:wt.data,Ss=gs==null?void 0:gs.data,yn=ks==null?void 0:ks.data,Js=Is==null?void 0:Is.data,Ut=Xs==null?void 0:Xs.data,hn=(Js||[]).map(Cr=>Cr.id),[hr,Rs]=await Promise.all([hn.length?q.from("community_comment_reactions").select("*").in("comment_id",hn):Promise.resolve({data:[]}),(()=>{const Cr=(Ut||[]).filter(Un=>Un.resource_type==="template").map(Un=>Un.resource_id);return Cr.length===0?Promise.resolve({data:[]}):q.from("canva_templates").select("id, name, preview_image_url").in("id",Cr)})()]),jr=(hr==null?void 0:hr.data)||[],kr=(Rs==null?void 0:Rs.data)||[],$n=new Map(kr.map(Cr=>[Cr.id,{name:Cr.name,preview_image_url:Cr.preview_image_url}])),kn=Array.from(new Set([...as.map(Cr=>Cr.user_id),...(yn||[]).map(Cr=>Cr.user_id),...(Js||[]).map(Cr=>Cr.user_id),...jr.map(Cr=>Cr.user_id)])),[Fn,bn]=await Promise.all([kn.length?q.from("profiles").select("id, name").in("id",kn):Promise.resolve({data:[]}),LOt(kn)]),xs=new Map(((Qn=Fn==null?void 0:Fn.data)==null?void 0:Qn.map(Cr=>[Cr.id,Cr.name]))||[]),Lr=new Map((ds||[]).map(Cr=>[Cr.id,Cr])),Or=Cr=>{const Un=new Map,dr=[];return Cr.forEach(Pa=>{Un.set(Pa.id,{...Pa,user_name:xs.get(Pa.user_id)||"Unknown User",user_avatar:bn.get(Pa.user_id),reactions:jr.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:[]})}),Cr.forEach(Pa=>{const ii=Un.get(Pa.id);if(Pa.parent_comment_id&&Un.has(Pa.parent_comment_id)){const $i=Un.get(Pa.parent_comment_id);$i.replies=$i.replies||[],$i.replies.push(ii)}else dr.push(ii)}),dr};return{posts:as.map(Cr=>{const Un=(Ut||[]).filter(dr=>dr.post_id===Cr.id).map(dr=>{let Pa="",ii=null;if(dr.resource_type==="template"){const $i=$n.get(dr.resource_id);Pa=($i==null?void 0:$i.name)||"Unknown Template",ii=($i==null?void 0:$i.preview_image_url)||null}return{id:dr.id,resource_type:dr.resource_type,resource_id:dr.resource_id,resource_name:Pa,resource_preview_url:ii}});return{...Cr,user_name:xs.get(Cr.user_id)||"Unknown User",user_avatar:bn.get(Cr.user_id),category:Cr.category_id?Lr.get(Cr.category_id):null,media:(Ss||[]).filter(dr=>dr.post_id===Cr.id),reactions:((yn||[]).filter(dr=>dr.post_id===Cr.id)||[]).map(dr=>({...dr,user_name:xs.get(dr.user_id)||"Unknown User",user_avatar:bn.get(dr.user_id)})),comments:Or((Js||[]).filter(dr=>dr.post_id===Cr.id)),resources:Un}}),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]),Ne=mt({mutationFn:async()=>{P(!0);const{data:gt,error:ss}=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(ss)throw ss;for(let ts=0;ts0){const ts=le.filter(ys=>ys!==s.id).map(ys=>({post_id:gt.id,mentioned_user_id:ys,mentioned_by_user_id:s.id}));ts.length>0&&await q.from("community_post_mentions").insert(ts)}const Yt=ohn(h);if(Yt.length>0){const ts=Yt.map(ys=>({post_id:gt.id,resource_type:"template",resource_id:ys}));await q.from("community_post_resources").insert(ts)}return gt},onSuccess:async gt=>{var ss;o.invalidateQueries({queryKey:["community-posts"]}),m(""),ne([]),J([]),g(""),y(""),b([]),S([]),E(""),l({title:"Post created!"});try{const Yt=((ss=s==null?void 0:s.user_metadata)==null?void 0:ss.name)||"Someone",ts=h.replace(/@\[([^\]]+)\]\([^)]+\)/g,"@$1"),ys=ts.length>50?ts.substring(0,50)+"...":ts;await q.functions.invoke("send-push-notification",{body:{title:"New Community Post",body:`${Yt}: ${ys}`,url:"/community"}})}catch(Yt){console.error("Failed to send push notification:",Yt)}},onError:gt=>{l({title:"Error creating post",description:gt.message,variant:"destructive"})},onSettled:()=>P(!1)}),Ae=mt({mutationFn:async({postId:gt,content:ss})=>{const{error:Yt}=await q.from("community_posts").update({content:ss}).eq("id",gt);if(Yt)throw Yt},onSuccess:()=>{o.invalidateQueries({queryKey:["community-posts"]}),D(null),U(""),l({title:"Post updated!"})}}),Ce=mt({mutationFn:async gt=>{const{error:ss}=await q.from("community_posts").delete().eq("id",gt);if(ss)throw ss},onSuccess:()=>{o.invalidateQueries({queryKey:["community-posts"]}),l({title:"Post deleted"})}}),Ve=mt({mutationFn:async({postId:gt,isPinned:ss})=>{const{error:Yt}=await q.from("community_posts").update({is_pinned:!ss,pinned_at:ss?null:new Date().toISOString(),pinned_by:ss?null:s==null?void 0:s.id}).eq("id",gt);if(Yt)throw Yt},onSuccess:(gt,{isPinned:ss})=>{o.invalidateQueries({queryKey:["community-posts"]}),l({title:ss?"Post unpinned":"Post pinned to top"})}}),ze=mt({mutationFn:async({postId:gt,reactionType:ss})=>{var ts;const Yt=(ts=Be.find(ys=>ys.id===gt))==null?void 0:ts.reactions.find(ys=>ys.user_id===(s==null?void 0:s.id));Yt?Yt.reaction_type===ss?await q.from("community_reactions").delete().eq("id",Yt.id):await q.from("community_reactions").update({reaction_type:ss}).eq("id",Yt.id):await q.from("community_reactions").insert({post_id:gt,user_id:s.id,reaction_type:ss})},onSuccess:()=>o.invalidateQueries({queryKey:["community-posts"]})}),qe=mt({mutationFn:async({postId:gt,content:ss})=>{const{data:Yt,error:ts}=await q.from("community_comments").insert({post_id:gt,user_id:s.id,content:ss}).select("id").single();if(ts)throw ts;const ys=X[gt]||[];if(ys.length>0&&Yt){const Bt=ys.filter(Ft=>Ft!==s.id).map(Ft=>({comment_id:Yt.id,mentioned_user_id:Ft,mentioned_by_user_id:s.id}));Bt.length>0&&await q.from("community_comment_mentions").insert(Bt)}},onSuccess:(gt,{postId:ss})=>{o.invalidateQueries({queryKey:["community-posts"]}),Y(Yt=>({...Yt,[ss]:""})),ae(Yt=>({...Yt,[ss]:[]}))}});mt({mutationFn:async gt=>{const{error:ss}=await q.from("community_comments").delete().eq("id",gt);if(ss)throw ss},onSuccess:()=>o.invalidateQueries({queryKey:["community-posts"]})});const dt=gt=>{const ss=Array.from(gt.target.files||[]);if(ss.length+v.length>10){l({title:"Maximum 10 files allowed",variant:"destructive"});return}b(Yt=>[...Yt,...ss]),ss.forEach(Yt=>{const ts=new FileReader;ts.onloadend=()=>{S(ys=>[...ys,ts.result])},ts.readAsDataURL(Yt)})},Xe=gt=>{b(ss=>ss.filter((Yt,ts)=>ts!==gt)),S(ss=>ss.filter((Yt,ts)=>ts!==gt))},at=gt=>gt.split(" ").map(ss=>ss[0]).join("").toUpperCase().slice(0,2),rt=gt=>{const ss={};return gt.forEach(Yt=>{ss[Yt.reaction_type]=(ss[Yt.reaction_type]||0)+1}),ss},Ke=gt=>{var ss;return(ss=gt.find(Yt=>Yt.user_id===(s==null?void 0:s.id)))==null?void 0:ss.reaction_type},Je=gt=>gt.reduce((ss,Yt)=>ss+1+(Yt.replies?Je(Yt.replies):0),0),pt=gt=>{if(r)return!0;if(!t||!gt.private_group_id)return!1;const ss=ue.find(Yt=>Yt.id===gt.private_group_id);return ss!=null&&ss.brokerage_id?n.some(Yt=>Yt.id===ss.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(Uun,{categories:he,privateGroups:ue,selectedFilter:d,onFilterChange:u,onlineUsers:i}),e.jsxs("div",{className:"flex-1 min-w-0 max-w-2xl mx-auto lg:mx-0 space-y-6",children:[e.jsxs("div",{className:"px-1",children:[e.jsx("h1",{className:"text-4xl lg:text-5xl font-bold text-foreground",children:"Community"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Connect and share with fellow agents"})]}),e.jsx(qun,{categories:he,privateGroups:ue,selectedFilter:d,onFilterChange:u,onlineUsers:i}),e.jsx(je,{children:e.jsx(Ie,{className:"pt-6",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsxs(Oa,{className:"h-10 w-10",children:[e.jsx(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(UTe,{placeholder:r?"What's on your mind? Use @ to mention someone, # to link a template":"What's on your mind? Use @ to mention someone",value:h,onChange:m,onMentionsChange:ne,onTemplatesChange:J,mentionFormat:"encoded",minHeight:"80px",enableTemplateMentions:r}),w.length>0&&e.jsx("div",{className:"grid grid-cols-3 gap-2",children:w.map((gt,ss)=>{var Yt;return e.jsxs("div",{className:"relative aspect-square rounded-lg overflow-hidden bg-muted",children:[(Yt=v[ss])!=null&&Yt.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:()=>Xe(ss),children:e.jsx(pr,{className:"h-3 w-3"})})]},ss)})}),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(pr,{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:dt,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(ua,{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(""),y("")):gt.startsWith("group:")?(y(gt.replace("group:","")),g("")):(g(gt),y(""))},children:[e.jsx(us,{className:"w-[130px] sm:w-[160px] h-8 text-xs sm:text-sm",children:e.jsx(fs,{placeholder:"Select..."})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"none",children:"No category"}),he.map(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:he.map(gt=>e.jsxs(Ge,{value:gt.id,children:[gt.icon," ",gt.name]},gt.id))})]}),e.jsxs($,{size:"sm",onClick:()=>Ne.mutate(),disabled:!h.trim()||I,children:[e.jsx(Kr,{className:"h-4 w-4 mr-1"}),"Post"]})]})]})]})]})})}),Se?e.jsx("div",{className:"space-y-4",children:[...Array(3)].map((gt,ss)=>e.jsx(je,{children:e.jsx(Ie,{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"})]})]})})},ss))}):Be.length===0?e.jsx(je,{children:e.jsxs(Ie,{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 ss,Yt,ts,ys;return e.jsx(je,{children:e.jsxs(Ie,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-start justify-between mb-3",children:[e.jsxs("div",{className:"flex gap-3 min-w-0",children:[e.jsxs(Oa,{className:"h-10 w-10",children:[e.jsx(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)||pt(gt))&&e.jsxs($u,{children:[e.jsx(Uu,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(l_,{className:"h-4 w-4"})})}),e.jsxs(Au,{align:"end",children:[pt(gt)&>.private_group_id&&e.jsx(ja,{onClick:()=>Ve.mutate({postId:gt.id,isPinned:gt.is_pinned}),children:gt.is_pinned?e.jsxs(e.Fragment,{children:[e.jsx(GJ,{className:"h-4 w-4 mr-2"}),"Unpin Post"]}):e.jsxs(e.Fragment,{children:[e.jsx(LE,{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(Hn,{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(LE,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium",children:"Pinned"})]}),e.jsx("div",{className:"mb-3",children:e.jsx(Rrt,{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((Bt,Ft)=>{const as=Ft===3&>.media.length>4,kt=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:()=>_e({open:!0,images:gt.media.map(Ks=>({url:Ks.media_url,type:Ks.media_type==="video"?"video":"image"})),index:Ft}),children:[Bt.media_type==="video"?e.jsx("video",{src:Bt.media_url,className:"w-full h-full object-cover transition-transform group-hover:scale-105"}):e.jsx("img",{src:Bt.media_url,alt:"",className:"w-full h-full object-cover transition-transform group-hover:scale-105"}),e.jsx("div",{className:"absolute inset-0 bg-black/0 group-hover:bg-black/20 transition-colors flex items-center justify-center",children:e.jsx("div",{className:"opacity-0 group-hover:opacity-100 transition-opacity text-white",children:e.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-8 w-8",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0zM10 7v3m0 0v3m0-3h3m-3 0H7"})})})}),as&&e.jsx("div",{className:"absolute inset-0 bg-black/60 flex items-center justify-center",children:e.jsxs("span",{className:"text-white text-2xl font-bold",children:["+",kt]})})]},Bt.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:Bt=>{Bt.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(kWt,{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(([Bt])=>{var Ft;return e.jsx("span",{className:"text-base",children:(Ft=Dde.find(as=>as.type===Bt))==null?void 0:Ft.emoji},Bt)})}),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(Kd,{children:[e.jsx(Yd,{asChild:!0,children:e.jsxs($,{variant:"ghost",size:"sm",className:"flex-1",children:[Ke(gt.reactions)?e.jsx("span",{className:"mr-1",children:(ss=Dde.find(Bt=>Bt.type===Ke(gt.reactions)))==null?void 0:ss.emoji}):e.jsx(qy,{className:"h-4 w-4 mr-1"}),Ke(gt.reactions)?(Yt=Dde.find(Bt=>Bt.type===Ke(gt.reactions)))==null?void 0:Yt.label:"Like"]})}),e.jsx(Od,{className:"w-auto p-2",side:"top",children:e.jsx("div",{className:"flex gap-1",children:Dde.map(Bt=>e.jsx("button",{onClick:()=>ze.mutate({postId:gt.id,reactionType:Bt.type}),className:"text-2xl hover:scale-125 transition-transform p-1",title:Bt.label,children:Bt.emoji},Bt.type))})})]}),e.jsxs($,{variant:"ghost",size:"sm",className:"flex-1",onClick:()=>V(Bt=>{const Ft=new Set(Bt);return Ft.has(gt.id)?Ft.delete(gt.id):Ft.add(gt.id),Ft}),children:[e.jsx(Ah,{className:"h-4 w-4 mr-1"}),(()=>{const Bt=Je(gt.comments);return Bt>0?`Comment (${Bt})`:"Comment"})()]})]}),W.has(gt.id)&&e.jsxs("div",{className:"space-y-3 mt-3",children:[gt.comments.map(Bt=>e.jsx(SWt,{comment:Bt,postId:gt.id,currentUserId:s==null?void 0:s.id,currentUserAvatar:a,currentUserEmail:s==null?void 0:s.email,canModerate:pt(gt)},Bt.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(((ts=s.email)==null?void 0:ts.split("@")[0])||"U")})]}),e.jsxs("div",{className:"flex-1 flex gap-2",children:[e.jsx(UTe,{placeholder:"Write a comment... (use @ to mention)",value:G[gt.id]||"",onChange:Bt=>Y(Ft=>({...Ft,[gt.id]:Bt})),onMentionsChange:Bt=>ae(Ft=>({...Ft,[gt.id]:Bt})),mentionFormat:"plain",onKeyDown:Bt=>{var Ft;Bt.defaultPrevented||Bt.key==="Enter"&&!Bt.shiftKey&&((Ft=G[gt.id])!=null&&Ft.trim())&&(Bt.preventDefault(),qe.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 Bt;(Bt=G[gt.id])!=null&&Bt.trim()&&qe.mutate({postId:gt.id,content:G[gt.id]})},disabled:!((ys=G[gt.id])!=null&&ys.trim()),className:"h-8 px-2 mt-0.5",children:e.jsx(Kr,{className:"h-4 w-4"})})]})]})]})]})},gt.id)}),Le&&e.jsx("div",{className:"flex justify-center pt-2",children:e.jsx($,{variant:"outline",onClick:()=>Fe(),disabled:ke,children:ke?"Loading…":"Load more posts"})})]}),e.jsx(zs,{open:!!R,onOpenChange:()=>D(null),children:e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Edit Post"})}),e.jsx(Ls,{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(ahn,{images:ce.images,initialIndex:ce.index,open:ce.open,onOpenChange:gt=>_e(ss=>({...ss,open:gt}))})]})]})})},chn=50*1024*1024;function CWt({value:s,onChange:t,disabled:n}){const{user:r}=bs(),a=j.useRef(null),[i,l]=j.useState(!1),o=async d=>{if(!d||!r)return;const u=[];l(!0);try{for(const h of Array.from(d)){if(!h.type.startsWith("image/")&&!h.type.startsWith("video/")){re.error(`${h.name}: only images and videos allowed`);continue}if(h.size>chn){re.error(`${h.name}: must be under 50MB`);continue}const m=h.name.split(".").pop()||"bin",f=`${r.id}/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${m}`,{error:g}=await q.storage.from("support-attachments").upload(f,h,{contentType:h.type,upsert:!1});if(g){re.error(`${h.name}: ${g.message}`);continue}u.push({path:f,type:h.type,name:h.name,size:h.size})}u.length&&t([...s,...u])}finally{l(!1),a.current&&(a.current.value="")}},c=async d=>{const u=s[d];t(s.filter((h,m)=>m!==d)),await q.storage.from("support-attachments").remove([u.path])};return e.jsxs("div",{className:"space-y-2",children:[s.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:s.map((d,u)=>e.jsxs("div",{className:"flex items-center gap-2 px-2 py-1 rounded-md border bg-muted/40 text-xs",children:[d.type.startsWith("video/")?e.jsx(wJ,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(qI,{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(pr,{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(ZI,{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 AWt({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 P$={open:{label:"Open",icon:da,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:Nu,color:"bg-muted-foreground"}},Twt={general:"General Support",technology:"Technology Support",crm:"CRM Support",marketing:"Marketing Support"};function dhn(){const{user:s}=bs(),t=Wt(),[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([]),re.success("Reply sent!")},onError:()=>{re.error("Failed to send reply")}}),m=()=>{!a.trim()&&l.length===0||h.mutate({content:a,attachments:l})};if(n){const f=P$[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:Twt[n.category]}),e.jsxs($e,{className:P$[n.status].color,children:[e.jsx(f,{className:"h-3 w-3 mr-1"}),P$[n.status].label]})]})]})]}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsxs(Gn,{children:["Created on ",en(new Date(n.created_at),"MMM d, yyyy 'at' h:mm a")]})}),e.jsx(Ie,{children:e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:n.description})})]}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-lg",children:"Conversation"})}),e.jsxs(Ie,{children:[e.jsx(uo,{className:"h-[300px] pr-4",children:u.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No replies yet"}):e.jsx("div",{className:"space-y-4",children:u.map(g=>{var x;return e.jsxs("div",{className:`p-4 rounded-lg ${g.is_admin_reply?"bg-primary/10 ml-4":"bg-muted mr-4"}`,children:[e.jsxs("div",{className:"flex justify-between items-start mb-2",children:[e.jsx("span",{className:"font-medium text-sm",children:g.is_admin_reply?"Support Team":((x=g.profiles)==null?void 0:x.name)||"You"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:en(new Date(g.created_at),"MMM d, h:mm a")})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:g.content}),g.attachments&&g.attachments.length>0&&e.jsx(AWt,{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(Ls,{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(Kr,{className:"h-4 w-4"})})]}),e.jsx(CWt,{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(Ie,{className:"p-6 sm:p-8",children:e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center gap-6",children:[e.jsx("div",{className:"p-4 bg-primary/20 rounded-full",children:e.jsx(e4,{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(VHe,{trigger:e.jsxs($,{size:"lg",className:"gap-2",children:[e.jsx(dn,{className:"h-5 w-5"}),"Submit a Ticket"]})}),e.jsxs("div",{className:"flex items-center gap-2 px-4 py-2 bg-muted rounded-lg",children:[e.jsx(Da,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:["Or text us: ",e.jsx("span",{className:"font-semibold text-foreground",children:"1-866-527-8668"})]})]})]})]})]})})}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Your Tickets"}),e.jsx(VHe,{trigger:e.jsxs($,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(dn,{className:"h-4 w-4"}),"New Ticket"]})})]}),d?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading tickets..."}):c.length===0?e.jsx(je,{className:"border-dashed",children:e.jsxs(Ie,{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=P$[f.status].icon;return e.jsx(je,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>r(f),children:e.jsx(Ie,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-medium truncate",children:f.subject}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx($e,{variant:"outline",className:"text-xs",children:Twt[f.category]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:en(new Date(f.created_at),"MMM d, yyyy")})]})]}),e.jsxs($e,{className:P$[f.status].color,children:[e.jsx(g,{className:"h-3 w-3 mr-1"}),P$[f.status].label]})]})})},f.id)})})]})})}function uhn({open:s,onOpenChange:t}){return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-3xl max-h-[90vh] overflow-hidden",children:[e.jsx(Us,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(Ta,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(Bs,{children:"Schedule Agent Onboarding"}),e.jsx(Pr,{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 hhn({open:s,onOpenChange:t}){const{brokerageId:n}=bs(),[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:y}=await q.from("profiles").select("id, name, email").eq("brokerage_id",n).order("name",{ascending:!0});if(y)throw y;return x},enabled:s&&!!n}),h=d==null?void 0:d.filter(x=>x.name.toLowerCase().includes(r.toLowerCase())||x.email.toLowerCase().includes(r.toLowerCase())),m=x=>{l(y=>y.includes(x)?y.filter(v=>v!==x):[...y,x])},f=async()=>{if(i.length===0){re.error("Please select at least one agent");return}c(!0);try{const{data:x,error:y}=await q.functions.invoke("send-onboarding-link",{body:{agentIds:i}});if(y)throw y;re.success(`Onboarding link sent to ${i.length} agent${i.length>1?"s":""}`),l([]),t(!1)}catch(x){console.error("Error sending onboarding link:",x),re.error(x.message||"Failed to send onboarding link")}finally{c(!1)}},g=x=>{x||(l([]),a("")),t(x)};return e.jsx(zs,{open:s,onOpenChange:g,children:e.jsxs(Os,{className:"max-w-md",children:[e.jsx(Us,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(Kr,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(Bs,{children:"Send Onboarding Link"}),e.jsx(Pr,{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(Zr,{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(uo,{className:"h-[300px] border rounded-lg",children:e.jsx("div",{className:"p-2 space-y-1",children:h==null?void 0:h.map(x=>e.jsxs("div",{className:"flex items-center gap-3 p-2 rounded-lg hover:bg-muted cursor-pointer",onClick:()=>m(x.id),children:[e.jsx(ai,{checked:i.includes(x.id),onCheckedChange:()=>m(x.id)}),e.jsx(Oa,{className:"h-8 w-8",children:e.jsx(za,{className:"text-xs",children:x.name.split(" ").map(y=>y[0]).join("").toUpperCase()})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:x.name}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:x.email})]})]},x.id))})}),i.length>0&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:[i.length," agent",i.length>1?"s":""," selected"]})]}),e.jsxs(Sr,{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(Kr,{className:"h-4 w-4 mr-2"}),"Send Link"]})})]})]})})}function mhn(){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(Gn,{children:"Schedule onboarding sessions for yourself or your agents"})]})]})}),e.jsx(Ie,{children:e.jsxs("div",{className:"flex flex-wrap gap-4",children:[e.jsxs($,{onClick:()=>t(!0),className:"flex items-center gap-2",children:[e.jsx(Ta,{className:"h-4 w-4"}),"Schedule Agent Onboarding"]}),e.jsxs($,{variant:"outline",onClick:()=>r(!0),className:"flex items-center gap-2",children:[e.jsx(Kr,{className:"h-4 w-4"}),"Send New Agent Onboarding Link"]})]})})]}),e.jsx(uhn,{open:s,onOpenChange:t}),e.jsx(hhn,{open:n,onOpenChange:r})]})}function fhn({open:s,onOpenChange:t}){return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-3xl max-h-[90vh] overflow-hidden",children:[e.jsx(Us,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(qg,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(Bs,{children:"Schedule Launch Meeting"}),e.jsx(Pr,{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 phn(){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(qg,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx(Et,{children:"Launch or ReLaunch Meeting"}),e.jsx(Gn,{children:"Schedule a private LevelUp information session for your brokerage. Have one of our staff host a meeting to help your team get the most out of all our trainings, tools, and resources."})]})]})}),e.jsx(Ie,{children:e.jsxs($,{onClick:()=>t(!0),className:"flex items-center gap-2",children:[e.jsx(qg,{className:"h-4 w-4"}),"Schedule Launch Meeting"]})})]}),e.jsx(fhn,{open:s,onOpenChange:t})]})}function ghn(){const s=Xn(),[t,n]=j.useState(""),[r,a]=j.useState(null),{data:i,isLoading:l}=st({queryKey:["brokerage-resources-published"],queryFn:async()=>{const{data:x,error:y}=await q.from("brokerage_resources").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(y)throw y;return x}}),{data:o}=st({queryKey:["brokerage-resource-categories"],queryFn:async()=>{const{data:x,error:y}=await q.from("brokerage_resource_categories").select("*").order("sort_order",{ascending:!0});if(y)throw y;return x}}),{data:c}=st({queryKey:["brokerage-resource-pdfs-all"],queryFn:async()=>{const{data:x,error:y}=await q.from("brokerage_resource_pdfs").select("resource_id");if(y)throw y;return x}}),{data:d}=st({queryKey:["brokerage-resource-videos-all"],queryFn:async()=>{const{data:x,error:y}=await q.from("brokerage_resource_videos").select("resource_id");if(y)throw y;return x}}),{data:u}=st({queryKey:["brokerage-resource-links-all"],queryFn:async()=>{const{data:x,error:y}=await q.from("brokerage_resource_links").select("resource_id");if(y)throw y;return x}}),h=i==null?void 0:i.filter(x=>{var b;const y=x.title.toLowerCase().includes(t.toLowerCase())||((b=x.description)==null?void 0:b.toLowerCase().includes(t.toLowerCase())),v=!r||x.category_id===r;return y&&v}),m=o==null?void 0:o.filter(x=>i==null?void 0:i.some(y=>y.category_id===x.id)),f=x=>{const y=(c==null?void 0:c.filter(w=>w.resource_id===x).length)||0,v=(d==null?void 0:d.filter(w=>w.resource_id===x).length)||0,b=(u==null?void 0:u.filter(w=>w.resource_id===x).length)||0;return{pdfCount:y,videoCount:v,linkCount:b}},g=x=>{s(`/brokerage-resources/${x}`)};return e.jsx(Vs,{title:"Brokerage Resources",description:"Access exclusive resources for brokerage managers",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(mhn,{}),e.jsx(phn,{}),e.jsxs("div",{className:"relative max-w-md",children:[e.jsx(Zr,{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,y)=>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(Ie,{children:[e.jsx(xn,{className:"h-4 w-full mb-2"}),e.jsx(xn,{className:"h-4 w-2/3"})]})]},y))}):(h==null?void 0:h.length)===0?e.jsxs(je,{className:"p-12 text-center",children:[e.jsx(kx,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No resources found"}),e.jsx("p",{className:"text-muted-foreground",children:t||r?"Try adjusting your filters":"Check back later for new resources"})]}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6",children:h==null?void 0:h.map(x=>{const{pdfCount:y,videoCount:v,linkCount:b}=f(x.id),w=o==null?void 0:o.find(S=>S.id===x.category_id);return e.jsxs(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(kx,{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(Ie,{children:[x.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3",children:x.description}),e.jsxs("div",{className:"flex items-center gap-4 text-sm text-muted-foreground",children:[y>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Jr,{className:"h-4 w-4"}),y]}),v>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ua,{className:"h-4 w-4"}),v]}),b>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Sd,{className:"h-4 w-4"}),b]})]})]})]},x.id)})})]})})}const xhn=()=>{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(wr,{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(Ie,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(ua,{className:"h-4 w-4"}),"Videos (",t.videos.length,")"]}),e.jsx("div",{className:"space-y-4",children:t.videos.map(a=>e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium",children:a.title}),e.jsx("div",{className:"relative w-full",style:{paddingTop:"56.25%"},children:e.jsx("iframe",{src:a.video_url,className:"absolute top-0 left-0 w-full h-full rounded-lg border",allow:"accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture",allowFullScreen:!0})})]},a.id))})]})}),t.pdfs&&t.pdfs.length>0&&e.jsx(je,{children:e.jsxs(Ie,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Jr,{className:"h-4 w-4"}),"Documents (",t.pdfs.length,")"]}),e.jsx("div",{className:"grid gap-2",children:t.pdfs.map(a=>e.jsxs("a",{href:a.file_url,target:"_blank",rel:"noopener noreferrer",className:"flex items-center justify-between p-3 rounded-lg border hover:bg-muted transition-colors group",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-md bg-primary/10",children:e.jsx(Jr,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:a.name}),a.file_size&&e.jsx("div",{className:"text-xs text-muted-foreground",children:r(a.file_size)})]})]}),e.jsx(xi,{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(Ie,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Fr,{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(Fr,{className:"h-4 w-4 text-primary"})}),e.jsx("div",{className:"font-medium text-sm",children:a.title})]}),e.jsx(Fr,{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(kx,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold",children:"Resource not found"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"This resource may have been removed or is not available."}),e.jsx($,{asChild:!0,className:"mt-4",children:e.jsx(wr,{to:"/brokerage-resources",children:"Back to Resources"})})]})})};function yhn(){const{onlineUsers:s,totalOnline:t}=UFt(),{user:n}=bs();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(Og,{className:"h-2 w-2 fill-green-500 text-green-500 mr-1"}),t," online"]})]})}),e.jsx(Ie,{children:s.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No users online right now"}):e.jsx(uo,{className:"h-[300px] pr-4",children:e.jsx("div",{className:"space-y-3",children:s.map(r=>{var a;return e.jsxs("div",{className:"flex items-center gap-3 p-2 rounded-lg hover:bg-muted/50 transition-colors",children:[e.jsxs("div",{className:"relative",children:[e.jsxs(Oa,{className:"h-9 w-9",children:[e.jsx(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 Mwt={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:ul,path:"/admin/partnerships",color:"bg-indigo-500/10 text-indigo-600"},{title:"Invite Codes",description:"Create and manage signup invite codes",icon:t7,path:"/admin/invite-codes",color:"bg-amber-500/10 text-amber-600"},{title:"Subscriptions",description:"Track and manage user subscriptions",icon:Nv,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:gJ,path:"/admin/credits",color:"bg-gradient-to-br from-emerald-500/20 to-teal-500/10 text-emerald-600"},{title:"Subscription Discounts",description:"Create and manage coupon codes",icon:Ap,path:"/admin/discounts",color:"bg-red-500/10 text-red-600"},{title:"Referral Program",description:"Track brokerage referrals and discounts",icon:Fd,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:nh,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:QN,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:L4,path:"/admin/toolbox",color:"bg-orange-500/10 text-orange-600"},{title:"Social Swag",description:"Manage social media content and links",icon:Nn,path:"/admin/social-swag",color:"bg-fuchsia-500/10 text-fuchsia-600"},{title:"Social Swag 2.0",description:"New monthly social media images",icon:Nn,path:"/admin/social-swag-2",color:"bg-cyan-500/10 text-cyan-600"},{title:"Newsletters",description:"Manage monthly newsletter templates",icon:QN,path:"/admin/newsletters",color:"bg-violet-500/10 text-violet-600"},{title:"Newsletter Graphics",description:"Upload branded graphics agents drop into newsletters & emails",icon:QN,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:_b,path:"/admin/live",color:"bg-red-500/10 text-red-600"},{title:"Additional Services",description:"Manage additional service offerings",icon:kx,path:"/admin/additional-services",color:"bg-lime-500/10 text-lime-600"},{title:"Brokerage Resources",description:"Manage resources for brokerage managers",icon:kx,path:"/admin/brokerage-resources",color:"bg-slate-500/10 text-slate-600"},{title:"Agent Email Templates",description:"Manage curated email templates for agents",icon:mn,path:"/admin/agent-email-templates",color:"bg-rose-500/10 text-rose-600"},{title:"Mass Email Templates",description:"Create and manage shared campaign templates",icon: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:WI,path:"/admin/dashboard-management",color:"bg-teal-500/10 text-teal-600"},{title:"Manage Apps",description:"Configure app tiles and access requirements",icon:Fj,path:"/admin/apps",color:"bg-purple-500/10 text-purple-600"},{title:"Email Templates",description:"Customize system email templates",icon:mn,path:"/admin/email-templates",color:"bg-sky-500/10 text-sky-600"},{title:"The LevelUp Brief",description:"Create popup briefs with videos, links, and polls",icon: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:KN,path:"/admin/onboarding-checklist",color:"bg-emerald-500/10 text-emerald-600"},{title:"Marketplace",description:"Manage store categories, products, and orders",icon:I4,path:"/admin/marketplace",color:"bg-gradient-to-br from-orange-500/20 to-amber-500/10 text-orange-600"},{title:"Reward Store",description:"Manage reward items agents can redeem with points",icon:ul,path:"/admin/reward-store",color:"bg-purple-500/10 text-purple-600"},{title:"Agent Points",description:"View agent points, leaderboard, and award bonus points",icon:Kl,path:"/admin/agent-points",color:"bg-amber-500/10 text-amber-600"},{title:"Integrations",description:"Connect Canva, Facebook & Instagram for platform-level features",icon:Wd,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:eo,path:"/admin/community",color:"bg-cyan-500/10 text-cyan-600"},{title:"Support Tickets",description:"View and respond to agent support requests",icon:zq,path:"/admin/support-tickets",color:"bg-rose-500/10 text-rose-600"},{title:"Wishlist",description:"Review and manage community feature requests",icon:JS,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:mn,path:"/admin/weekly-digest",color:"bg-indigo-500/10 text-indigo-600"}]},insights:{label:"Insights",sections:[{title:"Analytics",description:"View activity logs and platform statistics",icon: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:Xf,path:"/admin/brokerage-content-activity",color:"bg-sky-500/10 text-sky-600"},{title:"Music Videos",description:"View all listing music videos created by agents across the platform",icon:bb,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:bb,path:"/admin/presentation-analytics",color:"bg-gradient-to-br from-violet-500/20 to-indigo-500/10 text-violet-600"},{title:"Listing Presentation Studio",description:"Track every listing presentation agents build, generate, and send",icon:Jr,path:"/admin/listing-presentation-studio",color:"bg-gradient-to-br from-slate-500/20 to-zinc-500/10 text-slate-600"},{title:"Listing Revival",description:"Track expired-listing campaigns, seller leads, and manage who has access",icon:Nn,path:"/admin/listing-revival",color:"bg-gradient-to-br from-amber-500/20 to-yellow-500/10 text-amber-600"},{title:"Staging Studio",description:"Member conversions gallery, credits, subscriptions, and credit pack pricing",icon: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:Xf,path:"/admin/guest-book-analytics",color:"bg-gradient-to-br from-emerald-500/20 to-teal-500/10 text-emerald-600"}]},beta:{label:"🧪 Beta Lab",sections:[{title:"Social Post Generator",description:"Auto-generate branded social media posts from MLS listing data",icon:Hc,path:"/admin/beta/social-post-generator",color:"bg-gradient-to-br from-fuchsia-500/20 to-pink-500/10 text-fuchsia-600"},{title:"Mail Studio Designs",description:"Upload postcard designs for the Mail Studio template library",icon:mn,path:"/admin/beta/postcard-manager",color:"bg-gradient-to-br from-orange-500/20 to-amber-500/10 text-orange-600"},{title:"ReelFlow",description:"Turn property photos into cinematic video reels for social media",icon:VI,path:"/admin/beta/homereel",color:"bg-gradient-to-br from-violet-500/20 to-indigo-500/10 text-violet-600"}]},"lead-sites":{label:"Lead Sites",sections:[{title:"All Sites",description:"Overview of all agent websites with status and quick actions",icon:dl,path:"/admin/lead-sites",color:"bg-gradient-to-br from-sky-500/20 to-blue-500/10 text-sky-600"},{title:"MLS Feeds",description:"Manage MLS data feed connections, API keys, and coverage areas",icon:Aq,path:"/admin/mls-feeds",color:"bg-gradient-to-br from-emerald-500/20 to-green-500/10 text-emerald-600"},{title:"Free Website Offers",description:"Choose which brokerages get a free luxury website, and set their default template",icon:ul,path:"/admin/lead-sites/offers",color:"bg-gradient-to-br from-violet-500/20 to-purple-500/10 text-violet-600"},{title:"Lead Analytics",description:"Cross-site lead capture stats, conversions, and top-performing sites",icon: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:Jr,path:"/admin/website-requests",color:"bg-gradient-to-br from-sky-500/20 to-blue-500/10 text-sky-600"},{title:"Website Interests",description:"Track interest form submissions from TheLocalMove.com",icon:Jr,path:"/admin/website-interests",color:"bg-gradient-to-br from-rose-500/20 to-pink-500/10 text-rose-600"},{title:"Website Order Tracker",description:"Full setup requests with all build details from /get-started",icon:Jr,path:"/admin/website-orders",color:"bg-gradient-to-br from-emerald-500/20 to-teal-500/10 text-emerald-600"},{title:"MLS Fee Tracker",description:"Track MLS providers, setup fees, and monthly costs",icon:nu,path:"/admin/mls-fee-tracker",color:"bg-gradient-to-br from-teal-500/20 to-cyan-500/10 text-teal-600"}]}};function Pwt(){const s=Xn();return console.log("[AdminDashboard] render"),e.jsx(Vs,{title:"Admin Dashboard",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Admin Dashboard"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage all aspects of your platform"})]}),e.jsxs(ha,{defaultValue:"users",className:"w-full",children:[e.jsx(ma,{className:"w-full justify-start flex-wrap h-auto gap-1 bg-muted/50 p-1 overflow-x-auto",children:Object.entries(Mwt).map(([t,n])=>e.jsx(Zt,{value:t,className:"data-[state=active]:bg-background",children:n.label},t))}),Object.entries(Mwt).map(([t,n])=>e.jsx(Xt,{value:t,className:"mt-6",children:e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:n.sections.map(r=>e.jsxs(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(Ie,{className:"pt-0",children:e.jsx(Gn,{className:"text-sm",children:r.description})})]},r.path))})},t))]}),e.jsx(yhn,{})]})})}const vhn=()=>{const{isAdmin:s}=bs(),t=Xn(),[n,r]=j.useState([]),[a,i]=j.useState(!0),[l,o]=j.useState(!1),[c,d]=j.useState(null);j.useEffect(()=>{if(!s){t("/dashboard");return}u()},[s]);const u=async()=>{try{const{data:x,error:y}=await q.from("app_tiles").select("*").order("name");if(y)throw y;r(x||[])}catch(x){console.error("Error loading apps:",x),re.error("Failed to load apps")}finally{i(!1)}},h=async x=>{x.preventDefault();const y=new FormData(x.currentTarget),v={name:y.get("name"),description:y.get("description"),icon:y.get("icon"),app_id:y.get("app_id"),target_url:y.get("target_url"),required_tags:y.get("required_tags").split(",").map(b=>b.trim()).filter(Boolean)};try{if(c){const{error:b}=await q.from("app_tiles").update(v).eq("id",c.id);if(b)throw b;re.success("App updated successfully")}else{const{error:b}=await q.from("app_tiles").insert([v]);if(b)throw b;re.success("App created successfully")}o(!1),d(null),u()}catch(b){console.error("Error saving app:",b),re.error("Failed to save app")}},m=async x=>{if(await fo("Are you sure you want to delete this app?"))try{const{error:y}=await q.from("app_tiles").delete().eq("id",x);if(y)throw y;re.success("App deleted successfully"),u()}catch(y){console.error("Error deleting app:",y),re.error("Failed to delete app")}},f=x=>{d(x),o(!0)},g=()=>{d(null),o(!0)};return a?e.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}):e.jsxs("div",{className:"min-h-screen bg-background",children:[e.jsx("header",{className:"border-b bg-card",children:e.jsx("div",{className:"container mx-auto px-4 py-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>t("/dashboard"),children:[e.jsx(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(zs,{open:l,onOpenChange:o,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{onClick:g,children:[e.jsx(dn,{className:"mr-2 h-4 w-4"}),"Add App"]})}),e.jsxs(Os,{className:"max-w-2xl",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:c?"Edit App":"Create New App"}),e.jsx(Pr,{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(Ls,{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(Gn,{children:"Manage the apps that appear on the member dashboard"})]}),e.jsx(Ie,{children:n.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx("p",{className:"text-muted-foreground mb-4",children:"No apps configured yet"}),e.jsxs($,{onClick:g,children:[e.jsx(dn,{className:"mr-2 h-4 w-4"}),"Create First App"]})]}):e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Icon"}),e.jsx(Dt,{children:"Name"}),e.jsx(Dt,{children:"App ID"}),e.jsx(Dt,{children:"Target URL"}),e.jsx(Dt,{children:"Tags"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(fi,{children:n.map(x=>e.jsxs(En,{children:[e.jsx(_t,{className:"text-2xl",children:x.icon}),e.jsx(_t,{className:"font-medium",children:x.name}),e.jsx(_t,{className:"font-mono text-sm",children:x.app_id}),e.jsx(_t,{className:"text-sm text-muted-foreground max-w-xs truncate",children:x.target_url}),e.jsx(_t,{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:x.required_tags.map(y=>e.jsx("span",{className:"text-xs bg-secondary text-secondary-foreground px-2 py-1 rounded",children:y},y))})}),e.jsx(_t,{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(Hn,{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(wr,{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 Iwt=({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(da,{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(da,{className:"h-3 w-3"}),"Trial: ",a," days left"]}):e.jsxs($e,{variant:"secondary",className:Pt("gap-1",t),children:[e.jsx(da,{className:"h-3 w-3"}),"Trial: ",a," days left"]})},EWt=({open:s,onOpenChange:t,brokerages:n,fixedBrokerageId:r,onSuccess:a})=>{const{toast:i}=Bi(),l=j.useRef(null),[o,c]=j.useState([]),[d,u]=j.useState(""),[h,m]=j.useState(!1),[f,g]=j.useState("upload"),[x,y]=j.useState(null),v=()=>{c([]),u(""),g("upload"),y(null),l.current&&(l.current.value="")},b=()=>{v(),t(!1)},w=P=>{const R=P.split(` `).map(V=>V.trim()).filter(V=>V);if(R.length===0)return[];const D=R[0].toLowerCase(),U=D.includes("first")||D.includes("last")||D.includes("email")||D.includes("name")||D.includes("phone")||D.includes("sms")||D.includes("consent")?R.slice(1):R,W=[];for(const V of U){const Y=(V.includes(" ")?V.split(" "):V.split(",")).map(X=>X.trim().replace(/^["']|["']$/g,""));if(Y.length>=2){let X="",ae="",le="",ne="",te;if(Y.length===2){const _e=Y[0].split(" ");X=_e[0]||"",ae=_e.slice(1).join(" ")||"",le=Y[1]}else if(Y.length===3)X=Y[0],ae=Y[1],le=Y[2];else if(Y.length===4)X=Y[0],ae=Y[1],le=Y[2],ne=Y[3];else if(Y.length>=5){X=Y[0],ae=Y[1],le=Y[2],ne=Y[3];const _e=Y[4].toLowerCase();te=_e==="true"||_e==="yes"||_e==="1"||_e==="y"}const ce=/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(le);W.push({firstName:X.trim(),lastName:ae.trim(),email:le.trim().toLowerCase(),phone:ne.trim()||void 0,smsConsent:te,isValid:ce&&X.trim().length>0,error:ce?X.trim()?void 0:"Missing name":"Invalid email"})}}return W},S=P=>{var O;const R=(O=P.target.files)==null?void 0:O[0];if(!R)return;const D=new FileReader;D.onload=U=>{var G;const W=(G=U.target)==null?void 0:G.result,V=w(W);if(V.length===0){i({title:"No data found",description:"The CSV file appears to be empty or in an unsupported format.",variant:"destructive"});return}c(V),g("preview")},D.readAsText(R)},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");y(U),g("result"),U.created>0&&a(),i({title:"Import Complete",description:`${U.created} user(s) created successfully.${U.failed>0?` ${U.failed} failed.`:""}`})}catch(D){console.error("Import error:",D),i({title:"Import Failed",description:D.message||"Failed to import users",variant:"destructive"})}finally{m(!1)}},E=o.filter(P=>P.isValid).length,I=o.filter(P=>!P.isValid).length;return e.jsx(zs,{open:s,onOpenChange:b,children:e.jsxs(Os,{className:"max-w-2xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(YN,{className:"h-5 w-5"}),"Import Agents from CSV"]}),e.jsx(Pr,{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(ll,{className:"h-4 w-4"}),e.jsxs("span",{children:[I," invalid"]})]})]}),e.jsxs("div",{className:"flex-1 overflow-auto border rounded-lg",children:[e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{className:"bg-muted/30",children:[e.jsx(Dt,{children:"First Name"}),e.jsx(Dt,{children:"Last Name"}),e.jsx(Dt,{children:"Email"}),e.jsx(Dt,{children:"Phone"}),e.jsx(Dt,{children:"SMS"}),e.jsx(Dt,{children:"Status"})]})}),e.jsx(fi,{children:o.slice(0,100).map((P,R)=>e.jsxs(En,{children:[e.jsx(_t,{children:P.firstName}),e.jsx(_t,{children:P.lastName}),e.jsx(_t,{children:P.email}),e.jsx(_t,{className:"text-muted-foreground",children:P.phone||"-"}),e.jsx(_t,{className:"text-muted-foreground",children:P.smsConsent===!0?"✓":P.smsConsent===!1?"✗":"-"}),e.jsx(_t,{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(Sr,{children:[f==="upload"&&e.jsx($,{variant:"outline",onClick:b,children:"Cancel"}),f==="preview"&&e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"outline",onClick:v,children:"Back"}),e.jsx($,{onClick: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(Dg,{className:"h-3.5 w-3.5 shrink-0"}):e.jsx(zy,{className:"h-3.5 w-3.5 shrink-0 opacity-40"})]})})}function bie(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 bhn=[{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:Cx}];function TWt({open:s,onOpenChange:t,userId:n,userName:r}){const[a,i]=j.useState("custom"),[l,o]=j.useState(""),[c,d]=j.useState(""),u=wRs(),h=f=>{i(f.type),o(f.title),d(f.message)},m=async f=>{if(f.preventDefault(),!l.trim()){_a({title:"Title required",description:"Please enter a celebration title",variant:"destructive"});return}try{await u.mutateAsync({user_id:n,celebration_type:a,title:l.trim(),message:c.trim()||void 0}),_a({title:"Celebration sent! 🎉",description:`${r} will see confetti on their next visit!`}),t(!1),o(""),d(""),i("custom")}catch{_a({title:"Error",description:"Failed to send celebration",variant:"destructive"})}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(Cx,{className:"h-5 w-5 text-primary"}),"Send Celebration to ",r]}),e.jsx(Pr,{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:bhn.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(nu,{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(Ls,{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(Cx,{className:"h-4 w-4 mr-2"}),u.isPending?"Sending...":"Send Celebration"]})]})]})]})})}const QBe={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:nu,color:"bg-green-500"},custom:{label:"Custom",icon:Nn,color:"bg-purple-500"}};function _hn(){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 y,v,b;return{...x,user_name:((y=g.get(x.user_id))==null?void 0:y.name)||"Unknown",user_email:((v=g.get(x.user_id))==null?void 0:v.email)||"",creator_name:x.created_by?((b=g.get(x.created_by))==null?void 0:b.name)||"System":"Auto-triggered"}})}}),c=l.filter(u=>{var g,x;const h=((g=u.user_name)==null?void 0:g.toLowerCase().includes(s.toLowerCase()))||((x=u.user_email)==null?void 0:x.toLowerCase().includes(s.toLowerCase()))||u.title.toLowerCase().includes(s.toLowerCase()),m=n==="all"||u.celebration_type===n,f=a==="all"||a==="seen"&&u.seen_at||a==="unseen"&&!u.seen_at;return h&&m&&f}),d={total:l.length,seen:l.filter(u=>u.seen_at).length,unseen:l.filter(u=>!u.seen_at).length,byType:Object.keys(QBe).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(Ie,{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(Ie,{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(Ie,{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(Ie,{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(Cx,{className:"h-5 w-5"}),"Celebration History"]}),e.jsx(Gn,{children:"View all celebrations awarded to agents"})]}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Zr,{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(QBe).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(En,{children:[e.jsx(Dt,{children:"Type"}),e.jsx(Dt,{children:"Agent"}),e.jsx(Dt,{children:"Title"}),e.jsx(Dt,{children:"Points"}),e.jsx(Dt,{children:"Created By"}),e.jsx(Dt,{children:"Created"}),e.jsx(Dt,{children:"Status"})]})}),e.jsx(fi,{children:c.length===0?e.jsx(En,{children:e.jsx(_t,{colSpan:7,className:"text-center py-8 text-muted-foreground",children:"No celebrations found"})}):c.map(u=>{const h=QBe[u.celebration_type],m=h.icon;return e.jsxs(En,{children:[e.jsx(_t,{children:e.jsxs($e,{variant:"outline",className:"gap-1",children:[e.jsx(m,{className:"h-3 w-3"}),h.label]})}),e.jsx(_t,{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(_t,{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(_t,{children:u.points_amount?e.jsxs($e,{variant:"secondary",children:["+",u.points_amount]}):e.jsx("span",{className:"text-muted-foreground",children:"-"})}),e.jsx(_t,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:u.creator_name})}),e.jsx(_t,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:en(new Date(u.created_at),"MMM d, yyyy h:mm a")})}),e.jsx(_t,{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 whn=()=>{const{user:s}=bs(),{toast:t}=Bi(),[n,r]=j.useState([]),[a,i]=j.useState(!0),[l,o]=j.useState(!1),[c,d]=j.useState("all"),[u,h]=j.useState("all"),[m,f]=j.useState("new"),[g,x]=j.useState(new Set),y=j.useCallback(async()=>{try{i(!0);const{data:W,error:V}=await q.from("profiles").select("id, name, email, phone, is_trial, trial_started_at, trial_expires_at, subscription_status, subscription_end_date, converted_from_trial_at, created_at, last_login").or("is_trial.eq.true,subscription_status.eq.trialing,converted_from_trial_at.not.is.null");if(V)throw V;const{data:G,error:Y}=await q.from("trial_email_exports").select("user_id");if(Y)throw Y;const X=new Set((G||[]).map(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,ne)=>new Date(ne.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(()=>{y()},[y]);const v=W=>W.trial_started_at?"ghl":"stripe",b=W=>W.trial_expires_at?W.trial_expires_at:W.subscription_end_date?W.subscription_end_date:null,w=W=>W.converted_from_trial_at!==null,S=W=>{if(w(W))return!1;const V=b(W);return V?new Date(V).getTime()<=Date.now():!1},A=n.filter(W=>!(c!=="all"&&v(W)!==c||u==="active"&&(S(W)||w(W))||u==="expired"&&!S(W)||u==="converted"&&!w(W)||m==="new"&&W.already_exported||m==="exported"&&!W.already_exported)),E=()=>{g.size===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]||"",_e=J.slice(1).join(" ")||"",he=v(te)==="stripe"?"Credit Card Trial":"Free Trial (No CC)",ue=w(te)?"Converted":S(te)?"Expired":"Active",ve=te.created_at?new Date(te.created_at).toLocaleDateString():"",Ee=b(te)?new Date(b(te)).toLocaleDateString():"";return`"${ce}","${_e}","${te.email}","${te.phone||""}","${he}","${ue}","${ve}","${Ee}"`}),Y=[V,...G].join(` `),X=new Blob([Y],{type:"text/csv"}),ae=URL.createObjectURL(X),le=document.createElement("a");le.href=ae,le.download=`trial-users-${new Date().toISOString().split("T")[0]}.csv`,le.click(),URL.revokeObjectURL(ae);const ne=W.filter(te=>!te.already_exported).map(te=>({user_id:te.id,exported_by:s.id}));if(ne.length>0){const{error:te}=await q.from("trial_email_exports").upsert(ne,{onConflict:"user_id"});te&&console.error("Error marking exports:",te)}t({title:"Export complete",description:`Downloaded ${W.length} trial user(s). ${ne.length} newly marked as exported.`}),x(new Set),y()}catch(W){console.error("Export error:",W),t({title:"Error",description:"Failed to export",variant:"destructive"})}finally{o(!1)}},R=n.filter(W=>!W.already_exported).length,D=n.filter(W=>W.already_exported).length,O=n.filter(W=>w(W)).length,U=n.filter(W=>!S(W)&&!w(W)).length;return a?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(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(Gn,{children:"Total"}),e.jsx(Et,{className:"text-2xl",children:n.length})]})}),e.jsx(je,{children:e.jsxs(St,{className:"pb-2",children:[e.jsx(Gn,{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(Gn,{children:"Active Trials"}),e.jsx(Et,{className:"text-2xl",children:U})]})}),e.jsx(je,{children:e.jsxs(St,{className:"pb-2",children:[e.jsx(Gn,{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(Gn,{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(xi,{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(En,{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(En,{children:e.jsx(_t,{colSpan:9,className:"text-center py-8 text-muted-foreground",children:"No trial users match the current filters"})}):A.map(W=>{const V=v(W),G=w(W),Y=S(W),X=b(W);return e.jsxs(En,{className:`hover:bg-muted/30 ${G?"bg-primary/5":""}`,children:[e.jsx(_t,{children:e.jsx(ai,{checked:g.has(W.id),onCheckedChange:()=>I(W.id)})}),e.jsx(_t,{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(_t,{className:"text-muted-foreground",children:W.email}),e.jsx(_t,{children:V==="stripe"?e.jsxs($e,{variant:"outline",className:"gap-1",children:[e.jsx(Nv,{className:"h-3 w-3"}),"Credit Card"]}):e.jsxs($e,{variant:"secondary",className:"gap-1",children:[e.jsx(mn,{className:"h-3 w-3"}),"Free (No CC)"]})}),e.jsx(_t,{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"]}):Y?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(_t,{className:"text-sm",children:W.created_at?new Date(W.created_at).toLocaleDateString():"—"}),e.jsx(_t,{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(_t,{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(_t,{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"]})]})},jhn=s=>s==null?'""':`"${String(s).replace(/"/g,'""')}"`,Nhn=()=>{const[s,t]=j.useState([]),[n,r]=j.useState(!0);j.useEffect(()=>{(async()=>{const{data:l,error:o}=await q.from("user_deletion_log").select("*").order("created_at",{ascending:!1});!o&&l&&t(l),r(!1)})()},[]);const a=()=>{if(s.length===0){re.info("No deletion records to export");return}const i=["Date","Deleted User","Deleted Email","Brokerage","Type","Deleted By"],l=s.map(h=>[en(new Date(h.created_at),"MMM d, yyyy h:mm a"),h.deleted_user_name||"—",h.deleted_user_email||"—",h.brokerage_name||"—",h.deletion_type==="deleted"?"Account Deleted":"Removed",h.deleted_by_name||h.deleted_by_email||"—"]),o=[i.join(","),...l.map(h=>h.map(jhn).join(","))].join(` `),c=new Blob([o],{type:"text/csv"}),d=URL.createObjectURL(c),u=document.createElement("a");u.href=d,u.download=`deletion-log-${new Date().toISOString().split("T")[0]}.csv`,u.click(),URL.revokeObjectURL(d),re.success(`Exported ${s.length} deletion record(s)`)};return n?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):s.length===0?e.jsx(je,{children:e.jsxs(Ie,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(Hn,{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(xi,{className:"h-4 w-4 mr-2"}),"Export CSV"]})]}),e.jsx(Ie,{children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Date"}),e.jsx(Dt,{children:"User"}),e.jsx(Dt,{children:"Email"}),e.jsx(Dt,{children:"Brokerage"}),e.jsx(Dt,{children:"Type"}),e.jsx(Dt,{children:"Deleted By"})]})}),e.jsx(fi,{children:s.map(i=>e.jsxs(En,{children:[e.jsx(_t,{className:"whitespace-nowrap text-sm",children:en(new Date(i.created_at),"MMM d, yyyy h:mm a")}),e.jsx(_t,{className:"font-medium",children:i.deleted_user_name||"—"}),e.jsx(_t,{className:"text-sm text-muted-foreground",children:i.deleted_user_email||"—"}),e.jsx(_t,{children:i.brokerage_name||"—"}),e.jsx(_t,{children:e.jsx($e,{variant:i.deletion_type==="deleted"?"destructive":"secondary",children:i.deletion_type==="deleted"?"Account Deleted":"Removed"})}),e.jsx(_t,{className:"text-sm",children:i.deleted_by_name||i.deleted_by_email||"—"})]},i.id))})]})})]})},u3=s=>{const{user:t}=bs(),n=Wt(),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(v=>v.user_id),{data:x}=await q.from("profiles").select("id, name, email, avatar_url").in("id",g),y=new Map((x||[]).map(v=>[v.id,v]));return(m||[]).map(v=>({...v,profile:y.get(v.user_id)||null}))},enabled:!!h}),i=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"]}),re.success("Team created!")},onError:h=>{re.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"]}),re.success("Team updated")},onError:h=>{re.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"]}),re.success("Team deleted")},onError:h=>{re.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]}),re.success("Member added to team")},onError:h=>{re.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]}),re.success("Member removed from team")},onError:h=>{re.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]}),re.success("Member role updated")},onError:h=>{re.error("Failed to update role: "+h.message)}});return{teams:r.data||[],isLoading:r.isLoading,createTeam:i,updateTeam:l,deleteTeam:o,addMember:c,removeMember:d,updateMemberRole:u,useTeamMembers:a}},Drt=s=>{const t=Wt(),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(),re.success("Pond created")},onError:o=>re.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(),re.success("Pond updated")},onError:o=>re.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(),re.success("Pond deleted")},onError:o=>re.error(o.message)});return{ponds:n.data||[],isLoading:n.isLoading,createPond:a,updatePond:i,deletePond:l}},khn=s=>{const t=Wt(),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=>re.error(a.message)});return{assignedUserIds:(n.data||[]).map(a=>a.user_id),isLoading:n.isLoading,setAssigned:r}},Shn=({pond:s,teamId:t})=>{const{useTeamMembers:n}=u3(),{data:r=[],isLoading:a}=n(t),{assignedUserIds:i,isLoading:l,setAssigned:o}=khn(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)})})]})},MWt=({teamId:s})=>{const{ponds:t,isLoading:n,createPond:r,updatePond:a,deletePond:i}=Drt(s),[l,o]=j.useState(!1),[c,d]=j.useState(""),[u,h]=j.useState(""),[m,f]=j.useState(null),[g,x]=j.useState(null),y=async()=>{c.trim()&&(await r.mutateAsync({name:c.trim(),description:u.trim()}),d(""),h(""),o(!1))};return e.jsxs(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(Gn,{children:"Create multiple ponds (by area, source, or specialty) and assign which agents can see each one."})]}),e.jsxs($,{size:"sm",onClick:()=>o(!0),children:[e.jsx(dn,{className:"mr-1 h-4 w-4"})," New Pond"]})]}),e.jsxs(Ie,{className:"space-y-3",children:[n&&e.jsx(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(v=>e.jsxs("div",{className:"rounded-lg border p-3 space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(g1,{className:"h-4 w-4 text-primary"}),e.jsx("p",{className:"font-medium",children:v.name}),v.is_default&&e.jsx($e,{variant:"secondary",className:"text-[10px]",children:"Default"})]}),v.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:v.description}),e.jsxs("div",{className:"mt-1 flex flex-wrap gap-2 text-[11px] text-muted-foreground",children:[e.jsxs("span",{children:[v.available_count," available"]}),e.jsx("span",{children:"·"}),e.jsxs("span",{children:[v.claimed_count," claimed"]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs($,{size:"sm",variant:"ghost",onClick:()=>x(g===v.id?null:v.id),children:[e.jsx(Yn,{className:"mr-1 h-3.5 w-3.5"}),g===v.id?"Hide agents":"Assign agents"]}),e.jsx($,{size:"icon",variant:"ghost",onClick:()=>f(v),children:e.jsx(pi,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"icon",variant:"ghost",onClick:()=>{confirm(`Delete "${v.name}"? Leads in this pond will no longer be shared.`)&&i.mutate(v.id)},children:e.jsx(Hn,{className:"h-3.5 w-3.5 text-destructive"})})]})]}),g===v.id&&e.jsx(Shn,{pond:v,teamId:s})]},v.id))]}),e.jsx(zs,{open:l,onOpenChange:o,children:e.jsxs(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"New Lead Pond"}),e.jsx(Pr,{children:"Leave agents unassigned to make the pond open to the whole team."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Pond name"}),e.jsx(pe,{value:c,onChange:v=>d(v.target.value),placeholder:"e.g. Northland Buyers"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Description (optional)"}),e.jsx(pe,{value:u,onChange:v=>h(v.target.value),placeholder:"What kind of leads go in this pond?"})]})]}),e.jsxs(Sr,{children:[e.jsx($,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx($,{onClick:y,disabled:!c.trim()||r.isPending,children:"Create Pond"})]})]})}),e.jsx(zs,{open:!!m,onOpenChange:v=>!v&&f(null),children:e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Edit Pond"})}),m&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Pond name"}),e.jsx(pe,{value:m.name,onChange:v=>f({...m,name:v.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Description"}),e.jsx(pe,{value:m.description||"",onChange:v=>f({...m,description:v.target.value})})]})]}),e.jsxs(Sr,{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"})]})]})})]})},Chn=(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}),Ahn=()=>{const{user:s}=bs();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})},PWt=(s,t)=>{const{user:n}=bs(),r=Wt(),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"]}),re.success("Contact added to Lead Pond")},onError:c=>{re.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"]}),re.success("Lead claimed and added to your contacts, tagged with the pond name. Your notes and follow-ups stay visible to your team leader and the agent who shared it.")},onError:c=>{re.error(c.message)}}),o=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"]}),re.success("Lead returned to pond")},onError:c=>{re.error(c.message)}});return{leadPondItems:a.data||[],isLoading:a.isLoading,addToLeadPond:i,claimLead:l,returnLead:o}},Ehn=(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}),Thn=()=>{const s=Wt();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"]}),re.success("Contact transferred successfully")},onError:t=>{re.error(t.message||"Failed to transfer contact")}})};function IWt({open:s,onOpenChange:t,contactIds:n,contactNames:r=[],onComplete:a}){var A;const{user:i}=bs(),{data:l}=zw(),{useTeamMembers:o}=u3(),{data:c=[]}=o((l==null?void 0:l.teamId)||""),d=Thn(),[u,h]=j.useState(null),[m,f]=j.useState(""),[g,x]=j.useState(!1),y=c.filter(E=>E.user_id!==(i==null?void 0:i.id)),v=async()=>{if(u){x(!0);try{for(const E of n)await d.mutateAsync({contactId:E,toUserId:u,notes:m||void 0});t(!1),h(null),f(""),a==null||a()}catch{}finally{x(!1)}}},b=y.find(E=>E.user_id===u),w=n.length>1,S=r.length>0?w?`${r.length} contacts`:r[0]:w?`${n.length} contacts`:"this contact";return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(C4,{className:"h-5 w-5"}),"Transfer ",S]}),e.jsxs(Pr,{children:["Select a team member to transfer ",w?"these contacts":"this contact"," to. The contact will be removed from the current owner's CRM and added to the selected member's."]})]}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm font-medium mb-2 block",children:"Transfer to:"}),e.jsx("div",{className:"space-y-1 max-h-[240px] overflow-y-auto",children:y.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No other team members available"}):y.map(E=>{var I,P,R;return e.jsxs("button",{onClick:()=>h(E.user_id),className:`w-full flex items-center gap-3 p-3 rounded-lg text-left transition-colors ${u===E.user_id?"bg-primary/10 border border-primary/30":"hover:bg-accent border border-transparent"}`,children:[e.jsxs(Oa,{className:"h-8 w-8",children:[e.jsx(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(Ls,{id:"transfer-notes",value:m,onChange:E=>f(E.target.value),placeholder:"Reason for transfer...",className:"mt-1",rows:2})]})]}),e.jsxs(Sr,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{onClick:v,disabled:!u||g,children:[g?e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(C4,{className:"h-4 w-4 mr-2"}),"Transfer",b?` to ${(A=b.profile)==null?void 0:A.name}`:""]})]})]})})}const aRe=()=>{const s=Xn(),{data:t,isLoading:n}=Ahn(),{data:r}=zw(),[a,i]=j.useState(""),[l,o]=j.useState("all"),[c,d]=j.useState(null),[u,h]=j.useState(""),m=(r==null?void 0:r.role)==="team_leader",f=j.useMemo(()=>{if(!t)return[];const x=new Map;return t.forEach(y=>{x.has(y.owner_user_id)||x.set(y.owner_user_id,{id:y.owner_user_id,name:y.owner_name||"Unknown",avatar:y.owner_avatar_url})}),Array.from(x.values())},[t]),g=j.useMemo(()=>{if(!t)return[];let x=t;if(l!=="all"&&(x=x.filter(y=>y.owner_user_id===l)),a.trim()){const y=a.toLowerCase();x=x.filter(v=>{var b,w,S;return(v.first_name+" "+(v.last_name||"")).toLowerCase().includes(y)||((b=v.email)==null?void 0:b.toLowerCase().includes(y))||((w=v.phone)==null?void 0:w.includes(y))||((S=v.owner_name)==null?void 0:S.toLowerCase().includes(y))})}return x},[t,a,l]);return n?e.jsxs("div",{className:"space-y-4",children:[e.jsx(xn,{className:"h-10 w-full"}),e.jsx(xn,{className:"h-64 w-full"})]}):!t||t.length===0?e.jsx(je,{children:e.jsxs(Ie,{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(Ie,{className:"p-4",children:e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Zr,{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(Ie,{className:"p-0 overflow-x-auto",children:e.jsxs(hi,{className:"min-w-[800px]",children:[e.jsx(mi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Name"}),e.jsx(Dt,{children:"Agent"}),e.jsx(Dt,{children:"Contact Info"}),e.jsx(Dt,{children:"Address"}),e.jsx(Dt,{children:"Lead Source"}),e.jsx(Dt,{children:"Date Added"}),m&&e.jsx(Dt,{className:"w-[80px]",children:"Actions"})]})}),e.jsx(fi,{children:g.length===0?e.jsx(En,{children:e.jsx(_t,{colSpan:m?7:6,className:"text-center py-8 text-muted-foreground",children:a||l!=="all"?"No contacts match your filters":"No team contacts available"})}):g.map(x=>e.jsxs(En,{className:`hover:bg-accent/50 ${m?"cursor-pointer":""}`,onClick:m?()=>s(`/mission-control/contacts/${x.id}`):void 0,children:[e.jsx(_t,{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(_t,{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(_t,{children:e.jsxs("div",{className:"space-y-1 text-sm",children:[x.email&&e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(mn,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate",children:x.email})]}),x.phone&&e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(Da,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{children:x.phone})]}),!x.email&&!x.phone&&e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"No contact info"})]})}),e.jsx(_t,{children:x.address?e.jsxs("div",{className:"flex items-center gap-1 text-sm text-muted-foreground",children:[e.jsx(ci,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate max-w-[180px]",children:x.address})]}):e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"—"})}),e.jsx(_t,{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(_t,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:en(new Date(x.created_at),"MMM d, yyyy")})}),m&&e.jsx(_t,{children:e.jsx($,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:y=>{y.stopPropagation(),d(x.id),h(`${x.first_name} ${x.last_name||""}`.trim())},title:"Transfer to team member",children:e.jsx(C4,{className:"h-4 w-4"})})})]},x.id))})]})})}),e.jsx(IWt,{open:!!c,onOpenChange:x=>{x||d(null)},contactIds:c?[c]:[],contactNames:u?[u]:[],onComplete:()=>d(null)})]})},Mhn=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)},Phn=({leadPondId:s})=>{const{data:t,isLoading:n,error:r}=Chn(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(e7,{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:Mhn(a.occurred_at)})]})]},i))})},Ihn=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)):"",Lhn=s=>{var n;const t=((n=s.contact_name)==null?void 0:n.trim())||"A lead";switch(s.event_type){case"claimed":return{icon:Lq,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:Ax,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:g1,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"]})}}},Lwt=({teamId:s,pondId:t})=>{const{data:n,isLoading:r}=Ehn(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(Aw,{className:"h-4 w-4"}),"Pond Activity History"]})}),e.jsx(Ie,{className:"space-y-3",children:r?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(c=>e.jsx(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=Lhn(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:Ihn(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(yb,{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`]})]})})]})},Rhn=s=>s?new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric"}).format(new Date(s)):null,Dhn=({item:s,isClaimer:t,onReturn:n,returning:r})=>{var o,c,d;const[a,i]=j.useState(!1),l=Rhn(s.last_activity_at);return e.jsx(je,{children:e.jsxs(Ie,{className:"space-y-3 p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0 space-y-1.5",children:[e.jsxs("p",{className:"text-sm font-medium",children:[(o=s.contact)==null?void 0:o.first_name," ",((c=s.contact)==null?void 0:c.last_name)||""]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs($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(da,{className:"h-3 w-3"}),l?`Last activity ${l}`:"No activity yet"]})]}),t&&e.jsxs("p",{className:"flex items-center gap-1 text-[11px] text-muted-foreground",children:[e.jsx(Ca,{className:"h-3 w-3"}),"Your notes and follow-ups on this lead are visible to the team leader and the agent who shared it."]})]}),t&&e.jsxs($,{size:"sm",variant:"outline",onClick:n,disabled:r,children:[e.jsx(Ax,{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(yb,{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(Phn,{leadPondId:s.id})]})]})})},iRe=({teamId:s})=>{const{user:t}=bs(),[n,r]=j.useState(null),{ponds:a}=Drt(s),i=a.filter(f=>f.has_access),{leadPondItems:l,isLoading:o,claimLead:c,returnLead:d}=PWt(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(g1,{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(Ie,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(g1,{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(Lwt,{teamId:s,pondId:n})]});const h=l.filter(f=>f.status==="available"),m=l.filter(f=>f.status==="claimed");return e.jsxs("div",{className:"space-y-6",children:[u,e.jsxs("div",{children:[e.jsxs("h3",{className:"text-sm font-semibold text-muted-foreground mb-3",children:["Available (",h.length,")"]}),h.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No leads available right now."}):e.jsx("div",{className:"space-y-2",children:h.map(f=>{var g,x,y,v,b,w,S,A,E,I,P;return e.jsx(je,{children:e.jsxs(Ie,{className:"flex flex-col gap-3 p-4 sm:flex-row sm:items-start sm:justify-between",children:[e.jsxs("div",{className:"min-w-0 space-y-1.5",children:[e.jsxs("p",{className:"font-medium text-sm",children:[((g=f.contact)==null?void 0:g.first_name)||"Unnamed"," ",((x=f.contact)==null?void 0:x.last_name)||""]}),e.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1",children:[((y=f.contact)==null?void 0:y.email)&&e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(mn,{className:"h-3 w-3"})," ",f.contact.email]}),((v=f.contact)==null?void 0:v.phone)&&e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Da,{className:"h-3 w-3"})," ",f.contact.phone]}),((b=f.contact)==null?void 0:b.address)&&e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(ci,{className:"h-3 w-3"})," ",f.contact.address]})]}),f.pond_name&&n===null&&i.length>1&&e.jsxs($e,{variant:"secondary",className:"text-[10px]",children:[e.jsx(g1,{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(e7,{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(Lq,{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(Dhn,{item:f,isClaimer:f.claimed_by===(t==null?void 0:t.id),onReturn:()=>d.mutate(f.id),returning:d.isPending},f.id))})]}),e.jsx(Lwt,{teamId:s,pondId:n})]})},Frt=({teamId:s})=>{const{useTeamMembers:t}=u3(),{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(Ie,{className:"flex items-center gap-3 p-4",children:[e.jsx(bb,{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(Ie,{className:"flex items-center gap-3 p-4",children:[e.jsx(va,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:o.length}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Guest Books"})]})]})}),e.jsx(je,{children:e.jsxs(Ie,{className:"flex items-center gap-3 p-4",children:[e.jsx(ua,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:d.length}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Videos"})]})]})})]}),e.jsxs(ha,{defaultValue:"presentations",className:"space-y-4",children:[e.jsxs(ma,{children:[e.jsxs(Zt,{value:"presentations",children:["Presentations (",i.length,")"]}),e.jsxs(Zt,{value:"guest-books",children:["Guest Books (",o.length,")"]}),e.jsxs(Zt,{value:"videos",children:["Videos (",d.length,")"]})]}),e.jsx(Xt,{value:"presentations",className:"space-y-2",children:i.length===0?e.jsx(JBe,{icon:e.jsx(bb,{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(Ie,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsxs(Oa,{className:"h-8 w-8 shrink-0",children:[e.jsx(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," · ",en(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(Ca,{className:"h-3 w-3"}),f.view_count||0]})]})]})},f.id)})}),e.jsx(Xt,{value:"guest-books",className:"space-y-2",children:o.length===0?e.jsx(JBe,{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(Ie,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsxs(Oa,{className:"h-8 w-8 shrink-0",children:[e.jsx(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," · ",en(new Date(f.event_date),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[f.is_active?e.jsx($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(Xt,{value:"videos",className:"space-y-2",children:d.length===0?e.jsx(JBe,{icon:e.jsx(ua,{className:"h-10 w-10"}),label:"No videos yet"}):d.map(f=>{const g=m(f.owner_user_id);return e.jsx(je,{children:e.jsxs(Ie,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsxs(Oa,{className:"h-8 w-8 shrink-0",children:[e.jsx(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," · ",en(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(Ca,{className:"h-3 w-3"}),f.view_count||0]})]})]})},f.id)})})]})]})},JBe=({icon:s,label:t})=>e.jsx(je,{children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center py-8 text-center text-muted-foreground",children:[s,e.jsx("p",{className:"mt-2 text-sm",children:t})]})}),LWt=({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}=u3(),{data:h=[],isLoading:m}=u(s.id),[f,g]=j.useState(!1),[x,y]=j.useState(""),[v,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,v),y(""),b("team_member"),g(!1))};return e.jsxs("div",{className:"space-y-6",children:[e.jsx($,{variant:"ghost",onClick:n,className:"mb-2",children:"← Back to Teams"}),e.jsxs(ha,{defaultValue:"members",className:"space-y-4",children:[e.jsxs(ma,{children:[e.jsx(Zt,{value:"members",children:"Members"}),e.jsxs(Zt,{value:"contacts",children:[e.jsx(UI,{className:"mr-1 h-3.5 w-3.5"}),"Team Contacts"]}),s.lead_pond_enabled&&e.jsxs(Zt,{value:"lead-pond",children:[e.jsx(g1,{className:"mr-1 h-3.5 w-3.5"}),"Lead Pond"]}),s.shared_assets_enabled&&e.jsxs(Zt,{value:"shared-assets",children:[e.jsx(kv,{className:"mr-1 h-3.5 w-3.5"}),"Shared Assets"]}),e.jsx(Zt,{value:"settings",children:"Settings"})]}),e.jsxs(Xt,{value:"members",className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h3",{className:"text-lg font-semibold",children:[s.name," — Members"]}),e.jsxs(zs,{open:f,onOpenChange:g,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{size:"sm",children:[e.jsx(lc,{className:"mr-2 h-4 w-4"}),"Add Member"]})}),e.jsxs(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Add Team Member"}),e.jsxs(Pr,{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(Kd,{children:[e.jsx(Yd,{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(Sw,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Od,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(S2,{children:[e.jsx(C2,{placeholder:"Search agents..."}),e.jsxs(A2,{children:[e.jsx(E2,{children:"No agents found."}),e.jsx(Dw,{children:A.map(R=>{const D=w==null?void 0:w.get(R.id);return e.jsxs(m1,{value:R.name||R.email||R.id,onSelect:()=>y(R.id),children:[e.jsx(ca,{className:Pt("mr-2 h-4 w-4",x===R.id?"opacity-100":"opacity-0")}),R.name||R.email,D!=null&&D.length?e.jsxs("span",{className:"text-xs text-muted-foreground ml-1",children:["(also on ",D.join(", "),")"]}):null]},R.id)})})]})]})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Role"}),e.jsxs(ms,{value:v,onValueChange:b,children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"team_leader",children:"Team Leader"}),e.jsx(Ge,{value:"team_member",children:"Team Member"})]})]})]})]}),e.jsxs(Sr,{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(Ie,{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(Ie,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(Oa,{className:"h-10 w-10",children:[e.jsx(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(Bg,{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(Tg,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-muted-foreground hover:text-destructive",children:e.jsx(cV,{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(Xt,{value:"contacts",className:"space-y-4",children:e.jsx(aRe,{})}),s.lead_pond_enabled&&e.jsx(Xt,{value:"lead-pond",className:"space-y-4",children:e.jsx(iRe,{teamId:s.id})}),s.shared_assets_enabled&&e.jsx(Xt,{value:"shared-assets",className:"space-y-4",children:e.jsx(Frt,{teamId:s.id})}),e.jsxs(Xt,{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(Gn,{children:"Configure how this team operates."})]}),e.jsxs(Ie,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Team Name"}),e.jsx(pe,{defaultValue:s.name,onBlur:R=>{R.target.value!==s.name&&r({name:R.target.value})}})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Description"}),e.jsx(Ls,{defaultValue:s.description||"",onBlur:R=>{R.target.value!==(s.description||"")&&r({description:R.target.value||null})},rows:3})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Contact Visibility"}),e.jsxs(ms,{defaultValue:s.contact_visibility,onValueChange:R=>r({contact_visibility:R}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"private",children:"Private — Members keep their contacts private"}),e.jsx(Ge,{value:"leader_only",children:"Leader Only — Only team leaders can see member contacts"}),e.jsx(Ge,{value:"full_team",children:"Full Team — All team members can see shared contacts"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Controls whether team leaders and members can view each other's contacts."})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Lead Pond"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Enable a shared lead pool where leaders can drop leads for members to claim."})]}),e.jsx(Sn,{checked:s.lead_pond_enabled,onCheckedChange:R=>r({lead_pond_enabled:R})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Shared Assets"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Allow team members to access shared presentations, guest books, and videos."})]}),e.jsx(Sn,{checked:s.shared_assets_enabled,onCheckedChange:R=>r({shared_assets_enabled:R})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Shared Video Library"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Let team members browse and use each other's videos from the Video Library."})]}),e.jsx(Sn,{checked:s.shared_videos_enabled??!1,onCheckedChange:R=>r({shared_videos_enabled:R})})]})]})]}),s.lead_pond_enabled&&e.jsx(MWt,{teamId:s.id}),e.jsxs(fc,{children:[e.jsx(Tg,{asChild:!0,children:e.jsxs($,{variant:"destructive",size:"sm",children:[e.jsx(Hn,{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"})]})]})]})]})]})]})},RWt=({open:s,onOpenChange:t,onCreateTeam:n,isCreating:r,brokerageAgents:a,isAdmin:i,allBrokerages:l,activeBrokerageId:o})=>{const[c,d]=j.useState(1),[u,h]=j.useState(""),[m,f]=j.useState(""),[g,x]=j.useState(""),[y,v]=j.useState(""),[b,w]=j.useState([]),S=()=>{d(1),h(""),f(""),x(""),v(""),w([])},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:y||void 0,memberIds:b.length>0?b:void 0}),S()},I=R=>{R!==y&&w(D=>D.includes(R)?D.filter(O=>O!==R):[...D,R])},P=a.filter(R=>R.id!==y);return e.jsx(zs,{open:s,onOpenChange:A,children:e.jsxs(Os,{className:"sm:max-w-lg max-h-[90vh] flex flex-col",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:c===1?"Create New Team":"Assign Team Members"}),e.jsx(Pr,{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(Ls,{id:"team-desc",value:m,onChange:R=>f(R.target.value),placeholder:"What is this team focused on?",rows:3})]}),i&&l&&l.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Brokerage"}),e.jsxs(ms,{value:g,onValueChange:x,children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"No brokerage (independent team)"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"none",children:"No brokerage (independent)"}),l.map(R=>e.jsx(Ge,{value:R.id,children:R.name},R.id))]})]})]})]}):e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{className:"flex items-center gap-1.5",children:[e.jsx(Bg,{className:"h-3.5 w-3.5 text-[hsl(var(--chart-4))]"}),"Team Leader"]}),e.jsxs(ms,{value:y,onValueChange:R=>{v(R),w(D=>D.filter(O=>O!==R))},children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Select a team leader (optional)"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"none",children:"No leader for now"}),a.map(R=>e.jsx(Ge,{value:R.id,children:R.name||R.email||"Unknown"},R.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{className:"flex items-center gap-1.5",children:[e.jsx(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(ca,{className:"h-3 w-3"})})]},R.id)})})]})]})}),e.jsx(Sr,{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"})]})})]})})},Fhn=()=>{const{teams:s,isLoading:t,createTeam:n,updateTeam:r,deleteTeam:a,addMember:i,removeMember:l,updateMemberRole:o}=u3(),[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}),y=(u==null?void 0:u.brokerage_id)||null,{data:v}=st({queryKey:["brokerage-agents-for-teams",y],queryFn:async()=>{let A=q.from("profiles").select("id, name, email, avatar_url").order("name");y&&(A=A.eq("brokerage_id",y));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(LWt,{team:u,brokerageAgents:v||[],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(Zr,{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(dn,{className:"mr-2 h-4 w-4"}),"Create Team"]})]}),e.jsx(RWt,{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(En,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Dt,{className:"font-semibold",children:"Team Name"}),e.jsx(Dt,{className:"font-semibold",children:"Brokerage"}),e.jsx(Dt,{className:"font-semibold",children:"Leader"}),e.jsx(Dt,{className:"font-semibold",children:"Members"}),e.jsx(Dt,{className:"font-semibold",children:"Visibility"}),e.jsx(Dt,{className:"w-[100px]"})]})}),e.jsx(fi,{children:t?e.jsx(e.Fragment,{children:[1,2,3].map(A=>e.jsxs(En,{children:[e.jsx(_t,{children:e.jsx(xn,{className:"h-4 w-32"})}),e.jsx(_t,{children:e.jsx(xn,{className:"h-4 w-24"})}),e.jsx(_t,{children:e.jsx(xn,{className:"h-4 w-28"})}),e.jsx(_t,{children:e.jsx(xn,{className:"h-4 w-12"})}),e.jsx(_t,{children:e.jsx(xn,{className:"h-4 w-20"})}),e.jsx(_t,{children:e.jsx(xn,{className:"h-4 w-16"})})]},A))}):S.length===0?e.jsx(En,{children:e.jsx(_t,{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(En,{className:"hover:bg-muted/30",children:[e.jsxs(_t,{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(_t,{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(_t,{children:E!=null&&E.leaderName?e.jsxs("span",{className:"text-sm flex items-center gap-1",children:[e.jsx(Bg,{className:"h-3 w-3 text-[hsl(var(--chart-4))]"}),E.leaderName]}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"No leader"})}),e.jsx(_t,{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(_t,{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(_t,{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 fo(`Delete team "${A.name}"? This cannot be undone.`)&&a.mutate(A.id)},title:"Delete team",children:e.jsx(Hn,{className:"h-3.5 w-3.5"})})]})})]},A.id)})})]})})]})};function Rwt(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 Ohn({open:s,onOpenChange:t,recipients:n}){const{toast:r}=Bi(),[a,i]=j.useState([]),[l,o]=j.useState(!1),[c,d]=j.useState(""),[u,h]=j.useState(""),[m,f]=j.useState(""),[g,x]=j.useState(!1),[y,v]=j.useState(!1),b=j.useMemo(()=>a.find(E=>E.id===c)||null,[a,c]);j.useEffect(()=>{s&&(o(!0),(async()=>{const E=new Date().toISOString(),{data:I,error:P}=await q.from("events").select("id,title,description,event_date,zoom_link,image_url,is_published").gte("event_date",E).order("event_date",{ascending:!0}).limit(50);P?r({title:"Could not load events",description:P.message,variant:"destructive"}):i(I||[]),o(!1)})())},[s,r]);const w=j.useMemo(()=>n.filter(E=>E.email&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(E.email)),[n]),S=()=>{if(!b){r({title:"Pick an event first",variant:"destructive"});return}if(w.length===0){r({title:"No valid recipient emails",variant:"destructive"});return}v(!0)},A=async()=>{if(b){v(!1),x(!0);try{const{data:{session:E}}=await q.auth.getSession(),I=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/admin-send-event-invite",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${E==null?void 0:E.access_token}`},body:JSON.stringify({event_id:b.id,recipients:w.map(U=>({email:U.email,name:U.name,user_id:U.id})),custom_subject:u.trim()||void 0,custom_intro:m.trim()||void 0})}),P=await I.json().catch(()=>({}));if(!I.ok)throw new Error((P==null?void 0:P.error)||"Failed to send event invite");const R=(P==null?void 0:P.sent)??0,D=(P==null?void 0:P.failed)??0,O=(P==null?void 0:P.already_invited)??0;r({title:"Invites sent",description:`Sent: ${R}${O?` · Skipped (already invited): ${O}`:""}${D?` · Failed: ${D}`:""}`}),t(!1),f(""),h(""),d("")}catch(E){const I=E instanceof Error?E.message:"Send failed";r({title:"Send failed",description:I,variant:"destructive"})}finally{x(!1)}}};return e.jsxs(e.Fragment,{children:[e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(mn,{className:"h-5 w-5 text-primary"}),"Send Event Invite"]}),e.jsxs(Pr,{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:[Rwt(E.event_date),!E.is_published&&" · (Draft)"]})]})},E.id))})]})]}),b&&e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3 space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(Ta,{className:"h-4 w-4 text-primary"}),b.title]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Rwt(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(Ls,{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(Sr,{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(Kr,{className:"h-4 w-4 mr-2"})," Send to ",w.length]})})]})]})}),e.jsx(fc,{open:y,onOpenChange:v,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(Kr,{className:"h-4 w-4 mr-2"})," Send"]})]})]})})]})}const zhn=()=>{var au;const s=Xn(),{user:t,isAdmin:n}=bs(),{startImpersonation:r,isLoading:a}=uLe(),{toast:i}=Bi(),[l,o]=j.useState([]),[c,d]=j.useState([]),[u,h]=j.useState([]),[m,f]=j.useState({}),[g,x]=j.useState(!0),[y,v]=j.useState({}),[b,w]=j.useState(!1),[S,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"),[Y,X]=j.useState(!1),[ae,le]=j.useState(!1),[ne,te]=j.useState({done:0,total:0}),[J,ce]=j.useState(null),[_e,he]=j.useState("all"),[ue,ve]=j.useState("all"),[Ee,Se]=j.useState("all"),[Le,Fe]=j.useState("all"),[ke,Be]=j.useState(!1),[Ne,Ae]=j.useState(!1),[Ce,Ve]=j.useState(!1),[ze,qe]=j.useState(""),[dt,Xe]=j.useState(!1),[at,rt]=j.useState(null),[Ke,Je]=j.useState(null),[pt,gt]=j.useState(!1),[ss,Yt]=j.useState({name:"",email:"",brokerage_id:"",phone:""}),[ts,ys]=j.useState(null),[Bt,Ft]=j.useState(!1),[as,kt]=j.useState(""),[Ks,wt]=j.useState(!1),[gs,ks]=j.useState(!1),[Is,Xs]=j.useState(null),[ds,Ss]=j.useState(""),[yn,Js]=j.useState(!1),[Ut,hn]=j.useState(!1),[hr,Rs]=j.useState(null),[jr,kr]=j.useState(!1),[$n,kn]=j.useState(!1),[Fn,bn]=j.useState(null),[xs,Lr]=j.useState(""),[Or,la]=j.useState(!1),[Qn,Cr]=j.useState({email:"",name:"",password:"",phone:""}),[Un,dr]=j.useState(!1),[Pa,ii]=j.useState(null),[$i,Rn]=j.useState([]),[xa,Ya]=j.useState("none"),[ho,Tc]=j.useState(!1),[zd,Nl]=j.useState(""),[Ho,ti]=j.useState(!1),[Xr,Eo]=j.useState(!1),[Th,ah]=j.useState(""),[ao,ta]=j.useState(new Set),[xc,fl]=j.useState(!1),[Co,fu]=j.useState(!1),[cc,nd]=j.useState(null),[zr,Hi]=j.useState(!1),[zc,Bc]=j.useState(null),[yc,$l]=j.useState([]),[rg,Ix]=j.useState([]),[Yo,Mc]=j.useState(!1),[Mh,lm]=j.useState({});j.useEffect(()=>{if(!t||!n){t&&!n&&x(!1);return}_s(),Xa()},[t,n]);const Yc=async()=>{try{const{data:qt,error:Cn}=await q.from("brokerage_manager_assignments").select("user_id, brokerage_id");if(Cn)throw Cn;const rr={};for(const ra of qt??[])rr[ra.brokerage_id]||(rr[ra.brokerage_id]=[]),rr[ra.brokerage_id].push(ra.user_id);f(rr)}catch(qt){console.error("Error loading brokerage manager assignments:",qt)}},_s=async()=>{try{x(!0);const{data:qt,error:Cn}=await q.functions.invoke("get-user-details");if(Cn)throw Cn;const rr=qt.users||[];o(rr),h(qt.brokerages||[]),await Yc();const ra=rr.filter(Yr=>Yr.roles.includes("assistant"));if(ra.length>0){const Yr=ra.map(gi=>gi.id),{data:Aa}=await q.from("agent_assistant_assignments").select("agent_id, assistant_id").in("assistant_id",Yr);if(Aa&&Aa.length>0){const gi=[...new Set(Aa.map(zo=>zo.agent_id))],{data:Ia}=await q.from("profiles").select("id, name, email").in("id",gi),el={};for(const zo of Aa){const Pc=Ia==null?void 0:Ia.find(Tu=>Tu.id===zo.agent_id);Pc&&(el[zo.assistant_id]={agent_name:Pc.name||"",agent_email:Pc.email||""})}lm(el)}}}catch(qt){console.error("Error loading members:",qt),i({title:"Error",description:"Failed to load members",variant:"destructive"})}finally{x(!1)}},Xa=async()=>{try{const{data:qt,error:Cn}=await q.from("app_tiles").select("id, name, icon, app_id, required_tags").order("name");if(Cn)throw Cn;d(qt||[])}catch(qt){console.error("Error loading apps:",qt),i({title:"Error",description:"Failed to load apps",variant:"destructive"})}},No=async qt=>{if(!ss.name.trim()||!ss.email.trim()){i({title:"Error",description:"Name and email are required",variant:"destructive"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(ss.email)){i({title:"Error",description:"Please enter a valid email address",variant:"destructive"});return}try{const{error:rr}=await q.from("profiles").update({name:ss.name.trim(),email:ss.email.trim(),brokerage_id:ss.brokerage_id||null,phone:ss.phone.trim()||null}).eq("id",qt);if(rr)throw rr;i({title:"Success",description:"Member details updated successfully"}),rt(null),_s()}catch(rr){console.error("Error updating member:",rr),i({title:"Error",description:rr.message||"Failed to update member",variant:"destructive"})}},Ba=async qt=>{try{const{data:{session:Cn}}=await q.auth.getSession(),rr=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Cn==null?void 0:Cn.access_token}`},body:JSON.stringify({userId:qt})}),ra=await rr.json();if(!rr.ok)throw new Error(ra.error||"Failed to resend welcome email");i({title:"Success",description:"Welcome email sent successfully"})}catch(Cn){console.error("Error resending welcome email:",Cn),i({title:"Error",description:Cn.message||"Failed to resend welcome email",variant:"destructive"})}},io=async(qt,Cn)=>{try{const{error:rr}=await q.functions.invoke("send-password-reset",{body:{email:qt,redirectTo:"https://dashboard.relevelup.com/profile?reset=true"}});if(rr)throw rr;i({title:"Password Reset Sent",description:`Password reset email sent to ${Cn}`})}catch(rr){console.error("Error sending password reset:",rr),i({title:"Error",description:rr.message||"Failed to send password reset email",variant:"destructive"})}},ko=async(qt,Cn)=>{if(await fo(`Are you sure you want to delete ${Cn}? This action cannot be undone.`))try{const{data:{session:rr}}=await q.auth.getSession(),ra=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/delete-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${rr==null?void 0:rr.access_token}`},body:JSON.stringify({userId:qt})}),Yr=await ra.json();if(!ra.ok)throw new Error(Yr.error||"Failed to delete user");i({title:"Success",description:"User deleted successfully"}),_s()}catch(rr){console.error("Error deleting user:",rr),i({title:"Error",description:rr.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:qt}}=await q.auth.getSession(),Cn=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${qt==null?void 0:qt.access_token}`},body:JSON.stringify(S)}),rr=await Cn.json();if(!Cn.ok)throw new Error(rr.error||"Failed to create user");if(S.role&&S.role!=="user"&&rr.userId){const ra=S.role==="brokerage_manager"?S.brokerage_id:void 0;await cm(rr.userId,S.role,"add",ra)}i({title:"Success",description:`User ${S.email} created successfully`}),A({email:"",name:"",password:"",brokerage_id:"",role:"user",phone:"",trial_days:""}),I(!1),_s()}catch(qt){console.error("Error creating user:",qt),i({title:"Error",description:qt.message||"Failed to create user",variant:"destructive"})}finally{w(!1)}},cm=async(qt,Cn,rr,ra)=>{try{const{data:{session:Yr}}=await q.auth.getSession(),Aa={userId:qt,role:Cn,action:rr};if(Cn==="brokerage_manager"){if(!ra){i({title:"Error",description:"Please choose a brokerage for this manager assignment",variant:"destructive"});return}Aa.brokerageId=ra}const gi=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Yr==null?void 0:Yr.access_token}`},body:JSON.stringify(Aa)}),Ia=await gi.json();if(!gi.ok)throw new Error(Ia.error||"Failed to manage user role");i({title:"Success",description:`Role ${rr==="add"?"added":"removed"} successfully`}),_s()}catch(Yr){console.error("Error managing user role:",Yr),i({title:"Error",description:Yr.message||"Failed to manage user role",variant:"destructive"})}},Zo=(qt,Cn)=>Cn.length===0?!0:Cn.some(rr=>qt.includes(rr)),vo=async(qt,Cn,rr)=>{const ra=`${qt}-${Cn.id}`;ys(ra);try{if(rr){const Yr=l.find(gi=>gi.id===qt),Aa=Cn.required_tags.filter(gi=>Yr==null?void 0:Yr.tags.includes(gi));for(const gi of Aa){const{error:Ia}=await q.from("user_tags").delete().eq("user_id",qt).eq("tag",gi);if(Ia)throw Ia}i({title:"Access Removed",description:`Removed access to ${Cn.name}`})}else if(Cn.required_tags.length>0){const{error:Yr}=await q.from("user_tags").insert({user_id:qt,tag:Cn.required_tags[0]});if(Yr)throw Yr;i({title:"Access Granted",description:`Granted access to ${Cn.name}`})}await _s()}catch(Yr){console.error("Error toggling access:",Yr),i({title:"Error",description:Yr.message||"Failed to update access",variant:"destructive"})}finally{ys(null)}},Zg=async()=>{const qt=as.trim();if(!qt){i({title:"Error",description:"Brokerage name is required",variant:"destructive"});return}if(qt.length>100){i({title:"Error",description:"Brokerage name must be less than 100 characters",variant:"destructive"});return}if(u.find(rr=>rr.name.toLowerCase()===qt.toLowerCase())){i({title:"Error",description:"A brokerage with this name already exists",variant:"destructive"});return}wt(!0);try{const{error:rr}=await q.from("brokerages").insert({name:qt});if(rr)throw rr;i({title:"Success",description:`Brokerage "${qt}" created successfully`}),kt(""),Ft(!1),_s()}catch(rr){console.error("Error creating brokerage:",rr),i({title:"Error",description:rr.message||"Failed to create brokerage",variant:"destructive"})}finally{wt(!1)}},Fl=qt=>{Xs(qt),Ss(qt.name),ks(!0)},Ol=()=>{Xs(null),Ss(""),ks(!1)},xy=async()=>{if(!Is)return;const qt=ds.trim();if(!qt){i({title:"Error",description:"Brokerage name is required",variant:"destructive"});return}if(qt.length>100){i({title:"Error",description:"Brokerage name must be less than 100 characters",variant:"destructive"});return}Js(!0);try{const{error:Cn}=await q.from("brokerages").update({name:qt}).eq("id",Is.id);if(Cn)throw Cn;i({title:"Success",description:"Brokerage updated successfully"}),Ol(),_s()}catch(Cn){console.error("Error updating brokerage:",Cn),i({title:"Error",description:Cn.message||"Failed to update brokerage",variant:"destructive"})}finally{Js(!1)}},Zd=async(qt,Cn)=>{var rr;if(!Cn||typeof Cn!="string"){i({title:"Error",description:"Please select a brokerage first",variant:"destructive"});return}try{const ra={userId:qt,role:"brokerage_manager",action:"add",brokerageId:Cn};console.debug("[assignManagerToBrokerage] payload",ra);const{data:{session:Yr}}=await q.auth.getSession(),Aa=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Yr==null?void 0:Yr.access_token}`},body:JSON.stringify(ra)}),gi=await Aa.json();if(!Aa.ok&&!((rr=gi.error)!=null&&rr.includes("duplicate")))throw new Error(gi.error||"Failed to add role");i({title:"Success",description:"Manager assigned to brokerage"}),await _s()}catch(ra){console.error("Error assigning manager:",ra),i({title:"Error",description:ra.message||"Failed to assign manager",variant:"destructive"})}},Vh=qt=>{Rs(qt),hn(!0)},cf=async()=>{if(hr){kr(!0);try{const qt=l.filter(ra=>ra.brokerage_id===hr.id),{data:{session:Cn}}=await q.auth.getSession();for(const ra of qt){const Yr=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/delete-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Cn==null?void 0:Cn.access_token}`},body:JSON.stringify({userId:ra.id})});if(!Yr.ok){const Aa=await Yr.json();console.error(`Failed to delete user ${ra.email}:`,Aa.error)}}const{error:rr}=await q.from("brokerages").delete().eq("id",hr.id);if(rr)throw rr;i({title:"Success",description:`Brokerage "${hr.name}" and ${qt.length} member(s) deleted`}),hn(!1),Rs(null),_s()}catch(qt){console.error("Error deleting brokerage:",qt),i({title:"Error",description:qt.message||"Failed to delete brokerage",variant:"destructive"})}finally{kr(!1)}}},Ky=qt=>{bn(qt),Lr(""),kn(!0)},ih=()=>{bn(null),Lr(""),kn(!1)},gh=async qt=>{try{const{error:Cn}=await q.from("profiles").update({brokerage_id:null}).eq("id",qt);if(Cn)throw Cn;i({title:"Success",description:"User removed from brokerage"}),_s()}catch(Cn){console.error("Error removing user from brokerage:",Cn),i({title:"Error",description:Cn.message||"Failed to remove user",variant:"destructive"})}},xt=async(qt,Cn)=>{try{const{error:rr}=await q.from("profiles").update({brokerage_id:Cn}).eq("id",qt);if(rr)throw rr;i({title:"Success",description:"User added to brokerage"}),_s()}catch(rr){console.error("Error adding user to brokerage:",rr),i({title:"Error",description:rr.message||"Failed to add user",variant:"destructive"})}};j.useEffect(()=>{(async()=>{var Cn;if(!(Fn!=null&&Fn.id)){ii(null),Rn([]),Ya("none");return}try{const{data:rr}=await q.from("partnership_programs").select("id, name, enabled").eq("brokerage_id",Fn.id).maybeSingle();if(!rr||!rr.enabled){ii(null),Rn([]),Ya("none");return}const{data:ra}=await q.from("partnership_packages").select("id, name, description, sort_order").eq("program_id",rr.id).order("sort_order",{ascending:!0});ii({id:rr.id,name:rr.name}),Rn(ra||[]),Ya(((Cn=ra==null?void 0:ra[0])==null?void 0:Cn.id)||"none")}catch(rr){console.error("Error loading partnership packages:",rr)}})()},[Fn==null?void 0:Fn.id]);const We=async()=>{if(!Fn||!Qn.email||!Qn.name||!Qn.password){i({title:"Error",description:"Please fill in all fields",variant:"destructive"});return}dr(!0);try{const{data:{session:qt}}=await q.auth.getSession(),Cn=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${qt==null?void 0:qt.access_token}`},body:JSON.stringify({...Qn,brokerage_id:Fn.id,role:"user",partnershipPackageId:Pa&&xa!=="none"?xa:void 0})}),rr=await Cn.json();if(!Cn.ok)throw new Error(rr.error||"Failed to create agent");i({title:"Success",description:`Agent ${Qn.email} created successfully`}),Cr({email:"",name:"",password:"",phone:""}),la(!1),_s()}catch(qt){console.error("Error creating agent:",qt),i({title:"Error",description:qt.message||"Failed to create agent",variant:"destructive"})}finally{dr(!1)}},ct=qt=>l.filter(Cn=>Cn.brokerage_id===qt),jt=qt=>{const Cn=ct(qt);if(!xs)return Cn;const rr=xs.toLowerCase();return Cn.filter(ra=>ra.name.toLowerCase().includes(rr)||ra.email.toLowerCase().includes(rr))},Rt=qt=>l.filter(Cn=>Cn.brokerage_id!==qt),zt=l.filter(qt=>{var rr;if(P){const ra=P.toLowerCase();if(!(qt.name.toLowerCase().includes(ra)||qt.email.toLowerCase().includes(ra)||((rr=qt.brokerage_name)==null?void 0:rr.toLowerCase().includes(ra))))return!1}if(V==="claimed"&&!qt.claimed||V==="unclaimed"&&qt.claimed||_e!=="all"&&!qt.roles.includes(_e))return!1;const Cn=qt.is_trial||qt.subscription_status==="trialing";if(ue==="trial"&&!Cn||ue==="non-trial"&&Cn||Ee==="none"&&qt.brokerage_id||Ee!=="all"&&Ee!=="none"&&qt.brokerage_id!==Ee)return!1;if(Le!=="all"){if(!qt.created_at)return!1;const ra=parseInt(Le,10),Yr=Date.now()-ra*24*60*60*1e3;if(new Date(qt.created_at).getTime(){var Cn;return((Cn=qt.name)==null?void 0:Cn.toLowerCase())||""},brokerage:qt=>{var Cn;return((Cn=qt.brokerage_name)==null?void 0:Cn.toLowerCase())||""},status:qt=>qt.claimed?"active":"pending",role:qt=>qt.roles[0]||"",last_login:qt=>qt.last_sign_in_at?new Date(qt.last_sign_in_at).getTime():null,created_at:qt=>qt.created_at?new Date(qt.created_at).getTime():null}),fn=Ms.length,gn=U===0,vn=gn?1:Math.ceil(fn/U),Pn=gn?0:(D-1)*U,ir=gn?fn:Pn+U,er=Ms.slice(Pn,ir),tr=qt=>{R(qt),O(1)},vr=qt=>{W(qt),O(1)},yr=(qt,Cn)=>{qt(Cn),O(1)},qa=async(qt,Cn)=>{Ae(!0);try{const rr=l.find(gi=>gi.id===qt);if(!rr)return;const ra=rr.trial_expires_at?new Date(rr.trial_expires_at):new Date,Yr=new Date(ra.getTime()+Cn*24*60*60*1e3),{error:Aa}=await q.from("profiles").update({trial_expires_at:Yr.toISOString()}).eq("id",qt);if(Aa)throw Aa;i({title:"Trial Extended",description:`Trial extended by ${Cn} days`}),_s()}catch(rr){console.error("Error extending trial:",rr),i({title:"Error",description:rr.message||"Failed to extend trial",variant:"destructive"})}finally{Ae(!1)}},et=async(qt,Cn,rr)=>{Ve(!0);try{const{error:ra}=await q.from("profiles").update({is_paused:Cn,paused_at:Cn?new Date().toISOString():null,paused_reason:Cn&&(rr==null?void 0:rr.trim())||null}).eq("id",qt);if(ra)throw ra;o(Yr=>Yr.map(Aa=>Aa.id===qt?{...Aa,is_paused:Cn,paused_reason:Cn&&(rr==null?void 0:rr.trim())||null,paused_at:Cn?new Date().toISOString():null}:Aa)),Je(Yr=>Yr&&Yr.id===qt?{...Yr,is_paused:Cn,paused_reason:Cn&&(rr==null?void 0:rr.trim())||null}:Yr),i({title:Cn?"Account paused":"Account reactivated",description:Cn?"This member can no longer sign in and will see a paused message.":"This member can sign in again."})}catch(ra){console.error("Error updating pause state:",ra),i({title:"Error",description:ra.message||"Failed to update account",variant:"destructive"})}finally{Ve(!1)}},Vt=async qt=>{Xe(!0);try{const{error:Cn}=await q.from("profiles").update({is_trial:!1,trial_expires_at:null,trial_started_at:null,trial_claimed_at:null}).eq("id",qt);if(Cn)throw Cn;i({title:"Account Converted",description:"User has been converted to a full account"}),_s(),Qr()}catch(Cn){console.error("Error converting trial:",Cn),i({title:"Error",description:Cn.message||"Failed to convert account",variant:"destructive"})}finally{Xe(!1)}},[Es,ln]=j.useState(!1),tn=async(qt,Cn)=>{if(await fo(`Revert this user to a ${Cn}-day free trial? This will clear their paid/grandfathered status. Any active Stripe subscription will need to be cancelled separately.`)){ln(!0);try{const rr=new Date,ra=new Date(rr.getTime()+Cn*24*60*60*1e3),{error:Yr}=await q.from("profiles").update({is_trial:!0,trial_started_at:rr.toISOString(),trial_expires_at:ra.toISOString(),trial_claimed_at:rr.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",qt);if(Yr)throw Yr;i({title:"Reverted to Trial",description:`User is now on a ${Cn}-day free trial.`}),_s()}catch(rr){console.error("Error reverting to trial:",rr),i({title:"Error",description:rr.message||"Failed to revert to trial",variant:"destructive"})}finally{ln(!1)}}},sr=async qt=>{Mc(!0);try{const{data:Cn}=await q.from("agent_assistant_assignments").select("id, assistant_id, permissions").eq("agent_id",qt);if(Cn&&Cn.length>0){const ra=Cn.map(Aa=>Aa.assistant_id),{data:Yr}=await q.from("profiles").select("id, name, email").in("id",ra);$l(Cn.map(Aa=>{const gi=Yr==null?void 0:Yr.find(Ia=>Ia.id===Aa.assistant_id);return{id:Aa.id,assistant_id:Aa.assistant_id,assistant_name:(gi==null?void 0:gi.name)||"Unknown",assistant_email:(gi==null?void 0:gi.email)||"",permissions:Aa.permissions||{}}}))}else $l([]);const{data:rr}=await q.from("agent_assistant_assignments").select("id, agent_id, permissions").eq("assistant_id",qt);if(rr&&rr.length>0){const ra=rr.map(Aa=>Aa.agent_id),{data:Yr}=await q.from("profiles").select("id, name, email").in("id",ra);Ix(rr.map(Aa=>{const gi=Yr==null?void 0:Yr.find(Ia=>Ia.id===Aa.agent_id);return{id:Aa.id,agent_id:Aa.agent_id,agent_name:(gi==null?void 0:gi.name)||"Unknown",agent_email:(gi==null?void 0:gi.email)||"",permissions:Aa.permissions||{}}}))}else Ix([])}catch(Cn){console.error("Error loading assistant data:",Cn)}finally{Mc(!1)}},nr=qt=>{Je(qt),Yt({name:qt.name,email:qt.email,brokerage_id:qt.brokerage_id||"",phone:qt.phone||""}),gt(!0),sr(qt.id)},Qr=()=>{Je(null),gt(!1),Yt({name:"",email:"",brokerage_id:"",phone:""})},na=async()=>{Ke&&(await No(Ke.id),Qr())},$a=qt=>{ta(Cn=>{const rr=new Set(Cn);return rr.has(qt)?rr.delete(qt):rr.add(qt),rr})},Na=()=>{if(ao.size===er.length&&er.every(qt=>ao.has(qt.id))){const qt=new Set(ao);er.forEach(Cn=>qt.delete(Cn.id)),ta(qt)}else{const qt=new Set(ao);er.forEach(Cn=>qt.add(Cn.id)),ta(qt)}},La=()=>{ta(new Set)},to=async()=>{if(ao.size===0)return;fl(!0);let qt=0,Cn=0;try{const{data:{session:rr}}=await q.auth.getSession();for(const ra of ao)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${rr==null?void 0:rr.access_token}`},body:JSON.stringify({userId:ra,redirectTo:"https://dashboard.relevelup.com/profile?reset=true"})})).ok?qt++:Cn++}catch{Cn++}i({title:"Bulk Email Complete",description:`Sent ${qt} emails${Cn>0?`, ${Cn} failed`:""}`}),La()}catch(rr){i({title:"Error",description:rr.message||"Failed to send emails",variant:"destructive"})}finally{fl(!1)}},xo=async()=>{if(ao.size===0)return;fl(!0);let qt=0,Cn=0;try{const{data:{session:rr}}=await q.auth.getSession();for(const ra of ao)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/send-password-reset",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${rr==null?void 0:rr.access_token}`},body:JSON.stringify({userId:ra})})).ok?qt++:Cn++}catch{Cn++}i({title:"Bulk Password Reset Complete",description:`Sent ${qt} reset emails${Cn>0?`, ${Cn} failed`:""}`}),La()}catch(rr){i({title:"Error",description:rr.message||"Failed to send password reset emails",variant:"destructive"})}finally{fl(!1)}},oo=async qt=>{le(!0),te({done:0,total:qt.length});const Cn=[];try{const{data:{session:rr}}=await q.auth.getSession(),ra=5;for(let Aa=0;Aa{try{const el=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/send-password-reset",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${rr==null?void 0:rr.access_token}`},body:JSON.stringify({userId:Ia.id,variant:"activation"})}),zo=await el.json().catch(()=>({}));el.ok&&(zo==null?void 0:zo.sent)!==!1?Cn.push({email:Ia.email,ok:!0}):Cn.push({email:Ia.email,ok:!1,reason:(zo==null?void 0:zo.reason)||`HTTP ${el.status}`})}catch(el){Cn.push({email:Ia.email,ok:!1,reason:(el==null?void 0:el.message)||"Network error"})}})),te({done:Math.min(Aa+ra,qt.length),total:qt.length}),Aa+rasetTimeout(Ia,1200))}ce(Cn);const Yr=Cn.filter(Aa=>Aa.ok).length;i({title:"Activation emails sent",description:`${Yr} of ${qt.length} sent successfully`})}finally{le(!1)}},Lo=async()=>{if(ao.size===0)return;const qt=l.filter(Yr=>ao.has(Yr.id)).map(Yr=>Yr.name).slice(0,5).join(", "),Cn=ao.size>5?` and ${ao.size-5} more`:"";if(!await fo(`Are you sure you want to delete ${ao.size} users (${qt}${Cn})? This action cannot be undone.`))return;fl(!0);let rr=0,ra=0;try{const{data:{session:Yr}}=await q.auth.getSession();for(const Aa of ao)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/delete-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Yr==null?void 0:Yr.access_token}`},body:JSON.stringify({userId:Aa})})).ok?rr++:ra++}catch{ra++}i({title:"Bulk Delete Complete",description:`Deleted ${rr} users${ra>0?`, ${ra} failed`:""}`}),La(),_s()}catch(Yr){i({title:"Error",description:Yr.message||"Failed to delete users",variant:"destructive"})}finally{fl(!1)}},Ul=async()=>{fu(!0);try{const{data:{session:qt}}=await q.auth.getSession(),Cn=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ghl-phone-sync",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${qt==null?void 0:qt.access_token}`}});if(!Cn.ok){const ra=await Cn.json();throw new Error(ra.error||"Failed to sync phones")}const rr=await Cn.json();i({title:"Phone Sync Complete",description:`Pulled ${rr.summary.pulledFromGHL} from GHL, pushed ${rr.summary.pushedToGHL} to GHL, ${rr.summary.alreadySynced} already synced`}),_s()}catch(qt){i({title:"Error",description:qt.message||"Failed to sync phones with GHL",variant:"destructive"})}finally{fu(!1)}},po=async(qt,Cn)=>{nd(qt);try{const{data:{session:rr}}=await q.auth.getSession(),{data:ra}=await q.from("profiles").select("phone").eq("id",qt).single(),Yr=(ra==null?void 0:ra.phone)||"",Aa=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ghl-tag-sync",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${rr==null?void 0:rr.access_token}`},body:JSON.stringify({email:Cn,action:"update",phone:Yr||void 0})});if(!Aa.ok){const Ia=await Aa.json();throw new Error(Ia.error||"Failed to sync with GHL")}const gi=await fetch(`https://services.leadconnectorhq.com/contacts/lookup?locationId=&email=${encodeURIComponent(Cn)}`,{method:"GET",headers:{"Content-Type":"application/json"}});i({title:"Phone Synced",description:Yr?`Phone ${Yr} synced to GHL`:"Sync attempted - run bulk sync to pull phone from GHL"}),_s()}catch(rr){i({title:"Error",description:rr.message||"Failed to sync phone",variant:"destructive"})}finally{nd(null)}},nl=async qt=>{await r(qt)},Pl=()=>{if(ao.size===0){i({title:"No members selected",description:"Please select members to export",variant:"destructive"});return}const qt=l.filter(Ia=>ao.has(Ia.id)),Cn=["Name","Email","Phone","Brokerage","Roles","Status","Created At"],rr=qt.map(Ia=>[Ia.name,Ia.email,Ia.phone||"",Ia.brokerage_name||"",Ia.roles.join("; "),Ia.claimed?"Claimed":"Unclaimed",new Date(Ia.created_at).toLocaleDateString()]),ra=[Cn.join(","),...rr.map(Ia=>Ia.map(el=>`"${(el||"").replace(/"/g,'""')}"`).join(","))].join(` `),Yr=new Blob([ra],{type:"text/csv"}),Aa=URL.createObjectURL(Yr),gi=document.createElement("a");gi.href=Aa,gi.download=`members-export-${new Date().toISOString().split("T")[0]}.csv`,gi.click(),URL.revokeObjectURL(Aa),i({title:"Export complete",description:`Exported ${qt.length} member(s)`})},Cd=()=>{if(zt.length===0){i({title:"No members to export",description:"Adjust filters to include at least one member",variant:"destructive"});return}const qt=["Name","Email","Phone","Brokerage","Roles","Status","Created At"],Cn=zt.map(Ia=>[Ia.name,Ia.email,Ia.phone||"",Ia.brokerage_name||"",Ia.roles.join("; "),Ia.claimed?"Claimed":"Unclaimed",Ia.created_at?new Date(Ia.created_at).toLocaleDateString():""]),rr=[qt.join(","),...Cn.map(Ia=>Ia.map(el=>`"${(el||"").replace(/"/g,'""')}"`).join(","))].join(` `),ra=new Blob([rr],{type:"text/csv"}),Yr=URL.createObjectURL(ra),Aa=document.createElement("a"),gi=Le!=="all"?`-last-${Le}days`:"";Aa.href=Yr,Aa.download=`members-export${gi}-${new Date().toISOString().split("T")[0]}.csv`,Aa.click(),URL.revokeObjectURL(Yr),i({title:"Export complete",description:`Exported ${zt.length} member(s)`})};return g?e.jsx(Vs,{title:"Members",children:e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):e.jsxs(Vs,{title:"Members",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsx(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(YN,{className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Import CSV"}),e.jsx("span",{className:"sm:hidden",children:"Import"})]}),e.jsxs(zs,{open:E,onOpenChange:I,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{size:"sm",children:[e.jsx(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(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Create New User"}),e.jsx(Pr,{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:qt=>A({...S,name:qt.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:qt=>A({...S,email:qt.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:qt=>A({...S,password:qt.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:qt=>A({...S,phone:qt.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:qt=>A({...S,brokerage_id:qt==="none"?"":qt}),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(qt=>e.jsx(Ge,{value:qt.id,children:qt.name},qt.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"role",children:"Role"}),e.jsxs(ms,{value:S.role,onValueChange:qt=>A({...S,role:qt}),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:qt=>A({...S,trial_days:qt==="none"?"":qt}),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(Sr,{children:[e.jsx($,{variant:"outline",onClick:()=>I(!1),children:"Cancel"}),e.jsx($,{onClick:qi,disabled:b,children:b?"Creating...":"Create User"})]})]})]})]})]}),e.jsxs(ha,{defaultValue:new URLSearchParams(window.location.search).get("tab")||"members",className:"space-y-6",children:[e.jsxs(ma,{children:[e.jsx(Zt,{value:"members",children:"Members"}),e.jsx(Zt,{value:"brokerages",children:"Brokerages"}),e.jsx(Zt,{value:"teams",children:"Teams"}),e.jsx(Zt,{value:"trials",children:"Trial Users"}),e.jsx(Zt,{value:"access",children:"Access Matrix"}),e.jsx(Zt,{value:"celebrations",children:"Celebrations"}),e.jsx(Zt,{value:"deletions",children:"Deletion Log"})]}),e.jsxs(Xt,{value:"members",className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsxs("div",{className:"relative flex-1 min-w-[200px] max-w-md",children:[e.jsx(Zr,{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:qt=>tr(qt.target.value),className:"pl-10 h-9"})]}),e.jsxs(ms,{value:V,onValueChange:qt=>yr(G,qt),children:[e.jsx(us,{className:"w-[130px] h-9",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Status"}),e.jsx(Ge,{value:"claimed",children:"Active"}),e.jsx(Ge,{value:"unclaimed",children:"Pending"})]})]}),e.jsxs(ms,{value:_e,onValueChange:qt=>yr(he,qt),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:qt=>yr(ve,qt),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:qt=>yr(Se,qt),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(qt=>e.jsx(Ge,{value:qt.id,children:qt.name},qt.id))]})]}),e.jsxs(ms,{value:Le,onValueChange:qt=>yr(Fe,qt),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(xi,{className:"h-4 w-4 mr-1"}),"Export Filtered"]}),e.jsxs($,{size:"sm",variant:"outline",className:"h-9",disabled:Ms.filter(qt=>!qt.claimed&&qt.email).length===0,onClick:()=>{ce(null),X(!0)},title:"Email every pending (never signed in) member a link to set their password",children:[e.jsx(mn,{className:"h-4 w-4 mr-1"}),"Email Pending (",Ms.filter(qt=>!qt.claimed&&qt.email).length,")"]}),e.jsx(zs,{open:Y,onOpenChange:qt=>{ae||X(qt)},children:e.jsxs(Os,{className:"max-w-lg",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Email pending members"}),e.jsx(Pr,{children:'Sends the branded "Activate your account" email with a set-password link to every member in the current filter who has never signed in. Sent in small batches, so this can take a few minutes.'})]}),ae&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Sending… ",ne.done," of ",ne.total]}),J&&!ae&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-sm",children:[J.filter(qt=>qt.ok).length," sent",J.some(qt=>!qt.ok)&&`, ${J.filter(qt=>!qt.ok).length} failed`]}),J.some(qt=>!qt.ok)&&e.jsx("div",{className:"max-h-48 overflow-y-auto rounded border p-2 text-xs space-y-1",children:J.filter(qt=>!qt.ok).map(qt=>e.jsxs("div",{className:"flex justify-between gap-2",children:[e.jsx("span",{className:"truncate",children:qt.email}),e.jsx("span",{className:"text-muted-foreground truncate",children:qt.reason})]},qt.email))})]}),e.jsxs(Sr,{children:[e.jsx($,{variant:"outline",disabled:ae,onClick:()=>X(!1),children:"Close"}),!J&&e.jsx($,{disabled:ae,onClick:()=>oo(Ms.filter(qt=>!qt.claimed&&qt.email).map(qt=>({id:qt.id,email:qt.email,name:qt.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(qt=>!qt.claimed&&qt.email).length} members`})]})]})}),(P||V!=="all"||_e!=="all"||ue!=="all"||Ee!=="all"||Le!=="all")&&e.jsxs($,{variant:"ghost",size:"sm",className:"h-9",onClick:()=>{R(""),G("all"),he("all"),ve("all"),Se("all"),Fe("all"),O(1)},children:[e.jsx(pr,{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:gn?`Showing all ${fn} members`:`Showing ${Pn+1}-${Math.min(ir,fn)} of ${fn} members`}),e.jsxs(ms,{value:U.toString(),onValueChange:qt=>vr(Number(qt)),children:[e.jsx(us,{className:"h-9 w-[110px]",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"50",children:"50 / page"}),e.jsx(Ge,{value:"100",children:"100 / page"}),e.jsx(Ge,{value:"250",children:"250 / page"}),e.jsx(Ge,{value:"0",children:"All"})]})]})]})]}),ao.size>0&&e.jsxs("div",{className:"flex flex-col gap-2 p-3 bg-primary/10 border border-primary/20 rounded-lg",children:[er.length>0&&er.every(qt=>ao.has(qt.id))&&Ms.length>ao.size&&e.jsxs("div",{className:"flex items-center justify-between gap-2 px-1 text-sm",children:[e.jsxs("span",{className:"text-muted-foreground",children:["All ",ao.size," on this page are selected."]}),e.jsxs($,{size:"sm",variant:"link",className:"h-auto p-0 text-primary",onClick:()=>ta(new Set(Ms.map(qt=>qt.id))),children:["Select all ",Ms.length," filtered members"]})]}),Ms.length>0&&ao.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(Vj,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{className:"text-sm font-medium",children:[ao.size," selected"]})]}),e.jsx("div",{className:"flex-1"}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs($,{size:"sm",variant:"outline",onClick:to,disabled:xc,children:[xc?e.jsx(Ct,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(mn,{className:"h-4 w-4 mr-1"}),e.jsx("span",{className:"hidden sm:inline",children:"Resend Invite"}),e.jsx("span",{className:"sm:hidden",children:"Invite"})]}),e.jsxs($,{size:"sm",variant:"outline",onClick:xo,disabled:xc,children:[xc?e.jsx(Ct,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(w_,{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:xc,className:"bg-primary/5 border-primary/30 text-primary hover:bg-primary/10",children:[e.jsx(XS,{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(xi,{className:"h-4 w-4 mr-1"}),e.jsx("span",{className:"hidden sm:inline",children:"Export"}),e.jsx("span",{className:"sm:hidden",children:"CSV"})]}),e.jsxs($,{size:"sm",variant:"destructive",onClick:Lo,disabled:xc,children:[xc?e.jsx(Ct,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(Hn,{className:"h-4 w-4 mr-1"}),e.jsx("span",{className:"hidden sm:inline",children:"Delete"}),e.jsx("span",{className:"sm:hidden",children:"Del"})]}),e.jsx($,{size:"sm",variant:"ghost",onClick:La,disabled:xc,children:e.jsx(pr,{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(En,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Dt,{className:"w-[50px]",children:e.jsx(ai,{checked:er.length>0&&er.every(qt=>ao.has(qt.id)),onCheckedChange:Na,"aria-label":"Select all on page"})}),e.jsx(Mm,{sortKey:"name",currentSortKey:Ht,currentDirection:ws,onSort:Ts,children:"Name"}),e.jsx(Mm,{sortKey:"brokerage",currentSortKey:Ht,currentDirection:ws,onSort:Ts,children:"Brokerage"}),e.jsx(Mm,{sortKey:"status",currentSortKey:Ht,currentDirection:ws,onSort:Ts,children:"Status"}),e.jsx(Mm,{sortKey:"role",currentSortKey:Ht,currentDirection:ws,onSort:Ts,children:"Role"}),e.jsx(Mm,{sortKey:"last_login",currentSortKey:Ht,currentDirection:ws,onSort:Ts,children:"Last Login"}),e.jsx(Mm,{sortKey:"created_at",currentSortKey:Ht,currentDirection:ws,onSort:Ts,children:"Member Since"}),e.jsx(Dt,{className:"w-[100px]"})]})}),e.jsx(fi,{children:er.length===0?e.jsx(En,{children:e.jsx(_t,{colSpan:8,className:"text-center py-12 text-muted-foreground",children:"No members found"})}):er.map(qt=>e.jsxs(En,{className:`hover:bg-muted/30 ${ao.has(qt.id)?"bg-primary/5":""}`,children:[e.jsx(_t,{children:e.jsx(ai,{checked:ao.has(qt.id),onCheckedChange:()=>$a(qt.id),"aria-label":`Select ${qt.name}`})}),e.jsx(_t,{children:e.jsxs("div",{children:[e.jsx("button",{onClick:()=>nr(qt),className:"text-primary hover:underline font-medium text-left",children:qt.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:qt.email})]})}),e.jsx(_t,{className:"text-muted-foreground",children:qt.brokerage_name||"—"}),e.jsx(_t,{children:e.jsx("div",{className:"flex flex-col",children:(()=>{const Cn=qt.trial_expires_at||qt.subscription_end_date;if((qt.is_trial||qt.subscription_status==="trialing")&&Cn){const ra=Math.ceil((new Date(Cn).getTime()-Date.now())/864e5),Yr=ra<=0,Aa=ra<=3;return e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx($e,{variant:"outline",className:Pt("w-fit",Yr?"border-destructive text-destructive":Aa?"border-amber-500 text-amber-600":"border-violet-300 text-violet-700 bg-violet-50"),children:Yr?"Trial Expired":`Trial · ${ra}d left`}),e.jsx("button",{type:"button",title:"Copy upgrade link — paste into an email so this agent can sign in and pay on their existing account",className:"text-muted-foreground hover:text-primary transition-colors",onClick:async()=>{const 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(Ha,{className:"h-3.5 w-3.5"})})]})}return e.jsx($e,{variant:qt.claimed?"default":"secondary",className:qt.claimed?"bg-primary text-primary-foreground w-fit":"w-fit",children:qt.claimed?"Active":"Pending"})})()})}),e.jsx(_t,{children:e.jsxs("div",{className:"flex flex-col",children:[qt.roles.length>0?e.jsx("span",{className:"text-sm capitalize",children:qt.roles[0]}):e.jsx("span",{className:"text-muted-foreground",children:"—"}),qt.roles.includes("assistant")&&Mh[qt.id]&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["→ ",Mh[qt.id].agent_name||Mh[qt.id].agent_email]})]})}),e.jsx(_t,{className:"text-muted-foreground",children:qt.last_sign_in_at?new Date(qt.last_sign_in_at).toLocaleDateString():"—"}),e.jsx(_t,{className:"text-muted-foreground",children:qt.created_at?new Date(qt.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):"—"}),e.jsx(_t,{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(qt),Hi(!0)},title:"Send celebration",children:e.jsx(Cx,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>nr(qt),title:"Edit member",children:e.jsx(pi,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>po(qt.id,qt.email),disabled:cc===qt.id,title:"Sync phone with GHL",children:cc===qt.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(qt.id),title:"Resend welcome email",children:e.jsx(mn,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>io(qt.email,qt.name),title:"Send password reset",children:e.jsx(GI,{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(qt.id),disabled:a||qt.id===(t==null?void 0:t.id),title:qt.id===(t==null?void 0:t.id)?"Cannot impersonate yourself":`Login as ${qt.name}`,children:a?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(KI,{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(qt.id,qt.name),title:"Delete user",children:e.jsx(Hn,{className:"h-4 w-4"})})]})})]},qt.id))})]})}),vn>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 ",vn]}),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(qt=>Math.max(1,qt-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,vn)},(qt,Cn)=>{let rr;return vn<=5||D<=3?rr=Cn+1:D>=vn-2?rr=vn-4+Cn:rr=D-2+Cn,e.jsx($,{variant:D===rr?"default":"outline",size:"sm",className:"h-8 w-8 p-0",onClick:()=>O(rr),children:rr},rr)})}),e.jsx($,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>O(qt=>Math.min(vn,qt+1)),disabled:D===vn,children:e.jsx(Di,{className:"h-4 w-4"})}),e.jsx($,{variant:"outline",size:"sm",onClick:()=>O(vn),disabled:D===vn,children:"Last"})]})]})]}),e.jsx(zs,{open:pt,onOpenChange:gt,children:e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Edit Member"}),e.jsx(Pr,{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:ss.name,onChange:qt=>Yt({...ss,name:qt.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:ss.email,onChange:qt=>Yt({...ss,email:qt.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:ss.phone,onChange:qt=>Yt({...ss,phone:qt.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:ss.brokerage_id||"none",onValueChange:qt=>Yt({...ss,brokerage_id:qt==="none"?"":qt}),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(qt=>e.jsx(Ge,{value:qt.id,children:qt.name},qt.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(qt=>e.jsxs($e,{variant:"default",className:"gap-1",children:[e.jsx(Tf,{className:"h-3 w-3"}),qt,qt==="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,qt,"remove"),className:"ml-1 rounded-full hover:bg-destructive/20",title:"Remove role",children:e.jsx(pr,{className:"h-3 w-3"})})]},qt)),Ke.roles.length===0&&e.jsx("span",{className:"text-sm text-muted-foreground",children:"No roles assigned"})]}),e.jsxs(ms,{onValueChange:qt=>cm(Ke.id,qt,"add"),children:[e.jsx(us,{className:"w-[200px]",children:e.jsx(fs,{placeholder:"Add role..."})}),e.jsxs(hs,{children:[!Ke.roles.includes("admin")&&e.jsx(Ge,{value:"admin",children:"Admin"}),!Ke.roles.includes("user")&&e.jsx(Ge,{value:"user",children:"User"})]})]}),!Ke.roles.includes("brokerage_manager")&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"To add as brokerage manager, use Brokerages tab → Manage"})]}),(yc.length>0||rg.length>0||Ke.roles.includes("assistant"))&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h3",{className:"text-sm font-semibold flex items-center gap-2",children:[e.jsx(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:[yc.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Has assistants:"}),yc.map(qt=>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:qt.assistant_name}),e.jsx($e,{variant:"outline",className:"text-xs",children:"Assistant"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:qt.assistant_email}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:Object.entries(qt.permissions).filter(([,Cn])=>Cn).map(([Cn])=>e.jsx($e,{variant:"secondary",className:"text-[10px] capitalize",children:Cn},Cn))})]},qt.id))]}),rg.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Assists agents:"}),rg.map(qt=>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:qt.agent_name}),e.jsx($e,{variant:"outline",className:"text-xs",children:"Agent"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:qt.agent_email}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:Object.entries(qt.permissions).filter(([,Cn])=>Cn).map(([Cn])=>e.jsx($e,{variant:"secondary",className:"text-[10px] capitalize",children:Cn},Cn))})]},qt.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(qt=>{const Cn=Zo(Ke.tags,qt.required_tags),rr=`${Ke.id}-${qt.id}`,ra=ts===rr,Yr=qt.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:qt.icon}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:qt.name}),Yr&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Available to all members"})]})]}),e.jsx("div",{className:"flex items-center gap-2",children:ra?e.jsx(Ct,{className:"h-4 w-4 animate-spin text-muted-foreground"}):Yr?e.jsx($e,{variant:"secondary",className:"text-xs",children:"Always On"}):e.jsx(Sn,{checked:Cn,onCheckedChange:()=>vo(Ke.id,qt,Cn)})})]},qt.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:qt=>qe(qt.target.value)}),e.jsx($,{size:"sm",variant:"destructive",onClick:async()=>{await et(Ke.id,!0,ze),qe("")},disabled:Ce,children:"Pause account"})]})]}),(Ke.is_trial||Ke.subscription_status==="trialing")&&e.jsxs("div",{className:"space-y-3 pt-4 border-t",children:[e.jsxs("h3",{className:"text-sm font-semibold flex items-center gap-2",children:[e.jsx(da,{className:"h-4 w-4"}),"Trial Status"]}),e.jsxs("div",{className:"p-4 rounded-lg border bg-amber-50 dark:bg-amber-950/20 border-amber-200 dark:border-amber-800",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{children:[Ke.trial_expires_at&&e.jsx(Iwt,{expiresAt:Ke.trial_expires_at}),!Ke.trial_expires_at&&Ke.subscription_status==="trialing"&&Ke.subscription_end_date&&e.jsx(Iwt,{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:Ne,children:[e.jsx(bv,{className:"h-4 w-4 mr-1"}),"+7 Days"]}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>qa(Ke.id,14),disabled:Ne,children:[e.jsx(bv,{className:"h-4 w-4 mr-1"}),"+14 Days"]}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>qa(Ke.id,30),disabled:Ne,children:[e.jsx(bv,{className:"h-4 w-4 mr-1"}),"+30 Days"]}),e.jsxs($,{size:"sm",variant:"default",onClick:()=>Vt(Ke.id),disabled:dt,className:"bg-green-600 hover:bg-green-700",children:[e.jsx(m2,{className:"h-4 w-4 mr-1"}),"Convert to Full Account"]})]}),Ke.trial_started_at&&e.jsxs("div",{className:"mt-3 text-xs text-muted-foreground",children:["Trial started: ",new Date(Ke.trial_started_at).toLocaleDateString(),Ke.trial_claimed_at&&e.jsxs("span",{children:[" • Claimed: ",new Date(Ke.trial_claimed_at).toLocaleDateString()]})]})]})]}),!(Ke.is_trial||Ke.subscription_status==="trialing")&&e.jsxs("div",{className:"space-y-3 pt-4 border-t",children:[e.jsxs("h3",{className:"text-sm font-semibold flex items-center gap-2",children:[e.jsx(da,{className:"h-4 w-4"}),"Revert to Free Trial"]}),e.jsxs("div",{className:"p-4 rounded-lg border bg-blue-50 dark:bg-blue-950/20 border-blue-200 dark:border-blue-800",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"Move this user back to a free trial. Clears paid/grandfathered status. If they have an active Stripe subscription, cancel it separately in Stripe."}),e.jsx("div",{className:"flex flex-wrap gap-2",children:[7,14,30,60,90].map(qt=>e.jsxs($,{size:"sm",variant:"outline",onClick:()=>tn(Ke.id,qt),disabled:Es,children:[e.jsx(bv,{className:"h-4 w-4 mr-1"}),qt,"-day trial"]},qt))})]})]}),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(Sr,{children:[e.jsx($,{variant:"outline",onClick:Qr,children:"Cancel"}),e.jsx($,{onClick:na,children:"Save Changes"})]})]})}),e.jsxs(Xt,{value:"access",children:[c.length===0?e.jsx(je,{children:e.jsxs(Ie,{className:"py-12 text-center",children:[e.jsx("p",{className:"text-muted-foreground mb-4",children:"No apps configured yet"}),e.jsx($,{onClick:()=>s("/admin/apps"),children:"Configure Apps"})]})}):e.jsxs(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(Gn,{children:"Toggle switches to grant or revoke app access for each member"})]}),e.jsxs("div",{className:"relative w-full sm:w-72",children:[e.jsx(Zr,{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:qt=>{R(qt.target.value),O(1)},className:"pl-9"})]})]}),e.jsxs(Ie,{children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b",children:[e.jsx("th",{className:"text-left p-4 font-semibold sticky left-0 bg-card z-10",children:"Member"}),c.map(qt=>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:qt.icon}),e.jsx("span",{className:"text-sm",children:qt.name})]})},qt.id))]})}),e.jsxs("tbody",{children:[er.map(qt=>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:qt.name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:qt.email})]})}),c.map(Cn=>{const rr=Zo(qt.tags,Cn.required_tags),ra=`${qt.id}-${Cn.id}`,Yr=ts===ra;return e.jsx("td",{className:"p-4 text-center",children:e.jsx("div",{className:"flex items-center justify-center",children:Yr?e.jsx(Ct,{className:"h-5 w-5 animate-spin text-muted-foreground"}):e.jsx(Sn,{checked:rr,onCheckedChange:()=>vo(qt.id,Cn,rr),disabled:Cn.required_tags.length===0})})},Cn.id)})]},qt.id)),er.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"})})]})]})}),vn>1&&e.jsxs("div",{className:"flex items-center justify-between px-2 py-4 border-t",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:["Showing ",Pn+1,"-",Math.min(ir,fn)," of ",fn," • Page ",D," of ",vn]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx($,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>O(qt=>Math.max(1,qt-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(qt=>Math.min(vn,qt+1)),disabled:D===vn,children:e.jsx(Di,{className:"h-4 w-4"})})]})]})]})]}),e.jsx("div",{className:"mt-6",children:e.jsx($,{variant:"outline",onClick:()=>s("/admin/apps"),children:"Manage Apps"})})]}),e.jsxs(Xt,{value:"brokerages",className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(Zr,{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:zd,onChange:qt=>Nl(qt.target.value),className:"pl-10"})]}),e.jsxs("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:[u.filter(qt=>qt.name.toLowerCase().includes(zd.toLowerCase())).length," of ",u.length," brokerages"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{size:"sm",variant:"outline",onClick:()=>{const qt=[];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+/),Tu=Pc[0]||"",iu=Pc.slice(1).join(" ")||"";qt.push({firstName:Tu,lastName:iu,email:zo.email,brokerageName:gi.name})}}}if(qt.length===0){i({title:"No managers found to export"});return}const rr=[["First Name","Last Name","Email","Brokerage Name"].join(","),...qt.map(gi=>[gi.firstName,gi.lastName,gi.email,gi.brokerageName].map(Ia=>`"${(Ia||"").replace(/"/g,'""')}"`).join(","))].join(` `),ra=new Blob([rr],{type:"text/csv"}),Yr=URL.createObjectURL(ra),Aa=document.createElement("a");Aa.href=Yr,Aa.download=`brokerage-managers-${new Date().toISOString().slice(0,10)}.csv`,Aa.click(),URL.revokeObjectURL(Yr),i({title:`Exported ${qt.length} managers`})},children:[e.jsx(xi,{className:"mr-2 h-4 w-4"}),"Export Managers"]}),e.jsxs(zs,{open:Bt,onOpenChange:Ft,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{size:"sm",children:[e.jsx(ji,{className:"mr-2 h-4 w-4"}),"Add Brokerage"]})}),e.jsxs(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Create New Brokerage"}),e.jsx(Pr,{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:as,onChange:qt=>kt(qt.target.value),maxLength:100})]})}),e.jsxs(Sr,{children:[e.jsx($,{variant:"outline",onClick:()=>Ft(!1),children:"Cancel"}),e.jsx($,{onClick:Zg,disabled:Ks,children:Ks?"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(En,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Dt,{className:"font-semibold",children:"Brokerage Name"}),e.jsx(Dt,{className:"font-semibold",children:"Manager(s)"}),e.jsx(Dt,{className:"font-semibold",children:"Agents"}),e.jsx(Dt,{className:"w-[150px]"})]})}),e.jsx(fi,{children:(()=>{const qt=u.filter(Cn=>Cn.name.toLowerCase().includes(zd.toLowerCase()));return qt.length===0?e.jsx(En,{children:e.jsx(_t,{colSpan:4,className:"text-center py-12 text-muted-foreground",children:zd?"No brokerages match your search":"No brokerages found"})}):qt.map(Cn=>{const rr=l.filter(gi=>gi.brokerage_id===Cn.id),Yr=(m[Cn.id]??[]).map(gi=>l.find(Ia=>Ia.id===gi)).filter(Boolean),Aa=rr.length;return e.jsxs(En,{className:"hover:bg-muted/30",children:[e.jsx(_t,{children:e.jsx("button",{onClick:()=>Fl(Cn),className:"text-primary hover:underline font-medium",children:Cn.name})}),e.jsx(_t,{children:Yr.length>0?e.jsx("div",{className:"flex flex-wrap gap-1",children:Yr.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(_t,{children:[Aa," member",Aa!==1?"s":""]}),e.jsx(_t,{children:e.jsxs("div",{className:"flex gap-1 justify-end",children:[e.jsxs($,{size:"sm",variant:"outline",className:"h-8",onClick:()=>Ky(Cn),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(Cn),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(Cn),title:"Delete brokerage",children:e.jsx(Hn,{className:"h-4 w-4"})})]})})]},Cn.id)})})()})]})}),e.jsx(zs,{open:gs,onOpenChange:ks,children:e.jsxs(Os,{className:"max-w-lg",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Edit Brokerage"}),e.jsx(Pr,{children:"Update brokerage details and manage managers"})]}),Is&&e.jsxs("div",{className:"space-y-6 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"edit-brokerage-name",children:"Brokerage Name"}),e.jsx(pe,{id:"edit-brokerage-name",value:ds,onChange:qt=>Ss(qt.target.value),maxLength:100})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(ee,{children:"Managers"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Click × to remove manager access for this brokerage (keeps them as a member)"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:(()=>{const Cn=(m[Is.id]??[]).map(rr=>l.find(ra=>ra.id===rr)).filter(Boolean);return Cn.length===0?e.jsx("span",{className:"text-sm text-muted-foreground",children:"No managers assigned"}):Cn.map(rr=>e.jsxs($e,{variant:"default",className:"gap-1",children:[e.jsx(Tf,{className:"h-3 w-3"}),rr.name,e.jsx("button",{onClick:()=>cm(rr.id,"brokerage_manager","remove",Is.id),className:"ml-1 rounded-full hover:bg-destructive/20",title:"Remove manager from this brokerage",children:e.jsx(pr,{className:"h-3 w-3"})})]},rr.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(Kd,{open:Ho,onOpenChange:ti,children:[e.jsx(Yd,{asChild:!0,children:e.jsxs($,{variant:"outline",role:"combobox","aria-expanded":Ho,className:"w-full justify-between",children:["Search for a member...",e.jsx(Zr,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Od,{className:"w-full p-0",align:"start",children:e.jsxs(S2,{children:[e.jsx(C2,{placeholder:"Search by name or email..."}),e.jsxs(A2,{className:"max-h-[200px]",children:[e.jsx(E2,{children:"No members found."}),e.jsx(Dw,{children:(()=>{const qt=new Set(m[Is.id]??[]);return l.filter(Cn=>!qt.has(Cn.id)&&(n||Cn.brokerage_id===Is.id)).map(Cn=>e.jsxs(m1,{value:`${Cn.name} ${Cn.email}`,onSelect:()=>{Zd(Cn.id,Is.id),ti(!1)},children:[Cn.name," (",Cn.email,")"]},Cn.id))})()})]})]})})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Members in this Brokerage"}),e.jsx("div",{className:"max-h-32 overflow-y-auto border rounded p-2",children:l.filter(qt=>qt.brokerage_id===Is.id).length===0?e.jsx("span",{className:"text-sm text-muted-foreground",children:"No members"}):l.filter(qt=>qt.brokerage_id===Is.id).map(qt=>e.jsxs("div",{className:"text-sm py-1 flex items-center justify-between",children:[e.jsx("span",{children:qt.name}),qt.roles.includes("brokerage_manager")&&e.jsx($e,{variant:"outline",className:"text-xs",children:"Manager"})]},qt.id))})]})]}),e.jsxs(Sr,{children:[e.jsx($,{variant:"outline",onClick:Ol,children:"Cancel"}),e.jsx($,{onClick:xy,disabled:yn,children:yn?"Saving...":"Save Changes"})]})]})}),e.jsx(zs,{open:Ut,onOpenChange:hn,children:e.jsxs(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{className:"text-destructive",children:"Delete Brokerage"}),e.jsxs(Pr,{children:['Are you sure you want to delete "',hr==null?void 0:hr.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 "',hr==null?void 0:hr.name,'"']}),e.jsxs("li",{children:["All ",l.filter(qt=>qt.brokerage_id===(hr==null?void 0:hr.id)).length," member(s) assigned to this brokerage"]}),e.jsx("li",{children:"All their data, roles, and access"})]})]})}),e.jsxs(Sr,{children:[e.jsx($,{variant:"outline",onClick:()=>hn(!1),children:"Cancel"}),e.jsx($,{variant:"destructive",onClick:cf,disabled:jr,children:jr?"Deleting...":"Yes, Delete Brokerage"})]})]})}),e.jsx(zs,{open:$n,onOpenChange:kn,children:e.jsxs(Os,{className:"max-w-4xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(ji,{className:"h-5 w-5"}),"Manage ",Fn==null?void 0:Fn.name]}),e.jsx(Pr,{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(Zr,{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:qt=>Lr(qt.target.value),className:"pl-10 h-9"})]}),e.jsxs(zs,{open:Or,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(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Add New Agent"}),e.jsxs(Pr,{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:Qn.name,onChange:qt=>Cr({...Qn,name:qt.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:Qn.email,onChange:qt=>Cr({...Qn,email:qt.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:Qn.password,onChange:qt=>Cr({...Qn,password:qt.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:Qn.phone,onChange:qt=>Cr({...Qn,phone:qt.target.value})})]}),Pa&&$i.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{htmlFor:"agent-package",children:[Pa.name," Package"]}),e.jsxs(ms,{value:xa,onValueChange:Ya,children:[e.jsx(us,{id:"agent-package",children:e.jsx(fs,{placeholder:"Select a package"})}),e.jsxs(hs,{children:[$i.map(qt=>e.jsx(Ge,{value:qt.id,children:qt.name},qt.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(qt=>qt.id===xa))==null?void 0:au.description)||"Entitlements and the welcome email reflect this package."})]})]}),e.jsxs(Sr,{children:[e.jsx($,{variant:"outline",onClick:()=>la(!1),children:"Cancel"}),e.jsx($,{onClick:We,disabled:Un,children:Un?"Creating...":"Create Agent"})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ee,{className:"text-sm text-muted-foreground whitespace-nowrap",children:"Add existing user:"}),e.jsxs(Kd,{open:Xr,onOpenChange:Eo,children:[e.jsx(Yd,{asChild:!0,children:e.jsxs($,{variant:"outline",role:"combobox","aria-expanded":Xr,className:"w-[300px] justify-between",children:["Select a user to add...",e.jsx(Zr,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Od,{className:"w-[300px] p-0",align:"start",children:e.jsxs(S2,{children:[e.jsx(C2,{placeholder:"Search users...",value:Th,onValueChange:ah}),e.jsxs(A2,{children:[e.jsx(E2,{children:"No users found."}),e.jsx(Dw,{children:Rt(Fn.id).filter(qt=>Th===""||qt.name.toLowerCase().includes(Th.toLowerCase())||qt.email.toLowerCase().includes(Th.toLowerCase())).map(qt=>e.jsxs(m1,{value:`${qt.name} ${qt.email}`,onSelect:()=>{xt(qt.id,Fn.id),Eo(!1),ah("")},children:[qt.name," (",qt.email,")"]},qt.id))})]})]})})]})]}),e.jsx("div",{className:"flex-1 overflow-auto border rounded-lg",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Dt,{className:"font-semibold",children:"Name"}),e.jsx(Dt,{className:"font-semibold",children:"Email"}),e.jsx(Dt,{className:"font-semibold",children:"Status"}),e.jsx(Dt,{className:"font-semibold",children:"Role"}),e.jsx(Dt,{className:"w-[120px]"})]})}),e.jsx(fi,{children:jt(Fn.id).length===0?e.jsx(En,{children:e.jsx(_t,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:xs?"No matching members found":"No members in this brokerage"})}):jt(Fn.id).map(qt=>e.jsxs(En,{className:"hover:bg-muted/30",children:[e.jsx(_t,{className:"font-medium",children:qt.name}),e.jsx(_t,{className:"text-muted-foreground",children:qt.email}),e.jsx(_t,{children:qt.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(_t,{children:qt.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(_t,{children:e.jsxs("div",{className:"flex gap-1 justify-end",children:[!qt.claimed&&e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>Ba(qt.id),title:"Resend welcome email",children:e.jsx(mn,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>gh(qt.id),title:"Remove from brokerage",children:e.jsx(pr,{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(qt.id),disabled:a||qt.id===(t==null?void 0:t.id),title:qt.id===(t==null?void 0:t.id)?"Cannot impersonate yourself":`Login as ${qt.name}`,children:a?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(KI,{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(qt.id,qt.name),title:"Delete user",children:e.jsx(Hn,{className:"h-4 w-4"})})]})})]},qt.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(qt=>qt.roles.includes("brokerage_manager")).length," manager",ct(Fn.id).filter(qt=>qt.roles.includes("brokerage_manager")).length!==1?"s":""]})]}),e.jsx(Sr,{children:e.jsx($,{variant:"outline",onClick:ih,children:"Close"})})]})})]}),e.jsx(Xt,{value:"teams",children:e.jsx(Fhn,{})}),e.jsx(Xt,{value:"trials",children:e.jsx(whn,{})}),e.jsx(Xt,{value:"celebrations",children:e.jsx(_hn,{})}),e.jsx(Xt,{value:"deletions",children:e.jsx(Nhn,{})})]})]}),e.jsx(EWt,{open:ho,onOpenChange:Tc,brokerages:u,onSuccess:_s}),zc&&e.jsx(TWt,{open:zr,onOpenChange:qt=>{Hi(qt),qt||Bc(null)},userId:zc.id,userName:zc.name}),e.jsx(Ohn,{open:ke,onOpenChange:Be,recipients:l.filter(qt=>ao.has(qt.id)).map(qt=>({id:qt.id,name:qt.name,email:qt.email}))})]})};function Bhn(){const{toast:s}=Bi(),t=Wt(),[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:y=[]}=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||[]}}),v=j.useMemo(()=>{const P=n.toLowerCase().trim();return P?g.filter(R=>(R.name||"").toLowerCase().includes(P)||(R.email||"").toLowerCase().includes(P)||(R.phone||"").toLowerCase().includes(P)):g},[g,n]),b=j.useMemo(()=>{var R;const P=new Map;for(const D of g){const O=(R=(D.email||"").split("@")[1])==null?void 0:R.toLowerCase();O&&(["gmail.com","yahoo.com","hotmail.com","outlook.com","icloud.com","aol.com","me.com","comcast.net"].includes(O)||P.set(O,(P.get(O)||0)+1))}return Array.from(P.entries()).sort((D,O)=>O[1]-D[1]).slice(0,10)},[g]),w=P=>{i(R=>{const D=new Set(R);return D.has(P)?D.delete(P):D.add(P),D})},S=()=>{a.size===v.length?i(new Set):i(new Set(v.map(P=>P.id)))},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(Ie,{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(ji,{className:"h-4 w-4"})," Selected"]})}),e.jsx(Ie,{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(Nn,{className:"h-4 w-4"})," Top email domains"]})}),e.jsx(Ie,{children:e.jsx("div",{className:"text-3xl font-bold",children:b.length})})]})]}),b.length>0&&e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-base",children:"Domain suggestions"})}),e.jsx(Ie,{children:e.jsx("div",{className:"flex flex-wrap gap-2",children:b.map(([P,R])=>{const D=y.find(O=>O.name.toLowerCase().replace(/[^a-z0-9]/g,"").includes(P.split(".")[0].toLowerCase()));return e.jsxs("div",{className:"flex items-center gap-2 rounded-md border bg-muted/30 px-3 py-2",children:[e.jsxs("span",{className:"font-mono text-sm",children:["@",P]}),e.jsx($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:y.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(Zr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{value:n,onChange:P=>r(P.target.value),placeholder:"Search name, email, phone…",className:"pl-9"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(ms,{value:u,onValueChange:h,children:[e.jsx(us,{className:"w-[240px]",children:e.jsx(fs,{placeholder:"Bulk assign to brokerage…"})}),e.jsx(hs,{children:y.map(P=>e.jsx(Ge,{value:P.id,children:P.name},P.id))})]}),e.jsxs($,{onClick:E,disabled:!u||a.size===0||m,children:[m&&e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),"Assign ",a.size||""]})]})]}),e.jsx(Ie,{children:x?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):v.length===0?e.jsx("div",{className:"py-12 text-center text-muted-foreground",children:"🎉 No unassigned members."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{children:[e.jsx(Dt,{className:"w-10",children:e.jsx(ai,{checked:a.size===v.length&&v.length>0,onCheckedChange:S})}),e.jsx(Dt,{children:"Name"}),e.jsx(Dt,{children:"Email"}),e.jsx(Dt,{children:"Signed up"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{children:"Assign to brokerage"}),e.jsx(Dt,{className:"w-24"})]})}),e.jsx(fi,{children:v.map(P=>{const R=l[P.id]||"";return e.jsxs(En,{children:[e.jsx(_t,{children:e.jsx(ai,{checked:a.has(P.id),onCheckedChange:()=>w(P.id)})}),e.jsx(_t,{className:"font-medium",children:P.name||"—"}),e.jsx(_t,{className:"text-sm text-muted-foreground",children:P.email}),e.jsx(_t,{className:"text-sm text-muted-foreground",children:hu(new Date(P.created_at),{addSuffix:!0})}),e.jsx(_t,{children:e.jsx($e,{variant:"outline",children:P.subscription_status||"none"})}),e.jsx(_t,{children:e.jsxs(ms,{value:R,onValueChange:D=>o(O=>({...O,[P.id]:D})),children:[e.jsx(us,{className:"h-9 w-[240px]",children:e.jsx(fs,{placeholder:"Pick brokerage…"})}),e.jsx(hs,{children:y.map(D=>e.jsx(Ge,{value:D.id,children:D.name},D.id))})]})}),e.jsx(_t,{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 $hn=()=>{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?(re.error("Failed to load invite codes"),console.error(E)):t(A||[]),r(!1)},x=async A=>{if(A.preventDefault(),!l.trim()){re.error("Please enter a code");return}i(!0);const{error:E}=await q.from("invite_codes").insert({code:l.trim().toUpperCase(),description:c.trim()||null,max_uses:u?parseInt(u):null,trial_days:m?parseInt(m):null});E?E.code==="23505"?re.error("This code already exists"):(re.error("Failed to create invite code"),console.error(E)):(re.success("Invite code created"),o(""),d(""),h(""),f(""),g()),i(!1)},y=async(A,E)=>{const{error:I}=await q.from("invite_codes").update({is_active:!E}).eq("id",A);I?re.error("Failed to update code"):t(s.map(P=>P.id===A?{...P,is_active:!E}:P))},v=async A=>{const{error:E}=await q.from("invite_codes").delete().eq("id",A);E?re.error("Failed to delete code"):(re.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),re.success("Link copied to clipboard")},S=`${b}/join`;return e.jsx(Vs,{title:"Invite Codes",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(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(Gn,{children:["Share link: ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded text-sm",children:S})]})]}),e.jsx(Ie,{children:e.jsxs("form",{onSubmit:x,className:"flex flex-wrap gap-4 items-end",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"code",children:"Code"}),e.jsx(pe,{id:"code",placeholder:"WELCOME2024",value:l,onChange: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(dn,{className:"h-4 w-4 mr-2"}),"Create"]})]})})]}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{children:"Active Codes"})}),e.jsx(Ie,{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(En,{children:[e.jsx(Dt,{children:"Code"}),e.jsx(Dt,{children:"Description"}),e.jsx(Dt,{children:"Uses"}),e.jsx(Dt,{children:"Trial"}),e.jsx(Dt,{children:"Created"}),e.jsx(Dt,{children:"Active"}),e.jsx(Dt,{className:"w-24",children:"Actions"})]})}),e.jsx(fi,{children:s.map(A=>e.jsxs(En,{children:[e.jsx(_t,{className:"font-mono font-medium",children:A.code}),e.jsx(_t,{className:"text-muted-foreground",children:A.description||"—"}),e.jsxs(_t,{children:[A.uses_count,A.max_uses&&` / ${A.max_uses}`]}),e.jsx(_t,{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(_t,{className:"text-muted-foreground",children:en(new Date(A.created_at),"MMM d, yyyy")}),e.jsx(_t,{children:e.jsx(Sn,{checked:A.is_active,onCheckedChange:()=>y(A.id,A.is_active)})}),e.jsx(_t,{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(Ha,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>v(A.id),className:"text-destructive hover:text-destructive",title:"Delete code",children:e.jsx(Hn,{className:"h-4 w-4"})})]})})]},A.id))})]})})]})]})})},_E=q;function CSr(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 Uhn(s){return s.toLowerCase().replace(/[^a-z0-9\s-]/g,"").trim().replace(/\s+/g,"-").slice(0,70)}const qhn="https://dashboard.relevelup.com";function ASr(s,t){const r=`${typeof window<"u"&&window.location.hostname==="localhost"?window.location.origin:qhn}/live/${s}`;return t?`${r}?i=${t}`:r}function ESr(){const s=Wt(),t=st({queryKey:["live-events"],queryFn:async()=>{const{data:i,error:l}=await _E.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 _E.from("live_events").insert({...i,created_by:(d=l.user)==null?void 0:d.id}).select().single();if(c)throw c;return o},onSuccess:()=>{s.invalidateQueries({queryKey:["live-events"]}),re.success("Live event created")},onError:i=>re.error((i==null?void 0:i.message)||"Could not create event")}),r=mt({mutationFn:async({id:i,...l})=>{const{error:o}=await _E.from("live_events").update(l).eq("id",i);if(o)throw o},onSuccess:(i,l)=>{s.invalidateQueries({queryKey:["live-events"]}),s.invalidateQueries({queryKey:["live-event",l.id]}),re.success("Saved")},onError:i=>re.error((i==null?void 0:i.message)||"Could not save")}),a=mt({mutationFn:async i=>{const{error:l}=await _E.from("live_events").delete().eq("id",i);if(l)throw l},onSuccess:()=>{s.invalidateQueries({queryKey:["live-events"]}),re.success("Event deleted")},onError:i=>re.error((i==null?void 0:i.message)||"Could not delete")});return{list:t,create:n,update:r,remove:a}}function TSr(s){return st({queryKey:["live-event",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await _E.from("live_events").select("*").eq("id",s).maybeSingle();if(n)throw n;return t}})}function MSr(s){return st({queryKey:["live-registrations",s],enabled:!!s,refetchInterval:2e4,queryFn:async()=>{const{data:t,error:n}=await _E.from("live_registrations").select("*").eq("event_id",s).order("created_at",{ascending:!1});if(n)throw n;return t||[]}})}function PSr(s){const t=Wt(),n=st({queryKey:["live-invites",s],enabled:!!s,queryFn:async()=>{const{data:i,error:l}=await _E.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 _E.from("live_invites").insert(o).select();if(d)throw d;return c||[]},onSuccess:i=>{t.invalidateQueries({queryKey:["live-invites",s]}),re.success(`${i.length} invite link${i.length===1?"":"s"} created`)},onError:i=>re.error((i==null?void 0:i.message)||"Could not create invites")}),a=mt({mutationFn:async i=>{const{error:l}=await _E.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 _ie=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}},bK=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}}},Vhn=async(s,t)=>await _ie("new_templates")?bK({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}),Hhn=async(s,t)=>bK({title:"New Academy Video",body:`New video added: ${s}`,url:`/academy/${t}`}),Ghn=async(s,t)=>await _ie("new_events")?bK({title:"New Event",body:`New event: ${s}`,url:`/events/${t}`}):(console.log("New event notifications are disabled"),{success:!1,skipped:!0}),Whn=async(s,t)=>await _ie("new_toolbox")?bK({title:"New Resource Kit",body:`New resource kit available: ${s}`,url:`/toolbox/${t}`}):(console.log("New toolbox notifications are disabled"),{success:!1,skipped:!0}),UWe=async(s,t)=>await _ie("new_social_swag")?bK({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}),Khn=async(s,t)=>await _ie("new_newsletters")?bK({title:"New Newsletter",body:`New newsletter available: ${s}`,url:`/newsletters/${t}`}):(console.log("New newsletter notifications are disabled"),{success:!1,skipped:!0}),e9e=400;function Yhn(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 Y=!1;return(async()=>{h(!0);try{const[X,ae,le]=await Promise.all([Zhn(),Dwt("event_registrations",n.id),Dwt("event_attendees",n.id)]);if(Y)return;f(X),x(ae),v(le)}catch(X){Y||r({title:"Could not load audience",description:X instanceof Error?X.message:"Unknown error",variant:"destructive"})}finally{Y||h(!1)}})(),()=>{Y=!0}},[s,n,r]),j.useEffect(()=>{s||(A(null),d(""),o(""),i("not_registered"))},[s]);const D=j.useMemo(()=>a==="all"?m:a==="not_registered"?m.filter(Y=>!g.has(Y.id)):m.filter(Y=>g.has(Y.id)&&!y.has(Y.id)),[a,m,g,y]),O={all:m.length,not_registered:m.filter(Y=>!g.has(Y.id)).length,registered_never_attended:m.filter(Y=>g.has(Y.id)&&!y.has(Y.id)).length},U=async(Y,X=!1)=>{const{data:{session:ae}}=await q.auth.getSession(),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:Y.map(te=>({email:te.email,name:te.name,user_id:te.id})),custom_subject:l.trim()||void 0,custom_intro:c.trim()||void 0,force_resend:X||void 0})}),ne=await le.json().catch(()=>({}));if(!le.ok)throw new Error((ne==null?void 0:ne.error)||`HTTP ${le.status}`);return{sent:(ne==null?void 0:ne.sent)??0,failed:(ne==null?void 0:ne.failed)??0,alreadyInvited:(ne==null?void 0:ne.already_invited)??0}},W=async()=>{var Y;if(n){R(!0);try{const{data:{session:X}}=await q.auth.getSession(),ae=X==null?void 0:X.user;if(!(ae!=null&&ae.email))throw new Error("No signed-in email found");const le=await U([{id:ae.id,name:((Y=ae.user_metadata)==null?void 0:Y.name)||"",email:ae.email}],!0);r({title:"Test sent",description:`Sent to ${ae.email} · Sent: ${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 Y=0,X=0,ae=0;for(let le=0;le!b&&t(Y),children:e.jsxs(Os,{className:"max-w-2xl max-h-[92vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(Nn,{className:"h-5 w-5 text-primary"}),"Invite Members to Event"]}),e.jsx(Pr,{children:n?e.jsxs("span",{className:"flex items-center gap-2 text-sm",children:[e.jsx(Cu,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium text-foreground",children:n.title}),e.jsx("span",{children:"·"}),e.jsx("span",{children:Yhn(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(vw,{value:a,onValueChange:Y=>i(Y),className:"space-y-2",children:[e.jsxs("label",{htmlFor:"aud-not-reg",className:"flex items-start gap-3 rounded-lg border p-3 cursor-pointer hover:bg-muted/40 transition",children:[e.jsx(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:Y=>o(Y.target.value),disabled:b}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Leave blank for the default."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"ev-inv-intro",children:"Personal message (optional)"}),e.jsx(Ls,{id:"ev-inv-intro",placeholder:"e.g. Our Wednesday live training this week is on lead conversion. Grab your seat — it's a game-changer.",value:c,onChange:Y=>d(Y.target.value),rows:4,disabled:b}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Appears at the top of the email above the event details."})]}),S&&e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3 space-y-2",children:[e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"text-muted-foreground",children:["Sending ",S.done.toLocaleString()," / ",S.total.toLocaleString()]}),e.jsxs("span",{className:"font-medium",children:["✓ ",S.sent.toLocaleString(),S.failed>0&&e.jsxs("span",{className:"text-destructive",children:[" · ✗ ",S.failed.toLocaleString()]})]})]}),e.jsx(Yi,{value:G})]})]}),e.jsxs(Sr,{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(mn,{className:"h-4 w-4 mr-2"})," Send test to me"]})}),e.jsx($,{variant:"ghost",onClick:()=>t(!1),disabled:b,children:"Cancel"}),e.jsx($,{onClick:()=>I(!0),disabled:b||u||D.length===0,children:b?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"})," Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Kr,{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(Kr,{className:"h-4 w-4 mr-2"})," Send now"]})]})]})})]})}const Fde={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 Qhn(){const s=Xn(),t=Wt(),[n,r]=j.useState(!1),[a,i]=j.useState(null),[l,o]=j.useState(Fde),[c,d]=j.useState(null),[u,h]=j.useState(null),[m,f]=j.useState(!1),g=j.useRef(null),[x,y]=j.useState(!1),[v,b]=j.useState(null),[w,S]=j.useState(!1),[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,Y]=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 pt=1e3;for(;;){const{data:ss,error:Yt}=await q.from("event_registrations").select("event_id").range(Je,Je+pt-1);if(Yt)throw Yt;if(!ss||ss.length===0||(Ke=Ke.concat(ss),ss.length{gt[ss.event_id]=(gt[ss.event_id]||0)+1}),gt}}),{data:ne,isLoading:te}=st({queryKey:["event-registrations-details",v==null?void 0:v.id],queryFn:async()=>{if(!v)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",v.id).order("registered_at",{ascending:!1});if(Je)throw Je;if(!Ke||Ke.length===0)return[];const pt=Ke.map(Yt=>Yt.user_id).filter(Boolean);let gt=[];if(pt.length>0){const{data:Yt,error:ts}=await q.from("profiles").select("id, name, email").in("id",pt);if(ts)throw ts;gt=Yt||[]}const ss=new Map((gt==null?void 0:gt.map(Yt=>[Yt.id,Yt]))||[]);return Ke.map(Yt=>({...Yt,profiles:Yt.user_id&&ss.get(Yt.user_id)||null}))},enabled:!!v}),{data:J,isLoading:ce}=st({queryKey:["event-attendees-details",v==null?void 0:v.id],queryFn:async()=>{if(!v)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",v.id).order("created_at",{ascending:!1});if(Je)throw Je;if(!Ke||Ke.length===0)return[];const pt=Ke.map(ys=>ys.user_id).filter(Boolean);let gt=[];if(pt.length>0){const{data:ys,error:Bt}=await q.from("profiles").select("id, name, email").in("id",pt);if(Bt)throw Bt;gt=ys||[]}const{data:ss}=await q.from("agent_points").select("user_id").eq("event_id",v.id),Yt=new Set((ss==null?void 0:ss.map(ys=>ys.user_id))||[]),ts=new Map((gt==null?void 0:gt.map(ys=>[ys.id,ys]))||[]);return Ke.map(ys=>({...ys,profiles:ys.user_id&&ts.get(ys.user_id)||null,points_awarded:ys.user_id?Yt.has(ys.user_id):!1}))},enabled:!!v}),_e=Ke=>{b(Ke),y(!0)},he=mt({mutationFn:async Ke=>{const{data:{session:Je}}=await q.auth.getSession();if(!Je)throw new Error("Not authenticated");const pt=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 pt.json();if(!pt.ok){const ss=new Error(gt.error||"Failed to sync");throw ss.scopeError=!!gt.scope_error,ss.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,ss}return gt},onSuccess:Ke=>{if(t.invalidateQueries({queryKey:["event-registrations-details",v==null?void 0:v.id]}),t.invalidateQueries({queryKey:["event-registrations-count"]}),Ke!=null&&Ke.scope_error||(Ke==null?void 0:Ke.success)===!1){re.error("Zoom needs one more authorization step",{description:Ke!=null&&Ke.scope_error?"The app is working, but Zoom is still issuing a token without meeting:read:list_registrants:admin. Make that scope required, not Optional, then Continue/Activate/Save in Zoom and retry. If it still shows 7 scopes, update the saved Zoom credentials to the app you edited.":(Ke==null?void 0:Ke.message)||"Zoom registration sync could not complete.",duration:2e4});return}re.success(Ke.message)},onError:Ke=>{re.error("Failed to sync Zoom registrations",{description:Ke.scopeError&&Ke.details||Ke.message,duration:Ke.scopeError?2e4:5e3})}}),ue=mt({mutationFn:async Ke=>{const{data:{session:Je}}=await q.auth.getSession();if(!Je)throw new Error("Not authenticated");const pt=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 pt.json();if(!pt.ok)throw new Error(gt.error||"Failed to sync attendees");return gt},onSuccess:Ke=>{if(t.invalidateQueries({queryKey:["event-attendees-details",v==null?void 0:v.id]}),t.invalidateQueries({queryKey:["event-leaderboard"]}),t.invalidateQueries({queryKey:["admin-agent-points"]}),Ke!=null&&Ke.scope_error||(Ke==null?void 0:Ke.success)===!1){re.error((Ke==null?void 0:Ke.message)||"Zoom sync failed",{description:Ke!=null&&Ke.scope_error?"Zoom must be re-authorized after adding the missing report scope.":void 0,duration:15e3});return}Ke!=null&&Ke.message?re.success(Ke.message):re.success(`Synced ${Ke.synced||0} attendees. ${Ke.points_awarded||0} points awarded!`)},onError:Ke=>{re.error("Failed to sync attendees: "+Ke.message)}}),ve=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",v==null?void 0:v.id]}),t.invalidateQueries({queryKey:["event-registrations-count"]}),re.success(`Retry complete: ${(Ke==null?void 0:Ke.successCount)??0} fixed, ${(Ke==null?void 0:Ke.failCount)??0} still failing, ${(Ke==null?void 0:Ke.rateLimitedCount)??0} rate-limited`)},onError:Ke=>{re.error("Retry failed: "+Ke.message)}}),Ee=mt({mutationFn:async({eventId:Ke,testMode:Je})=>{const{data:{session:pt}}=await q.auth.getSession();if(!pt)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 ${pt.access_token}`},body:JSON.stringify({event_id:Ke,test_mode:Je})}),ss=await gt.json();if(!gt.ok)throw new Error(ss.error||"Failed to send reminders");return ss},onSuccess:Ke=>{Ke.test?re.success(Ke.message||"Test email sent!"):re.success(Ke.message||`Reminder emails sent to ${Ke.sent} registrants!`)},onError:Ke=>{re.error("Failed to send reminders: "+Ke.message)}}),{data:Se}=st({queryKey:["all-profiles-for-linking"],queryFn:async()=>{let Ke=[],Je=0;const pt=1e3;for(;;){const{data:gt,error:ss}=await q.from("profiles").select("id, name, email").order("name",{ascending:!0}).range(Je,Je+pt-1);if(ss)throw ss;if(!gt||gt.length===0||(Ke=[...Ke,...gt],gt.length{const{error:ss}=await q.from("event_attendees").update({user_id:Je}).eq("id",Ke);if(ss)throw ss;if(gt&&pt){const{error:ts}=await q.from("zoom_email_aliases").upsert({user_id:Je,zoom_email:pt.toLowerCase()},{onConflict:"zoom_email"});ts&&console.error("Failed to save alias:",ts)}const Yt=v==null?void 0:v.id;if(Yt){const{data:ts}=await q.from("user_roles").select("id").eq("user_id",Je).eq("role","admin").single();if(!ts){const{data:ys}=await q.from("agent_points").select("id").eq("user_id",Je).eq("event_id",Yt).single();ys||(await q.rpc("award_attendance_points",{p_user_id:Je,p_event_id:Yt,p_points:10,p_reason:"Event Attendance (Manual Link)"}),await q.rpc("check_and_award_badges",{p_user_id:Je}))}}return{userId:Je,zoomEmail:pt,shouldSaveAlias:gt}},onSuccess:Ke=>{t.invalidateQueries({queryKey:["event-attendees-details",v==null?void 0:v.id]}),t.invalidateQueries({queryKey:["event-leaderboard"]}),t.invalidateQueries({queryKey:["admin-agent-points"]});let Je="Attendee linked and points awarded!";Ke.shouldSaveAlias&&Ke.zoomEmail&&(Je+=` Email "${Ke.zoomEmail}" will be auto-matched in the future.`),re.success(Je),S(!1),E(null),P(null),U("")},onError:Ke=>{re.error("Failed to link attendee: "+Ke.message)}}),Fe=Ke=>{E(Ke),P(null),D(!0),U(""),S(!0)},ke=()=>{!A||!I||Le.mutate({attendeeId:A.id,userId:I,zoomEmail:A.zoom_email,shouldSaveAlias:R})},Be=(Se==null?void 0:Se.filter(Ke=>{var pt,gt;if(!O)return!0;const Je=O.toLowerCase();return((pt=Ke.name)==null?void 0:pt.toLowerCase().includes(Je))||((gt=Ke.email)==null?void 0:gt.toLowerCase().includes(Je))}))||[],Ne=async Ke=>{const Je=Ke.name.split(".").pop(),gt=`${`${crypto.randomUUID()}.${Je}`}`,{error:ss}=await q.storage.from("event-images").upload(gt,Ke);if(ss)throw ss;const{data:{publicUrl:Yt}}=q.storage.from("event-images").getPublicUrl(gt);return Yt},Ae=Ke=>{var pt;const Je=(pt=Ke.target.files)==null?void 0:pt[0];if(Je){if(Je.size>5*1024*1024){re.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="")},Ve=mt({mutationFn:async Ke=>{f(!0);let Je=Ke.image_url;c&&(Je=await Ne(c)||"");const pt=new Date(Ke.event_date),[gt,ss]=Ke.event_time.split(":");pt.setHours(parseInt(gt),parseInt(ss));const Yt=[new Date(pt)];if(Ke.is_recurring&&Ke.recurrence_end_date){let Ft=new Date(pt);for(;Ke.recurrence_pattern==="weekly"?Ft=a8(Ft,1):Ke.recurrence_pattern==="biweekly"?Ft=a8(Ft,2):Ft=Ev(Ft,1),!(Ft>Ke.recurrence_end_date);)Yt.push(new Date(Ft))}const ts=Yt.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:ys,error:Bt}=await q.from("events").insert(ts).select();if(Bt)throw Bt;return ys&&ys.length>0&&Ghn(Ke.title,ys[0].id),Yt.length},onSuccess:Ke=>{t.invalidateQueries({queryKey:["admin-events"]}),re.success(Ke>1?`${Ke} recurring events created successfully`:"Event created successfully"),r(!1),o(Fde),d(null),h(null),f(!1)},onError:Ke=>{re.error("Failed to create event: "+Ke.message),f(!1)}}),ze=mt({mutationFn:async({id:Ke,data:Je})=>{f(!0);let pt=Je.image_url;c&&(pt=await Ne(c)||"");const gt=new Date(Je.event_date),[ss,Yt]=Je.event_time.split(":");gt.setHours(parseInt(ss),parseInt(Yt));const{error:ts}=await q.from("events").update({title:Je.title,description:Je.description||null,image_url:pt||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(ts)throw ts},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-events"]}),re.success("Event updated successfully"),r(!1),i(null),o(Fde),d(null),h(null),f(!1)},onError:Ke=>{re.error("Failed to update event: "+Ke.message),f(!1)}}),qe=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"]}),re.success("Event deleted successfully")},onError:Ke=>{re.error("Failed to delete event: "+Ke.message)}}),dt=mt({mutationFn:async Ke=>{var Ft;const{data:Je}=await q.auth.getUser(),pt=new Date(Ke.event_date),gt=new Date(pt.getTime()+60*60*1e3),ss=Uhn(Ke.title),Yt=Math.random().toString(36).slice(2,7),ts=`${ss}-${Yt}`,{data:ys,error:Bt}=await q.from("live_events").insert({slug:ts,title:Ke.title,description:Ke.description||null,hero_image_url:Ke.image_url||null,starts_at:Ke.event_date,ends_at: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(Bt)throw Bt;return ys},onSuccess:Ke=>{t.invalidateQueries({queryKey:["live-events"]}),re.success("Cloned to LevelUp Live — configure stream next"),s(`/admin/live/${Ke.id}`)},onError:Ke=>{re.error("Failed to clone to LevelUp Live: "+Ke.message)}}),Xe=Ke=>{var pt;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:en(Je,"HH:mm"),zoom_link:Ke.zoom_link,zoom_meeting_id:Ke.zoom_meeting_id||"",capacity:((pt=Ke.capacity)==null?void 0:pt.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){re.error("Please select a date");return}if(l.is_recurring&&!l.recurrence_end_date){re.error("Please select an end date for recurring events");return}a?ze.mutate({id:a.id,data:l}):Ve.mutate(l)},rt=()=>{r(!1),i(null),o(Fde),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(zs,{open:n,onOpenChange:Ke=>!Ke&&rt(),children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{onClick:()=>r(!0),children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Add Event"]})}),e.jsxs(Os,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(Bs,{children:a?"Edit Event":"Create New Event"})}),e.jsxs("form",{onSubmit: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(Sk,{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(pr,{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(Kd,{children:[e.jsx(Yd,{asChild:!0,children:e.jsxs($,{variant:"outline",className:Pt("w-full justify-start text-left font-normal",!l.event_date&&"text-muted-foreground"),children:[e.jsx(Ta,{className:"mr-2 h-4 w-4"}),l.event_date?en(l.event_date,"PPP"):"Pick a date"]})}),e.jsx(Od,{className:"w-auto p-0",align:"start",children:e.jsx(T2,{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(FE,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ee,{htmlFor:"is_recurring",children:"Recurring Event"})]}),e.jsx(Sn,{id:"is_recurring",checked:l.is_recurring,onCheckedChange:Ke=>o({...l,is_recurring:Ke})})]}),l.is_recurring&&e.jsxs("div",{className:"space-y-3 pt-1",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Frequency"}),e.jsxs(ms,{value:l.recurrence_pattern,onValueChange:Ke=>o({...l,recurrence_pattern:Ke}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"weekly",children:"Weekly"}),e.jsx(Ge,{value:"biweekly",children:"Every 2 Weeks"}),e.jsx(Ge,{value:"monthly",children:"Monthly"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Repeat Until"}),e.jsxs(Kd,{children:[e.jsx(Yd,{asChild:!0,children:e.jsxs($,{variant:"outline",className:Pt("w-full justify-start text-left font-normal",!l.recurrence_end_date&&"text-muted-foreground"),children:[e.jsx(Ta,{className:"mr-2 h-4 w-4"}),l.recurrence_end_date?en(l.recurrence_end_date,"PPP"):"Pick end date"]})}),e.jsx(Od,{className:"w-auto p-0",align:"start",children:e.jsx(T2,{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"?a8(Je,1):l.recurrence_pattern==="biweekly"?a8(Je,2):Ev(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(Sn,{id:"is_published",checked:l.is_published,onCheckedChange:Ke=>o({...l,is_published:Ke})})]}),e.jsxs("div",{className:"flex gap-2 pt-4",children:[e.jsx($,{type:"button",variant:"outline",onClick:rt,className:"flex-1",children:"Cancel"}),e.jsx($,{type:"submit",className:"flex-1",disabled:Ve.isPending||ze.isPending||m,children:m?"Uploading...":a?"Update Event":l.is_recurring&&l.event_date&&l.recurrence_end_date?"Create Recurring Events":"Create Event"})]})]})]})]})]}),e.jsx(Ie,{children:ae?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading events..."}):(X==null?void 0:X.length)===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No events yet. Create your first event!"}):(()=>{const Ke=new Date,Je=[...X||[]],pt=Je.filter(ys=>new Date(ys.event_date)>=Ke).sort((ys,Bt)=>new Date(ys.event_date).getTime()-new Date(Bt.event_date).getTime()),gt=Je.filter(ys=>new Date(ys.event_date)new Date(Bt.event_date).getTime()-new Date(ys.event_date).getTime()),ss=pt[0],Yt=ys=>e.jsxs(En,{children:[e.jsx(_t,{className:"font-medium",children:ys.title}),e.jsx(_t,{className:"whitespace-nowrap",children:en(new Date(ys.event_date),"PPP p")}),e.jsx(_t,{children:e.jsxs($,{variant:"ghost",size:"sm",className:"gap-1",onClick:()=>_e(ys),children:[e.jsx(Yn,{className:"h-4 w-4"}),(le==null?void 0:le[ys.id])||0,ys.capacity&&` / ${ys.capacity}`]})}),e.jsx(_t,{children:e.jsx("span",{className:Pt("px-2 py-1 rounded-full text-xs font-medium",ys.is_published?"bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200":"bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200"),children:ys.is_published?"Published":"Draft"})}),e.jsx(_t,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsxs($,{variant:"outline",size:"sm",className:"gap-1.5",onClick:()=>{Y(ys),V(!0)},title:"Send invite email to members",children:[e.jsx(Kr,{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:()=>dt.mutate(ys),disabled:dt.isPending,title:"Clone to LevelUp Live",children:[e.jsx(_b,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:"LevelUp Live"})]}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>window.open(ys.zoom_link,"_blank"),title:"Open Zoom Link",children:e.jsx(Fr,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>Xe(ys),children:e.jsx(pi,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:async()=>{await fo("Are you sure you want to delete this event?")&&qe.mutate(ys.id)},children:e.jsx(Hn,{className:"h-4 w-4 text-destructive"})})]})})]},ys.id),ts=(ys,Bt)=>ys.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:Bt}):e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Title"}),e.jsx(Dt,{children:"Date & Time"}),e.jsx(Dt,{children:"Registrations"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(fi,{children:ys.map(Yt)})]});return e.jsxs("div",{className:"space-y-6",children:[ss&&e.jsx("div",{className:"rounded-xl border bg-gradient-to-br from-primary/10 via-primary/5 to-transparent p-5",children:e.jsxs("div",{className:"flex items-start justify-between gap-4 flex-wrap",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-primary mb-1",children:[e.jsx(da,{className:"h-3.5 w-3.5"}),"Next Upcoming Event"]}),e.jsx("h3",{className:"text-xl font-bold truncate",children:ss.title}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:en(new Date(ss.event_date),"EEEE, PPP 'at' p")}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[(le==null?void 0:le[ss.id])||0," registered",ss.capacity?` of ${ss.capacity}`:""]})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs($,{size:"sm",className:"gap-1.5",onClick:()=>{Y(ss),V(!0)},children:[e.jsx(Kr,{className:"h-4 w-4"}),"Invite Members"]}),e.jsxs($,{size:"sm",variant:"outline",className:"gap-1.5",onClick:()=>_e(ss),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:()=>dt.mutate(ss),disabled:dt.isPending,children:[e.jsx(_b,{className:"h-4 w-4"}),"LevelUp Live"]}),e.jsxs($,{size:"sm",variant:"outline",className:"gap-1.5",onClick:()=>window.open(ss.zoom_link,"_blank"),children:[e.jsx(Fr,{className:"h-4 w-4"}),"Zoom"]})]})]})}),e.jsxs(ha,{defaultValue:"upcoming",className:"w-full",children:[e.jsxs(ma,{children:[e.jsxs(Zt,{value:"upcoming",className:"gap-2",children:[e.jsx(da,{className:"h-4 w-4"}),"Upcoming",e.jsx("span",{className:"ml-1 rounded-full bg-muted px-2 py-0.5 text-xs",children:pt.length})]}),e.jsxs(Zt,{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(Xt,{value:"upcoming",className:"mt-4",children:ts(pt,"No upcoming events scheduled.")}),e.jsx(Xt,{value:"past",className:"mt-4",children:ts(gt,"No past events.")})]})]})})()})]}),e.jsx(Xhn,{open:W,onOpenChange:V,event:G}),e.jsx(zs,{open:x,onOpenChange:y,children:e.jsxs(Os,{className:"max-w-3xl max-h-[80vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(Yn,{className:"h-5 w-5"}),v==null?void 0:v.title]}),e.jsx(Pr,{children:"View registrations and attendees for this event"})]}),e.jsxs("div",{className:"flex items-center justify-end mb-4 gap-2 flex-wrap",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>Ee.mutate({eventId:v.id,testMode:!0}),disabled:Ee.isPending,children:[e.jsx(mn,{className:Pt("h-4 w-4 mr-2",Ee.isPending&&"animate-spin")}),"Send Test to Me"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>Ee.mutate({eventId:v.id}),disabled:Ee.isPending||!(ne!=null&&ne.length),children:[e.jsx(mn,{className:Pt("h-4 w-4 mr-2",Ee.isPending&&"animate-spin")}),Ee.isPending?"Sending...":"Send Reminder to All"]}),(v==null?void 0:v.zoom_meeting_id)&&e.jsxs(e.Fragment,{children:[e.jsxs($,{variant:"outline",size:"sm",onClick:()=>he.mutate(v.id),disabled:he.isPending,children:[e.jsx(ro,{className:Pt("h-4 w-4 mr-2",he.isPending&&"animate-spin")}),he.isPending?"Syncing...":"Sync Registrations"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>ve.mutate(),disabled:ve.isPending,children:[e.jsx(ro,{className:Pt("h-4 w-4 mr-2",ve.isPending&&"animate-spin")}),ve.isPending?"Retrying...":"Retry Failed Registrations"]}),e.jsxs($,{variant:"default",size:"sm",onClick:()=>ue.mutate(v.id),disabled:ue.isPending,children:[e.jsx(Kl,{className:Pt("h-4 w-4 mr-2",ue.isPending&&"animate-spin")}),ue.isPending?"Syncing...":"Sync Attendees & Award Points"]})]})]}),e.jsxs(ha,{defaultValue:"registrations",className:"w-full",children:[e.jsxs(ma,{className:"grid w-full grid-cols-2",children:[e.jsxs(Zt,{value:"registrations",className:"gap-2",children:[e.jsx(Yn,{className:"h-4 w-4"}),"Registrations (",(ne==null?void 0:ne.length)||0,")"]}),e.jsxs(Zt,{value:"attendees",className:"gap-2",children:[e.jsx(Vr,{className:"h-4 w-4"}),"Attendees (",(J==null?void 0:J.length)||0,")"]})]}),e.jsx(Xt,{value:"registrations",className:"mt-4",children:te?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading registrations..."}):(ne==null?void 0:ne.length)===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx("p",{children:"No registrations yet for this event."}),(v==null?void 0:v.zoom_meeting_id)&&e.jsx("p",{className:"text-xs mt-2",children:'Click "Sync Registrations" to import from Zoom.'})]}):e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Name"}),e.jsx(Dt,{children:"Email"}),e.jsx(Dt,{children:"Registered"}),e.jsx(Dt,{children:"Status"})]})}),e.jsx(fi,{children:ne==null?void 0:ne.map(Ke=>{var ss,Yt;const Je=((ss=Ke.profiles)==null?void 0:ss.name)||Ke.zoom_name||"Unknown",pt=((Yt=Ke.profiles)==null?void 0:Yt.email)||Ke.zoom_email||null,gt=!Ke.user_id;return e.jsxs(En,{children:[e.jsx(_t,{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(_t,{children:pt?e.jsxs("a",{href:`mailto:${pt}`,className:"flex items-center gap-1 text-primary hover:underline",children:[e.jsx(mn,{className:"h-3 w-3"}),pt]}):e.jsx("span",{className:"text-muted-foreground",children:"No email"})}),e.jsx(_t,{className:"text-muted-foreground text-sm",children:en(new Date(Ke.registered_at),"MMM d, yyyy h:mm a")}),e.jsx(_t,{children:Ke.zoom_join_url?e.jsx("span",{className:"inline-flex items-center gap-1 text-xs px-2 py-1 rounded-full bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200",children:"Registered"}):e.jsx("span",{className:"inline-flex items-center gap-1 text-xs px-2 py-1 rounded-full bg-muted text-muted-foreground",children:"Pending"})})]},Ke.id)})})]})}),e.jsx(Xt,{value:"attendees",className:"mt-4",children:ce?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading attendees..."}):(J==null?void 0:J.length)===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx("p",{children:"No attendees recorded yet."}),(v==null?void 0:v.zoom_meeting_id)&&e.jsx("p",{className:"text-xs mt-2",children:'Click "Sync Attendees & Award Points" after the event ends to import actual participants from Zoom.'})]}):e.jsxs(e.Fragment,{children:[(J==null?void 0:J.filter(Ke=>!Ke.user_id).length)>0&&e.jsxs("div",{className:"mb-6 p-4 border border-amber-200 bg-amber-50 dark:border-amber-800 dark:bg-amber-950 rounded-lg",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(ll,{className:"h-4 w-4 text-amber-600 dark:text-amber-400"}),e.jsxs("h4",{className:"font-medium text-amber-800 dark:text-amber-200",children:["Unmatched Attendees (",J==null?void 0:J.filter(Ke=>!Ke.user_id).length,")"]})]}),e.jsx("p",{className:"text-xs text-amber-700 dark:text-amber-300 mb-3",children:"These attendees couldn't be matched to a profile. Link them to award points."}),e.jsx("div",{className:"space-y-2",children:J==null?void 0:J.filter(Ke=>!Ke.user_id).map(Ke=>e.jsxs("div",{className:"flex items-center justify-between p-2 bg-background rounded border",children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"font-medium text-sm",children:Ke.zoom_name||"Unknown"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Ke.zoom_email||"No email"})]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>Fe(Ke),className:"gap-1",children:[e.jsx(Wd,{className:"h-3 w-3"}),"Link to Profile"]})]},Ke.id))})]}),e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Name"}),e.jsx(Dt,{children:"Email"}),e.jsx(Dt,{children:"Duration"}),e.jsx(Dt,{children:"Points"})]})}),e.jsx(fi,{children:J==null?void 0:J.filter(Ke=>Ke.user_id).map(Ke=>{var gt,ss;const Je=((gt=Ke.profiles)==null?void 0:gt.name)||Ke.zoom_name||"Unknown",pt=((ss=Ke.profiles)==null?void 0:ss.email)||Ke.zoom_email||null;return e.jsxs(En,{children:[e.jsx(_t,{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(_t,{children:pt?e.jsxs("a",{href:`mailto:${pt}`,className:"flex items-center gap-1 text-primary hover:underline",children:[e.jsx(mn,{className:"h-3 w-3"}),pt]}):e.jsx("span",{className:"text-muted-foreground",children:"No email"})}),e.jsx(_t,{children:Ke.duration_minutes?e.jsxs("span",{className:"flex items-center gap-1 text-muted-foreground text-sm",children:[e.jsx(da,{className:"h-3 w-3"}),Ke.duration_minutes," min"]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(_t,{children:Ke.points_awarded?e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs px-2 py-1 rounded-full bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200",children:[e.jsx(Kl,{className:"h-3 w-3"}),"+10 pts"]}):e.jsx("span",{className:"inline-flex items-center gap-1 text-xs px-2 py-1 rounded-full bg-muted text-muted-foreground",children:"Pending"})})]},Ke.id)})})]})]})})]})]})}),e.jsx(zs,{open:w,onOpenChange:S,children:e.jsxs(Os,{className:"max-w-md",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(Wd,{className:"h-5 w-5"}),"Link Attendee to Profile"]}),e.jsx(Pr,{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(Zr,{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:ke,disabled:!I||Le.isPending,children:Le.isPending?"Linking...":"Link & Award Points"})]})]})]})})]})})}const Jhn={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 emn(){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(eV,{className:"h-5 w-5"}),"Recent activity"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:a==="issues"?"default":"outline",size:"sm",onClick:()=>i("issues"),children:"Issues only"}),e.jsx($,{variant:a==="all"?"default":"outline",size:"sm",onClick:()=>i("all"),children:"All calls"}),e.jsx($,{variant:"ghost",size:"sm",onClick:l,disabled:n,children:e.jsx(ro,{className:`h-4 w-4 ${n?"animate-spin":""}`})})]})]}),e.jsx(Ie,{children:n?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading…"}):s.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No entries."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"border-b text-left text-muted-foreground",children:e.jsxs("tr",{children:[e.jsx("th",{className:"py-2 pr-4",children:"When"}),e.jsx("th",{className:"py-2 pr-4",children:"Tool"}),e.jsx("th",{className:"py-2 pr-4",children:"Outcome"}),e.jsx("th",{className:"py-2 pr-4",children:"User"}),e.jsx("th",{className:"py-2 pr-4",children:"Client"}),e.jsx("th",{className:"py-2 pr-4",children:"ms"}),e.jsx("th",{className:"py-2 pr-4",children:"Error"})]})}),e.jsx("tbody",{children:s.map(o=>e.jsxs("tr",{className:"border-b last:border-0",children:[e.jsx("td",{className:"py-2 pr-4 whitespace-nowrap",children:new Date(o.created_at).toLocaleString()}),e.jsx("td",{className:"py-2 pr-4 font-mono text-xs",children:o.tool_name}),e.jsx("td",{className:"py-2 pr-4",children:e.jsx($e,{className:Jhn[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 tmn({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(pr,{className:"h-3 w-3"})})]},h.id))}),e.jsxs(Kd,{open:a,onOpenChange:i,children:[e.jsx(Yd,{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(Od,{className:"w-80 p-2",align:"start",children:[e.jsxs("div",{className:"relative mb-2",children:[e.jsx(Zr,{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 smn=()=>{const{user:s}=bs(),{toast:t}=Bi(),n=Wt(),[r,a]=gc(),[i,l]=j.useState(!1),[o,c]=j.useState(null),[d,u]=j.useState({name:"",description:"",category_id:"",type_id:"",publish_date:new Date().toISOString().split("T")[0],links:[{title:"",canva_share_link:"",sort_order:0}],guides:[],video_url:""}),[h,m]=j.useState(null),[f,g]=j.useState(0),[x,y]=j.useState(!1),[v,b]=j.useState(null),[w,S]=j.useState(""),[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:Ve}=await q.from("template_categories").select("*").order("name");if(Ve)throw Ve;return Ce}}),{data:Y=[]}=st({queryKey:["template-types"],queryFn:async()=>{const{data:Ce,error:Ve}=await q.from("template_types").select("*").order("name");if(Ve)throw Ve;return Ce}}),{data:X=[],isLoading:ae}=st({queryKey:["canva-templates-admin"],queryFn:async()=>{const{data:Ce,error:Ve}=await q.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).order("publish_date",{ascending:!1});if(Ve)throw Ve;const{data:ze,error:qe}=await q.from("template_links").select("*").order("sort_order");if(qe)throw qe;const{data:dt,error:Xe}=await q.from("template_guides").select("*").order("sort_order");if(Xe)throw Xe;return Ce.map(rt=>({...rt,links:(ze==null?void 0:ze.filter(Ke=>Ke.template_id===rt.id))||[],guides:(dt==null?void 0:dt.filter(Ke=>Ke.template_id===rt.id))||[]}))}});j.useEffect(()=>{const Ce=r.get("edit");if(Ce&&X.length>0){const Ve=X.find(ze=>ze.id===Ce);Ve&&(he(Ve),a({},{replace:!0}))}},[X,r]);const le=mt({mutationFn:async Ce=>{const{data:Ve,error:ze}=await q.from("template_categories").insert({name:Ce}).select().single();if(ze)throw ze;return Ve},onSuccess:Ce=>{n.invalidateQueries({queryKey:["template-categories"]}),u({...d,category_id:Ce.id}),P(""),U(!1),t({title:"Category added"})},onError:Ce=>{t({title:"Error adding category",description:Ce.message,variant:"destructive"})}}),ne=mt({mutationFn:async Ce=>{const{data:Ve,error:ze}=await q.from("template_types").insert({name:Ce}).select().single();if(ze)throw ze;return Ve},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 Xe;let Ve=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);Ve=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:Ve,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 qe=Ce.templateId;if(qe){const{error:at}=await q.from("canva_templates").update(ze).eq("id",qe);if(at)throw at;const{error:rt}=await q.from("template_links").delete().eq("template_id",qe);if(rt)throw rt;const Ke=((Xe=Ce.existingGuides)==null?void 0:Xe.map(gt=>gt.id).filter(Boolean))||[],Je=Ce.template.guides.map(gt=>gt.id).filter(Boolean),pt=Ke.filter(gt=>!Je.includes(gt));pt.length>0&&await q.from("template_guides").delete().in("id",pt)}else{const{data:at,error:rt}=await q.from("canva_templates").insert(ze).select().single();if(rt)throw rt;qe=at.id,Vhn(Ce.template.name,at.id)}const dt=Ce.template.links.filter(at=>at.title.trim()&&at.canva_share_link.trim());if(dt.length>0){const at=dt.map((Ke,Je)=>({template_id:qe,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:qe,kit_id:rt})));if(at)throw at}},onSuccess:()=>{n.invalidateQueries({queryKey:["canva-templates-admin"]}),n.invalidateQueries({queryKey:["canva-templates"]}),_e(),l(!1),t({title:o?"Template updated":"Template created"})},onError:Ce=>{t({title:"Error saving template",description:Ce.message,variant:"destructive"})}}),J=mt({mutationFn:async Ce=>{const{error:Ve}=await q.from("canva_templates").delete().eq("id",Ce);if(Ve)throw Ve},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:Ve})=>{const{error:ze}=await q.from("canva_templates").update({is_featured:Ve}).eq("id",Ce);if(ze)throw ze},onSuccess:()=>{n.invalidateQueries({queryKey:["canva-templates-admin"]}),n.invalidateQueries({queryKey:["canva-templates"]})},onError:Ce=>{t({title:"Error updating featured",description:Ce.message,variant:"destructive"})}}),_e=()=>{u({name:"",description:"",category_id:"",type_id:"",publish_date:new Date().toISOString().split("T")[0],links:[{title:"",canva_share_link:"",sort_order:0}],guides:[],video_url:""}),b(null),S(""),c(null),U(!1),V(!1),P(""),D(""),m(null),g(0),y(!1),E([])},he=async Ce=>{var ze;c(Ce),u({name:Ce.name,description:Ce.description||"",category_id:Ce.category_id||"",type_id:Ce.type_id||"",publish_date:Ce.publish_date?new Date(Ce.publish_date).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],links:Ce.links&&Ce.links.length>0?Ce.links.map(qe=>({id:qe.id,title:qe.title,canva_share_link:qe.canva_share_link,sort_order:qe.sort_order})):[{title:"",canva_share_link:"",sort_order:0}],guides:((ze=Ce.guides)==null?void 0:ze.map(qe=>({id:qe.id,name:qe.name,file_url:qe.file_url,file_type:qe.file_type,file_size:qe.file_size,sort_order:qe.sort_order})))||[],video_url:Ce.video_url||""}),S(Ce.preview_image_url||""),m(null);const{data:Ve}=await q.from("resource_kit_templates").select("kit_id").eq("template_id",Ce.id);E((Ve||[]).map(qe=>qe.kit_id)),l(!0)},ue=Ce=>{var ze;const Ve=(ze=Ce.target.files)==null?void 0:ze[0];Ve&&(b(Ve),S(URL.createObjectURL(Ve)))},ve=()=>{u({...d,links:[...d.links,{title:"",canva_share_link:"",sort_order:d.links.length}]})},Ee=Ce=>{if(d.links.length<=1)return;const Ve=d.links.filter((ze,qe)=>qe!==Ce);u({...d,links:Ve})},Se=(Ce,Ve,ze)=>{const qe=[...d.links];qe[Ce]={...qe[Ce],[Ve]:ze},u({...d,links:qe})},Le=Ce=>{const Ve=Ce.target.files;if(!Ve)return;const ze=Array.from(Ve).map((qe,dt)=>({name:qe.name.replace(/\.[^/.]+$/,""),file_url:"",file_type:qe.type,file_size:qe.size,sort_order:d.guides.length+dt,file:qe}));u({...d,guides:[...d.guides,...ze]}),Ce.target.value=""},Fe=Ce=>{const Ve=d.guides.filter((ze,qe)=>qe!==Ce);u({...d,guides:Ve})},ke=(Ce,Ve)=>{const ze=[...d.guides];ze[Ce]={...ze[Ce],name:Ve},u({...d,guides:ze})},Be=async()=>{if(!h)return null;y(!0),g(0);try{const{data:Ce,error:Ve}=await q.functions.invoke("bunny-upload",{body:{action:"create",title:d.name||h.name}});if(Ve)throw new Error(Ve.message);const{videoId:ze,libraryId:qe}=Ce,{data:dt,error:Xe}=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:ze}});if(Xe)throw new Error(Xe.message);const at=new XMLHttpRequest;return await new Promise((Ke,Je)=>{at.upload.addEventListener("progress",pt=>{if(pt.lengthComputable){const gt=Math.round(pt.loaded/pt.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",dt.uploadUrl),at.setRequestHeader("AccessKey",dt.apiKey),at.send(h)}),`https://player.mediadelivery.net/embed/${qe}/${ze}`}catch(Ce){return console.error("Bunny upload error:",Ce),t({title:"Video upload failed",description:Ce instanceof Error?Ce.message:"Unknown error",variant:"destructive"}),null}finally{y(!1)}},Ne=Ce=>{var ze;const Ve=(ze=Ce.target.files)==null?void 0:ze[0];Ve&&m(Ve),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(qe=>qe.title.trim()&&qe.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 qe=await Be();if(!qe)return;ze=qe}te.mutate({template:d,image:v,existingImageUrl:(o==null?void 0:o.preview_image_url)||null,templateId:o==null?void 0:o.id,existingGuides:o==null?void 0:o.guides,videoUrl:ze,linkedKitIds: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(Ie,{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(Ie,{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(Ie,{children:e.jsx("div",{className:"text-2xl font-bold",children:Y.length})})]})]}),e.jsxs(zs,{open:i,onOpenChange:Ce=>{l(Ce),Ce||_e()},children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{className:"gap-2",children:[e.jsx(dn,{className:"h-4 w-4"}),"Add Template"]})}),e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(Bs,{children:o?"Edit Template":"Add New Template"})}),e.jsxs("form",{onSubmit:Ae,className:"space-y-6 pt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"name",children:"Name *"}),e.jsx(pe,{id:"name",value:d.name,onChange:Ce=>u({...d,name:Ce.target.value}),placeholder:"Template name",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Description"}),e.jsx(Sk,{content:d.description,onChange:Ce=>u({...d,description:Ce}),placeholder:"Brief description of the template",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{children:"Canva Links *"}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:ve,className:"gap-1",children:[e.jsx(dn,{className:"h-3 w-3"}),"Add Link"]})]}),e.jsx("div",{className:"space-y-3",children:d.links.map((Ce,Ve)=>e.jsxs("div",{className:"flex gap-2 items-start p-3 border rounded-lg bg-muted/30",children:[e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(pe,{value:Ce.title,onChange:ze=>Se(Ve,"title",ze.target.value),placeholder:"Link title (e.g., Instagram Post, Story)"}),e.jsx(pe,{value:Ce.canva_share_link,onChange:ze=>Se(Ve,"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(Ve),children:e.jsx(pr,{className:"h-4 w-4"})})]},Ve))})]}),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(pr,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(ms,{value:d.category_id,onValueChange:Ce=>u({...d,category_id:Ce}),children:[e.jsx(us,{className:"flex-1",children:e.jsx(fs,{placeholder:"Select category"})}),e.jsx(hs,{children:G.map(Ce=>e.jsx(Ge,{value:Ce.id,children:Ce.name},Ce.id))})]}),e.jsx($,{type:"button",variant:"outline",size:"icon",onClick:()=>U(!0),children:e.jsx(dn,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Template Type"}),W?e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{value:R,onChange:Ce=>D(Ce.target.value),placeholder:"New type name",className:"flex-1"}),e.jsx($,{type:"button",size:"sm",onClick:()=>R.trim()&&ne.mutate(R.trim()),disabled:ne.isPending,children:"Add"}),e.jsx($,{type:"button",size:"sm",variant:"ghost",onClick:()=>{V(!1),D("")},children:e.jsx(pr,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(ms,{value:d.type_id,onValueChange:Ce=>u({...d,type_id:Ce}),children:[e.jsx(us,{className:"flex-1",children:e.jsx(fs,{placeholder:"Select type"})}),e.jsx(hs,{children:Y.map(Ce=>e.jsx(Ge,{value:Ce.id,children:Ce.name},Ce.id))})]}),e.jsx($,{type:"button",variant:"outline",size:"icon",onClick:()=>V(!0),children:e.jsx(dn,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(pe,{id:"publish_date",type:"date",value:d.publish_date,onChange:Ce=>u({...d,publish_date:Ce.target.value})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Templates are sorted by publish date (newest first) on the member page"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Preview Image"}),e.jsxs("div",{className:"flex items-start gap-4",children:[w?e.jsxs("div",{className:"relative w-32 h-24 rounded-lg overflow-hidden border bg-muted",children:[e.jsx("img",{src:w,alt:"Preview",className:"w-full h-full object-cover"}),e.jsx($,{type:"button",size:"icon",variant:"destructive",className:"absolute top-1 right-1 h-6 w-6",onClick:()=>{b(null),S("")},children:e.jsx(pr,{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(ua,{className:"h-5 w-5 text-primary shrink-0"}),e.jsx("span",{className:"text-sm flex-1 truncate",children:"Video uploaded"}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>u({...d,video_url:""}),className:"text-destructive hover:text-destructive",children:"Remove"})]}),e.jsx("div",{className:"aspect-video max-w-md rounded-lg overflow-hidden border",children:e.jsx("iframe",{src:d.video_url,className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})]}):x?e.jsxs("div",{className:"space-y-2 p-4 border rounded-lg bg-muted/30",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(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(ua,{className:"h-5 w-5 text-muted-foreground shrink-0"}),e.jsx("span",{className:"text-sm flex-1 truncate",children:h.name}),e.jsxs("span",{className:"text-xs text-muted-foreground shrink-0",children:[(h.size/1024/1024).toFixed(1)," MB"]}),e.jsx($,{type:"button",variant:"ghost",size:"icon",className:"shrink-0 text-muted-foreground hover:text-destructive h-8 w-8",onClick:()=>m(null),children:e.jsx(pr,{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:Ne,className:"hidden"}),e.jsxs("div",{className:"flex items-center justify-center gap-2 p-6 border-2 border-dashed rounded-lg hover:border-primary/50 transition-colors",children:[e.jsx(ua,{className:"h-8 w-8 text-muted-foreground/50"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Click to upload a video"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Upload a video to embed on the template page (Bunny.net)"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{children:"Guide Files (PDFs)"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(pe,{type:"file",accept:".pdf,.doc,.docx",multiple:!0,onChange:Le,className:"hidden"}),e.jsx($,{type:"button",variant:"outline",size:"sm",className:"gap-1",asChild:!0,children:e.jsxs("span",{children:[e.jsx(ni,{className:"h-3 w-3"}),"Add Files"]})})]})]}),d.guides.length>0?e.jsx("div",{className:"space-y-2",children:d.guides.map((Ce,Ve)=>e.jsxs("div",{className:"flex gap-2 items-center p-3 border rounded-lg bg-muted/30",children:[e.jsx(Jr,{className:"h-5 w-5 text-muted-foreground shrink-0"}),e.jsx(pe,{value:Ce.name,onChange:ze=>ke(Ve,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(Ve),children:e.jsx(pr,{className:"h-4 w-4"})})]},Ce.id||Ve))}):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(tmn,{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),_e()},children:"Cancel"}),e.jsx($,{type:"submit",disabled:te.isPending,children:te.isPending?"Saving...":o?"Update":"Create"})]})]})]})]})]}),e.jsx(je,{children:e.jsx(Ie,{className:"p-0",children:ae?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading..."}):X.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No templates yet. Add your first template!"}):e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Preview"}),e.jsx(Dt,{children:"Name"}),e.jsx(Dt,{children:"Links"}),e.jsx(Dt,{children:"Category"}),e.jsx(Dt,{children:"Type"}),e.jsx(Dt,{children:"Publish Date"}),e.jsx(Dt,{className:"w-[72px] text-center",children:"Featured"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(fi,{children:X.map(Ce=>{var Ve,ze,qe,dt,Xe;return e.jsxs(En,{children:[e.jsx(_t,{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(_t,{className:"font-medium",children:Ce.name}),e.jsx(_t,{children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs($e,{variant:"secondary",children:[((Ve=Ce.links)==null?void 0:Ve.length)||0," link",(((ze=Ce.links)==null?void 0:ze.length)||0)!==1?"s":""]}),(((qe=Ce.guides)==null?void 0:qe.length)||0)>0&&e.jsxs($e,{variant:"outline",className:"gap-1",children:[e.jsx(Jr,{className:"h-3 w-3"}),(dt=Ce.guides)==null?void 0:dt.length," guide",(((Xe=Ce.guides)==null?void 0:Xe.length)||0)!==1?"s":""]})]})}),e.jsx(_t,{children:Ce.category?e.jsx($e,{variant:"secondary",children:Ce.category.name}):e.jsx("span",{className:"text-muted-foreground",children:"-"})}),e.jsx(_t,{children:Ce.type?e.jsx($e,{variant:"outline",children:Ce.type.name}):e.jsx("span",{className:"text-muted-foreground",children:"-"})}),e.jsx(_t,{className:"text-muted-foreground",children:new Date(Ce.publish_date).toLocaleDateString()}),e.jsx(_t,{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(_t,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{size:"icon",variant:"ghost",onClick:()=>he(Ce),children:e.jsx(pi,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"ghost",className:"text-destructive hover:text-destructive",onClick:async()=>{await fo("Delete this template?")&&J.mutate(Ce.id)},children:e.jsx(Hn,{className:"h-4 w-4"})})]})})]},Ce.id)})})]})})})]})})};function DWt({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(c2,{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(pr,{className:"h-3 w-3"})})]},h.id))}),e.jsxs(Kd,{open:a,onOpenChange:i,children:[e.jsx(Yd,{asChild:!0,children:e.jsxs($,{type:"button",variant:"outline",size:"sm",className:"gap-1",children:[e.jsx(c2,{className:"h-3.5 w-3.5"}),"Add Template"]})}),e.jsxs(Od,{className:"w-80 p-2",align:"start",children:[e.jsxs("div",{className:"relative mb-2",children:[e.jsx(Zr,{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(c2,{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 nmn=[{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"}],Fwt=new Intl.DateTimeFormat("en-CA",{timeZone:"America/New_York",year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date),Owt=s=>{const[t,n,r]=s.split(/[-/T]/);return`${Number(n)}/${Number(r)}/${t}`},rmn=()=>{const{user:s}=bs(),[t,n]=gc(),{toast:r}=Bi(),a=Wt(),[i,l]=j.useState(!1),[o,c]=j.useState(null),[d,u]=j.useState({title:"",description:"",video_url:"",video_type:"youtube",duration:"",category_id:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),[h,m]=j.useState(null),[f,g]=j.useState(""),[x,y]=j.useState([]),[v,b]=j.useState([]),[w,S]=j.useState([]),[A,E]=j.useState([]),[I,P]=j.useState(""),[R,D]=j.useState(!1),[O,U]=j.useState(null),[W,V]=j.useState(0),[G,Y]=j.useState(!1),[X,ae]=j.useState(null),{data:le=[]}=st({queryKey:["academy-categories"],queryFn:async()=>{const{data:Ce,error:Ve}=await q.from("academy_categories").select("*").order("sort_order",{ascending:!0});if(Ve)throw Ve;return Ce}}),{data:ne=[],isLoading:te}=st({queryKey:["academy-videos-admin"],queryFn:async()=>{const{data:Ce,error:Ve}=await q.from("academy_videos").select(` *, category:academy_categories(id, name) `).order("publish_date",{ascending:!1});if(Ve)throw Ve;const{data:ze,error:qe}=await q.from("academy_resources").select("*").order("sort_order");if(qe)throw qe;return Ce.map(Xe=>({...Xe,resources:(ze==null?void 0:ze.filter(at=>at.video_id===Xe.id))||[]}))}});j.useEffect(()=>{const Ce=t.get("edit");if(Ce&&ne.length>0){const Ve=ne.find(ze=>ze.id===Ce);Ve&&(Se(Ve),n({},{replace:!0}))}},[ne,t]);const J=mt({mutationFn:async Ce=>{const{data:Ve,error:ze}=await q.from("academy_categories").insert({name:Ce,sort_order:le.length}).select().single();if(ze)throw ze;return Ve},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 Ve=Ce.existingThumbnailUrl;if(Ce.thumbnail){const dt=Ce.thumbnail.name.split(".").pop(),Xe=`thumbnails/${Date.now()}-${Math.random().toString(36).substring(7)}.${dt}`,{error:at}=await q.storage.from("academy-resources").upload(Xe,Ce.thumbnail);if(at)throw at;const{data:rt}=q.storage.from("academy-resources").getPublicUrl(Xe);Ve=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:Ve,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 qe=Ce.videoId;if(qe){const{error:dt}=await q.from("academy_videos").update(ze).eq("id",qe);if(dt)throw dt}else{const{data:dt,error:Xe}=await q.from("academy_videos").insert(ze).select().single();if(Xe)throw Xe;qe=dt.id,Hhn(Ce.video.title,dt.id)}if(Ce.resourcesToDelete.length>0){const{error:dt}=await q.from("academy_resources").delete().in("id",Ce.resourcesToDelete);if(dt)throw dt}for(let dt=0;dt0){const{error:dt}=await q.from("academy_video_templates").insert(A.map(Xe=>({video_id:qe,template_id:Xe})));if(dt)throw dt}},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-videos-admin"]}),a.invalidateQueries({queryKey:["academy-videos"]}),Ee(),l(!1),r({title:o?"Video updated":"Video created"})},onError:Ce=>{r({title:"Error saving video",description:Ce.message,variant:"destructive"})}}),_e=mt({mutationFn:async Ce=>{const{error:Ve}=await q.from("academy_videos").delete().eq("id",Ce);if(Ve)throw Ve},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-videos-admin"]}),a.invalidateQueries({queryKey:["academy-videos"]}),r({title:"Video deleted"})},onError:Ce=>{r({title:"Error deleting video",description:Ce.message,variant:"destructive"})}}),he=mt({mutationFn:async({id:Ce,is_published:Ve})=>{const{error:ze}=await q.from("academy_videos").update({is_published:Ve}).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 Ve=Ce.public_slug||null,ze=!!Ce.is_public;if(!Ve||!ze){const dt=(Ce.title||"video").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||"video";if(!Ve){let at=dt;const{data:rt}=await q.from("academy_videos").select("id").eq("public_slug",at).maybeSingle();rt&&rt.id!==Ce.id&&(at=`${dt}-${Ce.id.slice(0,6)}`),Ve=at}const{error:Xe}=await q.from("academy_videos").update({public_slug:Ve,is_public:!0}).eq("id",Ce.id);if(Xe)throw Xe;a.invalidateQueries({queryKey:["academy-videos-admin"]})}const qe=`${window.location.origin}/watch/${Ve}`;await navigator.clipboard.writeText(qe),r({title:"Public link copied",description:qe})}catch(Ve){r({title:"Could not copy link",description:Ve.message,variant:"destructive"})}},ve=async Ce=>{if(!await fo("Disable the public teaser link for this video?"))return;const{error:Ve}=await q.from("academy_videos").update({is_public:!1}).eq("id",Ce.id);if(Ve){r({title:"Error",description:Ve.message,variant:"destructive"});return}a.invalidateQueries({queryKey:["academy-videos-admin"]}),r({title:"Public link disabled"})},Ee=()=>{u({title:"",description:"",video_url:"",video_type:"bunny_stream",duration:"",category_id:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),m(null),g(""),y([]),b([]),S([]),c(null),E([]),P(""),U(null),V(0),Y(!1),ae(null)},Se=async Ce=>{c(Ce),u({title:Ce.title,description:Ce.description||"",video_url:Ce.video_url,video_type:Ce.video_type,duration:Ce.duration||"",category_id:Ce.category_id||"",publish_date:Ce.publish_date?new Date(Ce.publish_date).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],is_published:Ce.is_published}),g(Ce.thumbnail_url||""),b(Ce.resources||[]),y([]),S([]);const{data:Ve}=await q.from("academy_video_templates").select("template_id").eq("video_id",Ce.id);E((Ve||[]).map(ze=>ze.template_id)),l(!0)},Le=Ce=>{var ze;const Ve=(ze=Ce.target.files)==null?void 0:ze[0];Ve&&(m(Ve),g(URL.createObjectURL(Ve)))},Fe=Ce=>{const Ve=Ce.target.files;if(Ve){const ze=Array.from(Ve).map(qe=>({file:qe,title:qe.name.replace(/\.[^/.]+$/,"")}));y([...x,...ze])}Ce.target.value=""},ke=Ce=>{y(x.filter((Ve,ze)=>ze!==Ce))},Be=Ce=>{S([...w,Ce]),b(v.filter(Ve=>Ve.id!==Ce))},Ne=async()=>{if(!O)return null;Y(!0),V(0);try{const{data:Ce,error:Ve}=await q.functions.invoke("bunny-upload",{body:{action:"create",title:d.title||O.name}});if(Ve)throw new Error(Ve.message);const{videoId:ze,libraryId:qe}=Ce;ae(ze);const{data:dt,error:Xe}=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:ze}});if(Xe)throw new Error(Xe.message);const at=new XMLHttpRequest;return await new Promise((Ke,Je)=>{at.upload.addEventListener("progress",pt=>{if(pt.lengthComputable){const gt=Math.round(pt.loaded/pt.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",dt.uploadUrl),at.setRequestHeader("AccessKey",dt.apiKey),at.send(O)}),`https://player.mediadelivery.net/embed/${qe}/${ze}`}catch(Ce){return console.error("Bunny upload error:",Ce),r({title:"Video upload failed",description:Ce instanceof Error?Ce.message:"Unknown error",variant:"destructive"}),null}finally{Y(!1)}},Ae=async Ce=>{if(Ce.preventDefault(),!d.title.trim()){r({title:"Please enter a video title",variant:"destructive"});return}let Ve=d.video_url;if(d.video_type==="bunny_stream"&&O&&!o){const ze=await Ne();if(!ze)return;Ve=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:Ve},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(Ie,{children:e.jsx("div",{className:"text-2xl font-bold",children:ne.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(Ie,{children:e.jsx("div",{className:"text-2xl font-bold",children:ne.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(Ie,{children:e.jsx("div",{className:"text-2xl font-bold",children:ne.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(Ie,{children:e.jsx("div",{className:"text-2xl font-bold",children:ne.reduce((Ce,Ve)=>Ce+(Ve.public_view_count||0),0).toLocaleString()})})]})]}),e.jsxs(zs,{open:i,onOpenChange:Ce=>{l(Ce),Ce||Ee()},children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{className:"gap-2",children:[e.jsx(dn,{className:"h-4 w-4"}),"Add Video"]})}),e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(Bs,{children:o?"Edit Video":"Add New Video"})}),e.jsxs("form",{onSubmit:Ae,className:"space-y-6 pt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"title",children:"Title *"}),e.jsx(pe,{id:"title",value:d.title,onChange:Ce=>u({...d,title:Ce.target.value}),placeholder:"Video title",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Description"}),e.jsx(Sk,{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:nmn.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 Ve=(ze=Ce.target.files)==null?void 0:ze[0];Ve&&U(Ve)},disabled:G}),O&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(ua,{className:"h-4 w-4"}),O.name," (",(O.size/(1024*1024)).toFixed(1)," MB)"]}),G&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(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(pr,{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(dn,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Thumbnail Image"}),e.jsxs("div",{className:"flex items-start gap-4",children:[f&&e.jsx("img",{src:f,alt:"Thumbnail preview",className:"w-32 h-20 object-cover rounded-md border"}),e.jsxs("div",{className:"flex-1",children:[e.jsx(pe,{type:"file",accept:"image/*",onChange:Le,className:"cursor-pointer"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Recommended: 16:9 aspect ratio"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{children:"Resource Files"}),e.jsx($,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsxs("label",{className:"cursor-pointer gap-1",children:[e.jsx(ni,{className:"h-3 w-3"}),"Add Files",e.jsx("input",{type:"file",multiple:!0,accept:".pdf,.pptx,.ppt,.xlsx,.xls,.docx,.doc,.zip",onChange:Fe,className:"hidden"})]})})]}),(v.length>0||x.length>0)&&e.jsxs("div",{className:"space-y-2 mt-2",children:[v.map(Ce=>e.jsxs("div",{className:"flex items-center gap-2 p-2 border rounded-md bg-muted/30",children:[e.jsx(Jr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"flex-1 text-sm truncate",children:Ce.title}),e.jsx($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(pr,{className:"h-4 w-4"})})]},Ce.id)),x.map((Ce,Ve)=>e.jsxs("div",{className:"flex items-center gap-2 p-2 border rounded-md bg-muted/30",children:[e.jsx(Jr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(pe,{value:Ce.title,onChange:ze=>{const qe=[...x];qe[Ve].title=ze.target.value,y(qe)},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:()=>ke(Ve),className:"text-destructive hover:text-destructive",children:e.jsx(pr,{className:"h-4 w-4"})})]},Ve))]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Supported: PDF, PowerPoint, Excel, Word, ZIP"})]}),e.jsx(DWt,{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(Sn,{id:"is_published",checked:d.is_published,onCheckedChange:Ce=>u({...d,is_published:Ce})}),e.jsx(ee,{htmlFor:"is_published",children:"Published"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:d.is_published?d.publish_date>Fwt?`Scheduled — goes live automatically on ${Owt(d.publish_date)}.`:"Live now for members.":"Draft — hidden from members until you turn this on."})]}),e.jsxs(Sr,{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(Ie,{className:"p-0",children:te?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):ne.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(ua,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No videos yet"}),e.jsx("p",{className:"text-sm",children:"Add your first academy video"})]}):e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Title"}),e.jsx(Dt,{children:"Category"}),e.jsx(Dt,{children:"Duration"}),e.jsx(Dt,{children:"Resources"}),e.jsx(Dt,{children:"Publish Date"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{children:"Public Views"}),e.jsx(Dt,{className:"w-[120px]",children:"Actions"})]})}),e.jsx(fi,{children:ne.map(Ce=>e.jsxs(En,{children:[e.jsx(_t,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[Ce.thumbnail_url?e.jsx("img",{src:Ce.thumbnail_url,alt:"",className:"w-16 h-10 object-cover rounded"}):e.jsx("div",{className:"w-16 h-10 bg-muted rounded flex items-center justify-center",children:e.jsx(ua,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:Ce.title}),e.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:Ce.video_type.replace("_"," ")})]})]})}),e.jsx(_t,{children:Ce.category?e.jsx($e,{variant:"outline",children:Ce.category.name}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(_t,{children:Ce.duration||"-"}),e.jsx(_t,{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(_t,{children:Owt(Ce.publish_date)}),e.jsx(_t,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sn,{checked:Ce.is_published,onCheckedChange:Ve=>he.mutate({id:Ce.id,is_published:Ve})}),Ce.is_published?Ce.publish_date.slice(0,10)>Fwt?e.jsxs($e,{variant:"outline",className:"gap-1",children:[e.jsx(da,{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(_t,{children:Ce.is_public?e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Ca,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-sm font-medium",children:(Ce.public_view_count||0).toLocaleString()})]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(_t,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx($,{variant:"ghost",size:"sm",title:Ce.is_public?"Copy public teaser link":"Make public & copy teaser link",onClick:()=>ue(Ce),children:Ce.is_public?e.jsx(Ha,{className:"h-4 w-4 text-primary"}):e.jsx(Fd,{className:"h-4 w-4"})}),Ce.is_public&&e.jsx($,{variant:"ghost",size:"sm",title:"Disable public link",onClick:()=>ve(Ce),children:e.jsx(dl,{className:"h-4 w-4 text-emerald-500"})}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>Se(Ce),children:e.jsx(pi,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>_e.mutate(Ce.id),className:"text-destructive hover:text-destructive",children:e.jsx(Hn,{className:"h-4 w-4"})})]})})]},Ce.id))})]})})})]})})},UZ=s=>s.toLowerCase().trim().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60),zwt={public_enabled:!1,public_slug:"",public_headline:"",public_subheadline:"",public_cta_text:"",public_benefits:"",public_hero_image_url:""};function amn(){var _e,he,ue;const s=Wt(),[t,n]=gc(),[r,a]=j.useState(!1),[i,l]=j.useState(null),[o,c]=j.useState({name:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,...zwt}),[d,u]=j.useState(null),[h,m]=j.useState(""),[f,g]=j.useState([]),[x,y]=j.useState([]),[v,b]=j.useState([]),[w,S]=j.useState(null),{data:A,isLoading:E}=st({queryKey:["resource-kits"],queryFn:async()=>{const{data:ve,error:Ee}=await q.from("resource_kits").select("*").order("publish_date",{ascending:!1});if(Ee)throw Ee;return ve}}),{data:I}=st({queryKey:["resource-kit-files"],queryFn:async()=>{const{data:ve,error:Ee}=await q.from("resource_kit_files").select("*").order("sort_order",{ascending:!0});if(Ee)throw Ee;return ve}}),{data:P}=st({queryKey:["resource-kit-links"],queryFn:async()=>{const{data:ve,error:Ee}=await q.from("resource_kit_links").select("*").order("sort_order",{ascending:!0});if(Ee)throw Ee;return ve}}),{data:R}=st({queryKey:["resource-kit-leads"],queryFn:async()=>{const{data:ve,error:Ee}=await q.from("resource_kit_leads").select("id, kit_id, full_name, email, brokerage, created_at").order("created_at",{ascending:!1}).limit(500);if(Ee)throw Ee;return ve}});j.useEffect(()=>{const ve=t.get("edit");if(ve&&A&&A.length>0&&I&&P){const Ee=A.find(Se=>Se.id===ve);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,...zwt}),u(null),m(""),g([]),y([]),b([]),l(null)},O=async ve=>{l(ve),c({name:ve.name,description:ve.description||"",publish_date:ve.publish_date.split("T")[0],is_published:ve.is_published,public_enabled:!!ve.public_enabled,public_slug:ve.public_slug||"",public_headline:ve.public_headline||"",public_subheadline:ve.public_subheadline||"",public_cta_text:ve.public_cta_text||"",public_benefits:Array.isArray(ve.public_benefits)?ve.public_benefits.join(` `):"",public_hero_image_url:ve.public_hero_image_url||""}),m(ve.featured_image_url||"");const Ee=(I==null?void 0:I.filter(Fe=>Fe.kit_id===ve.id))||[];g(Ee.map(Fe=>({id:Fe.id,name:Fe.name,file_url:Fe.file_url,file_type:Fe.file_type,file_size:Fe.file_size,sort_order:Fe.sort_order})));const Se=(P==null?void 0:P.filter(Fe=>Fe.kit_id===ve.id))||[];y(Se.map(Fe=>({id:Fe.id,title:Fe.title,canva_share_link:Fe.canva_share_link,sort_order:Fe.sort_order})));const{data:Le}=await q.from("resource_kit_templates").select("template_id").eq("kit_id",ve.id);b((Le||[]).map(Fe=>Fe.template_id)),a(!0)},U=ve=>{var Se;const Ee=(Se=ve.target.files)==null?void 0:Se[0];Ee&&(u(Ee),m(URL.createObjectURL(Ee)))},W=()=>{g([...f,{name:"",file_url:"",sort_order:f.length}])},V=ve=>{g(f.filter((Ee,Se)=>Se!==ve))},G=(ve,Ee,Se)=>{const Le=[...f];Le[ve]={...Le[ve],[Ee]:Se},g(Le)},Y=()=>{y([...x,{title:"",canva_share_link:"",sort_order:x.length}])},X=ve=>{y(x.filter((Ee,Se)=>Se!==ve))},ae=(ve,Ee,Se)=>{const Le=[...x];Le[ve]={...Le[ve],[Ee]:Se},y(Le)},le=(ve,Ee)=>{var Le;const Se=(Le=Ee.target.files)==null?void 0:Le[0];if(Se){const Fe=[...f],ke=Se.name.replace(/\.[^/.]+$/,"");Fe[ve]={...Fe[ve],file:Se,file_type:Se.type,file_size:Se.size,name:Fe[ve].name||ke},g(Fe)}},ne=mt({mutationFn:async()=>{let ve=(i==null?void 0:i.featured_image_url)||null;if(d){const Be=d.name.split(".").pop(),Ne=`${Date.now()}.${Be}`,{error:Ae}=await q.storage.from("resource-kits").upload(`featured/${Ne}`,d);if(Ae)throw Ae;const{data:Ce}=q.storage.from("resource-kits").getPublicUrl(`featured/${Ne}`);ve=Ce.publicUrl}const Ee=o.public_enabled?o.public_slug?UZ(o.public_slug):UZ(o.name):o.public_slug?UZ(o.public_slug):null,Se={name:o.name,description:o.description||null,featured_image_url:ve,publish_date:o.publish_date,is_published:o.is_published,public_enabled:o.public_enabled,public_slug:Ee||null,public_headline:o.public_headline||null,public_subheadline:o.public_subheadline||null,public_cta_text:o.public_cta_text||null,public_benefits:o.public_benefits.split(` `).map(Be=>Be.trim()).filter(Boolean),public_hero_image_url:o.public_hero_image_url||null};let Le;const Fe=!i,ke=(i==null?void 0:i.is_published)||!1;if(i){const{error:Be}=await q.from("resource_kits").update(Se).eq("id",i.id);if(Be)throw Be;Le=i.id;const Ne=(I==null?void 0:I.filter(dt=>dt.kit_id===i.id).map(dt=>dt.id))||[],Ae=f.filter(dt=>dt.id).map(dt=>dt.id),Ce=Ne.filter(dt=>!Ae.includes(dt));Ce.length>0&&await q.from("resource_kit_files").delete().in("id",Ce);const Ve=(P==null?void 0:P.filter(dt=>dt.kit_id===i.id).map(dt=>dt.id))||[],ze=x.filter(dt=>dt.id).map(dt=>dt.id),qe=Ve.filter(dt=>!ze.includes(dt));qe.length>0&&await q.from("resource_kit_links").delete().in("id",qe)}else{const{data:Be,error:Ne}=await q.from("resource_kits").insert(Se).select().single();if(Ne)throw Ne;Le=Be.id}for(let Be=0;Be0){const{error:Be}=await q.from("resource_kit_templates").insert(v.map(Ne=>({kit_id:Le,template_id:Ne})));if(Be)throw Be}return{kitId:Le,kitName:o.name,isNewKit:Fe,wasPublished:ke,isPublished:o.is_published}},onSuccess:ve=>{s.invalidateQueries({queryKey:["resource-kits"]}),s.invalidateQueries({queryKey:["resource-kit-files"]}),s.invalidateQueries({queryKey:["resource-kit-links"]}),re.success(i?"Resource kit updated":"Resource kit created"),ve.isPublished&&(ve.isNewKit||!ve.wasPublished)&&Whn(ve.kitName,ve.kitId),a(!1),D()},onError:ve=>{re.error("Failed to save resource kit: "+ve.message)}}),te=mt({mutationFn:async ve=>{const{error:Ee}=await q.from("resource_kits").delete().eq("id",ve);if(Ee)throw Ee},onSuccess:()=>{s.invalidateQueries({queryKey:["resource-kits"]}),s.invalidateQueries({queryKey:["resource-kit-files"]}),re.success("Resource kit deleted")},onError:ve=>{re.error("Failed to delete: "+ve.message)}}),J=ve=>{if(ve.preventDefault(),!o.name){re.error("Please enter a name");return}ne.mutate()},ce=ve=>(I==null?void 0:I.filter(Ee=>Ee.kit_id===ve).length)||0;return e.jsx(Vs,{title:"Toolbox Management",description:"Create and manage resource kits for agents",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs(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(Ie,{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(Ie,{children:e.jsx("div",{className:"text-2xl font-bold",children:(A==null?void 0:A.filter(ve=>ve.is_published).length)||0})})]})]}),e.jsxs($,{onClick:()=>{D(),a(!0)},children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Add Resource Kit"]})]}),e.jsx(je,{children:e.jsx(Ie,{className:"p-0",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Name"}),e.jsx(Dt,{children:"Files"}),e.jsx(Dt,{children:"Publish Date"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(fi,{children:E?e.jsx(En,{children:e.jsx(_t,{colSpan:5,className:"text-center py-8",children:"Loading..."})}):(A==null?void 0:A.length)===0?e.jsx(En,{children:e.jsx(_t,{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(ve=>e.jsxs(En,{children:[e.jsx(_t,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[ve.featured_image_url?e.jsx("img",{src:ve.featured_image_url,alt:ve.name,className:"w-10 h-10 rounded object-cover"}):e.jsx("div",{className:"w-10 h-10 rounded bg-muted flex items-center justify-center",children:e.jsx(ym,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:ve.name}),ve.description&&e.jsx("div",{className:"text-sm text-muted-foreground line-clamp-1",children:ve.description})]})]})}),e.jsx(_t,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Jr,{className:"h-4 w-4 text-muted-foreground"}),ce(ve.id)]})}),e.jsx(_t,{children:en(new Date(ve.publish_date),"MMM d, yyyy")}),e.jsx(_t,{children:e.jsx("span",{className:`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${ve.is_published?"bg-green-100 text-green-800":"bg-yellow-100 text-yellow-800"}`,children:ve.is_published?"Published":"Draft"})}),e.jsx(_t,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[ve.public_enabled&&ve.public_slug&&e.jsx($,{variant:"ghost",size:"icon",title:"Copy public landing page link",onClick:()=>{navigator.clipboard.writeText(`${window.location.origin}/resources/${ve.public_slug}`),re.success("Public link copied")},children:e.jsx(dl,{className:"h-4 w-4 text-emerald-600"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>{const Ee=(I==null?void 0:I.filter(Le=>Le.kit_id===ve.id))||[],Se=(P==null?void 0:P.filter(Le=>Le.kit_id===ve.id))||[];S({...ve,files:Ee,links:Se})},children:e.jsx(Ca,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>O(ve),children:e.jsx(pi,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:async()=>{await fo("Delete this resource kit?")&&te.mutate(ve.id)},children:e.jsx(Hn,{className:"h-4 w-4 text-destructive"})})]})})]},ve.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(Ie,{children:!R||R.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No leads yet. Turn on a public landing page for a kit and share the link."}):e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Agent"}),e.jsx(Dt,{children:"Email"}),e.jsx(Dt,{children:"Brokerage"}),e.jsx(Dt,{children:"Resource"}),e.jsx(Dt,{children:"Captured"})]})}),e.jsx(fi,{children:R.map(ve=>{var Ee;return e.jsxs(En,{children:[e.jsx(_t,{className:"font-medium",children:ve.full_name}),e.jsx(_t,{children:ve.email}),e.jsx(_t,{children:ve.brokerage||"—"}),e.jsx(_t,{children:((Ee=A==null?void 0:A.find(Se=>Se.id===ve.kit_id))==null?void 0:Ee.name)||"—"}),e.jsx(_t,{children:en(new Date(ve.created_at),"MMM d, yyyy")})]},ve.id)})})]})})]}),e.jsx(zs,{open:r,onOpenChange:a,children:e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(Bs,{children:i?"Edit Resource Kit":"Add Resource Kit"})}),e.jsxs("form",{onSubmit:J,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Featured Image"}),e.jsxs("div",{className:"flex items-center gap-4",children:[h?e.jsx("img",{src:h,alt:"Preview",className:"w-24 h-24 rounded object-cover"}):e.jsx("div",{className:"w-24 h-24 rounded bg-muted flex items-center justify-center",children:e.jsx(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:ve=>c({...o,name:ve.target.value}),placeholder:"Resource Kit Name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Description"}),e.jsx(Sk,{content:o.description,onChange:ve=>c({...o,description:ve}),placeholder:"Brief description of this resource kit",minHeight:"120px"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(pe,{id:"publish_date",type:"date",value:o.publish_date,onChange:ve=>c({...o,publish_date:ve.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Published"}),e.jsxs("div",{className:"flex items-center space-x-2 pt-2",children:[e.jsx(Sn,{checked:o.is_published,onCheckedChange:ve=>c({...o,is_published:ve})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:o.is_published?"Visible to agents":"Hidden from agents"})]})]})]}),e.jsxs("div",{className:"space-y-3 rounded-xl border p-4 bg-muted/30",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-base",children:"Public Landing Page"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Share this resource publicly and capture agent name, email and brokerage as leads."})]}),e.jsx(Sn,{checked:o.public_enabled,onCheckedChange:ve=>c({...o,public_enabled:ve,public_slug:o.public_slug||UZ(o.name)})})]}),o.public_enabled&&e.jsxs("div",{className:"space-y-3 pt-1",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Public link"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("div",{className:"flex items-center rounded-md border bg-background px-2 text-sm text-muted-foreground",children:"/resources/"}),e.jsx(pe,{value:o.public_slug,onChange:ve=>c({...o,public_slug:ve.target.value}),placeholder:"listing-checklist"}),e.jsxs($,{type:"button",variant:"outline",onClick:()=>{const ve=UZ(o.public_slug||o.name);navigator.clipboard.writeText(`${window.location.origin}/resources/${ve}`),re.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:ve=>c({...o,public_headline:ve.target.value}),placeholder:o.name||"The Ultimate Listing Checklist"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Subheadline"}),e.jsx(pe,{value:o.public_subheadline,onChange:ve=>c({...o,public_subheadline:ve.target.value}),placeholder:"Everything top agents do before a listing goes live."})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Button text"}),e.jsx(pe,{value:o.public_cta_text,onChange:ve=>c({...o,public_cta_text:ve.target.value}),placeholder:"Get Instant Access"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Hero image URL (optional)"}),e.jsx(pe,{value:o.public_hero_image_url,onChange:ve=>c({...o,public_hero_image_url:ve.target.value}),placeholder:"Defaults to featured image"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Benefit bullets (one per line)"}),e.jsx("textarea",{value:o.public_benefits,onChange:ve=>c({...o,public_benefits:ve.target.value}),rows:4,placeholder:`Save hours on every listing Proven scripts included Printable + editable`,className:"w-full rounded-md border bg-background px-3 py-2 text-sm"})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(ee,{children:"Resource Files"}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:W,children:[e.jsx(dn,{className:"h-4 w-4 mr-1"}),"Add File"]})]}),f.length===0?e.jsx("div",{className:"text-sm text-muted-foreground py-4 text-center border rounded-md border-dashed",children:'No files added yet. Click "Add File" to include resources.'}):e.jsx("div",{className:"space-y-3",children:f.map((ve,Ee)=>e.jsxs("div",{className:"border rounded-md p-3 space-y-2",children:[e.jsxs("div",{className:"flex justify-between items-start",children:[e.jsxs("span",{className:"text-sm font-medium",children:["File ",Ee+1]}),e.jsx($,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>V(Ee),children:e.jsx(pr,{className:"h-4 w-4"})})]}),e.jsx(pe,{placeholder:"File name (e.g., Getting Started Guide)",value:ve.name,onChange:Se=>G(Ee,"name",Se.target.value)}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pe,{type:"file",onChange:Se=>le(Ee,Se),className:"flex-1"}),ve.file_url&&!ve.file&&e.jsx("a",{href:ve.file_url,target:"_blank",rel:"noopener noreferrer",className:"text-sm text-primary hover:underline whitespace-nowrap",children:"Current file"}),ve.file&&e.jsx("span",{className:"text-sm text-green-600 whitespace-nowrap",children:"New file selected"})]})]},Ee))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(ee,{children:"Canva Links"}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:Y,children:[e.jsx(dn,{className:"h-4 w-4 mr-1"}),"Add Canva Link"]})]}),x.length===0?e.jsx("div",{className:"text-sm text-muted-foreground py-4 text-center border rounded-md border-dashed",children:'No Canva links added yet. Click "Add Canva Link" to include templates.'}):e.jsx("div",{className:"space-y-3",children:x.map((ve,Ee)=>e.jsxs("div",{className:"border rounded-md p-3 space-y-2",children:[e.jsxs("div",{className:"flex justify-between items-start",children:[e.jsxs("span",{className:"text-sm font-medium",children:["Canva Link ",Ee+1]}),e.jsx($,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>X(Ee),children:e.jsx(pr,{className:"h-4 w-4"})})]}),e.jsx(pe,{placeholder:"Link title (e.g., Social Media Post Template)",value:ve.title,onChange:Se=>ae(Ee,"title",Se.target.value)}),e.jsx(pe,{placeholder:"Canva share link (e.g., https://www.canva.com/design/...)",value:ve.canva_share_link,onChange:Se=>ae(Ee,"canva_share_link",Se.target.value)})]},Ee))})]}),e.jsx(DWt,{selectedTemplateIds:v,onChange:b}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx($,{type:"submit",disabled:ne.isPending,children:ne.isPending?"Saving...":i?"Update":"Create"})]})]})]})}),e.jsx(zs,{open:!!w,onOpenChange:()=>S(null),children:e.jsxs(Os,{className:"max-w-lg",children:[e.jsx(Us,{children:e.jsx(Bs,{children:w==null?void 0:w.name})}),e.jsxs("div",{className:"space-y-4",children:[(w==null?void 0:w.featured_image_url)&&e.jsx("img",{src:w.featured_image_url,alt:w.name,className:"w-full h-48 object-cover rounded-lg"}),(w==null?void 0:w.description)&&e.jsx("p",{className:"text-muted-foreground",children:w.description}),e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2",children:["Resource Files (",((_e=w==null?void 0:w.files)==null?void 0:_e.length)||0,")"]}),((he=w==null?void 0:w.files)==null?void 0:he.length)===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No files in this kit"}):e.jsx("div",{className:"space-y-2",children:(ue=w==null?void 0:w.files)==null?void 0:ue.map(ve=>e.jsxs("a",{href:ve.file_url,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 p-2 rounded-md hover:bg-muted transition-colors",children:[e.jsx(Jr,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm",children:ve.name})]},ve.id))})]}),(w==null?void 0:w.links)&&w.links.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2",children:["Canva Links (",w.links.length,")"]}),e.jsx("div",{className:"space-y-2",children:w.links.map(ve=>e.jsxs("a",{href:ve.canva_share_link,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 p-2 rounded-md hover:bg-muted transition-colors",children:[e.jsx(Sd,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm",children:ve.title})]},ve.id))})]})]})]})})]})})}const imn=()=>{const{user:s}=bs(),{toast:t}=Bi(),n=Wt(),[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(),Y=`${Date.now()}-${Math.random().toString(36).substring(7)}.${G}`,{error:X}=await q.storage.from("template-previews").upload(Y,P.image);if(X)throw X;const{data:ae}=q.storage.from("template-previews").getPublicUrl(Y);R=ae.publicUrl}const D={title:P.item.title,description:P.item.description||null,preview_image_url:R,publish_date:P.item.publish_date?new Date(P.item.publish_date).toISOString():new Date().toISOString(),is_published:P.item.is_published,created_by:s==null?void 0:s.id};let O=P.itemId;const U=!O,W=(i==null?void 0:i.is_published)||!1;if(O){const{error:G}=await q.from("social_swag").update(D).eq("id",O);if(G)throw G;await q.from("social_swag_links").delete().eq("swag_id",O)}else{const{data:G,error:Y}=await q.from("social_swag").insert(D).select().single();if(Y)throw Y;O=G.id}const V=P.item.links.filter(G=>G.title.trim()&&G.canva_share_link.trim());if(V.length>0){const G=V.map((X,ae)=>({swag_id:O,title:X.title.trim(),canva_share_link:X.canva_share_link.trim(),sort_order:ae})),{error:Y}=await q.from("social_swag_links").insert(G);if(Y)throw Y}return{itemId:O,itemTitle:P.item.title,isNewItem:U,wasPublished:W,isPublished:P.item.is_published}},onSuccess:P=>{n.invalidateQueries({queryKey:["social-swag-admin"]}),n.invalidateQueries({queryKey:["social-swag"]}),t({title:i?"Item updated":"Item created"}),P.isPublished&&(P.isNewItem||!P.wasPublished)&&UWe(P.itemTitle,P.itemId),a(!1),v()},onError:P=>{t({title:"Error saving item",description:P.message,variant:"destructive"})}}),y=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"})}}),v=()=>{c({title:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,links:[{title:"",canva_share_link:"",sort_order:0}]}),u(null),m(""),l(null)},b=P=>{l(P),c({title:P.title,description:P.description||"",publish_date:P.publish_date?new Date(P.publish_date).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],is_published:P.is_published,links:P.links&&P.links.length>0?P.links.map(R=>({id:R.id,title:R.title,canva_share_link:R.canva_share_link,sort_order:R.sort_order})):[{title:"",canva_share_link:"",sort_order:0}]}),m(P.preview_image_url||""),a(!0)},w=P=>{var D;const R=(D=P.target.files)==null?void 0:D[0];R&&(u(R),m(URL.createObjectURL(R)))},S=()=>{c({...o,links:[...o.links,{title:"",canva_share_link:"",sort_order:o.links.length}]})},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(Ie,{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(Ie,{children:e.jsx("div",{className:"text-2xl font-bold",children:f.filter(P=>P.is_published).length})})]})]}),e.jsxs(zs,{open:r,onOpenChange:P=>{a(P),P||v()},children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{className:"gap-2",children:[e.jsx(dn,{className:"h-4 w-4"}),"Add Item"]})}),e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(Bs,{children:i?"Edit Item":"Add New Item"})}),e.jsxs("form",{onSubmit:I,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"title",children:"Title *"}),e.jsx(pe,{id:"title",value:o.title,onChange:P=>c({...o,title:P.target.value}),placeholder:"Enter title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Description"}),e.jsx(Sk,{content:o.description,onChange:P=>c({...o,description:P}),placeholder:"Enter description",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(pe,{id:"publish_date",type:"date",value:o.publish_date,onChange:P=>c({...o,publish_date:P.target.value})})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Sn,{id:"is_published",checked:o.is_published,onCheckedChange:P=>c({...o,is_published:P})}),e.jsx(ee,{htmlFor:"is_published",children:"Published"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Preview Image"}),h?e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:h,alt:"Preview",className:"w-full max-h-48 object-contain rounded-lg border"}),e.jsx($,{type:"button",variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-6 w-6",onClick:()=>{u(null),m("")},children:e.jsx(pr,{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(dn,{className:"h-3 w-3 mr-1"}),"Add Link"]})]}),o.links.map((P,R)=>e.jsx(je,{children:e.jsxs(Ie,{className:"pt-4 pb-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-sm font-medium text-muted-foreground",children:["Link ",R+1]}),o.links.length>1&&e.jsx($,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>A(R),children:e.jsx(pr,{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(Ie,{className:"p-0",children:g?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):f.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:'No items yet. Click "Add Item" to create your first one.'}):e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{children:[e.jsx(Dt,{className:"w-16",children:"Preview"}),e.jsx(Dt,{children:"Title"}),e.jsx(Dt,{children:"Links"}),e.jsx(Dt,{children:"Publish Date"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(fi,{children:f.map(P=>{var R;return e.jsxs(En,{children:[e.jsx(_t,{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(_t,{className:"font-medium",children:P.title}),e.jsxs(_t,{children:[((R=P.links)==null?void 0:R.length)||0," links"]}),e.jsx(_t,{children:new Date(P.publish_date).toLocaleDateString()}),e.jsx(_t,{children:e.jsx($e,{variant:P.is_published?"default":"secondary",children:P.is_published?"Published":"Draft"})}),e.jsx(_t,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>window.open(`/social-swag/${P.id}`,"_blank"),children:e.jsx(Ca,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>b(P),children:e.jsx(pi,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:async()=>{await fo("Are you sure you want to delete this item?")&&y.mutate(P.id)},children:e.jsx(Hn,{className:"h-4 w-4"})})]})})]},P.id)})})]})})})]})})};function omn({item:s,onEdit:t,onDelete:n,onDateChange:r}){const{attributes:a,listeners:i,setNodeRef:l,transform:o,transition:c,isDragging:d}=x6e({id:s.id}),u={transform:PL.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(Ug,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-[10px] text-muted-foreground font-medium",children:"Drag to reorder"})]}),e.jsxs("div",{className:"relative aspect-[4/5]",children:[e.jsx("img",{src:s.image_url,alt:"Social swag",className:"w-full h-full object-cover",loading:"lazy",decoding:"async"}),e.jsxs("div",{className:"absolute top-2 right-2 flex gap-1",children:[e.jsx($,{variant:"secondary",size:"icon",className:"h-7 w-7 bg-black/50 hover:bg-black/70 border-0 text-white",onClick:()=>t(s),children:e.jsx(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(Hn,{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(Ta,{className:"h-2.5 w-2.5"}),en(new Date(s.post_date+"T00:00:00"),"MMM d")]})})]}),e.jsxs(Ie,{className:"p-3 space-y-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-3",children:s.caption}),e.jsxs(Kd,{children:[e.jsx(Yd,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:Pt("w-full h-7 text-[11px] gap-1 justify-start font-normal",!s.post_date&&"text-muted-foreground"),children:[e.jsx(Ta,{className:"h-3 w-3"}),s.post_date?en(new Date(s.post_date+"T00:00:00"),"MMM d, yyyy"):"Set post date"]})}),e.jsxs(Od,{className:"w-auto p-0",align:"start",children:[e.jsx(T2,{mode:"single",selected:s.post_date?new Date(s.post_date+"T00:00:00"):void 0,onSelect:h=>r(s.id,h?en(h,"yyyy-MM-dd"):null),className:"p-3 pointer-events-auto"}),s.post_date&&e.jsx("div",{className:"p-2 border-t",children:e.jsx($,{variant:"ghost",size:"sm",className:"w-full text-xs text-muted-foreground",onClick:()=>r(s.id,null),children:"Clear date"})})]})]})]})]})})}const lmn=()=>{const s=Wt(),[t,n]=j.useState("all"),[r,a]=j.useState(!1),[i,l]=j.useState(en(new Date,"yyyy-MM")),[o,c]=j.useState([]),[d,u]=j.useState(!1),[h,m]=j.useState(null),[f,g]=j.useState(null),[x,y]=j.useState(""),[v,b]=j.useState(null),[w,S]=j.useState(!1),[A,E]=j.useState(!1),[I,P]=j.useState(en(new Date,"yyyy-MM")),[R,D]=j.useState(null),[O,U]=j.useState(""),[W,V]=j.useState(""),[G,Y]=j.useState(""),[X,ae]=j.useState(!1),le=l6e(EG(dK,{activationConstraint:{distance:5}}),EG(u6e,{coordinateGetter:cUt})),{data:ne=[],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}}),_e=[...new Set(ne.map(rt=>rt.month))].sort((rt,Ke)=>Ke.localeCompare(rt)),he=t==="all"?ne:ne.filter(rt=>rt.month===t),ue=rt=>{const Ke=Ctt(rt,"yyyy-MM",new Date);return en(Ke,"MMMM yyyy")},ve=rt=>{g(rt),y(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:v}).eq("id",f.id);if(rt)throw rt;re.success("Image updated"),g(null),s.invalidateQueries({queryKey:["admin-social-swag-2"]}),s.invalidateQueries({queryKey:["social-swag-2"]})}catch{re.error("Failed to update image")}finally{S(!1)}}},Se=async rt=>{const{active:Ke,over:Je}=rt;if(!Je||Ke.id===Je.id)return;const pt=he,gt=pt.findIndex(ts=>ts.id===Ke.id),ss=pt.findIndex(ts=>ts.id===Je.id);if(gt===-1||ss===-1)return;const Yt=p6e(pt,gt,ss);s.setQueryData(["admin-social-swag-2"],ts=>{if(!ts)return ts;const ys={};return Yt.forEach((Bt,Ft)=>{ys[Bt.id]=Ft}),ts.map(Bt=>ys[Bt.id]!==void 0?{...Bt,sort_order:ys[Bt.id]}:Bt).sort((Bt,Ft)=>Bt.month!==Ft.month?Ft.month.localeCompare(Bt.month):Bt.sort_order-Ft.sort_order)});try{await Promise.all(Yt.map((ts,ys)=>q.from("social_swag_2").update({sort_order:ys}).eq("id",ts.id)))}catch{re.error("Failed to save order"),s.invalidateQueries({queryKey:["admin-social-swag-2"]})}},Le=rt=>{const Je=Array.from(rt.target.files||[]).sort((pt,gt)=>pt.name.localeCompare(gt.name,void 0,{numeric:!0,sensitivity:"base"})).slice(0,16-o.length).map(pt=>({file:pt,preview:URL.createObjectURL(pt),caption:""}));c(pt=>[...pt,...Je].slice(0,16))},Fe=rt=>{c(Ke=>{const Je=[...Ke];return URL.revokeObjectURL(Je[rt].preview),Je.splice(rt,1),Je})},ke=(rt,Ke)=>{c(Je=>{const pt=[...Je];return pt[rt]={...pt[rt],caption:Ke},pt})},Be=async()=>{var Ke;if(o.length===0){re.error("Please add at least one image");return}if(o.filter(Je=>!Je.caption.trim()).length>0){re.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),pt=(((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:()=>{re.success("Image deleted"),s.invalidateQueries({queryKey:["admin-social-swag-2"]})},onError:()=>re.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:()=>{re.success("Post date updated"),s.invalidateQueries({queryKey:["admin-social-swag-2"]}),s.invalidateQueries({queryKey:["social-swag-2"]})},onError:()=>re.error("Failed to update post date")}),Ce=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:()=>{re.success("Canva link updated"),m(null),s.invalidateQueries({queryKey:["admin-social-swag-2-months"]})},onError:()=>re.error("Failed to update Canva link")}),Ve=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,qe=rt=>{var Je;const Ke=(Je=rt.target.files)==null?void 0:Je[0];Ke&&(D(Ke),U(URL.createObjectURL(Ke)))},dt=()=>{O&&URL.revokeObjectURL(O),D(null),U(""),V(""),Y("")},Xe=async()=>{if(!R){re.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:pt}}=q.storage.from("social-swag-2").getPublicUrl(Ke),{error:gt}=await q.from("social_swag_2_reels").upsert({month:I,image_url:pt,canva_link:G||null,caption:W||null},{onConflict:"month"});if(gt)throw gt;re.success("Reel uploaded successfully!"),UWe(`${ue(I)} Reel`,"social-swag-2"),dt(),E(!1),s.invalidateQueries({queryKey:["admin-social-swag-2-reels"]})}catch(rt){console.error("Reel upload error:",rt),re.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:()=>{re.success("Reel deleted"),s.invalidateQueries({queryKey:["admin-social-swag-2-reels"]})},onError:()=>re.error("Failed to delete reel")});return e.jsxs(Vs,{title:"Admin - Social Swag 2.0",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Social Swag 2.0"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage monthly social media images and captions"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(zs,{open:r,onOpenChange:a,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{className:"gap-2",children:[e.jsx(dn,{className:"h-4 w-4"}),"Upload Images"]})}),e.jsxs(Os,{className:"max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Upload Social Swag Images"})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Month"}),e.jsx(pe,{type:"month",value:i,onChange: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:Le,className:"hidden",id:"swag-upload",disabled:o.length>=16}),e.jsxs("label",{htmlFor:"swag-upload",className:"cursor-pointer",children:[e.jsx(ni,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Click to select images (max 16)"})]})]})]}),o.length>0&&e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:o.map((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(pr,{className:"h-3 w-3"})})]}),e.jsx(Ls,{placeholder:"Caption...",value:rt.caption,onChange:Je=>ke(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(zs,{open:A,onOpenChange:rt=>{E(rt),rt||dt()},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(Os,{className:"max-w-lg max-h-[85vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Upload Monthly Reel"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Month"}),e.jsx(pe,{type:"month",value:I,onChange: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(pr,{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:qe,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=>Y(rt.target.value),placeholder:"https://www.canva.com/..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Caption"}),e.jsx(Ls,{value:W,onChange:rt=>V(rt.target.value),placeholder:"Enter caption for this reel...",className:"h-24"})]}),e.jsx($,{onClick:Xe,disabled:X||!R,className:"w-full gap-2",children:X?e.jsxs(e.Fragment,{children:[e.jsx(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(Ie,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:ne.length}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Total Images"})]})}),e.jsx(je,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:_e.length}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Months"})]})})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(ha,{value:t,onValueChange:n,children:e.jsxs(ma,{children:[e.jsx(Zt,{value:"all",children:"All"}),_e.map(rt=>e.jsx(Zt,{value:rt,children:ue(rt)},rt))]})}),t!=="all"&&e.jsx(je,{children:e.jsx(Ie,{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:Ve(t)||"No link set"}),e.jsx($,{size:"sm",variant:"outline",onClick:()=>m({month:t,link:Ve(t)}),children:"Edit"})]})]})]})})}),t!=="all"&&e.jsx(je,{children:e.jsx(Ie,{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(Hn,{className:"h-4 w-4"})})]}):e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"No reel uploaded for this month"})})()]})]})})})]}),te?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading..."}):he.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(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(f6e,{sensors:le,collisionDetection:c6e,onDragEnd:Se,children:e.jsx(g6e,{items:he.map(rt=>rt.id),strategy:eie,children:e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4",children:he.map(rt=>e.jsx(omn,{item:rt,onEdit:ve,onDelete:Ke=>Ne.mutate(Ke),onDateChange:(Ke,Je)=>Ae.mutate({id:Ke,postDate:Je})},rt.id))})})})]}),e.jsx(zs,{open:!!f,onOpenChange:rt=>{rt||g(null)},children:e.jsxs(Os,{className:"max-w-md",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Edit Image"})}),f&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"aspect-[4/5] max-h-48 w-full rounded-lg overflow-hidden bg-muted",children:e.jsx("img",{src:f.image_url,alt:"Preview",className:"w-full h-full object-cover"})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Caption"}),e.jsx(Ls,{value:x,onChange:rt=>y(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(Kd,{children:[e.jsx(Yd,{asChild:!0,children:e.jsxs($,{variant:"outline",className:Pt("flex-1 justify-start gap-2 font-normal",!v&&"text-muted-foreground"),children:[e.jsx(Ta,{className:"h-4 w-4"}),v?en(new Date(v+"T00:00:00"),"MMM d, yyyy"):"Pick a date"]})}),e.jsx(Od,{className:"w-auto p-0",align:"start",children:e.jsx(T2,{mode:"single",selected:v?new Date(v+"T00:00:00"):void 0,onSelect:rt=>b(rt?en(rt,"yyyy-MM-dd"):null),className:"p-3 pointer-events-auto"})})]}),v&&e.jsx($,{variant:"ghost",size:"icon",onClick:()=>b(null),children:e.jsx(pr,{className:"h-4 w-4"})})]})]})]}),e.jsxs(Sr,{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"})]})]})})]})},cmn=()=>{const{toast:s}=Bi(),t=Wt(),[n,r]=j.useState("categories"),[a,i]=j.useState(!1),[l,o]=j.useState(null),[c,d]=j.useState({name:"",description:"",icon:""}),[u,h]=j.useState(!1),[m,f]=j.useState(null),[g,x]=j.useState({name:"",description:"",icon:""}),[y,v]=j.useState(!1),[b,w]=j.useState(null),[S,A]=j.useState(""),{data:E=[],isLoading:I}=st({queryKey:["admin-community-categories"],queryFn:async()=>{const{data:Se,error:Le}=await q.from("community_categories").select("*").order("sort_order");if(Le)throw Le;return Se}}),{data:P=[],isLoading:R}=st({queryKey:["admin-private-groups"],queryFn:async()=>{const{data:Se,error:Le}=await q.from("community_private_groups").select("*").order("sort_order");if(Le)throw Le;return Se}}),{data:D=[]}=st({queryKey:["admin-group-members",b==null?void 0:b.id],queryFn:async()=>{if(!b)return[];const{data:Se,error:Le}=await q.from("community_private_group_members").select("*").eq("group_id",b.id);if(Le)throw Le;return Se},enabled:!!b}),{data:O=[]}=st({queryKey:["admin-all-profiles"],queryFn:async()=>{let Le=[],Fe=0,ke=!0;for(;ke;){const{data:Be,error:Ne}=await q.from("profiles").select("id, name, email, brokerage_id").order("name").range(Fe,Fe+1e3-1);if(Ne)throw Ne;Be&&Be.length>0?(Le=[...Le,...Be],Fe+=1e3,ke=Be.length===1e3):ke=!1}return Le}}),{data:U=[]}=st({queryKey:["admin-all-brokerages"],queryFn:async()=>{const{data:Se,error:Le}=await q.from("brokerages").select("*").order("name");if(Le)throw Le;return Se}}),W=mt({mutationFn:async Se=>{if(Se.id){const{error:Le}=await q.from("community_categories").update({name:Se.name,description:Se.description||null,icon:Se.icon||null}).eq("id",Se.id);if(Le)throw Le}else{const Le=Math.max(...E.map(ke=>ke.sort_order),0),{error:Fe}=await q.from("community_categories").insert({name:Se.name,description:Se.description||null,icon:Se.icon||null,sort_order:Le+1});if(Fe)throw Fe}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-community-categories"]}),i(!1),o(null),d({name:"",description:"",icon:""}),s({title:l?"Category updated!":"Category created!"})},onError:Se=>{s({title:"Error",description:Se.message,variant:"destructive"})}}),V=mt({mutationFn:async Se=>{const{error:Le}=await q.from("community_categories").delete().eq("id",Se);if(Le)throw Le},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-community-categories"]}),s({title:"Category deleted"})}}),G=mt({mutationFn:async({id:Se,direction:Le})=>{const Fe=E.findIndex(ke=>ke.id===Se);if(Le==="up"&&Fe>0){const ke=E[Fe-1],Be=E[Fe];await q.from("community_categories").update({sort_order:Be.sort_order}).eq("id",ke.id),await q.from("community_categories").update({sort_order:ke.sort_order}).eq("id",Be.id)}else if(Le==="down"&&Fet.invalidateQueries({queryKey:["admin-community-categories"]})}),Y=mt({mutationFn:async Se=>{if(Se.id){const{error:Le}=await q.from("community_private_groups").update({name:Se.name,description:Se.description||null,icon:Se.icon||null}).eq("id",Se.id);if(Le)throw Le}else{const Le=Math.max(...P.map(ke=>ke.sort_order),0),{error:Fe}=await q.from("community_private_groups").insert({name:Se.name,description:Se.description||null,icon:Se.icon||null,sort_order:Le+1});if(Fe)throw Fe}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-private-groups"]}),h(!1),f(null),x({name:"",description:"",icon:""}),s({title:m?"Private group updated!":"Private group created!"})},onError:Se=>{s({title:"Error",description:Se.message,variant:"destructive"})}}),X=mt({mutationFn:async Se=>{const{error:Le}=await q.from("community_private_groups").delete().eq("id",Se);if(Le)throw Le},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-private-groups"]}),s({title:"Private group deleted"})}}),ae=mt({mutationFn:async({id:Se,direction:Le})=>{const Fe=P.findIndex(ke=>ke.id===Se);if(Le==="up"&&Fe>0){const ke=P[Fe-1],Be=P[Fe];await q.from("community_private_groups").update({sort_order:Be.sort_order}).eq("id",ke.id),await q.from("community_private_groups").update({sort_order:ke.sort_order}).eq("id",Be.id)}else if(Le==="down"&&Fet.invalidateQueries({queryKey:["admin-private-groups"]})}),le=mt({mutationFn:async({groupId:Se,userId:Le,isMember:Fe})=>{if(Fe){const{error:ke}=await q.from("community_private_group_members").delete().eq("group_id",Se).eq("user_id",Le);if(ke)throw ke}else{const{error:ke}=await q.from("community_private_group_members").insert({group_id:Se,user_id:Le});if(ke)throw ke}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-group-members",b==null?void 0:b.id]})}}),ne=mt({mutationFn:async({groupId:Se,brokerageId:Le,isMember:Fe})=>{if(Fe){const{error:ke}=await q.from("community_private_group_members").delete().eq("group_id",Se).eq("brokerage_id",Le);if(ke)throw ke}else{const{error:ke}=await q.from("community_private_group_members").insert({group_id:Se,brokerage_id:Le});if(ke)throw ke}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-group-members",b==null?void 0:b.id]})}}),te=Se=>{o(Se),d({name:Se.name,description:Se.description||"",icon:Se.icon||""}),i(!0)},J=()=>{o(null),d({name:"",description:"",icon:""}),i(!0)},ce=Se=>{f(Se),x({name:Se.name,description:Se.description||"",icon:Se.icon||""}),h(!0)},_e=()=>{f(null),x({name:"",description:"",icon:""}),h(!0)},he=Se=>{w(Se),A(""),v(!0)},ue=Se=>D.some(Le=>Le.user_id===Se),ve=Se=>D.some(Le=>Le.brokerage_id===Se),Ee=O.filter(Se=>Se.name.toLowerCase().includes(S.toLowerCase())||Se.email.toLowerCase().includes(S.toLowerCase()));return e.jsx(Vs,{title:"Community Management",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Dm,{title:"Community Management",description:"Manage categories and private groups for community discussions"}),e.jsxs(ha,{value:n,onValueChange:r,children:[e.jsxs(ma,{children:[e.jsx(Zt,{value:"categories",children:"Public Categories"}),e.jsxs(Zt,{value:"private-groups",children:[e.jsx(pc,{className:"h-4 w-4 mr-1"}),"Private Groups"]})]}),e.jsxs(Xt,{value:"categories",className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Categories visible to all community members"}),e.jsxs($,{onClick:J,children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Add Category"]})]}),e.jsx(je,{children:e.jsx(Ie,{className:"pt-6",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{children:[e.jsx(Dt,{className:"w-[50px]",children:"Order"}),e.jsx(Dt,{className:"w-[80px]",children:"Icon"}),e.jsx(Dt,{children:"Name"}),e.jsx(Dt,{children:"Description"}),e.jsx(Dt,{className:"w-[100px]",children:"Actions"})]})}),e.jsx(fi,{children:I?e.jsx(En,{children:e.jsx(_t,{colSpan:5,className:"text-center py-8",children:"Loading..."})}):E.length===0?e.jsx(En,{children:e.jsx(_t,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No categories yet. Create your first one!"})}):E.map((Se,Le)=>e.jsxs(En,{children:[e.jsx(_t,{children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:Le===0,onClick:()=>G.mutate({id:Se.id,direction:"up"}),children:"↑"}),e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:Le===E.length-1,onClick:()=>G.mutate({id:Se.id,direction:"down"}),children:"↓"})]})}),e.jsx(_t,{className:"text-2xl",children:Se.icon||"📁"}),e.jsx(_t,{className:"font-medium",children:Se.name}),e.jsx(_t,{className:"text-muted-foreground",children:Se.description||"—"}),e.jsx(_t,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>te(Se),children:e.jsx(pi,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive",onClick:async()=>{await fo("Delete this category? Posts will be uncategorized.")&&V.mutate(Se.id)},children:e.jsx(Hn,{className:"h-4 w-4"})})]})})]},Se.id))})]})})})]}),e.jsxs(Xt,{value:"private-groups",className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Private groups visible only to assigned members or brokerages"}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(ji,{className:"h-3 w-3"}),"Brokerage groups are created automatically and sync with brokerage names"]})]}),e.jsxs($,{onClick:_e,children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Add Private Group"]})]}),e.jsx(je,{children:e.jsx(Ie,{className:"pt-6",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{children:[e.jsx(Dt,{className:"w-[50px]",children:"Order"}),e.jsx(Dt,{className:"w-[80px]",children:"Icon"}),e.jsx(Dt,{children:"Name"}),e.jsx(Dt,{children:"Description"}),e.jsx(Dt,{className:"w-[120px]",children:"Members"}),e.jsx(Dt,{className:"w-[140px]",children:"Actions"})]})}),e.jsx(fi,{children:R?e.jsx(En,{children:e.jsx(_t,{colSpan:6,className:"text-center py-8",children:"Loading..."})}):P.length===0?e.jsx(En,{children:e.jsx(_t,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No private groups yet. Create your first one!"})}):P.map((Se,Le)=>e.jsxs(En,{children:[e.jsx(_t,{children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:Le===0,onClick:()=>ae.mutate({id:Se.id,direction:"up"}),children:"↑"}),e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:Le===P.length-1,onClick:()=>ae.mutate({id:Se.id,direction:"down"}),children:"↓"})]})}),e.jsx(_t,{className:"text-2xl",children:Se.icon||"🔒"}),e.jsx(_t,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[Se.name,Se.brokerage_id?e.jsxs($e,{variant:"outline",className:"text-xs bg-blue-50 text-blue-700 border-blue-200",children:[e.jsx(ji,{className:"h-3 w-3 mr-1"}),"Auto-managed"]}):e.jsxs($e,{variant:"secondary",className:"text-xs",children:[e.jsx(pc,{className:"h-3 w-3 mr-1"}),"Private"]})]})}),e.jsx(_t,{className:"text-muted-foreground",children:Se.description||"—"}),e.jsx(_t,{children:e.jsxs($,{variant:"outline",size:"sm",onClick:()=>he(Se),children:[e.jsx(Yn,{className:"h-4 w-4 mr-1"}),"Manage"]})}),e.jsx(_t,{children:e.jsxs("div",{className:"flex gap-1",children:[!Se.brokerage_id&&e.jsx($,{variant:"ghost",size:"icon",onClick:()=>ce(Se),children:e.jsx(pi,{className:"h-4 w-4"})}),!Se.brokerage_id&&e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive",onClick:async()=>{await fo("Delete this private group? All posts in this group will be deleted.")&&X.mutate(Se.id)},children:e.jsx(Hn,{className:"h-4 w-4"})}),Se.brokerage_id&&e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"Managed via brokerage"})]})})]},Se.id))})]})})})]})]}),e.jsx(zs,{open:a,onOpenChange:i,children:e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsx(Bs,{children:l?"Edit Category":"Create Category"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Icon (emoji)"}),e.jsx(pe,{value:c.icon,onChange:Se=>d(Le=>({...Le,icon:Se.target.value})),placeholder:"💬",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Name *"}),e.jsx(pe,{value:c.name,onChange:Se=>d(Le=>({...Le,name:Se.target.value})),placeholder:"Category name",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Description"}),e.jsx(Ls,{value:c.description,onChange:Se=>d(Le=>({...Le,description:Se.target.value})),placeholder:"Brief description of this category",className:"mt-1"})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>i(!1),children:"Cancel"}),e.jsx($,{onClick:()=>W.mutate({...c,id:l==null?void 0:l.id}),disabled:!c.name.trim(),children:l?"Save Changes":"Create Category"})]})]})]})}),e.jsx(zs,{open:u,onOpenChange:h,children:e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsx(Bs,{children:m?"Edit Private Group":"Create Private Group"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Icon (emoji)"}),e.jsx(pe,{value:g.icon,onChange:Se=>x(Le=>({...Le,icon:Se.target.value})),placeholder:"🔒",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Name *"}),e.jsx(pe,{value:g.name,onChange:Se=>x(Le=>({...Le,name:Se.target.value})),placeholder:"e.g., Pioneers",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Description"}),e.jsx(Ls,{value:g.description,onChange:Se=>x(Le=>({...Le,description:Se.target.value})),placeholder:"Brief description of this private group",className:"mt-1"})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>h(!1),children:"Cancel"}),e.jsx($,{onClick:()=>Y.mutate({...g,id:m==null?void 0:m.id}),disabled:!g.name.trim(),children:m?"Save Changes":"Create Private Group"})]})]})]})}),e.jsx(zs,{open:y,onOpenChange:v,children:e.jsxs(Os,{className:"max-w-2xl",children:[e.jsx(Us,{children:e.jsxs(Bs,{children:["Manage Members: ",b==null?void 0:b.name]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs(ha,{defaultValue:"brokerages",children:[e.jsxs(ma,{className:"w-full",children:[e.jsx(Zt,{value:"brokerages",className:"flex-1",children:"By Brokerage"}),e.jsx(Zt,{value:"users",className:"flex-1",children:"Individual Users"})]}),e.jsxs(Xt,{value:"brokerages",className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Select brokerages to grant all their agents access to this private group."}),e.jsx(uo,{className:"h-[300px] border rounded-md p-4",children:e.jsxs("div",{className:"space-y-2",children:[U.map(Se=>e.jsxs("div",{className:"flex items-center justify-between p-2 hover:bg-muted rounded-md",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ai,{checked:ve(Se.id),onCheckedChange:()=>{b&&ne.mutate({groupId:b.id,brokerageId:Se.id,isMember:ve(Se.id)})}}),e.jsx("span",{className:"font-medium",children:Se.name})]}),e.jsxs($e,{variant:"secondary",children:[O.filter(Le=>Le.brokerage_id===Se.id).length," agents"]})]},Se.id)),U.length===0&&e.jsx("p",{className:"text-center text-muted-foreground py-4",children:"No brokerages found"})]})})]}),e.jsxs(Xt,{value:"users",className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Zr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search users...",value:S,onChange:Se=>A(Se.target.value),className:"pl-9"})]}),e.jsx(uo,{className:"h-[300px] border rounded-md p-4",children:e.jsxs("div",{className:"space-y-2",children:[Ee.map(Se=>e.jsx("div",{className:"flex items-center justify-between p-2 hover:bg-muted rounded-md",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ai,{checked:ue(Se.id),onCheckedChange:()=>{b&&le.mutate({groupId:b.id,userId:Se.id,isMember:ue(Se.id)})}}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Se.name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:Se.email})]})]})},Se.id)),Ee.length===0&&e.jsx("p",{className:"text-center text-muted-foreground py-4",children:"No users found"})]})})]})]}),e.jsx("div",{className:"flex justify-end",children:e.jsx($,{onClick:()=>v(!1),children:"Done"})})]})]})})]})})},Bwt=s=>{switch(s){case"academy_video":return e.jsx(zu,{className:"h-3 w-3"});case"template":return e.jsx(Jr,{className:"h-3 w-3"});case"toolbox":return e.jsx(ym,{className:"h-3 w-3"});case"newsletter":return e.jsx(QN,{className:"h-3 w-3"});case"social_swag":return e.jsx(Nn,{className:"h-3 w-3"});default:return e.jsx(Fr,{className:"h-3 w-3"})}},dmn=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}},umn=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}},hmn=()=>{const{toast:s}=Bi(),[t,n]=j.useState([]),[r,a]=j.useState([]),[i,l]=j.useState([]),[o,c]=j.useState(!0),[d,u]=j.useState(""),[h,m]=j.useState(null),[f,g]=j.useState([]),[x,y]=j.useState([]);j.useEffect(()=>{v()},[]);const v=async()=>{try{c(!0);const{data:D,error:O}=await q.from("activity_logs").select(` id, user_id, app_name, launched_at, profiles ( name, email, brokerages ( name ) ) `).order("launched_at",{ascending:!1}).limit(5e3);if(O)throw O;const{data:U,error:W}=await q.from("content_engagement_logs").select(` id, user_id, resource_type, resource_id, resource_title, action_type, created_at `).order("created_at",{ascending:!1}).limit(5e3);if(W)throw W;const V=[...new Set((U==null?void 0:U.map(te=>te.user_id))||[])],{data:G}=await q.from("profiles").select(` id, name, email, brokerages ( name ) `).in("id",V),Y=new Map((G==null?void 0:G.map(te=>[te.id,te]))||[]),X=(D==null?void 0:D.map(te=>{var J,ce,_e,he;return{id:te.id,user_id:te.user_id,app_name:te.app_name,launched_at:te.launched_at,user_name:((J=te.profiles)==null?void 0:J.name)||"Unknown",user_email:((ce=te.profiles)==null?void 0:ce.email)||"Unknown",brokerage_name:((he=(_e=te.profiles)==null?void 0:_e.brokerages)==null?void 0:he.name)||null}}))||[],ae=(U==null?void 0:U.map(te=>{var ce;const J=Y.get(te.user_id);return{id:te.id,user_id:te.user_id,resource_type:te.resource_type,resource_id:te.resource_id,resource_title:te.resource_title,action_type:te.action_type,created_at:te.created_at,user_name:(J==null?void 0:J.name)||"Unknown",user_email:(J==null?void 0:J.email)||"Unknown",brokerage_name:((ce=J==null?void 0:J.brokerages)==null?void 0:ce.name)||null}}))||[];n(X),a(ae);const 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 ne=Array.from(le.values()).sort((te,J)=>new Date(J.last_activity_at).getTime()-new Date(te.last_activity_at).getTime());l(ne)}catch(D){console.error("Error loading activity:",D),s({title:"Error",description:"Failed to load activity logs",variant:"destructive"})}finally{c(!1)}},b=D=>{m({id:D.user_id,name:D.user_name,email:D.user_email});const O=t.filter(W=>W.user_id===D.user_id),U=r.filter(W=>W.user_id===D.user_id);g(O),y(U)},w=()=>{m(null),g([]),y([])},{sortKey:S,sortDirection:A,handleSort:E,sortData:I}=bie("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(Ie,{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):e.jsxs(e.Fragment,{children:[e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{children:"User Activity"}),e.jsx(Gn,{children:"App launches and content engagement - click to see full history"})]}),e.jsxs(Ie,{children:[e.jsx("div",{className:"mb-4",children:e.jsxs("div",{className:"relative",children:[e.jsx(Zr,{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(En,{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(En,{children:e.jsx(_t,{colSpan:6,className:"text-center text-muted-foreground",children:"No activity found"})}):R.map(D=>e.jsxs(En,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>b(D),children:[e.jsx(_t,{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(_t,{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(_t,{children:e.jsx("div",{className:"flex items-center gap-2",children:D.last_activity_type==="app"?e.jsxs($e,{variant:"secondary",children:[e.jsx(Fr,{className:"h-3 w-3 mr-1"}),D.last_activity_name]}):e.jsxs($e,{variant:"outline",className:"flex items-center gap-1",children:[Bwt(D.last_activity_type),e.jsx("span",{className:"max-w-32 truncate",children:D.last_activity_name})]})})}),e.jsx(_t,{className:"text-sm text-muted-foreground",children:hu(new Date(D.last_activity_at),{addSuffix:!0})}),e.jsx(_t,{className:"text-right",children:e.jsx($e,{variant:"outline",children:D.total_app_launches})}),e.jsx(_t,{className:"text-right",children:e.jsx($e,{variant:"outline",children:D.total_content_views})})]},D.user_id))})]})})]})]}),e.jsx(zs,{open:!!h,onOpenChange:D=>!D&&w(),children:e.jsxs(Os,{className:"max-w-3xl max-h-[80vh] overflow-hidden flex flex-col",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{children:[h==null?void 0:h.name,"'s Activity"]}),e.jsx(Pr,{children:h==null?void 0:h.email})]}),e.jsxs(ha,{defaultValue:"content",className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(ma,{className:"grid w-full grid-cols-2",children:[e.jsxs(Zt,{value:"content",children:["Content (",x.length,")"]}),e.jsxs(Zt,{value:"apps",children:["App Launches (",f.length,")"]})]}),e.jsx(Xt,{value:"content",className:"flex-1 overflow-auto mt-4",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Type"}),e.jsx(Dt,{children:"Resource"}),e.jsx(Dt,{children:"Action"}),e.jsx(Dt,{children:"Time"})]})}),e.jsx(fi,{children:x.length===0?e.jsx(En,{children:e.jsx(_t,{colSpan:4,className:"text-center text-muted-foreground",children:"No content engagement"})}):x.map(D=>e.jsxs(En,{children:[e.jsx(_t,{children:e.jsxs($e,{variant:"outline",className:"flex items-center gap-1 w-fit",children:[Bwt(D.resource_type),dmn(D.resource_type)]})}),e.jsx(_t,{className:"max-w-48",children:e.jsx("span",{className:"truncate block",children:D.resource_title})}),e.jsx(_t,{children:e.jsx($e,{variant:"secondary",children:umn(D.action_type)})}),e.jsx(_t,{className:"text-sm text-muted-foreground",children:hu(new Date(D.created_at),{addSuffix:!0})})]},D.id))})]})})}),e.jsx(Xt,{value:"apps",className:"flex-1 overflow-auto mt-4",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"App"}),e.jsx(Dt,{children:"Time"})]})}),e.jsx(fi,{children:f.length===0?e.jsx(En,{children:e.jsx(_t,{colSpan:2,className:"text-center text-muted-foreground",children:"No app launches"})}):f.map(D=>e.jsxs(En,{children:[e.jsx(_t,{children:e.jsx($e,{variant:"secondary",children:D.app_name})}),e.jsx(_t,{className:"text-sm text-muted-foreground",children:hu(new Date(D.launched_at),{addSuffix:!0})})]},D.id))})]})})})]})]})})]})},mmn=()=>{const{toast:s}=Bi(),[t,n]=j.useState({totalUsers:0,activeUsers:0,pendingUsers:0,totalBrokerages:0,totalLaunches:0,launchesThisWeek:0,launchesThisMonth:0,uniqueActiveThisWeek:0}),[r,a]=j.useState(!0);j.useEffect(()=>{i()},[]);const i=async()=>{try{a(!0);const{count:l}=await q.from("profiles").select("*",{count:"exact",head:!0}),{count:o}=await q.from("profiles").select("*",{count:"exact",head:!0}).not("last_login","is",null),c=(l||0)-(o||0),{count:d}=await q.from("brokerages").select("*",{count:"exact",head:!0}),{count:u}=await q.from("activity_logs").select("*",{count:"exact",head:!0}),h=new Date;h.setDate(h.getDate()-7);const{count:m}=await q.from("activity_logs").select("*",{count:"exact",head:!0}).gte("launched_at",h.toISOString()),f=new Date;f.setMonth(f.getMonth()-1);const{count:g}=await q.from("activity_logs").select("*",{count:"exact",head:!0}).gte("launched_at",f.toISOString()),{data:x}=await q.from("activity_logs").select("user_id").gte("launched_at",h.toISOString()),y=new Set(x==null?void 0:x.map(v=>v.user_id)).size;n({totalUsers:l||0,activeUsers:o||0,pendingUsers:c,totalBrokerages:d||0,totalLaunches:u||0,launchesThisWeek:m||0,launchesThisMonth:g||0,uniqueActiveThisWeek:y})}catch(l){console.error("Error loading analytics:",l),s({title:"Error",description:"Failed to load analytics",variant:"destructive"})}finally{a(!1)}};return r?e.jsx(je,{children:e.jsx(Ie,{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):e.jsxs("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-4",children:[e.jsxs(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(Ie,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.totalUsers}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[t.activeUsers," active, ",t.pendingUsers," pending"]})]})]}),e.jsxs(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(Ie,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.activeUsers}),e.jsx("p",{className:"text-xs text-muted-foreground",children:t.totalUsers>0?`${Math.round(t.activeUsers/t.totalUsers*100)}% of total`:"0% of total"})]})]}),e.jsxs(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(da,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ie,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.pendingUsers}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Awaiting setup"})]})]}),e.jsxs(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(ji,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ie,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.totalBrokerages}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Total brokerages"})]})]}),e.jsxs(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(Ie,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.totalLaunches}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"All time"})]})]}),e.jsxs(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(Ie,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.launchesThisWeek}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Last 7 days"})]})]}),e.jsxs(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(Ie,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.launchesThisMonth}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Last 30 days"})]})]}),e.jsxs(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(Ie,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.uniqueActiveThisWeek}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Unique users"})]})]})]})},$wt={event:"Event",template:"Template",academy_video:"Academy Video",resource_kit:"Resource Kit",newsletter:"Newsletter",social_swag:"Social Swag"},Uwt={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 FWt({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}=bie("created_at","desc"),x=n.filter(E=>{var R,D;const I=l===""||E.resource_title.toLowerCase().includes(l.toLowerCase())||((R=E.sender)==null?void 0:R.name.toLowerCase().includes(l.toLowerCase()))||((D=E.recipient)==null?void 0:D.name.toLowerCase().includes(l.toLowerCase())),P=c==="all"||E.resource_type===c;return I&&P}),y=g(x,{resource:E=>{var I;return((I=E.resource_title)==null?void 0:I.toLowerCase())||""},type:E=>E.resource_type,sender:E=>{var I,P;return((P=(I=E.sender)==null?void 0:I.name)==null?void 0:P.toLowerCase())||""},recipient:E=>{var I,P;return((P=(I=E.recipient)==null?void 0:I.name)==null?void 0:P.toLowerCase())||""},status:E=>E.is_read?1:0,created_at:E=>new Date(E.created_at).getTime()}),v=n.length,b=new Set(n.map(E=>E.sender_id)).size,w=new Set(n.map(E=>E.recipient_id)).size,S=n.length>0?Math.round(n.filter(E=>E.is_read).length/n.length*100):0,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(Ie,{children:e.jsx(xn,{className:"h-8 w-16"})})]},I))}),e.jsx(je,{children:e.jsx(Ie,{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(Fd,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Ie,{children:e.jsx("div",{className:"text-2xl font-bold",children:v})})]}),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(Ie,{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(Ie,{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(Jr,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Ie,{children:e.jsxs("div",{className:"text-2xl font-bold",children:[S,"%"]})})]})]}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-sm font-medium",children:"Shares by Resource Type"})}),e.jsx(Ie,{children:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[Object.entries(A).map(([E,I])=>e.jsxs($e,{variant:"secondary",className:Uwt[E],children:[$wt[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(Gn,{children:["All resource shares ",s?"in your brokerage":"across the platform"]})]}),e.jsxs(Ie,{children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 mb-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Zr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search by resource, sender, or recipient...",value:l,onChange:E=>o(E.target.value),className:"pl-9"})]}),e.jsxs(ms,{value:c,onValueChange:d,children:[e.jsx(us,{className:"w-[180px]",children:e.jsx(fs,{placeholder:"Resource type"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Types"}),e.jsx(Ge,{value:"event",children:"Events"}),e.jsx(Ge,{value:"template",children:"Templates"}),e.jsx(Ge,{value:"academy_video",children:"Academy Videos"}),e.jsx(Ge,{value:"resource_kit",children:"Resource Kits"}),e.jsx(Ge,{value:"newsletter",children:"Newsletters"}),e.jsx(Ge,{value:"social_swag",children:"Social Swag"})]})]})]}),e.jsx(uo,{className:"h-[400px]",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{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:y.length===0?e.jsx(En,{children:e.jsx(_t,{colSpan:6,className:"text-center text-muted-foreground py-8",children:"No shares found"})}):y.map(E=>{var I,P;return e.jsxs(En,{children:[e.jsx(_t,{className:"font-medium max-w-[200px] truncate",children:E.resource_title}),e.jsx(_t,{children:e.jsx($e,{variant:"secondary",className:Uwt[E.resource_type],children:$wt[E.resource_type]})}),e.jsx(_t,{children:((I=E.sender)==null?void 0:I.name)||"Unknown"}),e.jsx(_t,{children:((P=E.recipient)==null?void 0:P.name)||"Unknown"}),e.jsx(_t,{children:e.jsx($e,{variant:E.is_read?"default":"outline",children:E.is_read?"Read":"Unread"})}),e.jsx(_t,{className:"text-muted-foreground",children:en(new Date(E.created_at),"MMM d, yyyy")})]},E.id)})})]})})]})]})]})}const t9e={academy_video:{label:"Academy Videos",icon:ua,color:"bg-purple-100 text-purple-800",actionLabel:"Watched",actionIcon:Ca},template:{label:"Templates",icon:LA,color:"bg-blue-100 text-blue-800",actionLabel:"Accessed",actionIcon:cb},toolbox:{label:"Toolkit",icon:L4,color:"bg-amber-100 text-amber-800",actionLabel:"Downloaded",actionIcon:xi},newsletter:{label:"Newsletters",icon:mn,color:"bg-emerald-100 text-emerald-800",actionLabel:"Clicked",actionIcon:cb},social_swag:{label:"Social Swag",icon:yd,color:"bg-pink-100 text-pink-800",actionLabel:"Accessed",actionIcon:cb},event:{label:"Events",icon:Ta,color:"bg-cyan-100 text-cyan-800",actionLabel:"Registered",actionIcon:cb}};function qwt(s){return s.resource_type==="toolbox"?s.total_downloads:s.total_clicks}function fmn(s,t){return s==="toolbox"?t.downloads:t.clicks}function pmn(){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}=bie("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(Ie,{children:e.jsx(xn,{className:"h-8 w-16"})})]},P))}),e.jsx(je,{children:e.jsx(Ie,{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),y=s.length,v=s.reduce((I,P)=>(I[P.resource_type]||(I[P.resource_type]={views:0,clicks:0,downloads:0,assets:0,uniqueUsers:0}),I[P.resource_type].views+=P.total_views,I[P.resource_type].clicks+=P.total_clicks,I[P.resource_type].downloads+=P.total_downloads,I[P.resource_type].assets+=1,I[P.resource_type].uniqueUsers+=P.unique_users,I),{}),b=a?s.filter(I=>I.resource_type===a):s,w=u(b,{asset:I=>{var P;return((P=I.resource_title)==null?void 0:P.toLowerCase())||""},type:I=>I.resource_type,views:I=>I.total_views,actions:I=>qwt(I),unique_users:I=>I.unique_users,last_activity:I=>I.last_engaged_at?new Date(I.last_engaged_at).getTime():0}),S=a?t9e[a]||{label:a,icon:Ca,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(Ca,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ie,{children:[e.jsx("div",{className:"text-2xl font-bold",children:f.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Across all content"})]})]}),e.jsxs(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(cb,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ie,{children:[e.jsx("div",{className:"text-2xl font-bold",children:g.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Link & Canva clicks"})]})]}),e.jsxs(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(xi,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ie,{children:[e.jsx("div",{className:"text-2xl font-bold",children:x.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"PDF downloads"})]})]}),e.jsxs(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(Ie,{children:[e.jsx("div",{className:"text-2xl font-bold",children:y}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Unique content items"})]})]}),e.jsxs(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(cb,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ie,{children:[e.jsxs("div",{className:"text-2xl font-bold",children:[f>0?Math.round((g+x)/f*100):0,"%"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Of views → actions"})]})]})]}),e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{className:"text-sm font-medium",children:"Engagement by Content Type"}),e.jsx(Gn,{children:"Click a category to see individual asset performance"})]}),e.jsx(Ie,{children:e.jsx("div",{className:"grid gap-3 grid-cols-2 md:grid-cols-3",children:Object.entries(v).map(([I,P])=>{const R=t9e[I]||{label:I,icon:Ca,color:"bg-muted text-muted-foreground",actionIcon:cb},D=R.icon,O=a===I;return e.jsxs("button",{type:"button",onClick:()=>m(I),className:`flex items-center gap-3 p-3 rounded-lg border text-left transition-colors cursor-pointer ${O?"ring-2 ring-primary border-primary bg-primary/5":"hover:bg-muted/50"}`,children:[e.jsx("div",{className:`p-2 rounded-md ${R.color}`,children:e.jsx(D,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:R.label}),e.jsxs("div",{className:"flex items-center gap-3 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ca,{className:"h-3 w-3"})," ",P.views]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(R.actionIcon,{className:"h-3 w-3"})," ",fmn(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(Gn,{children:a?`${b.length} ${((E=S==null?void 0:S.label)==null?void 0:E.toLowerCase())||"items"} ranked by total interactions`:"All tracked assets ranked by total interactions"})]}),a&&e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>i(null),className:"gap-1",children:[e.jsx(Va,{className:"h-3.5 w-3.5"}),"Show All"]})]})}),e.jsx(Ie,{children:b.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No engagement data yet. As users view and click content, stats will appear here."}):e.jsx(uo,{className:"h-[400px]",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{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=t9e[I.resource_type]||{label:I.resource_type,color:"bg-muted text-muted-foreground"};return e.jsxs(En,{children:[e.jsx(_t,{className:"text-muted-foreground text-xs",children:P+1}),e.jsx(_t,{children:e.jsx("p",{className:"font-medium text-sm truncate max-w-[250px]",children:I.resource_title})}),!a&&e.jsx(_t,{children:e.jsx($e,{className:`text-[10px] ${R.color}`,children:R.label})}),e.jsx(_t,{className:"text-right font-medium",children:I.total_views}),e.jsx(_t,{className:"text-right font-medium",children:qwt(I)}),e.jsx(_t,{className:"text-right",children:I.unique_users}),e.jsx(_t,{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 gmn=Array.isArray,Vw=gmn,xmn=typeof Sp=="object"&&Sp&&Sp.Object===Object&&Sp,OWt=xmn,ymn=OWt,vmn=typeof self=="object"&&self&&self.Object===Object&&self,bmn=ymn||vmn||Function("return this")(),h3=bmn,_mn=h3,wmn=_mn.Symbol,wie=wmn,Vwt=wie,zWt=Object.prototype,jmn=zWt.hasOwnProperty,Nmn=zWt.toString,qZ=Vwt?Vwt.toStringTag:void 0;function kmn(s){var t=jmn.call(s,qZ),n=s[qZ];try{s[qZ]=void 0;var r=!0}catch{}var a=Nmn.call(s);return r&&(t?s[qZ]=n:delete s[qZ]),a}var Smn=kmn,Cmn=Object.prototype,Amn=Cmn.toString;function Emn(s){return Amn.call(s)}var Tmn=Emn,Hwt=wie,Mmn=Smn,Pmn=Tmn,Imn="[object Null]",Lmn="[object Undefined]",Gwt=Hwt?Hwt.toStringTag:void 0;function Rmn(s){return s==null?s===void 0?Lmn:Imn:Gwt&&Gwt in Object(s)?Mmn(s):Pmn(s)}var LT=Rmn;function Dmn(s){return s!=null&&typeof s=="object"}var RT=Dmn,Fmn=LT,Omn=RT,zmn="[object Symbol]";function Bmn(s){return typeof s=="symbol"||Omn(s)&&Fmn(s)==zmn}var _K=Bmn,$mn=Vw,Umn=_K,qmn=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Vmn=/^\w*$/;function Hmn(s,t){if($mn(s))return!1;var n=typeof s;return n=="number"||n=="symbol"||n=="boolean"||s==null||Umn(s)?!0:Vmn.test(s)||!qmn.test(s)||t!=null&&s in Object(t)}var Ort=Hmn;function Gmn(s){var t=typeof s;return s!=null&&(t=="object"||t=="function")}var w6=Gmn;const wK=ru(w6);var Wmn=LT,Kmn=w6,Ymn="[object AsyncFunction]",Zmn="[object Function]",Xmn="[object GeneratorFunction]",Qmn="[object Proxy]";function Jmn(s){if(!Kmn(s))return!1;var t=Wmn(s);return t==Zmn||t==Xmn||t==Ymn||t==Qmn}var zrt=Jmn;const hc=ru(zrt);var efn=h3,tfn=efn["__core-js_shared__"],sfn=tfn,s9e=sfn,Wwt=function(){var s=/[^.]+$/.exec(s9e&&s9e.keys&&s9e.keys.IE_PROTO||"");return s?"Symbol(src)_1."+s:""}();function nfn(s){return!!Wwt&&Wwt in s}var rfn=nfn,afn=Function.prototype,ifn=afn.toString;function ofn(s){if(s!=null){try{return ifn.call(s)}catch{}try{return s+""}catch{}}return""}var BWt=ofn,lfn=zrt,cfn=rfn,dfn=w6,ufn=BWt,hfn=/[\\^$.*+?()[\]{}|]/g,mfn=/^\[object .+?Constructor\]$/,ffn=Function.prototype,pfn=Object.prototype,gfn=ffn.toString,xfn=pfn.hasOwnProperty,yfn=RegExp("^"+gfn.call(xfn).replace(hfn,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function vfn(s){if(!dfn(s)||cfn(s))return!1;var t=lfn(s)?yfn:mfn;return t.test(ufn(s))}var bfn=vfn;function _fn(s,t){return s==null?void 0:s[t]}var wfn=_fn,jfn=bfn,Nfn=wfn;function kfn(s,t){var n=Nfn(s,t);return jfn(n)?n:void 0}var KB=kfn,Sfn=KB,Cfn=Sfn(Object,"create"),oRe=Cfn,Kwt=oRe;function Afn(){this.__data__=Kwt?Kwt(null):{},this.size=0}var Efn=Afn;function Tfn(s){var t=this.has(s)&&delete this.__data__[s];return this.size-=t?1:0,t}var Mfn=Tfn,Pfn=oRe,Ifn="__lodash_hash_undefined__",Lfn=Object.prototype,Rfn=Lfn.hasOwnProperty;function Dfn(s){var t=this.__data__;if(Pfn){var n=t[s];return n===Ifn?void 0:n}return Rfn.call(t,s)?t[s]:void 0}var Ffn=Dfn,Ofn=oRe,zfn=Object.prototype,Bfn=zfn.hasOwnProperty;function $fn(s){var t=this.__data__;return Ofn?t[s]!==void 0:Bfn.call(t,s)}var Ufn=$fn,qfn=oRe,Vfn="__lodash_hash_undefined__";function Hfn(s,t){var n=this.__data__;return this.size+=this.has(s)?0:1,n[s]=qfn&&t===void 0?Vfn:t,this}var Gfn=Hfn,Wfn=Efn,Kfn=Mfn,Yfn=Ffn,Zfn=Ufn,Xfn=Gfn;function jK(s){var t=-1,n=s==null?0:s.length;for(this.clear();++t-1}var fpn=mpn,ppn=lRe;function gpn(s,t){var n=this.__data__,r=ppn(n,s);return r<0?(++this.size,n.push([s,t])):n[r][1]=t,this}var xpn=gpn,ypn=epn,vpn=lpn,bpn=upn,_pn=fpn,wpn=xpn;function NK(s){var t=-1,n=s==null?0:s.length;for(this.clear();++t0?1:-1},p8=function(t){return tB(t)&&t.indexOf("%")===t.length-1},yi=function(t){return Ugn(t)&&!SK(t)},Ggn=function(t){return Gc(t)},k0=function(t){return yi(t)||tB(t)},Wgn=0,YB=function(t){var n=++Wgn;return"".concat(t||"").concat(n)},v_=function(t,n){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0,a=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;if(!yi(t)&&!tB(t))return r;var i;if(p8(t)){var l=t.indexOf("%");i=n*parseFloat(t.slice(0,l))/100}else i=+t;return SK(i)&&(i=r),a&&i>n&&(i=n),i},CP=function(t){if(!t)return null;var n=Object.keys(t);return n&&n.length?t[n[0]]:null},Kgn=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 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}function VWe(s){"@babel/helpers - typeof";return VWe=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},VWe(s)}var tjt={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"},VE=function(t){return typeof t=="string"?t:t?t.displayName||t.name||"Component":""},sjt=null,r9e=null,Yrt=function s(t){if(t===sjt&&Array.isArray(r9e))return r9e;var n=[];return j.Children.forEach(t,function(r){Gc(r)||(Fgn.isFragment(r)?n=n.concat(s(r.props.children)):n.push(r))}),r9e=n,sjt=t,n};function v2(s,t){var n=[],r=[];return Array.isArray(t)?r=t.map(function(a){return VE(a)}):r=[VE(t)],Yrt(s).forEach(function(a){var i=y2(a,"type.displayName")||y2(a,"type.name");r.indexOf(i)!==-1&&n.push(a)}),n}function $j(s,t){var n=v2(s,t);return n&&n[0]}var njt=function(t){if(!t||!t.props)return!1;var n=t.props,r=n.width,a=n.height;return!(!yi(r)||r<=0||!yi(a)||a<=0)},sxn=["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"],nxn=function(t){return t&&t.type&&tB(t.type)&&sxn.indexOf(t.type)>=0},ZWt=function(t){return t&&VWe(t)==="object"&&"clipDot"in t},rxn=function(t,n,r,a){var i,l=(i=n9e==null?void 0:n9e[a])!==null&&i!==void 0?i:[];return n.startsWith("data-")||!hc(t)&&(a&&l.includes(n)||Xgn.includes(n))||r&&Krt.includes(n)},cl=function(t,n,r){if(!t||typeof t=="function"||typeof t=="boolean")return null;var a=t;if(j.isValidElement(t)&&(a=t.props),!wK(a))return null;var i={};return Object.keys(a).forEach(function(l){var o;rxn((o=a)===null||o===void 0?void 0:o[l],l,n,r)&&(i[l]=a[l])}),i},HWe=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 rjt(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 cxn(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 WWe(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=lxn(s,oxn),u=a||{width:n,height:r,x:0,y:0},h=sd("recharts-surface",i);return Gt.createElement("svg",GWe({},cl(d,!0,"svg"),{className:h,width:n,height:r,style:l,viewBox:"".concat(u.x," ").concat(u.y," ").concat(u.width," ").concat(u.height)}),Gt.createElement("title",null,o),Gt.createElement("desc",null,c),t)}var dxn=["children","className"];function KWe(){return KWe=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 hxn(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 Su=Gt.forwardRef(function(s,t){var n=s.children,r=s.className,a=uxn(s,dxn),i=sd("recharts-layer",r);return Gt.createElement("g",KWe({className:i},cl(a,!0),{ref:t}),n)}),oC=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:pxn(s,t,n)}var xxn=gxn,yxn="\\ud800-\\udfff",vxn="\\u0300-\\u036f",bxn="\\ufe20-\\ufe2f",_xn="\\u20d0-\\u20ff",wxn=vxn+bxn+_xn,jxn="\\ufe0e\\ufe0f",Nxn="\\u200d",kxn=RegExp("["+Nxn+yxn+wxn+jxn+"]");function Sxn(s){return kxn.test(s)}var XWt=Sxn;function Cxn(s){return s.split("")}var Axn=Cxn,QWt="\\ud800-\\udfff",Exn="\\u0300-\\u036f",Txn="\\ufe20-\\ufe2f",Mxn="\\u20d0-\\u20ff",Pxn=Exn+Txn+Mxn,Ixn="\\ufe0e\\ufe0f",Lxn="["+QWt+"]",YWe="["+Pxn+"]",ZWe="\\ud83c[\\udffb-\\udfff]",Rxn="(?:"+YWe+"|"+ZWe+")",JWt="[^"+QWt+"]",eKt="(?:\\ud83c[\\udde6-\\uddff]){2}",tKt="[\\ud800-\\udbff][\\udc00-\\udfff]",Dxn="\\u200d",sKt=Rxn+"?",nKt="["+Ixn+"]?",Fxn="(?:"+Dxn+"(?:"+[JWt,eKt,tKt].join("|")+")"+nKt+sKt+")*",Oxn=nKt+sKt+Fxn,zxn="(?:"+[JWt+YWe+"?",YWe,eKt,tKt,Lxn].join("|")+")",Bxn=RegExp(ZWe+"(?="+ZWe+")|"+zxn+Oxn,"g");function $xn(s){return s.match(Bxn)||[]}var Uxn=$xn,qxn=Axn,Vxn=XWt,Hxn=Uxn;function Gxn(s){return Vxn(s)?Hxn(s):qxn(s)}var Wxn=Gxn,Kxn=xxn,Yxn=XWt,Zxn=Wxn,Xxn=VWt;function Qxn(s){return function(t){t=Xxn(t);var n=Yxn(t)?Zxn(t):void 0,r=n?n[0]:t.charAt(0),a=n?Kxn(n,1).join(""):t.slice(1);return r[s]()+a}}var Jxn=Qxn,eyn=Jxn,tyn=eyn("toUpperCase"),syn=tyn;const wRe=ru(syn);function Vf(s){return function(){return s}}const rKt=Math.cos,HTe=Math.sin,kC=Math.sqrt,GTe=Math.PI,jRe=2*GTe,XWe=Math.PI,QWe=2*XWe,LO=1e-6,nyn=QWe-LO;function aKt(s){this._+=s[0];for(let t=1,n=s.length;t=0))throw new Error(`invalid digits: ${s}`);if(t>15)return aKt;const n=10**t;return function(r){this._+=r[0];for(let a=1,i=r.length;aLO)if(!(Math.abs(h*c-d*u)>LO)||!i)this._append`L${this._x1=t},${this._y1=n}`;else{let f=r-l,g=a-o,x=c*c+d*d,y=f*f+g*g,v=Math.sqrt(x),b=Math.sqrt(m),w=i*Math.tan((XWe-Math.acos((x+m-y)/(2*v*b)))/2),S=w/b,A=w/v;Math.abs(S-1)>LO&&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)>LO||Math.abs(this._y1-u)>LO)&&this._append`L${d},${u}`,r&&(m<0&&(m=m%QWe+QWe),m>nyn?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>LO&&this._append`A${r},${r},0,${+(m>=XWe)},${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 Zrt(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 ayn(t)}function Xrt(s){return typeof s=="object"&&"length"in s?s:Array.from(s)}function iKt(s){this._context=s}iKt.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 NRe(s){return new iKt(s)}function oKt(s){return s[0]}function lKt(s){return s[1]}function cKt(s,t){var n=Vf(!0),r=null,a=NRe,i=null,l=Zrt(o);s=typeof s=="function"?s:s===void 0?oKt:Vf(s),t=typeof t=="function"?t:t===void 0?lKt:Vf(t);function o(c){var d,u=(c=Xrt(c)).length,h,m=!1,f;for(r==null&&(i=a(f=l())),d=0;d<=u;++d)!(d=f;--g)o.point(w[g],S[g]);o.lineEnd(),o.areaEnd()}v&&(w[m]=+s(y,m,h),S[m]=+t(y,m,h),o.point(r?+r(y,m,h):w[m],n?+n(y,m,h):S[m]))}if(b)return o=null,b+""||null}function u(){return cKt().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 dKt{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 iyn(s){return new dKt(s,!0)}function oyn(s){return new dKt(s,!1)}const Qrt={draw(s,t){const n=kC(t/GTe);s.moveTo(n,0),s.arc(0,0,n,0,jRe)}},lyn={draw(s,t){const n=kC(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()}},uKt=kC(1/3),cyn=uKt*2,dyn={draw(s,t){const n=kC(t/cyn),r=n*uKt;s.moveTo(0,-n),s.lineTo(r,0),s.lineTo(0,n),s.lineTo(-r,0),s.closePath()}},uyn={draw(s,t){const n=kC(t),r=-n/2;s.rect(r,r,n,n)}},hyn=.8908130915292852,hKt=HTe(GTe/10)/HTe(7*GTe/10),myn=HTe(jRe/10)*hKt,fyn=-rKt(jRe/10)*hKt,pyn={draw(s,t){const n=kC(t*hyn),r=myn*n,a=fyn*n;s.moveTo(0,-n),s.lineTo(r,a);for(let i=1;i<5;++i){const l=jRe*i/5,o=rKt(l),c=HTe(l);s.lineTo(c*n,-o*n),s.lineTo(o*r-c*a,c*r+o*a)}s.closePath()}},a9e=kC(3),gyn={draw(s,t){const n=-kC(t/(a9e*3));s.moveTo(0,n*2),s.lineTo(-a9e*n,-n),s.lineTo(a9e*n,-n),s.closePath()}},sN=-.5,nN=kC(3)/2,JWe=1/kC(12),xyn=(JWe/2+1)*3,yyn={draw(s,t){const n=kC(t/xyn),r=n/2,a=n*JWe,i=r,l=n*JWe+n,o=-i,c=l;s.moveTo(r,a),s.lineTo(i,l),s.lineTo(o,c),s.lineTo(sN*r-nN*a,nN*r+sN*a),s.lineTo(sN*i-nN*l,nN*i+sN*l),s.lineTo(sN*o-nN*c,nN*o+sN*c),s.lineTo(sN*r+nN*a,sN*a-nN*r),s.lineTo(sN*i+nN*l,sN*l-nN*i),s.lineTo(sN*o+nN*c,sN*c-nN*o),s.closePath()}};function vyn(s,t){let n=null,r=Zrt(a);s=typeof s=="function"?s:Vf(s||Qrt),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 WTe(){}function KTe(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 mKt(s){this._context=s}mKt.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:KTe(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:KTe(this,s,t);break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t}};function byn(s){return new mKt(s)}function fKt(s){this._context=s}fKt.prototype={areaStart:WTe,areaEnd:WTe,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:KTe(this,s,t);break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t}};function _yn(s){return new fKt(s)}function pKt(s){this._context=s}pKt.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:KTe(this,s,t);break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t}};function wyn(s){return new pKt(s)}function gKt(s){this._context=s}gKt.prototype={areaStart:WTe,areaEnd:WTe,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 jyn(s){return new gKt(s)}function ijt(s){return s<0?-1:1}function ojt(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(ijt(i)+ijt(l))*Math.min(Math.abs(i),Math.abs(l),.5*Math.abs(o))||0}function ljt(s,t){var n=s._x1-s._x0;return n?(3*(s._y1-s._y0)/n-t)/2:t}function i9e(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 YTe(s){this._context=s}YTe.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:i9e(this,this._t0,ljt(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,i9e(this,ljt(this,n=ojt(this,s,t)),n);break;default:i9e(this,this._t0,n=ojt(this,s,t));break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t,this._t0=n}}};function xKt(s){this._context=new yKt(s)}(xKt.prototype=Object.create(YTe.prototype)).point=function(s,t){YTe.prototype.point.call(this,t,s)};function yKt(s){this._context=s}yKt.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 Nyn(s){return new YTe(s)}function kyn(s){return new xKt(s)}function vKt(s){this._context=s}vKt.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=cjt(s),a=cjt(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 Cyn(s){return new kRe(s,.5)}function Ayn(s){return new kRe(s,0)}function Eyn(s){return new kRe(s,1)}function zG(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 Tyn(s,t){return s[t]}function Myn(s){const t=[];return t.key=s,t}function Pyn(){var s=Vf([]),t=eKe,n=zG,r=Tyn;function a(i){var l=Array.from(s.apply(this,arguments),Myn),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 $yn(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 bKt={symbolCircle:Qrt,symbolCross:lyn,symbolDiamond:dyn,symbolSquare:uyn,symbolStar:pyn,symbolTriangle:gyn,symbolWye:yyn},Uyn=Math.PI/180,qyn=function(t){var n="symbol".concat(wRe(t));return bKt[n]||Qrt},Vyn=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*Uyn;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}},Hyn=function(t,n){bKt["symbol".concat(wRe(t))]=n},Jrt=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=Byn(t,Dyn),d=ujt(ujt({},c),{},{type:r,size:i,sizeType:o}),u=function(){var y=qyn(r),v=vyn().type(y).size(Vyn(i,o,r));return v()},h=d.className,m=d.cx,f=d.cy,g=cl(d,!0);return m===+m&&f===+f&&i===+i?Gt.createElement("path",tKe({},g,{className:sd("recharts-symbols",h),transform:"translate(".concat(m,", ").concat(f,")"),d:u()})):null};Jrt.registerSymbol=Hyn;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 sKe(){return sKe=Object.assign?Object.assign.bind():function(s){for(var t=1;t`);var b=f.inactive?d:f.color;return Gt.createElement("li",sKe({className:y,style:h,key:"legend-item-".concat(g)},sB(r.props,f,g)),Gt.createElement(WWe,{width:l,height:l,viewBox:u,style:m},r.renderIcon(f)),Gt.createElement("span",{className:"recharts-legend-item-text",style:{color:b}},x?x(v,f,g):v))})}},{key:"render",value:function(){var r=this.props,a=r.payload,i=r.layout,l=r.align;if(!a||!a.length)return null;var o={padding:0,margin:0,textAlign:i==="horizontal"?l:"left"};return Gt.createElement("ul",{className:"recharts-default-legend",style:o},this.renderItems())}}])}(j.PureComponent);Tse(eat,"displayName","Legend");Tse(eat,"defaultProps",{iconSize:14,layout:"horizontal",align:"center",verticalAlign:"middle",inactiveColor:"#ccc"});var t0n=cRe;function s0n(){this.__data__=new t0n,this.size=0}var n0n=s0n;function r0n(s){var t=this.__data__,n=t.delete(s);return this.size=t.size,n}var a0n=r0n;function i0n(s){return this.__data__.get(s)}var o0n=i0n;function l0n(s){return this.__data__.has(s)}var c0n=l0n,d0n=cRe,u0n=$rt,h0n=Urt,m0n=200;function f0n(s,t){var n=this.__data__;if(n instanceof d0n){var r=n.__data__;if(!u0n||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&D0n?new P0n:void 0;for(i.set(s,t),i.set(t,s);++h-1&&s%1==0&&s-1&&s%1==0&&s<=Bvn}var rat=$vn,Uvn=LT,qvn=rat,Vvn=RT,Hvn="[object Arguments]",Gvn="[object Array]",Wvn="[object Boolean]",Kvn="[object Date]",Yvn="[object Error]",Zvn="[object Function]",Xvn="[object Map]",Qvn="[object Number]",Jvn="[object Object]",ebn="[object RegExp]",tbn="[object Set]",sbn="[object String]",nbn="[object WeakMap]",rbn="[object ArrayBuffer]",abn="[object DataView]",ibn="[object Float32Array]",obn="[object Float64Array]",lbn="[object Int8Array]",cbn="[object Int16Array]",dbn="[object Int32Array]",ubn="[object Uint8Array]",hbn="[object Uint8ClampedArray]",mbn="[object Uint16Array]",fbn="[object Uint32Array]",vp={};vp[ibn]=vp[obn]=vp[lbn]=vp[cbn]=vp[dbn]=vp[ubn]=vp[hbn]=vp[mbn]=vp[fbn]=!0;vp[Hvn]=vp[Gvn]=vp[rbn]=vp[Wvn]=vp[abn]=vp[Kvn]=vp[Yvn]=vp[Zvn]=vp[Xvn]=vp[Qvn]=vp[Jvn]=vp[ebn]=vp[tbn]=vp[sbn]=vp[nbn]=!1;function pbn(s){return Vvn(s)&&qvn(s.length)&&!!vp[Uvn(s)]}var gbn=pbn;function xbn(s){return function(t){return s(t)}}var MKt=xbn,JTe={exports:{}};JTe.exports;(function(s,t){var n=OWt,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})(JTe,JTe.exports);var ybn=JTe.exports,vbn=gbn,bbn=MKt,yjt=ybn,vjt=yjt&&yjt.isTypedArray,_bn=vjt?bbn(vjt):vbn,PKt=_bn,wbn=kvn,jbn=sat,Nbn=Vw,kbn=TKt,Sbn=nat,Cbn=PKt,Abn=Object.prototype,Ebn=Abn.hasOwnProperty;function Tbn(s,t){var n=Nbn(s),r=!n&&jbn(s),a=!n&&!r&&kbn(s),i=!n&&!r&&!a&&Cbn(s),l=n||r||a||i,o=l?wbn(s.length,String):[],c=o.length;for(var d in s)(t||Ebn.call(s,d))&&!(l&&(d=="length"||a&&(d=="offset"||d=="parent")||i&&(d=="buffer"||d=="byteLength"||d=="byteOffset")||Sbn(d,c)))&&o.push(d);return o}var Mbn=Tbn,Pbn=Object.prototype;function Ibn(s){var t=s&&s.constructor,n=typeof t=="function"&&t.prototype||Pbn;return s===n}var Lbn=Ibn;function Rbn(s,t){return function(n){return s(t(n))}}var IKt=Rbn,Dbn=IKt,Fbn=Dbn(Object.keys,Object),Obn=Fbn,zbn=Lbn,Bbn=Obn,$bn=Object.prototype,Ubn=$bn.hasOwnProperty;function qbn(s){if(!zbn(s))return Bbn(s);var t=[];for(var n in Object(s))Ubn.call(s,n)&&n!="constructor"&&t.push(n);return t}var Vbn=qbn,Hbn=zrt,Gbn=rat;function Wbn(s){return s!=null&&Gbn(s.length)&&!Hbn(s)}var jie=Wbn,Kbn=Mbn,Ybn=Vbn,Zbn=jie;function Xbn(s){return Zbn(s)?Kbn(s):Ybn(s)}var SRe=Xbn,Qbn=mvn,Jbn=jvn,e1n=SRe;function t1n(s){return Qbn(s,e1n,Jbn)}var s1n=t1n,bjt=s1n,n1n=1,r1n=Object.prototype,a1n=r1n.hasOwnProperty;function i1n(s,t,n,r,a,i){var l=n&n1n,o=bjt(s),c=o.length,d=bjt(t),u=d.length;if(c!=u&&!l)return!1;for(var h=c;h--;){var m=o[h];if(!(l?m in t:a1n.call(t,m)))return!1}var f=i.get(s),g=i.get(t);if(f&&g)return f==t&&g==s;var x=!0;i.set(s,t),i.set(t,s);for(var y=l;++h-1}var rwn=nwn;function awn(s,t,n){for(var r=-1,a=s==null?0:s.length;++r=bwn){var d=t?null:ywn(s);if(d)return vwn(d);l=!1,a=xwn,c=new fwn}else c=t?[]:o;e:for(;++r=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function Dwn(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 Fwn(s){return s.value}function Own(s,t){if(Gt.isValidElement(s))return Gt.cloneElement(s,t);if(typeof s=="function")return Gt.createElement(s,t);t.ref;var n=Rwn(t,Cwn);return Gt.createElement(eat,n)}var Djt=1,CV=function(s){function t(){var n;Awn(this,t);for(var r=arguments.length,a=new Array(r),i=0;iDjt||Math.abs(a.height-this.lastBoundingBox.height)>Djt)&&(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?sA({},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 sA(sA({},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=sA(sA({position:"absolute",width:l||"auto",height:o||"auto"},this.getDefaultPosition(c)),c);return Gt.createElement("div",{className:"recharts-legend-wrapper",style:h,ref:function(f){r.wrapperNode=f}},Own(i,sA(sA({},this.props),{},{payload:BKt(u,d,Fwn)})))}}],[{key:"getWithHeight",value:function(r,a){var i=sA(sA({},this.defaultProps),r.props),l=i.layout;return l==="vertical"&&yi(r.props.height)?{height:r.props.height}:l==="horizontal"?{width:r.props.width||a}:null}}])}(j.PureComponent);CRe(CV,"displayName","Legend");CRe(CV,"defaultProps",{iconSize:14,layout:"horizontal",align:"center",verticalAlign:"bottom"});var Fjt=wie,zwn=sat,Bwn=Vw,Ojt=Fjt?Fjt.isConcatSpreadable:void 0;function $wn(s){return Bwn(s)||zwn(s)||!!(Ojt&&s&&s[Ojt])}var Uwn=$wn,qwn=AKt,Vwn=Uwn;function qKt(s,t,n,r,a){var i=-1,l=s.length;for(n||(n=Vwn),a||(a=[]);++i0&&n(o)?t>1?qKt(o,t-1,n,r,a):qwn(a,o):r||(a[a.length]=o)}return a}var VKt=qKt;function Hwn(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 Gwn=Hwn,Wwn=Gwn,Kwn=Wwn(),Ywn=Kwn,Zwn=Ywn,Xwn=SRe;function Qwn(s,t){return s&&Zwn(s,t,Xwn)}var HKt=Qwn,Jwn=jie;function ejn(s,t){return function(n,r){if(n==null)return n;if(!Jwn(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 fjn=mjn,d9e=Vrt,pjn=Hrt,gjn=m3,xjn=GKt,yjn=cjn,vjn=MKt,bjn=fjn,_jn=EK,wjn=Vw;function jjn(s,t,n){t.length?t=d9e(t,function(i){return wjn(i)?function(l){return pjn(l,i.length===1?i[0]:i)}:i}):t=[_jn];var r=-1;t=d9e(t,vjn(gjn));var a=xjn(s,function(i,l,o){var c=d9e(t,function(d){return d(i)});return{criteria:c,index:++r,value:i}});return yjn(a,function(i,l){return bjn(i,l,n)})}var Njn=jjn;function kjn(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 Sjn=kjn,Cjn=Sjn,Bjt=Math.max;function Ajn(s,t,n){return t=Bjt(t===void 0?s.length-1:t,0),function(){for(var r=arguments,a=-1,i=Bjt(r.length-t,0),l=Array(i);++a0){if(++t>=Ojn)return arguments[0]}else t=0;return s.apply(void 0,arguments)}}var Ujn=$jn,qjn=Fjn,Vjn=Ujn,Hjn=Vjn(qjn),Gjn=Hjn,Wjn=EK,Kjn=Ejn,Yjn=Gjn;function Zjn(s,t){return Yjn(Kjn(s,t,Wjn),s+"")}var Xjn=Zjn,Qjn=Brt,Jjn=jie,e2n=nat,t2n=w6;function s2n(s,t,n){if(!t2n(n))return!1;var r=typeof t;return(r=="number"?Jjn(n)&&e2n(t,n.length):r=="string"&&t in n)?Qjn(n[t],s):!1}var ARe=s2n,n2n=VKt,r2n=Njn,a2n=Xjn,Ujt=ARe,i2n=a2n(function(s,t){if(s==null)return[];var n=t.length;return n>1&&Ujt(s,t[0],t[1])?t=[]:n>2&&Ujt(t[0],t[1],t[2])&&(t=[t[0]]),r2n(s,n2n(t,1),[])}),o2n=i2n;const oat=ru(o2n);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 dKe(){return dKe=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(VZ,"-left"),yi(n)&&t&&yi(t.x)&&n=t.y),"".concat(VZ,"-top"),yi(r)&&t&&yi(t.y)&&rx?Math.max(u,c[r]):Math.max(h,c[r])}function w2n(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 j2n(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=Hjt({allowEscapeViewBox:t,coordinate:n,key:"x",offsetTopLeft:r,position:a,reverseDirection:i,tooltipDimension:l.width,viewBox:c,viewBoxDimension:c.width}),h=Hjt({allowEscapeViewBox:t,coordinate:n,key:"y",offsetTopLeft:r,position:a,reverseDirection:i,tooltipDimension:l.height,viewBox:c,viewBoxDimension:c.height}),d=w2n({translateX:u,translateY:h,useTranslate3d:o})):d=b2n,{cssProperties:d,cssClasses:_2n({translateX:u,translateY:h,coordinate:n})}}function UG(s){"@babel/helpers - typeof";return UG=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},UG(s)}function Gjt(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 Wjt(s){for(var t=1;tKjt||Math.abs(r.height-this.state.lastBoundingBox.height)>Kjt)&&this.setState({lastBoundingBox:{width:r.width,height:r.height}})}else(this.state.lastBoundingBox.width!==-1||this.state.lastBoundingBox.height!==-1)&&this.setState({lastBoundingBox:{width:-1,height:-1}})}},{key:"componentDidMount",value:function(){document.addEventListener("keydown",this.handleKeyDown),this.updateBBox()}},{key:"componentWillUnmount",value:function(){document.removeEventListener("keydown",this.handleKeyDown)}},{key:"componentDidUpdate",value:function(){var r,a;this.props.active&&this.updateBBox(),this.state.dismissed&&(((r=this.props.coordinate)===null||r===void 0?void 0:r.x)!==this.state.dismissedAtCoordinate.x||((a=this.props.coordinate)===null||a===void 0?void 0:a.y)!==this.state.dismissedAtCoordinate.y)&&(this.state.dismissed=!1)}},{key:"render",value:function(){var r=this,a=this.props,i=a.active,l=a.allowEscapeViewBox,o=a.animationDuration,c=a.animationEasing,d=a.children,u=a.coordinate,h=a.hasPayload,m=a.isAnimationActive,f=a.offset,g=a.position,x=a.reverseDirection,y=a.useTranslate3d,v=a.viewBox,b=a.wrapperStyle,w=j2n({allowEscapeViewBox:l,coordinate:u,offsetTopLeft:f,position:g,reverseDirection:x,tooltipBox:this.state.lastBoundingBox,useTranslate3d:y,viewBox:v}),S=w.cssClasses,A=w.cssProperties,E=Wjt(Wjt({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 Gt.createElement("div",{tabIndex:-1,className:S,style:E,ref:function(P){r.wrapperNode=P}},d)}}])}(j.PureComponent),I2n=function(){return!(typeof window<"u"&&window.document&&window.document.createElement&&window.setTimeout)},j6={isSsr:I2n()};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 Yjt(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 Zjt(s){for(var t=1;t0;return Gt.createElement(P2n,{allowEscapeViewBox:l,animationDuration:o,animationEasing:c,isAnimationActive:m,active:i,coordinate:u,hasPayload:E,offset:f,position:y,reverseDirection:v,useTranslate3d:b,viewBox:w,wrapperStyle:S},q2n(d,Zjt(Zjt({},this.props),{},{payload:A})))}}])}(j.PureComponent);lat(Cg,"displayName","Tooltip");lat(Cg,"defaultProps",{accessibilityLayer:!1,allowEscapeViewBox:{x:!1,y:!1},animationDuration:400,animationEasing:"ease",contentStyle:{},coordinate:{x:0,y:0},cursor:!0,cursorStyle:{},filterNull:!0,isAnimationActive:!j6.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 V2n=h3,H2n=function(){return V2n.Date.now()},G2n=H2n,W2n=/\s/;function K2n(s){for(var t=s.length;t--&&W2n.test(s.charAt(t)););return t}var Y2n=K2n,Z2n=Y2n,X2n=/^\s+/;function Q2n(s){return s&&s.slice(0,Z2n(s)+1).replace(X2n,"")}var J2n=Q2n,eNn=J2n,Xjt=w6,tNn=_K,Qjt=NaN,sNn=/^[-+]0x[0-9a-f]+$/i,nNn=/^0b[01]+$/i,rNn=/^0o[0-7]+$/i,aNn=parseInt;function iNn(s){if(typeof s=="number")return s;if(tNn(s))return Qjt;if(Xjt(s)){var t=typeof s.valueOf=="function"?s.valueOf():s;s=Xjt(t)?t+"":t}if(typeof s!="string")return s===0?s:+s;s=eNn(s);var n=nNn.test(s);return n||rNn.test(s)?aNn(s.slice(2),n?2:8):sNn.test(s)?Qjt:+s}var QKt=iNn,oNn=w6,h9e=G2n,Jjt=QKt,lNn="Expected a function",cNn=Math.max,dNn=Math.min;function uNn(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(lNn);t=Jjt(t)||0,oNn(n)&&(u=!!n.leading,h="maxWait"in n,i=h?cNn(Jjt(n.maxWait)||0,t):i,m="trailing"in n?!!n.trailing:m);function f(E){var I=r,P=a;return r=a=void 0,d=E,l=s.apply(P,I),l}function g(E){return d=E,o=setTimeout(v,t),u?f(E):l}function x(E){var I=E-c,P=E-d,R=t-I;return h?dNn(R,i-P):R}function y(E){var I=E-c,P=E-d;return c===void 0||I>=t||I<0||h&&P>=i}function v(){var E=h9e();if(y(E))return b(E);o=setTimeout(v,x(E))}function b(E){return o=void 0,m&&r?f(E):(r=a=void 0,l)}function w(){o!==void 0&&clearTimeout(o),d=0,r=c=a=o=void 0}function S(){return o===void 0?l:b(h9e())}function A(){var E=h9e(),I=y(E);if(r=arguments,a=this,c=E,I){if(o===void 0)return g(c);if(h)return clearTimeout(o),o=setTimeout(v,t),f(c)}return o===void 0&&(o=setTimeout(v,t)),l}return A.cancel=w,A.flush=S,A}var hNn=uNn,mNn=hNn,fNn=w6,pNn="Expected a function";function gNn(s,t,n){var r=!0,a=!0;if(typeof s!="function")throw new TypeError(pNn);return fNn(n)&&(r="leading"in n?!!n.leading:r,a="trailing"in n?!!n.trailing:a),mNn(s,t,{leading:r,maxWait:t,trailing:a})}var xNn=gNn;const JKt=ru(xNn);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 e2t(s,t){var n=Object.keys(s);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(s);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),n.push.apply(n,r)}return n}function $de(s){for(var t=1;ts.length)&&(t=s.length);for(var n=0,r=new Array(t);n0&&(W=JKt(W,x,{trailing:!0,leading:!1}));var V=new ResizeObserver(W),G=A.current.getBoundingClientRect(),Y=G.width,X=G.height;return O(Y,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;oC(p8(l)||p8(c),`The width(%s) and height(%s) are both fixed numbers, maybe you don't need to use a ResponsiveContainer.`,l,c),oC(!n||n>0,"The aspect(%s) must be greater than zero.",n);var G=p8(l)?W:l,Y=p8(c)?V:c;n&&n>0&&(G?Y=G/n:Y&&(G=Y*n),m&&Y>m&&(Y=m)),oC(G>0||Y>0,`The width(%s) and height(%s) of chart should be greater than 0, please check the style of container, or the props width(%s) and height(%s), or add a minWidth(%s) or minHeight(%s) or use aspect(%s) to control the height and width.`,G,Y,l,c,u,h,n);var X=!Array.isArray(f)&&VE(f.type).endsWith("Chart");return Gt.Children.map(f,function(ae){return Gt.isValidElement(ae)?j.cloneElement(ae,$de({width:G,height:Y},X?{style:$de({height:"100%",width:"100%",maxHeight:Y,maxWidth:G},ae.props.style)}:{})):ae})},[n,f,c,m,h,u,R,l]);return Gt.createElement("div",{id:y?"".concat(y):void 0,className:sd("recharts-responsive-container",v),style:$de($de({},S),{},{width:l,height:c,minWidth:u,minHeight:h,maxHeight:m}),ref:A},U)}),ZB=function(t){return null};ZB.displayName="Cell";function Lse(s){"@babel/helpers - typeof";return Lse=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},Lse(s)}function s2t(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 fKe(s){for(var t=1;t1&&arguments[1]!==void 0?arguments[1]:{};if(t==null||j6.isSsr)return{width:0,height:0};var r=MNn(n),a=JSON.stringify({text:t,copyStyle:r});if(I$.widthCache[a])return I$.widthCache[a];try{var i=document.getElementById(n2t);i||(i=document.createElement("span"),i.setAttribute("id",n2t),i.setAttribute("aria-hidden","true"),document.body.appendChild(i));var l=fKe(fKe({},TNn),r);Object.assign(i.style,l),i.textContent="".concat(t);var o=i.getBoundingClientRect(),c={width:o.width,height:o.height};return I$.widthCache[a]=c,++I$.cacheCount>ENn&&(I$.cacheCount=0,I$.widthCache={}),c}catch{return{width:0,height:0}}},PNn=function(t){return{top:t.top+window.scrollY-document.documentElement.clientTop,left:t.left+window.scrollX-document.documentElement.clientLeft}};function Rse(s){"@babel/helpers - typeof";return Rse=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},Rse(s)}function nMe(s,t){return DNn(s)||RNn(s,t)||LNn(s,t)||INn()}function INn(){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 LNn(s,t){if(s){if(typeof s=="string")return r2t(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 r2t(s,t)}}function r2t(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 d2t(s,t){return ekn(s)||JNn(s,t)||QNn(s,t)||XNn()}function XNn(){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 QNn(s,t){if(s){if(typeof s=="string")return u2t(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 u2t(s,t)}}function u2t(s,t){(t==null||t>s.length)&&(t=s.length);for(var n=0,r=new Array(t);n0&&arguments[0]!==void 0?arguments[0]:[];return G.reduce(function(Y,X){var ae=X.word,le=X.width,ne=Y[Y.length-1];if(ne&&(a==null||i||ne.width+le+rX.width?Y:X})};if(!u)return f;for(var x="…",y=function(G){var Y=h.slice(0,G),X=nYt({breakAll:d,style:c,children:Y+x}).wordsWithComputedWidth,ae=m(X),le=ae.length>l||g(ae).width>Number(a);return[le,ae]},v=0,b=h.length-1,w=0,S;v<=b&&w<=h.length-1;){var A=Math.floor((v+b)/2),E=A-1,I=y(E),P=d2t(I,2),R=P[0],D=P[1],O=y(A),U=d2t(O,1),W=U[0];if(!R&&!W&&(v=A+1),R&&W&&(b=A-1),!R&&W){S=D;break}w++}return S||f},h2t=function(t){var n=Gc(t)?[]:t.toString().split(sYt);return[{words:n}]},skn=function(t){var n=t.width,r=t.scaleToFit,a=t.children,i=t.style,l=t.breakAll,o=t.maxLines;if((n||r)&&!j6.isSsr){var c,d,u=nYt({breakAll:l,children:a,style:i});if(u){var h=u.wordsWithComputedWidth,m=u.spaceWidth;c=h,d=m}else return h2t(a);return tkn({breakAll:l,children:a,maxLines:o,style:i},c,d,n,r)}return h2t(a)},m2t="#808080",nB=function(t){var n=t.x,r=n===void 0?0:n,a=t.y,i=a===void 0?0:a,l=t.lineHeight,o=l===void 0?"1em":l,c=t.capHeight,d=c===void 0?"0.71em":c,u=t.scaleToFit,h=u===void 0?!1:u,m=t.textAnchor,f=m===void 0?"start":m,g=t.verticalAnchor,x=g===void 0?"end":g,y=t.fill,v=y===void 0?m2t:y,b=c2t(t,KNn),w=j.useMemo(function(){return skn({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=c2t(b,YNn);if(!k0(r)||!k0(i))return null;var D=r+(yi(S)?S:0),O=i+(yi(A)?A:0),U;switch(x){case"start":U=m9e("calc(".concat(d,")"));break;case"middle":U=m9e("calc(".concat((w.length-1)/2," * -").concat(o," + (").concat(d," / 2))"));break;default:U=m9e("calc(".concat(w.length-1," * -").concat(o,")"));break}var W=[];if(h){var V=w[0].width,G=b.width;W.push("scale(".concat((yi(G)?G/V:1)/V,")"))}return E&&W.push("rotate(".concat(E,", ").concat(D,", ").concat(O,")")),W.length&&(R.transform=W.join(" ")),Gt.createElement("text",pKe({},cl(R,!0),{x:D,y:O,className:sd("recharts-text",I),textAnchor:f,fill:v.includes("url")?m2t:v}),w.map(function(Y,X){var ae=Y.words.join(P?"":" ");return Gt.createElement("tspan",{x:D,dy:X===0?U:o,key:"".concat(ae,"-").concat(X)},ae)}))};function hL(s,t){return s==null||t==null?NaN:st?1:s>=t?0:NaN}function nkn(s,t){return s==null||t==null?NaN:ts?1:t>=s?0:NaN}function cat(s){let t,n,r;s.length!==2?(t=hL,n=(o,c)=>hL(s(o),c),r=(o,c)=>s(o)-c):(t=s===hL||s===nkn?s:rkn,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 rkn(){return 0}function rYt(s){return s===null?NaN:+s}function*akn(s,t){for(let n of s)n!=null&&(n=+n)>=n&&(yield n)}const ikn=cat(hL),Nie=ikn.right;cat(rYt).center;class f2t extends Map{constructor(t,n=ckn){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(p2t(this,t))}has(t){return super.has(p2t(this,t))}set(t,n){return super.set(okn(this,t),n)}delete(t){return super.delete(lkn(this,t))}}function p2t({_intern:s,_key:t},n){const r=t(n);return s.has(r)?s.get(r):n}function okn({_intern:s,_key:t},n){const r=t(n);return s.has(r)?s.get(r):(s.set(r,n),n)}function lkn({_intern:s,_key:t},n){const r=t(n);return s.has(r)&&(n=s.get(r),s.delete(r)),n}function ckn(s){return s!==null&&typeof s=="object"?s.valueOf():s}function dkn(s=hL){if(s===hL)return aYt;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 aYt(s,t){return(s==null||!(s>=s))-(t==null||!(t>=t))||(st?1:0)}const ukn=Math.sqrt(50),hkn=Math.sqrt(10),mkn=Math.sqrt(2);function rMe(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>=ukn?10:i>=hkn?5:i>=mkn?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 x2t(s,t){let n;for(const r of s)r!=null&&(n>r||n===void 0&&r>=r)&&(n=r);return n}function iYt(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?aYt:dkn(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));iYt(s,t,f,g,a)}const i=s[t];let l=n,o=r;for(HZ(s,n,t),a(s[r],i)>0&&HZ(s,n,r);l0;)--o}a(s[n],i)===0?HZ(s,n,o):(++o,HZ(s,o,r)),o<=t&&(n=o+1),t<=o&&(r=o-1)}return s}function HZ(s,t,n){const r=s[t];s[t]=s[n],s[n]=r}function fkn(s,t,n){if(s=Float64Array.from(akn(s)),!(!(r=s.length)||isNaN(t=+t))){if(t<=0||r<2)return x2t(s);if(t>=1)return g2t(s);var r,a=(r-1)*t,i=Math.floor(a),l=g2t(iYt(s,i).subarray(0,i+1)),o=x2t(s.subarray(i+1));return l+(o-l)*(a-i)}}function pkn(s,t,n=rYt){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 gkn(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?qde(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?qde(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=ykn.exec(s))?new bw(t[1],t[2],t[3],1):(t=vkn.exec(s))?new bw(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=bkn.exec(s))?qde(t[1],t[2],t[3],t[4]):(t=_kn.exec(s))?qde(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=wkn.exec(s))?N2t(t[1],t[2]/100,t[3]/100,1):(t=jkn.exec(s))?N2t(t[1],t[2]/100,t[3]/100,t[4]):y2t.hasOwnProperty(s)?_2t(y2t[s]):s==="transparent"?new bw(NaN,NaN,NaN,0):null}function _2t(s){return new bw(s>>16&255,s>>8&255,s&255,1)}function qde(s,t,n,r){return r<=0&&(s=t=n=NaN),new bw(s,t,n,r)}function Skn(s){return s instanceof kie||(s=zse(s)),s?(s=s.rgb(),new bw(s.r,s.g,s.b,s.opacity)):new bw}function bKe(s,t,n,r){return arguments.length===1?Skn(s):new bw(s,t,n,r??1)}function bw(s,t,n,r){this.r=+s,this.g=+t,this.b=+n,this.opacity=+r}uat(bw,bKe,lYt(kie,{brighter(s){return s=s==null?aMe:Math.pow(aMe,s),new bw(this.r*s,this.g*s,this.b*s,this.opacity)},darker(s){return s=s==null?Fse:Math.pow(Fse,s),new bw(this.r*s,this.g*s,this.b*s,this.opacity)},rgb(){return this},clamp(){return new bw(y7(this.r),y7(this.g),y7(this.b),iMe(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:w2t,formatHex:w2t,formatHex8:Ckn,formatRgb:j2t,toString:j2t}));function w2t(){return`#${g8(this.r)}${g8(this.g)}${g8(this.b)}`}function Ckn(){return`#${g8(this.r)}${g8(this.g)}${g8(this.b)}${g8((isNaN(this.opacity)?1:this.opacity)*255)}`}function j2t(){const s=iMe(this.opacity);return`${s===1?"rgb(":"rgba("}${y7(this.r)}, ${y7(this.g)}, ${y7(this.b)}${s===1?")":`, ${s})`}`}function iMe(s){return isNaN(s)?1:Math.max(0,Math.min(1,s))}function y7(s){return Math.max(0,Math.min(255,Math.round(s)||0))}function g8(s){return s=y7(s),(s<16?"0":"")+s.toString(16)}function N2t(s,t,n,r){return r<=0?s=t=n=NaN:n<=0||n>=1?s=t=NaN:t<=0&&(s=NaN),new US(s,t,n,r)}function cYt(s){if(s instanceof US)return new US(s.h,s.s,s.l,s.opacity);if(s instanceof kie||(s=zse(s)),!s)return new US;if(s instanceof US)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 US(l,o,c,s.opacity)}function Akn(s,t,n,r){return arguments.length===1?cYt(s):new US(s,t,n,r??1)}function US(s,t,n,r){this.h=+s,this.s=+t,this.l=+n,this.opacity=+r}uat(US,Akn,lYt(kie,{brighter(s){return s=s==null?aMe:Math.pow(aMe,s),new US(this.h,this.s,this.l*s,this.opacity)},darker(s){return s=s==null?Fse:Math.pow(Fse,s),new US(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 bw(f9e(s>=240?s-240:s+120,a,r),f9e(s,a,r),f9e(s<120?s+240:s-120,a,r),this.opacity)},clamp(){return new US(k2t(this.h),Vde(this.s),Vde(this.l),iMe(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=iMe(this.opacity);return`${s===1?"hsl(":"hsla("}${k2t(this.h)}, ${Vde(this.s)*100}%, ${Vde(this.l)*100}%${s===1?")":`, ${s})`}`}}));function k2t(s){return s=(s||0)%360,s<0?s+360:s}function Vde(s){return Math.max(0,Math.min(1,s||0))}function f9e(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 hat=s=>()=>s;function Ekn(s,t){return function(n){return s+n*t}}function Tkn(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 Mkn(s){return(s=+s)==1?dYt:function(t,n){return n-t?Tkn(t,n,s):hat(isNaN(t)?n:t)}}function dYt(s,t){var n=t-s;return n?Ekn(s,n):hat(isNaN(s)?t:s)}const S2t=function s(t){var n=Mkn(t);function r(a,i){var l=n((a=bKe(a)).r,(i=bKe(i)).r),o=n(a.g,i.g),c=n(a.b,i.b),d=dYt(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 Pkn(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:oMe(r,a)})),n=p9e.lastIndex;return nt&&(n=s,s=t,t=n),function(r){return Math.max(s,Math.min(t,r))}}function qkn(s,t,n){var r=s[0],a=s[1],i=t[0],l=t[1];return a2?Vkn:qkn,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),oMe)))(m)))},h.domain=function(m){return arguments.length?(s=Array.from(m,lMe),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=mat,u()},h.clamp=function(m){return arguments.length?(l=m?!0:b_,u()):l!==b_},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 fat(){return ERe()(b_,b_)}function Hkn(s){return Math.abs(s=Math.round(s))>=1e21?s.toLocaleString("en").replace(/,/g,""):s.toString(10)}function cMe(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 VG(s){return s=cMe(Math.abs(s)),s?s[1]:NaN}function Gkn(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 Wkn(s){return function(t){return t.replace(/[0-9]/g,function(n){return s[+n]})}}var Kkn=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function Bse(s){if(!(t=Kkn.exec(s)))throw new Error("invalid format: "+s);var t;return new pat({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]})}Bse.prototype=pat.prototype;function pat(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+""}pat.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 Ykn(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 dMe;function Zkn(s,t){var n=cMe(s,t);if(!n)return dMe=void 0,s.toPrecision(t);var r=n[0],a=n[1],i=a-(dMe=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")+cMe(s,Math.max(0,t+i-1))[0]}function A2t(s,t){var n=cMe(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 E2t={"%":(s,t)=>(s*100).toFixed(t),b:s=>Math.round(s).toString(2),c:s=>s+"",d:Hkn,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)=>A2t(s*100,t),r:A2t,s:Zkn,X:s=>Math.round(s).toString(16).toUpperCase(),x:s=>Math.round(s).toString(16)};function T2t(s){return s}var M2t=Array.prototype.map,P2t=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];function Xkn(s){var t=s.grouping===void 0||s.thousands===void 0?T2t:Gkn(M2t.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?T2t:Wkn(M2t.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=Bse(h);var f=h.fill,g=h.align,x=h.sign,y=h.symbol,v=h.zero,b=h.width,w=h.comma,S=h.precision,A=h.trim,E=h.type;E==="n"?(w=!0,E="g"):E2t[E]||(S===void 0&&(S=12),A=!0,E="g"),(v||f==="0"&&g==="=")&&(v=!0,f="0",g="=");var I=(m&&m.prefix!==void 0?m.prefix:"")+(y==="$"?n:y==="#"&&/[boxX]/.test(E)?"0"+E.toLowerCase():""),P=(y==="$"?r:/[%p]/.test(E)?l:"")+(m&&m.suffix!==void 0?m.suffix:""),R=E2t[E],D=/[defgprs%]/.test(E);S=S===void 0?6:/[gprs]/.test(E)?Math.max(1,Math.min(21,S)):Math.max(0,Math.min(20,S));function O(U){var W=I,V=P,G,Y,X;if(E==="c")V=R(U)+V,U="";else{U=+U;var ae=U<0||1/U<0;if(U=isNaN(U)?c:R(Math.abs(U),S),A&&(U=Ykn(U)),ae&&+U==0&&x!=="+"&&(ae=!1),W=(ae?x==="("?x:o:x==="-"||x==="("?"":x)+W,V=(E==="s"&&!isNaN(U)&&dMe!==void 0?P2t[8+dMe/3]:"")+V+(ae&&x==="("?")":""),D){for(G=-1,Y=U.length;++GX||X>57){V=(X===46?a+U.slice(G+1):U.slice(G))+V,U=U.slice(0,G);break}}}w&&!v&&(U=t(U,1/0));var le=W.length+U.length+V.length,ne=le>1)+W+U+V+ne.slice(le);break;default:U=ne+W+U+V;break}return i(U)}return O.toString=function(){return h+""},O}function u(h,m){var f=Math.max(-8,Math.min(8,Math.floor(VG(m)/3)))*3,g=Math.pow(10,-f),x=d((h=Bse(h),h.type="f",h),{suffix:P2t[8+f/3]});return function(y){return x(g*y)}}return{format:d,formatPrefix:u}}var Hde,gat,uYt;Qkn({thousands:",",grouping:[3],currency:["$",""]});function Qkn(s){return Hde=Xkn(s),gat=Hde.format,uYt=Hde.formatPrefix,Hde}function Jkn(s){return Math.max(0,-VG(Math.abs(s)))}function eSn(s,t){return Math.max(0,Math.max(-8,Math.min(8,Math.floor(VG(t)/3)))*3-VG(Math.abs(s)))}function tSn(s,t){return s=Math.abs(s),t=Math.abs(t)-s,Math.max(0,VG(t)-VG(s))+1}function hYt(s,t,n,r){var a=yKe(s,t,n),i;switch(r=Bse(r??",f"),r.type){case"s":{var l=Math.max(Math.abs(s),Math.abs(t));return r.precision==null&&!isNaN(i=eSn(a,l))&&(r.precision=i),uYt(r,l)}case"":case"e":case"g":case"p":case"r":{r.precision==null&&!isNaN(i=tSn(a,Math.max(Math.abs(s),Math.abs(t))))&&(r.precision=i-(r.type==="e"));break}case"f":case"%":{r.precision==null&&!isNaN(i=Jkn(a))&&(r.precision=i-(r.type==="%")*2);break}}return gat(r)}function N6(s){var t=s.domain;return s.ticks=function(n){var r=t();return gKe(r[0],r[r.length-1],n??10)},s.tickFormat=function(n,r){var a=t();return hYt(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=xKe(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 uMe(){var s=fat();return s.copy=function(){return Sie(s,uMe())},Ak.apply(s,arguments),N6(s)}function mYt(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,lMe),n):s.slice()},n.unknown=function(r){return arguments.length?(t=r,n):t},n.copy=function(){return mYt(s).unknown(t)},s=arguments.length?Array.from(s,lMe):[0,1],N6(n)}function fYt(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 iSn(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 R2t(s){return(t,n)=>-s(-t,n)}function xat(s){const t=s(I2t,L2t),n=t.domain;let r=10,a,i;function l(){return a=iSn(r),i=aSn(r),n()[0]<0?(a=R2t(a),i=R2t(i),s(sSn,nSn)):s(I2t,L2t),t}return t.base=function(o){return arguments.length?(r=+o,l()):r},t.domain=function(o){return arguments.length?(n(o),l()):n()},t.ticks=o=>{const c=n();let d=c[0],u=c[c.length-1];const h=u0){for(;m<=f;++m)for(g=1;gu)break;v.push(x)}}else for(;m<=f;++m)for(g=r-1;g>=1;--g)if(x=m>0?g/i(-m):g*i(m),!(xu)break;v.push(x)}v.length*2{if(o==null&&(o=10),c==null&&(c=r===10?"s":","),typeof c!="function"&&(!(r%1)&&(c=Bse(c)).precision==null&&(c.trim=!0),c=gat(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(fYt(n(),{floor:o=>i(Math.floor(a(o))),ceil:o=>i(Math.ceil(a(o)))})),t}function pYt(){const s=xat(ERe()).domain([1,10]);return s.copy=()=>Sie(s,pYt()).base(s.base()),Ak.apply(s,arguments),s}function D2t(s){return function(t){return Math.sign(t)*Math.log1p(Math.abs(t/s))}}function F2t(s){return function(t){return Math.sign(t)*Math.expm1(Math.abs(t))*s}}function yat(s){var t=1,n=s(D2t(t),F2t(t));return n.constant=function(r){return arguments.length?s(D2t(t=+r),F2t(t)):t},N6(n)}function gYt(){var s=yat(ERe());return s.copy=function(){return Sie(s,gYt()).constant(s.constant())},Ak.apply(s,arguments)}function O2t(s){return function(t){return t<0?-Math.pow(-t,s):Math.pow(t,s)}}function oSn(s){return s<0?-Math.sqrt(-s):Math.sqrt(s)}function lSn(s){return s<0?-s*s:s*s}function vat(s){var t=s(b_,b_),n=1;function r(){return n===1?s(b_,b_):n===.5?s(oSn,lSn):s(O2t(n),O2t(1/n))}return t.exponent=function(a){return arguments.length?(n=+a,r()):n},N6(t)}function bat(){var s=vat(ERe());return s.copy=function(){return Sie(s,bat()).exponent(s.exponent())},Ak.apply(s,arguments),s}function cSn(){return bat.apply(null,arguments).exponent(.5)}function z2t(s){return Math.sign(s)*s*s}function dSn(s){return Math.sign(s)*Math.sqrt(Math.abs(s))}function xYt(){var s=fat(),t=[0,1],n=!1,r;function a(i){var l=dSn(s(i));return isNaN(l)?r:n?Math.round(l):l}return a.invert=function(i){return s.invert(z2t(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,lMe)).map(z2t)),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 xYt(s.domain(),t).round(n).clamp(s.clamp()).unknown(r)},Ak.apply(a,arguments),N6(a)}function yYt(){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 vYt().domain([s,t]).range(a).unknown(i)},Ak.apply(N6(l),arguments)}function bYt(){var s=[.5],t=[0,1],n,r=1;function a(i){return i!=null&&i<=i?t[Nie(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 bYt().domain(s).range(t).unknown(n)},Ak.apply(a,arguments)}const g9e=new Date,x9e=new Date;function B0(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(dB0(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)=>(g9e.setTime(+i),x9e.setTime(+l),s(g9e),s(x9e),Math.floor(n(g9e,x9e))),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 hMe=B0(()=>{},(s,t)=>{s.setTime(+s+t)},(s,t)=>t-s);hMe.every=s=>(s=Math.floor(s),!isFinite(s)||!(s>0)?null:s>1?B0(t=>{t.setTime(Math.floor(t/s)*s)},(t,n)=>{t.setTime(+t+n*s)},(t,n)=>(n-t)/s):hMe);hMe.range;const wE=1e3,qN=wE*60,jE=qN*60,mT=jE*24,_at=mT*7,B2t=mT*30,y9e=mT*365,x8=B0(s=>{s.setTime(s-s.getMilliseconds())},(s,t)=>{s.setTime(+s+t*wE)},(s,t)=>(t-s)/wE,s=>s.getUTCSeconds());x8.range;const wat=B0(s=>{s.setTime(s-s.getMilliseconds()-s.getSeconds()*wE)},(s,t)=>{s.setTime(+s+t*qN)},(s,t)=>(t-s)/qN,s=>s.getMinutes());wat.range;const jat=B0(s=>{s.setUTCSeconds(0,0)},(s,t)=>{s.setTime(+s+t*qN)},(s,t)=>(t-s)/qN,s=>s.getUTCMinutes());jat.range;const Nat=B0(s=>{s.setTime(s-s.getMilliseconds()-s.getSeconds()*wE-s.getMinutes()*qN)},(s,t)=>{s.setTime(+s+t*jE)},(s,t)=>(t-s)/jE,s=>s.getHours());Nat.range;const kat=B0(s=>{s.setUTCMinutes(0,0,0)},(s,t)=>{s.setTime(+s+t*jE)},(s,t)=>(t-s)/jE,s=>s.getUTCHours());kat.range;const Cie=B0(s=>s.setHours(0,0,0,0),(s,t)=>s.setDate(s.getDate()+t),(s,t)=>(t-s-(t.getTimezoneOffset()-s.getTimezoneOffset())*qN)/mT,s=>s.getDate()-1);Cie.range;const TRe=B0(s=>{s.setUTCHours(0,0,0,0)},(s,t)=>{s.setUTCDate(s.getUTCDate()+t)},(s,t)=>(t-s)/mT,s=>s.getUTCDate()-1);TRe.range;const _Yt=B0(s=>{s.setUTCHours(0,0,0,0)},(s,t)=>{s.setUTCDate(s.getUTCDate()+t)},(s,t)=>(t-s)/mT,s=>Math.floor(s/mT));_Yt.range;function XB(s){return B0(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())*qN)/_at)}const MRe=XB(0),mMe=XB(1),uSn=XB(2),hSn=XB(3),HG=XB(4),mSn=XB(5),fSn=XB(6);MRe.range;mMe.range;uSn.range;hSn.range;HG.range;mSn.range;fSn.range;function QB(s){return B0(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)/_at)}const PRe=QB(0),fMe=QB(1),pSn=QB(2),gSn=QB(3),GG=QB(4),xSn=QB(5),ySn=QB(6);PRe.range;fMe.range;pSn.range;gSn.range;GG.range;xSn.range;ySn.range;const Sat=B0(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());Sat.range;const Cat=B0(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());Cat.range;const fT=B0(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());fT.every=s=>!isFinite(s=Math.floor(s))||!(s>0)?null:B0(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)});fT.range;const pT=B0(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());pT.every=s=>!isFinite(s=Math.floor(s))||!(s>0)?null:B0(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)});pT.range;function wYt(s,t,n,r,a,i){const l=[[x8,1,wE],[x8,5,5*wE],[x8,15,15*wE],[x8,30,30*wE],[i,1,qN],[i,5,5*qN],[i,15,15*qN],[i,30,30*qN],[a,1,jE],[a,3,3*jE],[a,6,6*jE],[a,12,12*jE],[r,1,mT],[r,2,2*mT],[n,1,_at],[t,1,B2t],[t,3,3*B2t],[s,1,y9e]];function o(d,u,h){const m=uy).right(l,m);if(f===l.length)return s.every(yKe(d/y9e,u/y9e,h));if(f===0)return hMe.every(Math.max(yKe(d,u,h),1));const[g,x]=l[m/l[f-1][2]53)return null;"w"in ke||(ke.w=1),"Z"in ke?(Ne=b9e(GZ(ke.y,0,1)),Ae=Ne.getUTCDay(),Ne=Ae>4||Ae===0?fMe.ceil(Ne):fMe(Ne),Ne=TRe.offset(Ne,(ke.V-1)*7),ke.y=Ne.getUTCFullYear(),ke.m=Ne.getUTCMonth(),ke.d=Ne.getUTCDate()+(ke.w+6)%7):(Ne=v9e(GZ(ke.y,0,1)),Ae=Ne.getDay(),Ne=Ae>4||Ae===0?mMe.ceil(Ne):mMe(Ne),Ne=Cie.offset(Ne,(ke.V-1)*7),ke.y=Ne.getFullYear(),ke.m=Ne.getMonth(),ke.d=Ne.getDate()+(ke.w+6)%7)}else("W"in ke||"U"in ke)&&("w"in ke||(ke.w="u"in ke?ke.u%7:"W"in ke?1:0),Ae="Z"in ke?b9e(GZ(ke.y,0,1)).getUTCDay():v9e(GZ(ke.y,0,1)).getDay(),ke.m=0,ke.d="W"in ke?(ke.w+6)%7+ke.W*7-(Ae+5)%7:ke.w+ke.U*7-(Ae+6)%7);return"Z"in ke?(ke.H+=ke.Z/100|0,ke.M+=ke.Z%100,b9e(ke)):v9e(ke)}}function P(Se,Le,Fe,ke){for(var Be=0,Ne=Le.length,Ae=Fe.length,Ce,Ve;Be=Ae)return-1;if(Ce=Le.charCodeAt(Be++),Ce===37){if(Ce=Le.charAt(Be++),Ve=A[Ce in $2t?Le.charAt(Be++):Ce],!Ve||(ke=Ve(Se,Fe,ke))<0)return-1}else if(Ce!=Fe.charCodeAt(ke++))return-1}return ke}function R(Se,Le,Fe){var ke=d.exec(Le.slice(Fe));return ke?(Se.p=u.get(ke[0].toLowerCase()),Fe+ke[0].length):-1}function D(Se,Le,Fe){var ke=f.exec(Le.slice(Fe));return ke?(Se.w=g.get(ke[0].toLowerCase()),Fe+ke[0].length):-1}function O(Se,Le,Fe){var ke=h.exec(Le.slice(Fe));return ke?(Se.w=m.get(ke[0].toLowerCase()),Fe+ke[0].length):-1}function U(Se,Le,Fe){var ke=v.exec(Le.slice(Fe));return ke?(Se.m=b.get(ke[0].toLowerCase()),Fe+ke[0].length):-1}function W(Se,Le,Fe){var ke=x.exec(Le.slice(Fe));return ke?(Se.m=y.get(ke[0].toLowerCase()),Fe+ke[0].length):-1}function V(Se,Le,Fe){return P(Se,t,Le,Fe)}function G(Se,Le,Fe){return P(Se,n,Le,Fe)}function Y(Se,Le,Fe){return P(Se,r,Le,Fe)}function X(Se){return l[Se.getDay()]}function ae(Se){return i[Se.getDay()]}function le(Se){return c[Se.getMonth()]}function ne(Se){return o[Se.getMonth()]}function te(Se){return a[+(Se.getHours()>=12)]}function J(Se){return 1+~~(Se.getMonth()/3)}function ce(Se){return l[Se.getUTCDay()]}function _e(Se){return i[Se.getUTCDay()]}function he(Se){return c[Se.getUTCMonth()]}function ue(Se){return o[Se.getUTCMonth()]}function ve(Se){return a[+(Se.getUTCHours()>=12)]}function Ee(Se){return 1+~~(Se.getUTCMonth()/3)}return{format:function(Se){var Le=E(Se+="",w);return Le.toString=function(){return Se},Le},parse:function(Se){var Le=I(Se+="",!1);return Le.toString=function(){return Se},Le},utcFormat:function(Se){var Le=E(Se+="",S);return Le.toString=function(){return Se},Le},utcParse:function(Se){var Le=I(Se+="",!0);return Le.toString=function(){return Se},Le}}}var $2t={"-":"",_:" ",0:"0"},Lv=/^\s*\d+/,NSn=/^%/,kSn=/[\\^$*+?|[\]().{}]/g;function qh(s,t,n){var r=s<0?"-":"",a=(r?-s:s)+"",i=a.length;return r+(i[t.toLowerCase(),n]))}function CSn(s,t,n){var r=Lv.exec(t.slice(n,n+1));return r?(s.w=+r[0],n+r[0].length):-1}function ASn(s,t,n){var r=Lv.exec(t.slice(n,n+1));return r?(s.u=+r[0],n+r[0].length):-1}function ESn(s,t,n){var r=Lv.exec(t.slice(n,n+2));return r?(s.U=+r[0],n+r[0].length):-1}function TSn(s,t,n){var r=Lv.exec(t.slice(n,n+2));return r?(s.V=+r[0],n+r[0].length):-1}function MSn(s,t,n){var r=Lv.exec(t.slice(n,n+2));return r?(s.W=+r[0],n+r[0].length):-1}function U2t(s,t,n){var r=Lv.exec(t.slice(n,n+4));return r?(s.y=+r[0],n+r[0].length):-1}function q2t(s,t,n){var r=Lv.exec(t.slice(n,n+2));return r?(s.y=+r[0]+(+r[0]>68?1900:2e3),n+r[0].length):-1}function PSn(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 ISn(s,t,n){var r=Lv.exec(t.slice(n,n+1));return r?(s.q=r[0]*3-3,n+r[0].length):-1}function LSn(s,t,n){var r=Lv.exec(t.slice(n,n+2));return r?(s.m=r[0]-1,n+r[0].length):-1}function V2t(s,t,n){var r=Lv.exec(t.slice(n,n+2));return r?(s.d=+r[0],n+r[0].length):-1}function RSn(s,t,n){var r=Lv.exec(t.slice(n,n+3));return r?(s.m=0,s.d=+r[0],n+r[0].length):-1}function H2t(s,t,n){var r=Lv.exec(t.slice(n,n+2));return r?(s.H=+r[0],n+r[0].length):-1}function DSn(s,t,n){var r=Lv.exec(t.slice(n,n+2));return r?(s.M=+r[0],n+r[0].length):-1}function FSn(s,t,n){var r=Lv.exec(t.slice(n,n+2));return r?(s.S=+r[0],n+r[0].length):-1}function OSn(s,t,n){var r=Lv.exec(t.slice(n,n+3));return r?(s.L=+r[0],n+r[0].length):-1}function zSn(s,t,n){var r=Lv.exec(t.slice(n,n+6));return r?(s.L=Math.floor(r[0]/1e3),n+r[0].length):-1}function BSn(s,t,n){var r=NSn.exec(t.slice(n,n+1));return r?n+r[0].length:-1}function $Sn(s,t,n){var r=Lv.exec(t.slice(n));return r?(s.Q=+r[0],n+r[0].length):-1}function USn(s,t,n){var r=Lv.exec(t.slice(n));return r?(s.s=+r[0],n+r[0].length):-1}function G2t(s,t){return qh(s.getDate(),t,2)}function qSn(s,t){return qh(s.getHours(),t,2)}function VSn(s,t){return qh(s.getHours()%12||12,t,2)}function HSn(s,t){return qh(1+Cie.count(fT(s),s),t,3)}function jYt(s,t){return qh(s.getMilliseconds(),t,3)}function GSn(s,t){return jYt(s,t)+"000"}function WSn(s,t){return qh(s.getMonth()+1,t,2)}function KSn(s,t){return qh(s.getMinutes(),t,2)}function YSn(s,t){return qh(s.getSeconds(),t,2)}function ZSn(s){var t=s.getDay();return t===0?7:t}function XSn(s,t){return qh(MRe.count(fT(s)-1,s),t,2)}function NYt(s){var t=s.getDay();return t>=4||t===0?HG(s):HG.ceil(s)}function QSn(s,t){return s=NYt(s),qh(HG.count(fT(s),s)+(fT(s).getDay()===4),t,2)}function JSn(s){return s.getDay()}function eCn(s,t){return qh(mMe.count(fT(s)-1,s),t,2)}function tCn(s,t){return qh(s.getFullYear()%100,t,2)}function sCn(s,t){return s=NYt(s),qh(s.getFullYear()%100,t,2)}function nCn(s,t){return qh(s.getFullYear()%1e4,t,4)}function rCn(s,t){var n=s.getDay();return s=n>=4||n===0?HG(s):HG.ceil(s),qh(s.getFullYear()%1e4,t,4)}function aCn(s){var t=s.getTimezoneOffset();return(t>0?"-":(t*=-1,"+"))+qh(t/60|0,"0",2)+qh(t%60,"0",2)}function W2t(s,t){return qh(s.getUTCDate(),t,2)}function iCn(s,t){return qh(s.getUTCHours(),t,2)}function oCn(s,t){return qh(s.getUTCHours()%12||12,t,2)}function lCn(s,t){return qh(1+TRe.count(pT(s),s),t,3)}function kYt(s,t){return qh(s.getUTCMilliseconds(),t,3)}function cCn(s,t){return kYt(s,t)+"000"}function dCn(s,t){return qh(s.getUTCMonth()+1,t,2)}function uCn(s,t){return qh(s.getUTCMinutes(),t,2)}function hCn(s,t){return qh(s.getUTCSeconds(),t,2)}function mCn(s){var t=s.getUTCDay();return t===0?7:t}function fCn(s,t){return qh(PRe.count(pT(s)-1,s),t,2)}function SYt(s){var t=s.getUTCDay();return t>=4||t===0?GG(s):GG.ceil(s)}function pCn(s,t){return s=SYt(s),qh(GG.count(pT(s),s)+(pT(s).getUTCDay()===4),t,2)}function gCn(s){return s.getUTCDay()}function xCn(s,t){return qh(fMe.count(pT(s)-1,s),t,2)}function yCn(s,t){return qh(s.getUTCFullYear()%100,t,2)}function vCn(s,t){return s=SYt(s),qh(s.getUTCFullYear()%100,t,2)}function bCn(s,t){return qh(s.getUTCFullYear()%1e4,t,4)}function _Cn(s,t){var n=s.getUTCDay();return s=n>=4||n===0?GG(s):GG.ceil(s),qh(s.getUTCFullYear()%1e4,t,4)}function wCn(){return"+0000"}function K2t(){return"%"}function Y2t(s){return+s}function Z2t(s){return Math.floor(+s/1e3)}var L$,CYt,AYt;jCn({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 jCn(s){return L$=jSn(s),CYt=L$.format,L$.parse,AYt=L$.utcFormat,L$.utcParse,L$}function NCn(s){return new Date(s)}function kCn(s){return s instanceof Date?+s:+new Date(+s)}function Aat(s,t,n,r,a,i,l,o,c,d){var u=fat(),h=u.invert,m=u.domain,f=d(".%L"),g=d(":%S"),x=d("%I:%M"),y=d("%I %p"),v=d("%a %d"),b=d("%b %d"),w=d("%B"),S=d("%Y");function A(E){return(c(E)t(a/(s.length-1)))},n.quantiles=function(r){return Array.from({length:r+1},(a,i)=>fkn(s,i/r))},n.copy=function(){return PYt(t).domain(s)},DT.apply(n,arguments)}function LRe(){var s=0,t=.5,n=1,r=1,a,i,l,o,c,d=b_,u,h=!1,m;function f(x){return isNaN(x=+x)?m:(x=.5+((x=+u(x))-i)*(r*xt}var DYt=PCn,ICn=RRe,LCn=DYt,RCn=EK;function DCn(s){return s&&s.length?ICn(s,RCn,LCn):void 0}var FCn=DCn;const _I=ru(FCn);function OCn(s,t){return ss.e^i.s<0?1:-1;for(r=i.d.length,a=s.d.length,t=0,n=rs.d[t]^i.s<0?1:-1;return r===a?0:r>a^i.s<0?1:-1};Io.decimalPlaces=Io.dp=function(){var s=this,t=s.d.length-1,n=(t-s.e)*wp;if(t=s.d[t],t)for(;t%10==0;t/=10)n--;return n<0?0:n};Io.dividedBy=Io.div=function(s){return HE(this,new this.constructor(s))};Io.dividedToIntegerBy=Io.idiv=function(s){var t=this,n=t.constructor;return Sf(HE(t,new n(s),0,1),n.precision)};Io.equals=Io.eq=function(s){return!this.cmp(s)};Io.exponent=function(){return Vy(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(Yj))throw Error(hk+"NaN");if(n.s<1)throw Error(hk+(n.s?"NaN":"-Infinity"));return n.eq(Yj)?new r(0):(Xp=!1,t=HE($se(n,i),$se(s,i),i),Xp=!0,Sf(t,a))};Io.minus=Io.sub=function(s){var t=this;return s=new t.constructor(s),t.s==s.s?$Yt(t,s):zYt(t,(s.s=-s.s,s))};Io.modulo=Io.mod=function(s){var t,n=this,r=n.constructor,a=r.precision;if(s=new r(s),!s.s)throw Error(hk+"NaN");return n.s?(Xp=!1,t=HE(n,s,0,1).times(s),Xp=!0,n.minus(t)):Sf(new r(n),a)};Io.naturalExponential=Io.exp=function(){return BYt(this)};Io.naturalLogarithm=Io.ln=function(){return $se(this)};Io.negated=Io.neg=function(){var s=new this.constructor(this);return s.s=-s.s||0,s};Io.plus=Io.add=function(s){var t=this;return s=new t.constructor(s),t.s==s.s?zYt(t,s):$Yt(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(v7+s);if(t=Vy(a)+1,r=a.d.length-1,n=r*wp+1,r=a.d[r],r){for(;r%10==0;r/=10)n--;for(r=a.d[0];r>=10;r/=10)n++}return s&&t>n?t:n};Io.squareRoot=Io.sqrt=function(){var s,t,n,r,a,i,l,o=this,c=o.constructor;if(o.s<1){if(!o.s)return new c(0);throw Error(hk+"NaN")}for(s=Vy(o),Xp=!1,a=Math.sqrt(+o),a==0||a==1/0?(t=x4(o.d),(t.length+s)%2==0&&(t+="0"),a=Math.sqrt(t),s=PK((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(HE(o,i,l+2)).times(.5),x4(i.d).slice(0,l)===(t=x4(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 Xp=!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%lv|0,t=o/lv|0;i[a]=(i[a]+t)%lv|0}for(;!i[--l];)i.pop();return t?++n:i.shift(),s.d=i,s.e=n,Xp?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:(X4(s,0,MK),t===void 0?t=r.rounding:X4(t,0,8),Sf(n,s+Vy(n)+1,t))};Io.toExponential=function(s,t){var n,r=this,a=r.constructor;return s===void 0?n=aB(r,!0):(X4(s,0,MK),t===void 0?t=a.rounding:X4(t,0,8),r=Sf(new a(r),s+1,t),n=aB(r,!0,s+1)),n};Io.toFixed=function(s,t){var n,r,a=this,i=a.constructor;return s===void 0?aB(a):(X4(s,0,MK),t===void 0?t=i.rounding:X4(t,0,8),r=Sf(new i(a),s+Vy(a)+1,t),n=aB(r.abs(),!1,s+Vy(r)+1),a.isneg()&&!a.isZero()?"-"+n:n)};Io.toInteger=Io.toint=function(){var s=this,t=s.constructor;return Sf(new t(s),Vy(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(Yj);if(o=new c(o),!o.s){if(s.s<1)throw Error(hk+"Infinity");return o}if(o.eq(Yj))return o;if(r=c.precision,s.eq(Yj))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)<=OYt){for(a=new c(Yj),t=Math.ceil(r/wp+4),Xp=!1;n%2&&(a=a.times(o),J2t(a.d,t)),n=PK(n/2),n!==0;)o=o.times(o),J2t(o.d,t);return Xp=!0,s.s<0?new c(Yj).div(a):Sf(a,r)}}else if(i<0)throw Error(hk+"NaN");return i=i<0&&s.d[Math.max(t,n)]&1?-1:1,o.s=1,Xp=!1,a=s.times($se(o,r+d)),Xp=!0,a=BYt(a),a.s=i,a};Io.toPrecision=function(s,t){var n,r,a=this,i=a.constructor;return s===void 0?(n=Vy(a),r=aB(a,n<=i.toExpNeg||n>=i.toExpPos)):(X4(s,1,MK),t===void 0?t=i.rounding:X4(t,0,8),a=Sf(new i(a),s,t),n=Vy(a),r=aB(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):(X4(s,1,MK),t===void 0?t=r.rounding:X4(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=Vy(s),n=s.constructor;return aB(s,t<=n.toExpNeg||t>=n.toExpPos)};function zYt(s,t){var n,r,a,i,l,o,c,d,u=s.constructor,h=u.precision;if(!s.s||!t.s)return t.s||(t=new u(s)),Xp?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/wp),o=l>o?l+1:o+1,i>o&&(i=o,r.length=1),r.reverse();i--;)r.push(0);r.reverse()}for(o=c.length,i=d.length,o-i<0&&(i=o,r=d,d=c,c=r),n=0;i;)n=(c[--i]=c[i]+d[i]+n)/lv|0,c[i]%=lv;for(n&&(c.unshift(n),++a),o=c.length;c[--o]==0;)c.pop();return t.d=c,t.e=a,Xp?Sf(t,h):t}function X4(s,t,n){if(s!==~~s||sn)throw Error(v7+s)}function x4(s){var t,n,r,a=s.length-1,i="",l=s[0];if(a>0){for(i+=l,t=1;tl?1:-1;else for(o=c=0;oa[o]?1:-1;break}return c}function n(r,a,i){for(var l=0;i--;)r[i]-=l,l=r[i]1;)r.shift()}return function(r,a,i,l){var o,c,d,u,h,m,f,g,x,y,v,b,w,S,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(hk+"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+(Vy(r)-Vy(a))+1:b=i,b<0)return new R(0);if(b=b/wp+2|0,d=0,I==1)for(u=0,U=U[0],b++;(d1&&(U=s(U,u),O=s(O,u),I=U.length,A=O.length),S=I,x=O.slice(0,I),y=x.length;y=lv/2&&++E;do u=0,o=t(U,x,I,y),o<0?(v=x[0],I!=y&&(v=v*lv+(x[1]||0)),u=v/E|0,u>1?(u>=lv&&(u=lv-1),h=s(U,u),m=h.length,y=x.length,o=t(h,x,m,y),o==1&&(u--,n(h,I16)throw Error(Mat+Vy(s));if(!s.s)return new u(Yj);for(Xp=!1,o=h,l=new u(.03125);s.abs().gte(.1);)s=s.times(l),d+=5;for(r=Math.log(DO(2,d))/Math.LN10*2+5|0,o+=r,n=a=i=new u(Yj),u.precision=o;;){if(a=Sf(a.times(s),o),n=n.times(++c),l=i.plus(HE(a,n,o)),x4(l.d).slice(0,o)===x4(i.d).slice(0,o)){for(;d--;)i=Sf(i.times(i),o);return u.precision=h,t==null?(Xp=!0,Sf(i,h)):i}i=l}}function Vy(s){for(var t=s.e*wp,n=s.d[0];n>=10;n/=10)t++;return t}function _9e(s,t,n){if(t>s.LN10.sd())throw Xp=!0,n&&(s.precision=n),Error(hk+"LN10 precision limit exceeded");return Sf(new s(s.LN10),t)}function gP(s){for(var t="";s--;)t+="0";return t}function $se(s,t){var n,r,a,i,l,o,c,d,u,h=1,m=10,f=s,g=f.d,x=f.constructor,y=x.precision;if(f.s<1)throw Error(hk+(f.s?"NaN":"-Infinity"));if(f.eq(Yj))return new x(0);if(t==null?(Xp=!1,d=y):d=t,f.eq(10))return t==null&&(Xp=!0),_9e(x,d);if(d+=m,x.precision=d,n=x4(g),r=n.charAt(0),i=Vy(f),Math.abs(i)<15e14){for(;r<7&&r!=1||r==1&&n.charAt(1)>3;)f=f.times(s),n=x4(f.d),r=n.charAt(0),h++;i=Vy(f),r>1?(f=new x("0."+n),i++):f=new x(r+"."+n.slice(1))}else return c=_9e(x,d+2,y).times(i+""),f=$se(new x(r+"."+n.slice(1)),d-m).plus(c),x.precision=y,t==null?(Xp=!0,Sf(f,y)):f;for(o=l=f=HE(f.minus(Yj),f.plus(Yj),d),u=Sf(f.times(f),d),a=3;;){if(l=Sf(l.times(u),d),c=o.plus(HE(l,new x(a),d)),x4(c.d).slice(0,d)===x4(o.d).slice(0,d))return o=o.times(2),i!==0&&(o=o.plus(_9e(x,d+2,y).times(i+""))),o=HE(o,new x(h),d),x.precision=y,t==null?(Xp=!0,Sf(o,y)):o;o=c,a+=2}}function Q2t(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=PK(n/wp),s.d=[],r=(n+1)%wp,n<0&&(r+=wp),rpMe||s.e<-pMe))throw Error(Mat+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+=wp,a=t,d=h[u=0];else{if(u=Math.ceil((r+1)/wp),i=h.length,u>=i)return s;for(d=i=h[u],l=1;i>=10;i/=10)l++;r%=wp,a=r-wp+l}if(n!==void 0&&(i=DO(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/DO(10,l-a):0:h[u-1])%10&1||n==(s.s<0?8:7))),t<1||!h[0])return c?(i=Vy(s),h.length=1,t=t-i-1,h[0]=DO(10,(wp-t%wp)%wp),s.e=PK(-t/wp)||0):(h.length=1,h[0]=s.e=s.s=0),s;if(r==0?(h.length=u,i=1,u--):(h.length=u+1,i=DO(10,wp-r),h[u]=a>0?(d/DO(10,l-a)%DO(10,a)|0)*i:0),c)for(;;)if(u==0){(h[0]+=i)==lv&&(h[0]=1,++s.e);break}else{if(h[u]+=i,h[u]!=lv)break;h[u--]=0,i=1}for(r=h.length;h[--r]===0;)h.pop();if(Xp&&(s.e>pMe||s.e<-pMe))throw Error(Mat+Vy(s));return s}function $Yt(s,t){var n,r,a,i,l,o,c,d,u,h,m=s.constructor,f=m.precision;if(!s.s||!t.s)return t.s?t.s=-t.s:t=new m(s),Xp?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/wp),o)+2,l>a&&(l=a,n.length=1),n.reverse(),a=l;a--;)n.push(0);n.reverse()}else{for(a=c.length,o=h.length,u=a0;--a)c[o++]=0;for(a=h.length;a>l;){if(c[--a]0?i=i.charAt(0)+"."+i.slice(1)+gP(r):l>1&&(i=i.charAt(0)+"."+i.slice(1)),i=i+(a<0?"e":"e+")+a):a<0?(i="0."+gP(-a-1)+i,n&&(r=n-l)>0&&(i+=gP(r))):a>=l?(i+=gP(a+1-l),n&&(r=n-a-1)>0&&(i=i+"."+gP(r))):((r=a+1)0&&(a+1===l&&(i+="."),i+=gP(r))),s.s<0?"-"+i:i}function J2t(s,t){if(s.length>t)return s.length=t,!0}function UYt(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(v7+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 Q2t(l,i.toString())}else if(typeof i!="string")throw Error(v7+i);if(i.charCodeAt(0)===45?(i=i.slice(1),l.s=-1):l.s=1,a5n.test(i))Q2t(l,i);else throw Error(v7+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=UYt,a.config=a.set=i5n,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(v7+n+": "+r);if((r=s[n="LN10"])!==void 0)if(r==Math.LN10)this[n]=new this(r);else throw Error(v7+n+": "+r);return this}var Pat=UYt(r5n);Yj=new Pat(1);const Ym=Pat;function o5n(s){return u5n(s)||d5n(s)||c5n(s)||l5n()}function l5n(){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 c5n(s,t){if(s){if(typeof s=="string")return jKe(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 jKe(s,t)}}function d5n(s){if(typeof Symbol<"u"&&Symbol.iterator in Object(s))return Array.from(s)}function u5n(s){if(Array.isArray(s))return jKe(s)}function jKe(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,eNt(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 S5n(s){if(Array.isArray(s))return s}function WYt(s){var t=Use(s,2),n=t[0],r=t[1],a=n,i=r;return n>r&&(a=r,i=n),[a,i]}function KYt(s,t,n){if(s.lte(0))return new Ym(0);var r=ORe.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 C5n(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(ORe.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=p5n(f5n(function(c){return a.add(new Ym(c-l).mul(r)).toNumber()}),NKe);return o(0,t)}function YYt(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=KYt(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?YYt(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 A5n(s){var t=Use(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=WYt([n,r]),c=Use(o,2),d=c[0],u=c[1];if(d===-1/0||u===1/0){var h=u===1/0?[d].concat(SKe(NKe(0,a-1).map(function(){return 1/0}))):[].concat(SKe(NKe(0,a-1).map(function(){return-1/0})),[u]);return n>r?kKe(h):h}if(d===u)return C5n(d,a,i);var m=YYt(d,u,l,i),f=m.step,g=m.tickMin,x=m.tickMax,y=ORe.rangeStep(g,x.add(new Ym(.1).mul(f)),f);return n>r?kKe(y):y}function E5n(s,t){var n=Use(s,2),r=n[0],a=n[1],i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,l=WYt([r,a]),o=Use(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=KYt(new Ym(d).sub(c).div(u-1),i,0),m=[].concat(SKe(ORe.rangeStep(new Ym(c),new Ym(d).sub(new Ym(.99).mul(h)),h)),[d]);return r>a?kKe(m):m}var T5n=HYt(A5n),M5n=HYt(E5n),P5n="Invariant failed";function iB(s,t){throw new Error(P5n)}var I5n=["offset","layout","width","dataKey","data","dataPointFormatter","xAxis","yAxis"];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 gMe(){return gMe=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 B5n(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 $5n(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function U5n(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(y_(h-u)!==y_(m-h)){var g=[];if(y_(m-h)===y_(c[1]-c[0])){f=m;var x=h+c[1]-c[0];g[0]=Math.min(x,(x+u)/2),g[1]=Math.max(x,(x+u)/2)}else{f=u;var y=m+c[1]-c[0];g[0]=Math.min(h,(y+h)/2),g[1]=Math.max(h,(y+h)/2)}var v=[Math.min(h,(f+h)/2),Math.max(h,(f+h)/2)];if(t>v[0]&&t<=v[1]||t>=g[0]&&t<=g[1]){l=a[d].index;break}}else{var b=Math.min(u,m),w=Math.max(u,m);if(t>(b+h)/2&&t<=(w+h)/2){l=a[d].index;break}}}else for(var S=0;S0&&S(r[S].coordinate+r[S-1].coordinate)/2&&t<=(r[S].coordinate+r[S+1].coordinate)/2||S===o-1&&t>(r[S].coordinate+r[S-1].coordinate)/2){l=r[S].index;break}return l},Iat=function(t){var n,r=t,a=r.type.displayName,i=(n=t.type)!==null&&n!==void 0&&n.defaultProps?xx(xx({},t.type.defaultProps),t.props):t.props,l=i.stroke,o=i.fill,c;switch(a){case"Line":c=l;break;case"Area":case"Radar":c=l&&l!=="none"?l:o;break;default:c=o;break}return c},a4n=function(t){var n=t.barSize,r=t.totalSize,a=t.stackGroups,i=a===void 0?{}:a;if(!i)return{};for(var l={},o=Object.keys(i),c=0,d=o.length;c=0});if(v&&v.length){var b=v[0].type.defaultProps,w=b!==void 0?xx(xx({},b),v[0].props):v[0].props,S=w.barSize,A=w[y];l[A]||(l[A]=[]);var E=Gc(S)?n:S;l[A].push({item:v[0],stackList:v.slice(1),barSize:Gc(E)?void 0:v_(E,r,0)})}}return l},i4n=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=v_(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,y={offset:x-d,size:0};u=l.reduce(function(S,A){var E={item:A.item,position:{offset:y.offset+y.size+d,size:m?f:A.barSize}},I=[].concat(nNt(S),[E]);return y=I[I.length-1].position,A.stackList&&A.stackList.length&&A.stackList.forEach(function(P){I.push({item:P,position:y})}),I},h)}else{var v=v_(r,a,0,!0);a-2*v-(c-1)*d<=0&&(d=0);var b=(a-2*v-(c-1)*d)/c;b>1&&(b>>=0);var w=o===+o?Math.min(b,o):b;u=l.reduce(function(S,A,E){var I=[].concat(nNt(S),[{item:A.item,position:{offset:v+(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},o4n=function(t,n,r,a){var i=r.children,l=r.width,o=r.margin,c=l-(o.left||0)-(o.right||0),d=JYt({children:i,legendWidth:c});if(d){var u=a||{},h=u.width,m=u.height,f=d.align,g=d.verticalAlign,x=d.layout;if((x==="vertical"||x==="horizontal"&&g==="middle")&&f!=="center"&&yi(t[f]))return xx(xx({},t),{},EV({},f,t[f]+(h||0)));if((x==="horizontal"||x==="vertical"&&f==="center")&&g!=="middle"&&yi(t[g]))return xx(xx({},t),{},EV({},g,t[g]+(m||0)))}return t},l4n=function(t,n,r){return Gc(n)?!0:t==="horizontal"?n==="yAxis":t==="vertical"||r==="x"?n==="xAxis":r==="y"?n==="yAxis":!0},eZt=function(t,n,r,a,i){var l=n.props.children,o=v2(l,Aie).filter(function(d){return l4n(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=ay(u,r);if(Gc(h))return d;var m=Array.isArray(h)?[DRe(h),_I(h)]:[h,h],f=c.reduce(function(g,x){var y=ay(u,x,0),v=m[0]-Math.abs(Array.isArray(y)?y[0]:y),b=m[1]+Math.abs(Array.isArray(y)?y[1]:y);return[Math.min(v,g[0]),Math.max(b,g[1])]},[1/0,-1/0]);return[Math.min(f[0],d[0]),Math.max(f[1],d[1])]},[1/0,-1/0])}return null},c4n=function(t,n,r,a,i){var l=n.map(function(o){return eZt(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},tZt=function(t,n,r,a,i){var l=n.map(function(c){var d=c.props.dataKey;return r==="number"&&d&&eZt(t,c,d,a)||Uee(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?y_(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!SK(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}})},w9e=new WeakMap,Gde=function(t,n){if(typeof n!="function")return t;w9e.has(t)||w9e.set(t,new WeakMap);var r=w9e.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},rZt=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:Dse(),realScaleType:"band"}:l==="radial"&&o==="angleAxis"?{scale:uMe(),realScaleType:"linear"}:i==="category"&&n&&(n.indexOf("LineChart")>=0||n.indexOf("AreaChart")>=0||n.indexOf("ComposedChart")>=0&&!r)?{scale:$ee(),realScaleType:"point"}:i==="category"?{scale:Dse(),realScaleType:"band"}:{scale:uMe(),realScaleType:"linear"};if(tB(a)){var c="scale".concat(wRe(a));return{scale:(X2t[c]||$ee)(),realScaleType:X2t[c]?c:"point"}}return hc(a)?{scale:a}:{scale:$ee(),realScaleType:"point"}},aNt=1e-4,aZt=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])-aNt,l=Math.max(a[0],a[1])+aNt,o=t(n[0]),c=t(n[r-1]);(ol||cl)&&t.domain([n[0],n[r-1]])}},d4n=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])}},m4n=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)}},f4n={sign:h4n,expand:Iyn,none:zG,silhouette:Lyn,wiggle:Ryn,positive:m4n},p4n=function(t,n,r){var a=n.map(function(o){return o.props.dataKey}),i=f4n[r],l=Pyn().keys(a).value(function(o,c){return+ay(o,c,0)}).order(eKe).offset(i);return l(t)},g4n=function(t,n,r,a,i,l){if(!t)return null;var o=l?n.reverse():n,c={},d=o.reduce(function(h,m){var f,g=(f=m.type)!==null&&f!==void 0&&f.defaultProps?xx(xx({},m.type.defaultProps),m.props):m.props,x=g.stackId,y=g.hide;if(y)return h;var v=g[r],b=h[v]||{hasStack:!1,stackGroups:{}};if(k0(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[YB("_stackId_")]={numericAxisId:r,cateAxisId:a,items:[m]};return xx(xx({},h),{},EV({},v,b))},c),u={};return Object.keys(d).reduce(function(h,m){var f=d[m];if(f.hasStack){var g={};f.stackGroups=Object.keys(f.stackGroups).reduce(function(x,y){var v=f.stackGroups[y];return xx(xx({},x),{},EV({},y,{numericAxisId:r,cateAxisId:a,items:v.items,stackedData:p4n(t,v.items,i)}))},g)}return xx(xx({},h),{},EV({},m,f))},u)},iZt=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=T5n(d,i,o);return t.domain([DRe(u),_I(u)]),{niceTicks:u}}if(i&&a==="number"){var h=t.domain(),m=M5n(h,i,o);return{niceTicks:m}}return null};function yMe(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=qTe(n,"value",a[t.dataKey]);if(o)return o.coordinate+r/2}return n[i]?n[i].coordinate+r/2:null}var c=ay(a,Gc(l)?t.dataKey:l);return Gc(c)?null:t.scale(c)}var iNt=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=ay(l,n.dataKey,n.domain[o]);return Gc(c)?null:n.scale(c)-i/2+a},x4n=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]},y4n=function(t,n){var r,a=(r=t.type)!==null&&r!==void 0&&r.defaultProps?xx(xx({},t.type.defaultProps),t.props):t.props,i=a.stackId;if(k0(i)){var l=n[i];if(l){var o=l.items.indexOf(t);return o>=0?l.stackedData[o]:null}}return null},v4n=function(t){return t.reduce(function(n,r){return[DRe(r.concat([n[0]]).filter(yi)),_I(r.concat([n[1]]).filter(yi))]},[1/0,-1/0])},oZt=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=v4n(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})},oNt=/^dataMin[\s]*-[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,lNt=/^dataMax[\s]*\+[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,TKe=function(t,n,r){if(hc(t))return t(n,r);if(!Array.isArray(t))return n;var a=[];if(yi(t[0]))a[0]=r?t[0]:Math.min(t[0],n[0]);else if(oNt.test(t[0])){var i=+oNt.exec(t[0])[1];a[0]=n[0]-i}else hc(t[0])?a[0]=t[0](n[0]):a[0]=n[0];if(yi(t[1]))a[1]=r?t[1]:Math.max(t[1],n[1]);else if(lNt.test(t[1])){var l=+lNt.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},vMe=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=oat(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},A4n=function(t,n,r,a,i){var l=t.width,o=t.height,c=t.startAngle,d=t.endAngle,u=v_(t.cx,l,l/2),h=v_(t.cy,o,o/2),m=dZt(l,o,r),f=v_(t.innerRadius,m,0),g=v_(t.outerRadius,m,m*.8),x=Object.keys(n);return x.reduce(function(y,v){var b=n[v],w=b.domain,S=b.reversed,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=w4n(E,2);c=I[0],d=I[1]}var P=rZt(b,i),R=P.realScaleType,D=P.scale;D.domain(w).range(A),aZt(D);var O=iZt(D,AA(AA({},b),{},{realScaleType:R})),U=AA(AA(AA({},b),O),{},{range:A,radius:g,realScaleType:R,scale:D,cx:u,cy:h,innerRadius:f,outerRadius:g,startAngle:c,endAngle:d});return AA(AA({},y),{},cZt({},v,U))},{})},E4n=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))},T4n=function(t,n){var r=t.x,a=t.y,i=n.cx,l=n.cy,o=E4n({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:C4n(d),angleInRadian:d}},M4n=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}},P4n=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},hNt=function(t,n){var r=t.x,a=t.y,i=T4n({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=M4n(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?AA(AA({},n),{},{radius:l,angle:P4n(f,n)}):null},uZt=function(t){return!j.isValidElement(t)&&!hc(t)&&typeof t!="boolean"?t.className:""};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 I4n=["offset"];function L4n(s){return O4n(s)||F4n(s)||D4n(s)||R4n()}function R4n(){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 D4n(s,t){if(s){if(typeof s=="string")return MKe(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 MKe(s,t)}}function F4n(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function O4n(s){if(Array.isArray(s))return MKe(s)}function MKe(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 B4n(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 mNt(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 r0(s){for(var t=1;t=0?1:-1,w,S;a==="insideStart"?(w=f+b*l,S=x):a==="insideEnd"?(w=g-b*l,S=!x):a==="end"&&(w=g+b*l,S=x),S=v<=0?S:!S;var A=Yf(d,u,y,w),E=Yf(d,u,y,w+(S?1:-1)*359),I="M".concat(A.x,",").concat(A.y,` A`).concat(y,",").concat(y,",0,1,").concat(S?0:1,`, `).concat(E.x,",").concat(E.y),P=Gc(t.id)?YB("recharts-radial-line-"):t.id;return Gt.createElement("text",Wse({},r,{dominantBaseline:"central",className:sd("recharts-radial-bar-label",o)}),Gt.createElement("defs",null,Gt.createElement("path",{id:P,d:I})),Gt.createElement("textPath",{xlinkHref:"#".concat(P)},n))},W4n=function(t){var n=t.viewBox,r=t.offset,a=t.position,i=n,l=i.cx,o=i.cy,c=i.innerRadius,d=i.outerRadius,u=i.startAngle,h=i.endAngle,m=(u+h)/2;if(a==="outside"){var f=Yf(l,o,d+r,m),g=f.x,x=f.y;return{x:g,y:x,textAnchor:g>=l?"start":"end",verticalAnchor:"middle"}}if(a==="center")return{x:l,y:o,textAnchor:"middle",verticalAnchor:"middle"};if(a==="centerTop")return{x:l,y:o,textAnchor:"middle",verticalAnchor:"start"};if(a==="centerBottom")return{x:l,y:o,textAnchor:"middle",verticalAnchor:"end"};var y=(c+d)/2,v=Yf(l,o,y,m),b=v.x,w=v.y;return{x:b,y:w,textAnchor:"middle",verticalAnchor:"middle"}},K4n=function(t){var n=t.viewBox,r=t.parentViewBox,a=t.offset,i=t.position,l=n,o=l.x,c=l.y,d=l.width,u=l.height,h=u>=0?1:-1,m=h*a,f=h>0?"end":"start",g=h>0?"start":"end",x=d>=0?1:-1,y=x*a,v=x>0?"end":"start",b=x>0?"start":"end";if(i==="top"){var w={x:o+d/2,y:c-h*a,textAnchor:"middle",verticalAnchor:f};return r0(r0({},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 r0(r0({},S),r?{height:Math.max(r.y+r.height-(c+u),0),width:d}:{})}if(i==="left"){var A={x:o-y,y:c+u/2,textAnchor:v,verticalAnchor:"middle"};return r0(r0({},A),r?{width:Math.max(A.x-r.x,0),height:u}:{})}if(i==="right"){var E={x:o+d+y,y:c+u/2,textAnchor:b,verticalAnchor:"middle"};return r0(r0({},E),r?{width:Math.max(r.x+r.width-E.x,0),height:u}:{})}var I=r?{width:d,height:u}:{};return i==="insideLeft"?r0({x:o+y,y:c+u/2,textAnchor:b,verticalAnchor:"middle"},I):i==="insideRight"?r0({x:o+d-y,y:c+u/2,textAnchor:v,verticalAnchor:"middle"},I):i==="insideTop"?r0({x:o+d/2,y:c+m,textAnchor:"middle",verticalAnchor:g},I):i==="insideBottom"?r0({x:o+d/2,y:c+u-m,textAnchor:"middle",verticalAnchor:f},I):i==="insideTopLeft"?r0({x:o+y,y:c+m,textAnchor:b,verticalAnchor:g},I):i==="insideTopRight"?r0({x:o+d-y,y:c+m,textAnchor:v,verticalAnchor:g},I):i==="insideBottomLeft"?r0({x:o+y,y:c+u-m,textAnchor:b,verticalAnchor:f},I):i==="insideBottomRight"?r0({x:o+d-y,y:c+u-m,textAnchor:v,verticalAnchor:f},I):wK(i)&&(yi(i.x)||p8(i.x))&&(yi(i.y)||p8(i.y))?r0({x:o+v_(i.x,d),y:c+v_(i.y,u),textAnchor:"end",verticalAnchor:"end"},I):r0({x:o+d/2,y:c+u/2,textAnchor:"middle",verticalAnchor:"middle"},I)},Y4n=function(t){return"cx"in t&&yi(t.cx)};function xv(s){var t=s.offset,n=t===void 0?5:t,r=z4n(s,I4n),a=r0({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=V4n(a);var g=Y4n(i),x=cl(a,!0);if(g&&(l==="insideStart"||l==="insideEnd"||l==="end"))return G4n(a,f,x);var y=g?W4n(a):K4n(a);return Gt.createElement(nB,Wse({className:sd("recharts-label",h)},x,y,{breakAll:m}),f)}xv.displayName="Label";var hZt=function(t){var n=t.cx,r=t.cy,a=t.angle,i=t.startAngle,l=t.endAngle,o=t.r,c=t.radius,d=t.innerRadius,u=t.outerRadius,h=t.x,m=t.y,f=t.top,g=t.left,x=t.width,y=t.height,v=t.clockWise,b=t.labelViewBox;if(b)return b;if(yi(x)&&yi(y)){if(yi(h)&&yi(m))return{x:h,y:m,width:x,height:y};if(yi(f)&&yi(g))return{x:f,y:g,width:x,height:y}}return yi(h)&&yi(m)?{x:h,y:m,width:0,height:0}:yi(n)&&yi(r)?{cx:n,cy:r,startAngle:i||a||0,endAngle:l||a||0,innerRadius:d||0,outerRadius:u||c||o||0,clockWise:v}:t.viewBox?t.viewBox:{}},Z4n=function(t,n){return t?t===!0?Gt.createElement(xv,{key:"label-implicit",viewBox:n}):k0(t)?Gt.createElement(xv,{key:"label-implicit",viewBox:n,value:t}):j.isValidElement(t)?t.type===xv?j.cloneElement(t,{key:"label-implicit",viewBox:n}):Gt.createElement(xv,{key:"label-implicit",content:t,viewBox:n}):hc(t)?Gt.createElement(xv,{key:"label-implicit",content:t,viewBox:n}):wK(t)?Gt.createElement(xv,Wse({viewBox:n},t,{key:"label-implicit"})):null:null},X4n=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=hZt(t),l=v2(a,xv).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(L4n(l))};xv.parseViewBox=hZt;xv.renderCallByParent=X4n;function Q4n(s){var t=s==null?0:s.length;return t?s[t-1]:void 0}var J4n=Q4n;const e3n=ru(J4n);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)}var t3n=["valueAccessor"],s3n=["data","dataKey","clockWise","id","textBreakAll"];function n3n(s){return o3n(s)||i3n(s)||a3n(s)||r3n()}function r3n(){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 a3n(s,t){if(s){if(typeof s=="string")return PKe(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 PKe(s,t)}}function i3n(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function o3n(s){if(Array.isArray(s))return PKe(s)}function PKe(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 u3n(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 h3n=function(t){return Array.isArray(t.value)?e3n(t.value):t.value};function B4(s){var t=s.valueAccessor,n=t===void 0?h3n:t,r=gNt(s,t3n),a=r.data,i=r.dataKey,l=r.clockWise,o=r.id,c=r.textBreakAll,d=gNt(r,s3n);return!a||!a.length?null:Gt.createElement(Su,{className:"recharts-label-list"},a.map(function(u,h){var m=Gc(i)?n(u,h):ay(u&&u.payload,i),f=Gc(o)?{}:{id:"".concat(o,"-").concat(h)};return Gt.createElement(xv,_Me({},cl(u,!0),d,f,{parentViewBox:u.parentViewBox,value:m,textBreakAll:c,viewBox:xv.parseViewBox(Gc(l)?u:pNt(pNt({},u),{},{clockWise:l})),key:"label-".concat(h),index:h}))}))}B4.displayName="LabelList";function m3n(s,t){return s?s===!0?Gt.createElement(B4,{key:"labelList-implicit",data:t}):Gt.isValidElement(s)||hc(s)?Gt.createElement(B4,{key:"labelList-implicit",data:t,content:s}):wK(s)?Gt.createElement(B4,_Me({data:t},s,{key:"labelList-implicit"})):null:null}function f3n(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=v2(r,B4).map(function(l,o){return j.cloneElement(l,{data:t,key:"labelList-".concat(o)})});if(!n)return a;var i=m3n(s.label,t);return[i].concat(n3n(a))}B4.renderCallByParent=f3n;function Yse(s){"@babel/helpers - typeof";return Yse=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},Yse(s)}function IKe(){return IKe=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},v3n=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=y_(u-d),m=Wde({cx:n,cy:r,radius:i,angle:d,sign:h,cornerRadius:l,cornerIsExternal:c}),f=m.circleTangency,g=m.lineTangency,x=m.theta,y=Wde({cx:n,cy:r,radius:i,angle:u,sign:-h,cornerRadius:l,cornerIsExternal:c}),v=y.circleTangency,b=y.lineTangency,w=y.theta,S=c?Math.abs(d-u):Math.abs(d-u)-x-w;if(S<0)return o?"M ".concat(g.x,",").concat(g.y,` a`).concat(l,",").concat(l,",0,0,1,").concat(l*2,`,0 a`).concat(l,",").concat(l,",0,0,1,").concat(-l*2,`,0 `):mZt({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(v.x,",").concat(v.y,` A`).concat(l,",").concat(l,",0,0,").concat(+(h<0),",").concat(b.x,",").concat(b.y,` `);if(a>0){var E=Wde({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=Wde({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},b3n={cx:0,cy:0,innerRadius:0,outerRadius:0,startAngle:0,endAngle:0,cornerRadius:0,forceCornerRadius:!1,cornerIsExternal:!1},fZt=function(t){var n=yNt(yNt({},b3n),t),r=n.cx,a=n.cy,i=n.innerRadius,l=n.outerRadius,o=n.cornerRadius,c=n.forceCornerRadius,d=n.cornerIsExternal,u=n.startAngle,h=n.endAngle,m=n.className;if(l0&&Math.abs(u-h)<360?y=v3n({cx:r,cy:a,innerRadius:i,outerRadius:l,cornerRadius:Math.min(x,g/2),forceCornerRadius:c,cornerIsExternal:d,startAngle:u,endAngle:h}):y=mZt({cx:r,cy:a,innerRadius:i,outerRadius:l,startAngle:u,endAngle:h}),Gt.createElement("path",IKe({},cl(n,!0),{className:f,d:y,role:"img"}))};function Zse(s){"@babel/helpers - typeof";return Zse=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Zse(s)}function LKe(){return LKe=Object.assign?Object.assign.bind():function(s){for(var t=1;tI3n.call(s,t));function JB(s,t){return s===t||!s&&!t&&s!==s&&t!==t}const D3n="__v",F3n="__o",O3n="_owner",z3n=typeof Float16Array<"u",{getOwnPropertyDescriptor:jNt,keys:NNt}=Object;function B3n(s,t){return s.byteLength===t.byteLength&&wMe(new Uint8Array(s),new Uint8Array(t))}function $3n(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 U3n(s,t){return s.byteLength===t.byteLength&&wMe(new Uint8Array(s.buffer,s.byteOffset,s.byteLength),new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}function q3n(s,t){return JB(s.getTime(),t.getTime())}function kNt(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 V3n(s,t){return s===t}function SNt(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 H3n=JB;function CNt(s,t,n){const r=NNt(s);let a=r.length;if(NNt(t).length!==a)return!1;for(;a-- >0;)if(!yZt(s,t,n,r[a]))return!1;return!0}function R$(s,t,n){const r=wNt(s);let a=r.length;if(wNt(t).length!==a)return!1;let i,l,o;for(;a-- >0;)if(i=r[a],!yZt(s,t,n,i)||(l=jNt(s,i),o=jNt(t,i),(l||o)&&(!l||!o||l.configurable!==o.configurable||l.enumerable!==o.enumerable||l.writable!==o.writable)))return!1;return!0}function G3n(s,t){return JB(s.valueOf(),t.valueOf())}function W3n(s,t){return s.source===t.source&&s.flags===t.flags}function ANt(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 wMe(s,t){let n=s.length;if(t.length!==n||s.byteOffset!==t.byteOffset)return!1;if(s instanceof Float64Array||s instanceof Float32Array||z3n&&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 K3n(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&&Y3n(s.searchParams,t.searchParams)}function Y3n(s,t){const n=s.toString(),r=t.toString();return n===r||ENt(n)===ENt(r)}function ENt(s){return s.split("&").sort().join("&")}function yZt(s,t,n,r){return(r===O3n||r===F3n||r===D3n)&&(s.$$typeof||t.$$typeof)?!0:R3n(t,r)&&n.equals(s[r],t[r],r,r,s,t,n)}const Z3n="[object ArrayBuffer]",X3n="[object Arguments]",Q3n="[object Boolean]",J3n="[object DataView]",eAn="[object Date]",tAn="[object Error]",sAn="[object Map]",nAn="[object Number]",rAn="[object Object]",aAn="[object RegExp]",iAn="[object Set]",oAn="[object String]",lAn={"[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},cAn="[object URL]",dAn=Object.prototype.toString;function uAn({areArrayBuffersEqual:s,areArraysEqual:t,areDataViewsEqual:n,areDatesEqual:r,areErrorsEqual:a,areFunctionsEqual:i,areMapsEqual:l,areNumbersEqual:o,areObjectsEqual:c,arePrimitiveWrappersEqual:d,areRegExpsEqual:u,areSetsEqual:h,areTypedArraysEqual:m,areUrlsEqual:f,unknownTagComparators:g}){return function(y,v,b){if(y===v)return!0;if(y==null||v==null)return!1;const w=typeof y;if(w!==typeof v)return!1;if(w!=="object")return w==="number"?o(y,v,b):w==="function"?i(y,v,b):!1;const S=y.constructor;if(S!==v.constructor)return!1;if(S===Object)return c(y,v,b);if(Array.isArray(y))return t(y,v,b);if(S===Date)return r(y,v,b);if(S===RegExp)return u(y,v,b);if(S===Map)return l(y,v,b);if(S===Set)return h(y,v,b);if(S==null)return c(y,v,b);const A=dAn.call(y);if(A===eAn)return r(y,v,b);if(A===aAn)return u(y,v,b);if(A===sAn)return l(y,v,b);if(A===iAn)return h(y,v,b);if(A===rAn)return typeof y.then!="function"&&typeof v.then!="function"&&c(y,v,b);if(A===cAn)return f(y,v,b);if(A===tAn)return a(y,v,b);if(A===X3n)return c(y,v,b);if(lAn[A])return m(y,v,b);if(A===Z3n)return s(y,v,b);if(A===J3n)return n(y,v,b);if(A===Q3n||A===nAn||A===oAn)return d(y,v,b);if(g){let E=g[A];if(!E){const I=L3n(y);I&&(E=g[I])}if(E)return E(y,v,b)}return!1}}function hAn({circular:s,createCustomConfig:t,strict:n}){let r={areArrayBuffersEqual:B3n,areArraysEqual:n?R$:$3n,areDataViewsEqual:U3n,areDatesEqual:q3n,areErrorsEqual:n?XZ(kNt,R$):XZ(kNt,CNt),areFunctionsEqual:V3n,areMapsEqual:n?XZ(SNt,R$):SNt,areNumbersEqual:H3n,areObjectsEqual:n?R$:CNt,arePrimitiveWrappersEqual:G3n,areRegExpsEqual:W3n,areSetsEqual:n?XZ(ANt,R$):ANt,areTypedArraysEqual:n?XZ(wMe,R$):wMe,areUrlsEqual:K3n,unknownTagComparators:void 0};if(t&&(r=Object.assign({},r,t(r))),s){const a=QZ(r.areArraysEqual),i=QZ(r.areErrorsEqual),l=QZ(r.areMapsEqual),o=QZ(r.areObjectsEqual),c=QZ(r.areSetsEqual);r=Object.assign({},r,{areArraysEqual:a,areErrorsEqual:i,areMapsEqual:l,areObjectsEqual:o,areSetsEqual:c})}return r}function mAn(s){return function(t,n,r,a,i,l,o){return s(t,n,o)}}function fAn({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 pAn=S6();S6({strict:!0});S6({circular:!0});S6({circular:!0,strict:!0});S6({createInternalComparator:()=>JB});S6({strict:!0,createInternalComparator:()=>JB});S6({circular:!0,createInternalComparator:()=>JB});S6({circular:!0,createInternalComparator:()=>JB,strict:!0});function S6(s={}){const{circular:t=!1,createInternalComparator:n,createState:r,strict:a=!1}=s,i=hAn(s),l=uAn(i),o=n?n(l):mAn(l);return fAn({circular:t,comparator:l,createState:r,equals:o,strict:a})}function gAn(s){typeof requestAnimationFrame<"u"&&requestAnimationFrame(s)}function TNt(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):gAn(a)};requestAnimationFrame(r)}function RKe(s){"@babel/helpers - typeof";return RKe=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},RKe(s)}function xAn(s){return _An(s)||bAn(s)||vAn(s)||yAn()}function yAn(){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 vAn(s,t){if(s){if(typeof s=="string")return MNt(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 MNt(s,t)}}function MNt(s,t){(t==null||t>s.length)&&(t=s.length);for(var n=0,r=new Array(t);ns.length)&&(t=s.length);for(var n=0,r=new Array(t);n1?1:v<0?0:v},x=function(v){for(var b=v>1?1:v,w=b,S=0;S<8;++S){var A=h(w)-b,E=f(w);if(Math.abs(A-b)0&&arguments[0]!==void 0?arguments[0]:{},n=t.stiff,r=n===void 0?100:n,a=t.damping,i=a===void 0?8:a,l=t.dt,o=l===void 0?17:l,c=function(u,h,m){var f=-(u-h)*r,g=m*i,x=m+(f-g)*o/1e3,y=m*o/1e3+u;return Math.abs(y-h)s.length)&&(t=s.length);for(var n=0,r=new Array(t);n=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function QAn(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 j9e(s){return sEn(s)||tEn(s)||eEn(s)||JAn()}function JAn(){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 eEn(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 tEn(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function sEn(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);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 kMe(s){return kMe=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(n){return n.__proto__||Object.getPrototypeOf(n)},kMe(s)}var xC=function(s){oEn(n,s);var t=lEn(n);function n(r,a){var i;nEn(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(qKe(i)),i.changeStyle=i.changeStyle.bind(qKe(i)),!o||f<=0)return i.state={style:{}},typeof m=="function"&&(i.state={style:u}),UKe(i);if(h&&h.length)i.state={style:h[0].style};else if(d){if(typeof m=="function")return i.state={style:d},UKe(i);i.state={style:c?bQ({},c,d):d}}else i.state={style:{}};return i}return aEn(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?bQ({},c,u):u};this.state&&m&&(c&&m[c]!==u||!c&&m!==u)&&this.setState(f);return}if(!(pAn(a.to,u)&&a.canBegin&&a.isActive)){var g=!a.canBegin||!a.isActive;this.manager&&this.manager.stop(),this.stopJSAnimation&&this.stopJSAnimation();var x=g||d?h:a.to;if(this.state&&m){var y={style:c?bQ({},c,x):x};(c&&m[c]!==x||!c&&m!==x)&&this.setState(y)}this.runAnimation(eS(eS({},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=YAn(l,o,OAn(d),c,this.changeStyle),g=function(){i.stopJSAnimation=f()};this.manager.start([m,u,g,c,h])}},{key:"runStepAnimation",value:function(a){var i=this,l=a.steps,o=a.begin,c=a.onAnimationStart,d=l[0],u=d.style,h=d.duration,m=h===void 0?0:h,f=function(x,y,v){if(v===0)return x;var b=y.duration,w=y.easing,S=w===void 0?"ease":w,A=y.style,E=y.properties,I=y.onAnimationEnd,P=v>0?l[v-1]:y,R=E||Object.keys(A);if(typeof S=="function"||S==="spring")return[].concat(j9e(x),[i.runJSAnimation.bind(i,{from:P.style,to:A,duration:b,easing:S}),b]);var D=LNt(R,b,S),O=eS(eS(eS({},P.style),A),{},{transition:D});return[].concat(j9e(x),[O,b,I]).filter(SAn)};return this.manager.start([c].concat(j9e(l.reduce(f,[u,Math.max(m,o)])),[a.onAnimationEnd]))}},{key:"runAnimation",value:function(a){this.manager||(this.manager=wAn());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?bQ({},o,c):c,y=LNt(Object.keys(x),l,d);g.start([u,i,eS(eS({},x),{},{transition:y}),l,h])}},{key:"render",value:function(){var a=this.props,i=a.children;a.begin;var l=a.duration;a.attributeName,a.easing;var o=a.isActive;a.steps,a.from,a.to,a.canBegin,a.onAnimationEnd,a.shouldReAnimate,a.onAnimationReStart;var c=XAn(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,y=x===void 0?{}:x,v=g.className,b=j.cloneElement(f,eS(eS({},c),{},{style:eS(eS({},y),u),className:v}));return b};return d===1?h(j.Children.only(i)):Gt.createElement("div",null,j.Children.map(i,function(m){return h(m)}))}}]),n}(j.PureComponent);xC.displayName="Animate";xC.defaultProps={begin:0,duration:1e3,from:"",to:"",attributeName:"",easing:"ease",isActive:!0,canBegin:!0,steps:[],onAnimationEnd:function(){},onAnimationStart:function(){}};xC.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 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 SMe(){return SMe=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},yEn=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},vEn={x:0,y:0,width:0,height:0,radius:0,isAnimationActive:!1,isUpdateAnimationActive:!1,animationBegin:0,animationDuration:1500,animationEasing:"ease"},Lat=function(t){var n=UNt(UNt({},vEn),t),r=j.useRef(),a=j.useState(-1),i=dEn(a,2),l=i[0],o=i[1];j.useEffect(function(){if(r.current&&r.current.getTotalLength)try{var S=r.current.getTotalLength();S&&o(S)}catch{}},[]);var c=n.x,d=n.y,u=n.width,h=n.height,m=n.radius,f=n.className,g=n.animationEasing,x=n.animationDuration,y=n.animationBegin,v=n.isAnimationActive,b=n.isUpdateAnimationActive;if(c!==+c||d!==+d||u!==+u||h!==+h||u===0||h===0)return null;var w=sd("recharts-rectangle",f);return b?Gt.createElement(xC,{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 Gt.createElement(xC,{canBegin:l>0,from:"0px ".concat(l===-1?1:l,"px"),to:"".concat(l,"px 0px"),attributeName:"strokeDasharray",begin:y,duration:x,isActive:v,easing:g},Gt.createElement("path",SMe({},cl(n,!0),{className:w,d:qNt(I,P,A,E,m),ref:r})))}):Gt.createElement("path",SMe({},cl(n,!0),{className:w,d:qNt(c,d,u,h,m)}))},bEn=["points","className","baseLinePoints","connectNulls"];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 wEn(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 VNt(s){return SEn(s)||kEn(s)||NEn(s)||jEn()}function jEn(){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 NEn(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 kEn(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function SEn(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);n0&&arguments[0]!==void 0?arguments[0]:[],n=[[]];return t.forEach(function(r){HNt(r)?n[n.length-1].push(r):n[n.length-1].length>0&&n.push([])}),HNt(t[0])&&n[n.length-1].push(t[0]),n[n.length-1].length<=0&&(n=n.slice(0,-1)),n},Vee=function(t,n){var r=CEn(t);n&&(r=[r.reduce(function(i,l){return[].concat(VNt(i),VNt(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},AEn=function(t,n,r){var a=Vee(t,r);return"".concat(a.slice(-1)==="Z"?a.slice(0,-1):a,"L").concat(Vee(n.reverse(),r).slice(1))},EEn=function(t){var n=t.points,r=t.className,a=t.baseLinePoints,i=t.connectNulls,l=_En(t,bEn);if(!n||!n.length)return null;var o=sd("recharts-polygon",r);if(a&&a.length){var c=l.stroke&&l.stroke!=="none",d=AEn(n,a,i);return Gt.createElement("g",{className:o},Gt.createElement("path",rq({},cl(l,!0),{fill:d.slice(-1)==="Z"?l.fill:"none",stroke:"none",d})),c?Gt.createElement("path",rq({},cl(l,!0),{fill:"none",d:Vee(n,i)})):null,c?Gt.createElement("path",rq({},cl(l,!0),{fill:"none",d:Vee(a,i)})):null)}var u=Vee(n,i);return Gt.createElement("path",rq({},cl(l,!0),{fill:u.slice(-1)==="Z"?l.fill:"none",className:o,d:u}))};function HKe(){return HKe=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 DEn(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 FEn=function(t,n,r,a,i,l){return"M".concat(t,",").concat(i,"v").concat(a,"M").concat(l,",").concat(n,"h").concat(r)},OEn=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=REn(t,TEn),y=MEn({x:r,y:i,top:o,left:d,width:h,height:f},x);return!yi(r)||!yi(i)||!yi(h)||!yi(f)||!yi(o)||!yi(d)?null:Gt.createElement("path",GKe({},cl(y,!0),{className:sd("recharts-cross",g),d:FEn(r,i,h,f,o,d)}))},zEn=RRe,BEn=DYt,$En=m3;function UEn(s,t){return s&&s.length?zEn(s,$En(t),BEn):void 0}var qEn=UEn;const VEn=ru(qEn);var HEn=RRe,GEn=m3,WEn=FYt;function KEn(s,t){return s&&s.length?HEn(s,GEn(t),WEn):void 0}var YEn=KEn;const ZEn=ru(YEn);var XEn=["cx","cy","angle","ticks","axisLine"],QEn=["ticks","tick","angle","tickFormatter","stroke"];function YG(s){"@babel/helpers - typeof";return YG=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},YG(s)}function Hee(){return Hee=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 JEn(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 eTn(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function YNt(s,t){for(var n=0;nQNt?l=a==="outer"?"start":"end":i<-QNt?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=vR(vR({},cl(this.props,!1)),{},{fill:"none"},cl(o,!1));if(c==="circle")return Gt.createElement(Eie,YO({className:"recharts-polar-angle-axis-line"},d,{cx:a,cy:i,r:l}));var u=this.props.ticks,h=u.map(function(m){return Yf(a,i,l,m.coordinate)});return Gt.createElement(EEn,YO({className:"recharts-polar-angle-axis-line"},d,{points:h}))}},{key:"renderTicks",value:function(){var r=this,a=this.props,i=a.ticks,l=a.tick,o=a.tickLine,c=a.tickFormatter,d=a.stroke,u=cl(this.props,!1),h=cl(l,!1),m=vR(vR({},u),{},{fill:"none"},cl(o,!1)),f=i.map(function(g,x){var y=r.getTickLineCoord(g),v=r.getTickTextAnchor(g),b=vR(vR(vR({textAnchor:v},u),{},{stroke:"none",fill:d},h),{},{index:x,payload:g,x:y.x2,y:y.y2});return Gt.createElement(Su,YO({className:sd("recharts-polar-angle-axis-tick",uZt(l)),key:"tick-".concat(g.coordinate)},sB(r.props,g,x)),o&&Gt.createElement("line",YO({className:"recharts-polar-angle-axis-tick-line"},m,y)),l&&t.renderTickItem(l,b,c?c(g.value,x):g.value))});return Gt.createElement(Su,{className:"recharts-polar-angle-axis-ticks"},f)}},{key:"render",value:function(){var r=this.props,a=r.ticks,i=r.radius,l=r.axisLine;return i<=0||!a||!a.length?null:Gt.createElement(Su,{className:sd("recharts-polar-angle-axis",this.props.className)},l&&this.renderAxisLine(),this.renderTicks())}}],[{key:"renderTickItem",value:function(r,a,i){var l;return Gt.isValidElement(r)?l=Gt.cloneElement(r,a):hc(r)?l=r(a):l=Gt.createElement(nB,YO({},a,{className:"recharts-polar-angle-axis-tick-value"}),i),l}}])}(j.PureComponent);$Re(URe,"displayName","PolarAngleAxis");$Re(URe,"axisType","angleAxis");$Re(URe,"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 pTn=IKt,gTn=pTn(Object.getPrototypeOf,Object),xTn=gTn,yTn=LT,vTn=xTn,bTn=RT,_Tn="[object Object]",wTn=Function.prototype,jTn=Object.prototype,EZt=wTn.toString,NTn=jTn.hasOwnProperty,kTn=EZt.call(Object);function STn(s){if(!bTn(s)||yTn(s)!=_Tn)return!1;var t=vTn(s);if(t===null)return!0;var n=NTn.call(t,"constructor")&&t.constructor;return typeof n=="function"&&n instanceof n&&EZt.call(n)==kTn}var CTn=STn;const ATn=ru(CTn);var ETn=LT,TTn=RT,MTn="[object Boolean]";function PTn(s){return s===!0||s===!1||TTn(s)&&ETn(s)==MTn}var ITn=PTn;const LTn=ru(ITn);function tne(s){"@babel/helpers - typeof";return tne=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},tne(s)}function EMe(){return EMe=Object.assign?Object.assign.bind():function(s){for(var t=1;ts.length)&&(t=s.length);for(var n=0,r=new Array(t);n0,from:{upperWidth:0,lowerWidth:0,height:m,x:c,y:d},to:{upperWidth:u,lowerWidth:h,height:m,x:c,y:d},duration:x,animationEasing:g,isActive:v},function(w){var S=w.upperWidth,A=w.lowerWidth,E=w.height,I=w.x,P=w.y;return Gt.createElement(xC,{canBegin:l>0,from:"0px ".concat(l===-1?1:l,"px"),to:"".concat(l,"px 0px"),attributeName:"strokeDasharray",begin:y,duration:x,easing:g},Gt.createElement("path",EMe({},cl(n,!0),{className:b,d:skt(I,P,S,A,E),ref:r})))}):Gt.createElement("g",null,Gt.createElement("path",EMe({},cl(n,!0),{className:b,d:skt(c,d,u,h,m)})))},HTn=["option","shapeType","propTransformer","activeClassName","isActive"];function sne(s){"@babel/helpers - typeof";return sne=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},sne(s)}function GTn(s,t){if(s==null)return{};var n=WTn(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 WTn(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 nkt(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 TMe(s){for(var t=1;t0?y2(w,"paddingAngle",0):0;if(A){var I=_0(A.endAngle-A.startAngle,w.endAngle-w.startAngle),P=qf(qf({},w),{},{startAngle:b+E,endAngle:b+I(x)+E});y.push(P),b=P.endAngle}else{var R=w.endAngle,D=w.startAngle,O=_0(0,R-D),U=O(x),W=qf(qf({},w),{},{startAngle:b+E,endAngle:b+U+E});y.push(W),b=W.endAngle}}),Gt.createElement(Su,null,r.renderSectorsStatically(y))})}},{key:"attachKeyboardHandlers",value:function(r){var a=this;r.onkeydown=function(i){if(!i.altKey)switch(i.key){case"ArrowLeft":{var l=++a.state.sectorToFocus%a.sectorRefs.length;a.sectorRefs[l].focus(),a.setState({sectorToFocus:l});break}case"ArrowRight":{var o=--a.state.sectorToFocus<0?a.sectorRefs.length-1:a.state.sectorToFocus%a.sectorRefs.length;a.sectorRefs[o].focus(),a.setState({sectorToFocus:o});break}case"Escape":{a.sectorRefs[a.state.sectorToFocus].blur(),a.setState({sectorToFocus:0});break}}}}},{key:"renderSectors",value:function(){var r=this.props,a=r.sectors,i=r.isAnimationActive,l=this.state.prevSectors;return i&&a&&a.length&&(!l||!rB(l,a))?this.renderSectorsWithAnimation():this.renderSectorsStatically(a)}},{key:"componentDidMount",value:function(){this.pieRef&&this.attachKeyboardHandlers(this.pieRef)}},{key:"render",value:function(){var r=this,a=this.props,i=a.hide,l=a.sectors,o=a.className,c=a.label,d=a.cx,u=a.cy,h=a.innerRadius,m=a.outerRadius,f=a.isAnimationActive,g=this.state.isAnimationFinished;if(i||!l||!l.length||!yi(d)||!yi(u)||!yi(h)||!yi(m))return null;var x=sd("recharts-pie",o);return Gt.createElement(Su,{tabIndex:this.props.rootTabIndex,className:x,ref:function(v){r.pieRef=v}},this.renderSectors(),c&&this.renderLabels(l),xv.renderCallByParent(this.props,null,!1),(!f||g)&&B4.renderCallByParent(this.props,l,!1))}}],[{key:"getDerivedStateFromProps",value:function(r,a){return a.prevIsAnimationActive!==r.isAnimationActive?{prevIsAnimationActive:r.isAnimationActive,prevAnimationId:r.animationId,curSectors:r.sectors,prevSectors:[],isAnimationFinished:!0}:r.isAnimationActive&&r.animationId!==a.prevAnimationId?{prevAnimationId:r.animationId,curSectors:r.sectors,prevSectors:a.curSectors,isAnimationFinished:!0}:r.sectors!==a.curSectors?{curSectors:r.sectors,isAnimationFinished:!0}:null}},{key:"getTextAnchor",value:function(r,a){return r>a?"start":r=360?b:b-1)*c,S=y-b*f-w,A=a.reduce(function(P,R){var D=ay(R,v,0);return P+(yi(D)?D:0)},0),E;if(A>0){var I;E=a.map(function(P,R){var D=ay(P,v,0),O=ay(P,u,R),U=(yi(D)?D:0)/A,W;R?W=I.endAngle+y_(x)*c*(D!==0?1:0):W=l;var V=W+y_(x)*((D!==0?f:0)+U*S),G=(W+V)/2,Y=(g.innerRadius+g.outerRadius)/2,X=[{name:O,value:D,payload:P,dataKey:v,type:m}],ae=Yf(g.cx,g.cy,Y,G);return I=qf(qf(qf({percent:U,cornerRadius:i,name:O,tooltipPayload:X,midAngle:G,middleRadius:Y,tooltipPosition:ae},P),g),{},{value:ay(P,v),startAngle:W,endAngle:V,payload:P,paddingAngle:y_(x)*c}),I})}return qf(qf({},g),{},{sectors:E,data:a})});var fMn=Math.ceil,pMn=Math.max;function gMn(s,t,n,r){for(var a=-1,i=pMn(fMn((t-s)/(n||1)),0),l=Array(i);i--;)l[r?i:++a]=s,s+=n;return l}var xMn=gMn,yMn=QKt,okt=1/0,vMn=17976931348623157e292;function bMn(s){if(!s)return s===0?s:0;if(s=yMn(s),s===okt||s===-okt){var t=s<0?-1:1;return t*vMn}return s===s?s:0}var IZt=bMn,_Mn=xMn,wMn=ARe,N9e=IZt;function jMn(s){return function(t,n,r){return r&&typeof r!="number"&&wMn(t,n,r)&&(n=r=void 0),t=N9e(t),n===void 0?(n=t,t=0):n=N9e(n),r=r===void 0?t0&&r.handleDrag(a.changedTouches[0])}),Aj(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()}),Aj(r,"handleLeaveWrapper",function(){(r.state.isTravellerMoving||r.state.isSlideMoving)&&(r.leaveTimer=window.setTimeout(r.handleDragEnd,r.props.leaveTimeOut))}),Aj(r,"handleEnterSlideOrTraveller",function(){r.setState({isTextActive:!0})}),Aj(r,"handleLeaveSlideOrTraveller",function(){r.setState({isTextActive:!1})}),Aj(r,"handleSlideDragStart",function(a){var i=hkt(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 FMn(t,s),IMn(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=ay(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 y=this.getIndex({startX:l+x,endX:o+x});(y.startIndex!==m||y.endIndex!==f)&&g&&g(y),this.setState({startX:l+x,endX:o+x,slideMoveStartX:r.pageX})}},{key:"handleTravellerDragStart",value:function(r,a){var i=hkt(a)?a.changedTouches[0]:a;this.setState({isSlideMoving:!1,isTravellerMoving:!0,movingTravellerId:r,brushMoveStartX:i.pageX}),this.attachDragEndListener()}},{key:"handleTravellerMove",value:function(r){var a=this.state,i=a.brushMoveStartX,l=a.movingTravellerId,o=a.endX,c=a.startX,d=this.state[l],u=this.props,h=u.x,m=u.width,f=u.travellerWidth,g=u.onChange,x=u.gap,y=u.data,v={startX:this.state.startX,endX:this.state.endX},b=r.pageX-i;b>0?b=Math.min(b,h+m-f-d):b<0&&(b=Math.max(b,h-d)),v[l]=d+b;var w=this.getIndex(v),S=w.startIndex,A=w.endIndex,E=function(){var P=y.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(Aj(Aj({},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(Aj({},a,f),function(){i.props.onChange(i.getIndex({startX:i.state.startX,endX:i.state.endX}))})}}}},{key:"renderBackground",value:function(){var r=this.props,a=r.x,i=r.y,l=r.width,o=r.height,c=r.fill,d=r.stroke;return Gt.createElement("rect",{stroke:d,fill:c,x:a,y:i,width:l,height:o})}},{key:"renderPanorama",value:function(){var r=this.props,a=r.x,i=r.y,l=r.width,o=r.height,c=r.data,d=r.children,u=r.padding,h=j.Children.only(d);return h?Gt.cloneElement(h,{x:a,y:i,width:l,height:o,margin:u,compact:!0,data:c}):null}},{key:"renderTravellerLayer",value:function(r,a){var i,l,o=this,c=this.props,d=c.y,u=c.travellerWidth,h=c.height,m=c.traveller,f=c.ariaLabel,g=c.data,x=c.startIndex,y=c.endIndex,v=Math.max(r,this.props.x),b=k9e(k9e({},cl(this.props,!1)),{},{x:v,y:d,width:u,height:h}),w=f||"Min value: ".concat((i=g[x])===null||i===void 0?void 0:i.name,", Max value: ").concat((l=g[y])===null||l===void 0?void 0:l.name);return Gt.createElement(Su,{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 Gt.createElement("rect",{className:"recharts-brush-slide",onMouseEnter:this.handleEnterSlideOrTraveller,onMouseLeave:this.handleLeaveSlideOrTraveller,onMouseDown:this.handleSlideDragStart,onTouchStart:this.handleSlideDragStart,style:{cursor:"move"},stroke:"none",fill:c,fillOpacity:.2,x:u,y:l,width:h,height:o})}},{key:"renderText",value:function(){var r=this.props,a=r.startIndex,i=r.endIndex,l=r.y,o=r.height,c=r.travellerWidth,d=r.stroke,u=this.state,h=u.startX,m=u.endX,f=5,g={pointerEvents:"none",fill:d};return Gt.createElement(Su,{className:"recharts-brush-texts"},Gt.createElement(nB,IMe({textAnchor:"end",verticalAnchor:"middle",x:Math.min(h,m)-f,y:l+o/2},g),this.getTextOfTick(a)),Gt.createElement(nB,IMe({textAnchor:"start",verticalAnchor:"middle",x:Math.max(h,m)+c+f,y:l+o/2},g),this.getTextOfTick(i)))}},{key:"render",value:function(){var r=this.props,a=r.data,i=r.className,l=r.children,o=r.x,c=r.y,d=r.width,u=r.height,h=r.alwaysShowText,m=this.state,f=m.startX,g=m.endX,x=m.isTextActive,y=m.isSlideMoving,v=m.isTravellerMoving,b=m.isTravellerFocused;if(!a||!a.length||!yi(o)||!yi(c)||!yi(d)||!yi(u)||d<=0||u<=0)return null;var w=sd("recharts-brush",i),S=Gt.Children.count(l)===1,A=MMn("userSelect","none");return Gt.createElement(Su,{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||y||v||b||h)&&this.renderText())}}],[{key:"renderDefaultTraveller",value:function(r){var a=r.x,i=r.y,l=r.width,o=r.height,c=r.stroke,d=Math.floor(i+o/2)-1;return Gt.createElement(Gt.Fragment,null,Gt.createElement("rect",{x:a,y:i,width:l,height:o,fill:c,stroke:"none"}),Gt.createElement("line",{x1:a+1,y1:d,x2:a+l-1,y2:d,fill:"none",stroke:"#fff"}),Gt.createElement("line",{x1:a+1,y1:d+2,x2:a+l-1,y2:d+2,fill:"none",stroke:"#fff"}))}},{key:"renderTraveller",value:function(r,a){var i;return Gt.isValidElement(r)?i=Gt.cloneElement(r,a):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 k9e({prevData:i,prevTravellerWidth:c,prevUpdateId:d,prevX:o,prevWidth:l},i&&i.length?zMn({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);Aj(JG,"displayName","Brush");Aj(JG,"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 BMn=iat;function $Mn(s,t){var n;return BMn(s,function(r,a,i){return n=t(r,a,i),!n}),!!n}var UMn=$Mn,qMn=kKt,VMn=m3,HMn=UMn,GMn=Vw,WMn=ARe;function KMn(s,t,n){var r=GMn(s)?qMn:HMn;return n&&WMn(s,t,n)&&(t=void 0),r(s,VMn(t))}var YMn=KMn;const ZMn=ru(YMn);var $4=function(t,n){var r=t.alwaysShow,a=t.ifOverflow;return r&&(a="extendDomain"),a===n},mkt=WKt;function XMn(s,t,n){t=="__proto__"&&mkt?mkt(s,t,{configurable:!0,enumerable:!0,value:n,writable:!0}):s[t]=n}var QMn=XMn,JMn=QMn,ePn=HKt,tPn=m3;function sPn(s,t){var n={};return t=tPn(t),ePn(s,function(r,a,i){JMn(n,a,t(r,a,i))}),n}var nPn=sPn;const rPn=ru(nPn);function aPn(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 wPn(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 jPn(s,t){var n=s.x,r=s.y,a=_Pn(s,xPn),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 JZ(JZ(JZ(JZ(JZ({},t),a),l?{x:l}:{}),c?{y:c}:{}),{},{height:u,width:m,name:t.name,radius:t.radius})}function pkt(s){return Gt.createElement(TZt,XKe({shapeType:"rectangle",propTransformer:jPn,activeClassName:"recharts-active-bar"},s))}var NPn=function(t){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;return function(r,a){if(typeof t=="number")return t;var i=yi(r)||Ggn(r);return i?t(r,a):(i||iB(),n)}},kPn=["value","background"],OZt;function eW(s){"@babel/helpers - typeof";return eW=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},eW(s)}function SPn(s,t){if(s==null)return{};var n=CPn(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 CPn(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 RMe(){return RMe=Object.assign?Object.assign.bind():function(s){for(var t=1;t0&&Math.abs(G)0&&Math.abs(V)0&&(W=Math.min((_e||0)-(V[he-1]||0),W))}),Number.isFinite(W)){var G=W/U,Y=x.layout==="vertical"?r.height:r.width;if(x.padding==="gap"&&(I=G*Y/2),x.padding==="no-gap"){var X=v_(t.barCategoryGap,G*Y),ae=G*Y/2;I=ae-X-(ae-X)/Y*X}}}a==="xAxis"?P=[r.left+(w.left||0)+(I||0),r.left+r.width-(w.right||0)-(I||0)]:a==="yAxis"?P=c==="horizontal"?[r.top+r.height-(w.bottom||0),r.top+(w.top||0)]:[r.top+(w.top||0)+(I||0),r.top+r.height-(w.bottom||0)-(I||0)]:P=x.range,A&&(P=[P[1],P[0]]);var le=rZt(x,i,m),ne=le.scale,te=le.realScaleType;ne.domain(v).range(P),aZt(ne);var J=iZt(ne,LS(LS({},x),{},{realScaleType:te}));a==="xAxis"?(O=y==="top"&&!S||y==="bottom"&&S,R=r.left,D=h[E]-O*x.height):a==="yAxis"&&(O=y==="left"&&!S||y==="right"&&S,R=h[E]-O*x.width,D=r.top);var ce=LS(LS(LS({},x),J),{},{realScaleType:te,x:R,y:D,scale:ne,width:a==="xAxis"?r.width:x.width,height:a==="yAxis"?r.height:x.height});return ce.bandSize=vMe(ce,J),!x.hide&&a==="xAxis"?h[E]+=(O?-1:1)*ce.height:x.hide||(h[E]+=(O?-1:1)*ce.width),LS(LS({},f),{},HRe({},g,ce))},{})},UZt=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)}},OPn=function(t){var n=t.x1,r=t.y1,a=t.x2,i=t.y2;return UZt({x:n,y:r},{x:a,y:i})},qZt=function(){function s(t){RPn(this,s),this.scale=t}return DPn(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)}}])}();HRe(qZt,"EPS",1e-4);var Dat=function(t){var n=Object.keys(t).reduce(function(r,a){return LS(LS({},r),{},HRe({},a,qZt.create(t[a])))},{});return LS(LS({},n),{},{apply:function(a){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},l=i.bandAware,o=i.position;return rPn(a,function(c,d){return n[d].apply(c,{bandAware:l,position:o})})},isInRange:function(a){return FZt(a,function(i,l){return n[l].isInRange(i)})}})};function zPn(s){return(s%180+180)%180}var BPn=function(t){var n=t.width,r=t.height,a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,i=zPn(a),l=i*Math.PI/180,o=Math.atan(r/n),c=l>o&&l-1?a[i?t[l]:l]:void 0}}var HPn=VPn,GPn=IZt;function WPn(s){var t=GPn(s),n=t%1;return t===t?n?t-n:t:0}var KPn=WPn,YPn=zKt,ZPn=m3,XPn=KPn,QPn=Math.max;function JPn(s,t,n){var r=s==null?0:s.length;if(!r)return-1;var a=n==null?0:XPn(n);return a<0&&(a=QPn(r+a,0)),YPn(s,ZPn(t),a)}var eIn=JPn,tIn=HPn,sIn=eIn,nIn=tIn(sIn),rIn=nIn;const aIn=ru(rIn);var iIn=Qpn(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("")}),Fat=j.createContext(void 0),Oat=j.createContext(void 0),VZt=j.createContext(void 0),HZt=j.createContext({}),GZt=j.createContext(void 0),WZt=j.createContext(0),KZt=j.createContext(0),bkt=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=iIn(i);return Gt.createElement(Fat.Provider,{value:r},Gt.createElement(Oat.Provider,{value:a},Gt.createElement(HZt.Provider,{value:i},Gt.createElement(VZt.Provider,{value:u},Gt.createElement(GZt.Provider,{value:l},Gt.createElement(WZt.Provider,{value:d},Gt.createElement(KZt.Provider,{value:c},o)))))))},oIn=function(){return j.useContext(GZt)},YZt=function(t){var n=j.useContext(Fat);n==null&&iB();var r=n[t];return r==null&&iB(),r},lIn=function(){var t=j.useContext(Fat);return CP(t)},cIn=function(){var t=j.useContext(Oat),n=aIn(t,function(r){return FZt(r.domain,Number.isFinite)});return n||CP(t)},ZZt=function(t){var n=j.useContext(Oat);n==null&&iB();var r=n[t];return r==null&&iB(),r},dIn=function(){var t=j.useContext(VZt);return t},uIn=function(){return j.useContext(HZt)},zat=function(){return j.useContext(KZt)},Bat=function(){return j.useContext(WZt)};function tW(s){"@babel/helpers - typeof";return tW=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},tW(s)}function hIn(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function mIn(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 KIn(s,t){return nXt(s,t+1)}function YIn(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:nXt(r,d)};var x=c,y,v=function(){return y===void 0&&(y=n(g,x)),y},b=g.coordinate,w=c===0||BMe(s,b,v,u,o);w||(c=0,u=l,d+=1),w&&(u=b+s*(v()/2+a),c+=d)},m;d<=i.length;)if(m=h(),m)return m.v;return[]}function one(s){"@babel/helpers - typeof";return one=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},one(s)}function Akt(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 l1(s){for(var t=1;t0?f.coordinate-y*s:f.coordinate})}else i[m]=f=l1(l1({},f),{},{tickCoord:f.coordinate});var v=BMe(s,f.tickCoord,x,o,c);v&&(c=f.tickCoord-s*(x()/2+a),i[m]=l1(l1({},f),{},{isShow:!0}))},u=l-1;u>=0;u--)d(u);return i}function eLn(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=l1(l1({},u),{},{tickCoord:m>0?u.coordinate-m*s:u.coordinate});var f=BMe(s,u.tickCoord,function(){return h},c,d);f&&(d=u.tickCoord-s*(h/2+a),l[o-1]=l1(l1({},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=l1(l1({},w),{},{tickCoord:E<0?w.coordinate-E*s:w.coordinate})}else l[b]=w=l1(l1({},w),{},{tickCoord:w.coordinate});var I=BMe(s,w.tickCoord,A,c,d);I&&(c=w.tickCoord+s*(A()/2+a),l[b]=l1(l1({},w),{},{isShow:!0}))},y=0;y=2?y_(a[1].coordinate-a[0].coordinate):1,v=WIn(i,y,f);return c==="equidistantPreserveStart"?YIn(y,v,x,a,l):(c==="preserveStart"||c==="preserveStartEnd"?m=eLn(y,v,x,a,l,c==="preserveStartEnd"):m=JIn(y,v,x,a,l),m.filter(function(b){return b.isShow}))}var tLn=["viewBox"],sLn=["viewBox"],nLn=["ticks"];function rW(s){"@babel/helpers - typeof";return rW=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},rW(s)}function iq(){return iq=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 rLn(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 aLn(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function Tkt(s,t){for(var n=0;n0?c(this.props):c(f)),l<=0||o<=0||!g||!g.length?null:Gt.createElement(Su,{className:sd("recharts-cartesian-axis",d),ref:function(y){r.layerReference=y}},i&&this.renderAxisLine(),this.renderTicks(g,this.state.fontSize,this.state.letterSpacing),xv.renderCallByParent(this.props))}}],[{key:"renderTickItem",value:function(r,a,i){var l,o=sd(a.className,"recharts-cartesian-axis-tick-value");return Gt.isValidElement(r)?l=Gt.cloneElement(r,s0(s0({},a),{},{className:o})):hc(r)?l=r(s0(s0({},a),{},{className:o})):l=Gt.createElement(nB,iq({},a,{className:"recharts-cartesian-axis-tick-value"}),i),l}}])}(j.Component);Vat(IK,"displayName","CartesianAxis");Vat(IK,"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 hLn=["x1","y1","x2","y2","key"],mLn=["offset"];function oB(s){"@babel/helpers - typeof";return oB=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},oB(s)}function Mkt(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 h1(s){for(var t=1;t=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function xLn(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 yLn=function(t){var n=t.fill;if(!n||n==="none")return null;var r=t.fillOpacity,a=t.x,i=t.y,l=t.width,o=t.height,c=t.ry;return Gt.createElement("rect",{x:a,y:i,ry:c,width:l,height:o,stroke:"none",fill:n,fillOpacity:r,className:"recharts-cartesian-grid-bg"})};function iXt(s,t){var n;if(Gt.isValidElement(s))n=Gt.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=Pkt(t,hLn),d=cl(c,!1);d.offset;var u=Pkt(d,mLn);n=Gt.createElement("line",y8({},u,{x1:r,y1:a,x2:i,y2:l,fill:"none",key:o}))}return n}function vLn(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=h1(h1({},s),{},{x1:t,y1:o,x2:t+n,y2:o,key:"line-".concat(c),index:c});return iXt(a,d)});return Gt.createElement("g",{className:"recharts-cartesian-grid-horizontal"},l)}function bLn(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=h1(h1({},s),{},{x1:o,y1:t,x2:o,y2:t+n,key:"line-".concat(c),index:c});return iXt(a,d)});return Gt.createElement("g",{className:"recharts-cartesian-grid-vertical"},l)}function _Ln(s){var t=s.horizontalFill,n=s.fillOpacity,r=s.x,a=s.y,i=s.width,l=s.height,o=s.horizontalPoints,c=s.horizontal,d=c===void 0?!0:c;if(!d||!t||!t.length)return null;var u=o.map(function(m){return Math.round(m+a-a)}).sort(function(m,f){return m-f});a!==u[0]&&u.unshift(0);var h=u.map(function(m,f){var g=!u[f+1],x=g?a+l-m:u[f+1]-m;if(x<=0)return null;var y=f%t.length;return Gt.createElement("rect",{key:"react-".concat(f),y:m,x:r,height:x,width:i,stroke:"none",fill:t[y],fillOpacity:n,className:"recharts-cartesian-grid-bg"})});return Gt.createElement("g",{className:"recharts-cartesian-gridstripes-horizontal"},h)}function wLn(s){var t=s.vertical,n=t===void 0?!0:t,r=s.verticalFill,a=s.fillOpacity,i=s.x,l=s.y,o=s.width,c=s.height,d=s.verticalPoints;if(!n||!r||!r.length)return null;var u=d.map(function(m){return Math.round(m+i-i)}).sort(function(m,f){return m-f});i!==u[0]&&u.unshift(0);var h=u.map(function(m,f){var g=!u[f+1],x=g?i+o-m:u[f+1]-m;if(x<=0)return null;var y=f%r.length;return Gt.createElement("rect",{key:"react-".concat(f),x:m,y:l,width:x,height:c,stroke:"none",fill:r[y],fillOpacity:a,className:"recharts-cartesian-grid-bg"})});return Gt.createElement("g",{className:"recharts-cartesian-gridstripes-vertical"},h)}var jLn=function(t,n){var r=t.xAxis,a=t.width,i=t.height,l=t.offset;return nZt(qat(h1(h1(h1({},IK.defaultProps),r),{},{ticks:NE(r,!0),viewBox:{x:0,y:0,width:a,height:i}})),l.left,l.left+l.width,n)},NLn=function(t,n){var r=t.yAxis,a=t.width,i=t.height,l=t.offset;return nZt(qat(h1(h1(h1({},IK.defaultProps),r),{},{ticks:NE(r,!0),viewBox:{x:0,y:0,width:a,height:i}})),l.top,l.top+l.height,n)},D$={horizontal:!0,vertical:!0,stroke:"#ccc",fill:"none",verticalFill:[],horizontalFill:[]};function gT(s){var t,n,r,a,i,l,o=zat(),c=Bat(),d=uIn(),u=h1(h1({},s),{},{stroke:(t=s.stroke)!==null&&t!==void 0?t:D$.stroke,fill:(n=s.fill)!==null&&n!==void 0?n:D$.fill,horizontal:(r=s.horizontal)!==null&&r!==void 0?r:D$.horizontal,horizontalFill:(a=s.horizontalFill)!==null&&a!==void 0?a:D$.horizontalFill,vertical:(i=s.vertical)!==null&&i!==void 0?i:D$.vertical,verticalFill:(l=s.verticalFill)!==null&&l!==void 0?l:D$.verticalFill,x:yi(s.x)?s.x:d.left,y:yi(s.y)?s.y:d.top,width:yi(s.width)?s.width:d.width,height:yi(s.height)?s.height:d.height}),h=u.x,m=u.y,f=u.width,g=u.height,x=u.syncWithTicks,y=u.horizontalValues,v=u.verticalValues,b=lIn(),w=cIn();if(!yi(f)||f<=0||!yi(g)||g<=0||!yi(h)||h!==+h||!yi(m)||m!==+m)return null;var S=u.verticalCoordinatesGenerator||jLn,A=u.horizontalCoordinatesGenerator||NLn,E=u.horizontalPoints,I=u.verticalPoints;if((!E||!E.length)&&hc(A)){var P=y&&y.length,R=A({yAxis:w?h1(h1({},w),{},{ticks:P?y:w.ticks}):void 0,width:o,height:c,offset:d},P?!0:x);oC(Array.isArray(R),"horizontalCoordinatesGenerator should return Array but instead it returned [".concat(oB(R),"]")),Array.isArray(R)&&(E=R)}if((!I||!I.length)&&hc(S)){var D=v&&v.length,O=S({xAxis:b?h1(h1({},b),{},{ticks:D?v:b.ticks}):void 0,width:o,height:c,offset:d},D?!0:x);oC(Array.isArray(O),"verticalCoordinatesGenerator should return Array but instead it returned [".concat(oB(O),"]")),Array.isArray(O)&&(I=O)}return Gt.createElement("g",{className:"recharts-cartesian-grid"},Gt.createElement(yLn,{fill:u.fill,fillOpacity:u.fillOpacity,x:u.x,y:u.y,width:u.width,height:u.height,ry:u.ry}),Gt.createElement(vLn,y8({},u,{offset:d,horizontalPoints:E,xAxis:b,yAxis:w})),Gt.createElement(bLn,y8({},u,{offset:d,verticalPoints:I,xAxis:b,yAxis:w})),Gt.createElement(_Ln,y8({},u,{horizontalPoints:E})),Gt.createElement(wLn,y8({},u,{verticalPoints:I})))}gT.displayName="CartesianGrid";var kLn=["type","layout","connectNulls","ref"],SLn=["key"];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 Ikt(s,t){if(s==null)return{};var n=CLn(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 CLn(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 Gee(){return Gee=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(F$(c.slice(0,g)),[h-x]);break}var y=f.length%2===0?[0,m]:[m];return[].concat(F$(t.repeat(c,u)),F$(f),y).map(function(v){return"".concat(v,"px")}).join(", ")}),RS(n,"id",YB("recharts-line-")),RS(n,"pathRef",function(l){n.mainCurve=l}),RS(n,"handleAnimationEnd",function(){n.setState({isAnimationFinished:!0}),n.props.onAnimationEnd&&n.props.onAnimationEnd()}),RS(n,"handleAnimationStart",function(){n.setState({isAnimationFinished:!1}),n.props.onAnimationStart&&n.props.onAnimationStart()}),n}return FLn(t,s),ILn(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=v2(u,Aie);if(!h)return null;var m=function(x,y){return{x:x.x,y:x.y,value:x.value,errorVal:ay(x.payload,y)}},f={clipPath:r?"url(#clipPath-".concat(a,")"):null};return Gt.createElement(Su,f,h.map(function(g){return Gt.cloneElement(g,{key:"bar-".concat(g.props.dataKey),data:l,xAxis:o,yAxis:c,layout:d,dataPointFormatter:m})}))}},{key:"renderDots",value:function(r,a,i){var l=this.props.isAnimationActive;if(l&&!this.state.isAnimationFinished)return null;var o=this.props,c=o.dot,d=o.points,u=o.dataKey,h=cl(this.props,!1),m=cl(c,!0),f=d.map(function(x,y){var v=Nj(Nj(Nj({key:"dot-".concat(y),r:3},h),m),{},{index:y,cx:x.x,cy:x.y,value:x.value,dataKey:u,payload:x.payload,points:d});return t.renderDotItem(c,v)}),g={clipPath:r?"url(#clipPath-".concat(a?"":"dots-").concat(i,")"):null};return Gt.createElement(Su,Gee({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=Ikt(o,kLn),m=Nj(Nj(Nj({},cl(h,!0)),{},{fill:"none",className:"recharts-line-curve",clipPath:a?"url(#clipPath-".concat(i,")"):null,points:r},l),{},{type:c,layout:d,connectNulls:u});return Gt.createElement(b7,Gee({},m,{pathRef:this.pathRef}))}},{key:"renderCurveWithAnimation",value:function(r,a){var i=this,l=this.props,o=l.points,c=l.strokeDasharray,d=l.isAnimationActive,u=l.animationBegin,h=l.animationDuration,m=l.animationEasing,f=l.animationId,g=l.animateNewValues,x=l.width,y=l.height,v=this.state,b=v.prevPoints,w=v.totalLength;return Gt.createElement(xC,{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],Y=_0(G.x,U.x),X=_0(G.y,U.y);return Nj(Nj({},U),{},{x:Y(A),y:X(A)})}if(g){var ae=_0(x*2,U.x),le=_0(y/2,U.y);return Nj(Nj({},U),{},{x:ae(A),y:le(A)})}return Nj(Nj({},U),{},{x:U.x,y:U.y})});return i.renderCurveStatically(I,r,a)}var P=_0(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||!rB(d,l))?this.renderCurveWithAnimation(r,a):this.renderCurveStatically(l,r,a)}},{key:"render",value:function(){var r,a=this.props,i=a.hide,l=a.dot,o=a.points,c=a.className,d=a.xAxis,u=a.yAxis,h=a.top,m=a.left,f=a.width,g=a.height,x=a.isAnimationActive,y=a.id;if(i||!o||!o.length)return null;var v=this.state.isAnimationFinished,b=o.length===1,w=sd("recharts-line",c),S=d&&d.allowDataOverflow,A=u&&u.allowDataOverflow,E=S||A,I=Gc(y)?this.id:y,P=(r=cl(l,!1))!==null&&r!==void 0?r:{r:3,strokeWidth:2},R=P.r,D=R===void 0?3:R,O=P.strokeWidth,U=O===void 0?2:O,W=ZWt(l)?l:{},V=W.clipDot,G=V===void 0?!0:V,Y=D*2+U;return Gt.createElement(Su,{className:w},S||A?Gt.createElement("defs",null,Gt.createElement("clipPath",{id:"clipPath-".concat(I)},Gt.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&&Gt.createElement("clipPath",{id:"clipPath-dots-".concat(I)},Gt.createElement("rect",{x:m-Y/2,y:h-Y/2,width:f+Y,height:g+Y}))):null,!b&&this.renderCurve(E,I),this.renderErrorBar(E,I),(b||l)&&this.renderDots(E,G,I),(!x||v)&&B4.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(F$(r),[0]):r,l=[],o=0;o=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function $Ln(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 v8(){return v8=Object.assign?Object.assign.bind():function(s){for(var t=1;t0||!rB(u,l)||!rB(h,o))?this.renderAreaWithAnimation(r,a):this.renderAreaStatically(l,o,r,a)}},{key:"render",value:function(){var r,a=this.props,i=a.hide,l=a.dot,o=a.points,c=a.className,d=a.top,u=a.left,h=a.xAxis,m=a.yAxis,f=a.width,g=a.height,x=a.isAnimationActive,y=a.id;if(i||!o||!o.length)return null;var v=this.state.isAnimationFinished,b=o.length===1,w=sd("recharts-area",c),S=h&&h.allowDataOverflow,A=m&&m.allowDataOverflow,E=S||A,I=Gc(y)?this.id:y,P=(r=cl(l,!1))!==null&&r!==void 0?r:{r:3,strokeWidth:2},R=P.r,D=R===void 0?3:R,O=P.strokeWidth,U=O===void 0?2:O,W=ZWt(l)?l:{},V=W.clipDot,G=V===void 0?!0:V,Y=D*2+U;return Gt.createElement(Su,{className:w},S||A?Gt.createElement("defs",null,Gt.createElement("clipPath",{id:"clipPath-".concat(I)},Gt.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&&Gt.createElement("clipPath",{id:"clipPath-dots-".concat(I)},Gt.createElement("rect",{x:u-Y/2,y:d-Y/2,width:f+Y,height:g+Y}))):null,b?null:this.renderArea(E,I),(l||b)&&this.renderDots(E,G,I),(!x||v)&&B4.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);cXt=Iw;y4(Iw,"displayName","Area");y4(Iw,"defaultProps",{stroke:"#3182bd",fill:"#3182bd",fillOpacity:.6,xAxisId:0,yAxisId:0,legendType:"line",connectNulls:!1,points:[],dot:!1,activeDot:!0,hide:!1,isAnimationActive:!j6.isSsr,animationBegin:0,animationDuration:1500,animationEasing:"ease"});y4(Iw,"getBaseValue",function(s,t,n,r){var a=s.layout,i=s.baseValue,l=t.props.baseValue,o=l??i;if(yi(o)&&typeof o=="number")return o;var c=a==="horizontal"?r:n,d=c.scale.domain();if(c.type==="number"){var u=Math.max(d[0],d[1]),h=Math.min(d[0],d[1]);return o==="dataMin"?h:o==="dataMax"||u<0?u:Math.max(Math.min(d[0],d[1]),0)}return o==="dataMin"?d[0]:o==="dataMax"?d[1]:d[0]});y4(Iw,"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=cXt.getBaseValue(t,n,r,a),y=f==="horizontal",v=!1,b=h.map(function(S,A){var E;g?E=d[u+A]:(E=ay(S,c),Array.isArray(E)?v=!0:E=[x,E]);var I=E[1]==null||g&&ay(S,c)==null;return y?{x:yMe({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:yMe({axis:a,ticks:l,bandSize:o,entry:S,index:A}),value:E,payload:S}}),w;return g||v?w=b.map(function(S){var A=Array.isArray(S.value)?S.value[0]:null;return y?{x:S.x,y:A!=null&&S.y!=null?a.scale(A):null}:{x:A!=null?r.scale(A):null,y:S.y}}):w=y?a.scale(x):r.scale(x),YM({points:b,baseLine:w,layout:f,isRange:v},m)});y4(Iw,"renderDotItem",function(s,t){var n;if(Gt.isValidElement(s))n=Gt.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=dXt(t,BLn);n=Gt.createElement(Eie,v8({},i,{key:a,className:r}))}return n});function oW(s){"@babel/helpers - typeof";return oW=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},oW(s)}function YLn(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 D6n(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 F6n(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function O6n(s,t){for(var n=0;ns.length)&&(t=s.length);for(var n=0,r=new Array(t);n0?l:t&&t.length&&yi(a)&&yi(i)?t.slice(a,i+1):[]};function SXt(s){return s==="number"?[0,"auto"]:void 0}var xYe=function(t,n,r,a){var i=t.graphicalItems,l=t.tooltipAxis,o=ZRe(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=qTe(f,l.dataKey,a)}else m=h&&h[r]||o[r];return m?[].concat(dW(c),[lZt(d,m)]):c},[])},qkt=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=r4n(l,o,d,c);if(u>=0&&d){var h=d[u]&&d[u].value,m=xYe(t,n,u,h),f=X6n(r,o,u,i);return{activeTooltipIndex:u,activeLabel:h,activePayload:m,activeCoordinate:f}}return null},Q6n=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=sZt(u,i);return r.reduce(function(g,x){var y,v=x.type.defaultProps!==void 0?ba(ba({},x.type.defaultProps),x.props):x.props,b=v.type,w=v.dataKey,S=v.allowDataOverflow,A=v.allowDuplicatedCategory,E=v.scale,I=v.ticks,P=v.includeHidden,R=v[l];if(g[R])return g;var D=ZRe(t.data,{graphicalItems:a.filter(function(J){var ce,_e=l in J.props?J.props[l]:(ce=J.type.defaultProps)===null||ce===void 0?void 0:ce[l];return _e===R}),dataStartIndex:c,dataEndIndex:d}),O=D.length,U,W,V;N6n(v.domain,S,b)&&(U=TKe(v.domain,null,S),f&&(b==="number"||E!=="auto")&&(V=Uee(D,w,"category")));var G=SXt(b);if(!U||U.length===0){var Y,X=(Y=v.domain)!==null&&Y!==void 0?Y:G;if(w){if(U=Uee(D,w,b),b==="category"&&f){var ae=Kgn(U);A&&ae?(W=U,U=PMe(0,O)):A||(U=cNt(X,U,x).reduce(function(J,ce){return J.indexOf(ce)>=0?J:[].concat(dW(J),[ce])},[]))}else if(b==="category")A?U=U.filter(function(J){return J!==""&&!Gc(J)}):U=cNt(X,U,x).reduce(function(J,ce){return J.indexOf(ce)>=0||ce===""||Gc(ce)?J:[].concat(dW(J),[ce])},[]);else if(b==="number"){var le=c4n(D,a.filter(function(J){var ce,_e,he=l in J.props?J.props[l]:(ce=J.type.defaultProps)===null||ce===void 0?void 0:ce[l],ue="hide"in J.props?J.props.hide:(_e=J.type.defaultProps)===null||_e===void 0?void 0:_e.hide;return he===R&&(P||!ue)}),w,i,u);le&&(U=le)}f&&(b==="number"||E!=="auto")&&(V=Uee(D,w,"category"))}else f?U=PMe(0,O):o&&o[R]&&o[R].hasStack&&b==="number"?U=m==="expand"?[0,1]:oZt(o[R].stackGroups,c,d):U=tZt(D,a.filter(function(J){var ce=l in J.props?J.props[l]:J.type.defaultProps[l],_e="hide"in J.props?J.props.hide:J.type.defaultProps.hide;return ce===R&&(P||!_e)}),b,u,!0);if(b==="number")U=fYe(h,U,R,i,I),X&&(U=TKe(X,U,S));else if(b==="category"&&X){var ne=X,te=U.every(function(J){return ne.indexOf(J)>=0});te&&(U=ne)}}return ba(ba({},g),{},uc({},R,ba(ba({},v),{},{axisType:i,domain:U,categoricalDomain:V,duplicateDomain:W,originalDomain:(y=v.domain)!==null&&y!==void 0?y:G,isCategorical:f,layout:u})))},{})},J6n=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=ZRe(t.data,{graphicalItems:r,dataStartIndex:c,dataEndIndex:d}),f=m.length,g=sZt(u,i),x=-1;return r.reduce(function(y,v){var b=v.type.defaultProps!==void 0?ba(ba({},v.type.defaultProps),v.props):v.props,w=b[l],S=SXt("number");if(!y[w]){x++;var A;return g?A=PMe(0,f):o&&o[w]&&o[w].hasStack?(A=oZt(o[w].stackGroups,c,d),A=fYe(h,A,w,i)):(A=TKe(S,tZt(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=fYe(h,A,w,i)),ba(ba({},y),{},uc({},w,ba(ba({axisType:i},a.defaultProps),{},{hide:!0,orientation:y2(K6n,"".concat(i,".").concat(x%2),null),domain:A,originalDomain:S,isCategorical:g,layout:u})))}return y},{})},eRn=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=v2(u,i),f={};return m&&m.length?f=Q6n(t,{axes:m,graphicalItems:l,axisType:a,axisIdKey:h,stackGroups:o,dataStartIndex:c,dataEndIndex:d}):l&&l.length&&(f=J6n(t,{Axis:i,graphicalItems:l,axisType:a,axisIdKey:h,stackGroups:o,dataStartIndex:c,dataEndIndex:d})),f},tRn=function(t){var n=CP(t),r=NE(n,!1,!0);return{tooltipTicks:r,orderedTooltipTicks:oat(r,function(a){return a.coordinate}),tooltipAxis:n,tooltipAxisBandSize:vMe(n,r)}},Vkt=function(t){var n=t.children,r=t.defaultShowTooltip,a=$j(n,JG),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}},sRn=function(t){return!t||!t.length?!1:t.some(function(n){var r=VE(n&&n.type);return r&&r.indexOf("Bar")>=0})},Hkt=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"}},nRn=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=$j(h,JG),g=$j(h,CV),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}),y=Object.keys(l).reduce(function(A,E){var I=l[E],P=I.orientation;return!I.mirror&&!I.hide?ba(ba({},A),{},uc({},P,y2(A,"".concat(P))+I.height)):A},{top:m.top||0,bottom:m.bottom||0}),v=ba(ba({},y),x),b=v.bottom;f&&(v.bottom+=f.props.height||JG.defaultProps.height),g&&n&&(v=o4n(v,a,r,n));var w=d-v.left-v.right,S=u-v.top-v.bottom;return ba(ba({brushBottom:b},v),{},{width:Math.max(w,0),height:Math.max(S,0)})},rRn=function(t,n){if(n==="xAxis")return t[n].width;if(n==="yAxis")return t[n].height},XRe=function(t){var n=t.chartName,r=t.GraphicalChild,a=t.defaultTooltipEventType,i=a===void 0?"axis":a,l=t.validateTooltipEventTypes,o=l===void 0?["axis"]:l,c=t.axisComponents,d=t.legendContent,u=t.formatAxisMap,h=t.defaultProps,m=function(v,b){var w=b.graphicalItems,S=b.stackGroups,A=b.offset,E=b.updateId,I=b.dataStartIndex,P=b.dataEndIndex,R=v.barSize,D=v.layout,O=v.barGap,U=v.barCategoryGap,W=v.maxBarSize,V=Hkt(D),G=V.numericAxisName,Y=V.cateAxisName,X=sRn(w),ae=[];return w.forEach(function(le,ne){var te=ZRe(v.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,_e=J.maxBarSize,he=J["".concat(G,"Id")],ue=J["".concat(Y,"Id")],ve={},Ee=c.reduce(function(Xe,at){var rt=b["".concat(at.axisType,"Map")],Ke=J["".concat(at.axisType,"Id")];rt&&rt[Ke]||at.axisType==="zAxis"||iB();var Je=rt[Ke];return ba(ba({},Xe),{},uc(uc({},at.axisType,Je),"".concat(at.axisType,"Ticks"),NE(Je)))},ve),Se=Ee[Y],Le=Ee["".concat(Y,"Ticks")],Fe=S&&S[he]&&S[he].hasStack&&y4n(le,S[he].stackGroups),ke=VE(le.type).indexOf("Bar")>=0,Be=vMe(Se,Le),Ne=[],Ae=X&&a4n({barSize:R,stackGroups:S,totalSize:rRn(Ee,Y)});if(ke){var Ce,Ve,ze=Gc(_e)?W:_e,qe=(Ce=(Ve=vMe(Se,Le,!0))!==null&&Ve!==void 0?Ve:ze)!==null&&Ce!==void 0?Ce:0;Ne=i4n({barGap:O,barCategoryGap:U,bandSize:qe!==Be?qe:Be,sizeList:Ae[ue],maxBarSize:ze}),qe!==Be&&(Ne=Ne.map(function(Xe){return ba(ba({},Xe),{},{position:ba(ba({},Xe.position),{},{offset:Xe.position.offset-qe/2})})}))}var dt=le&&le.type&&le.type.getComposedData;dt&&ae.push({props:ba(ba({},dt(ba(ba({},Ee),{},{displayedData:te,props:v,dataKey:ce,item:le,bandSize:Be,barPosition:Ne,offset:A,stackedData:Fe,layout:D,dataStartIndex:I,dataEndIndex:P}))),{},uc(uc(uc({key:le.key||"item-".concat(ne)},G,Ee[G]),Y,Ee[Y]),"animationId",E)),childIndex:ixn(le,v.children),item:le})}),ae},f=function(v,b){var w=v.props,S=v.dataStartIndex,A=v.dataEndIndex,E=v.updateId;if(!njt({props:w}))return null;var I=w.children,P=w.layout,R=w.stackOffset,D=w.data,O=w.reverseStackOrder,U=Hkt(P),W=U.numericAxisName,V=U.cateAxisName,G=v2(I,r),Y=g4n(D,G,"".concat(W,"Id"),"".concat(V,"Id"),R,O),X=c.reduce(function(J,ce){var _e="".concat(ce.axisType,"Map");return ba(ba({},J),{},uc({},_e,eRn(w,ba(ba({},ce),{},{graphicalItems:G,stackGroups:ce.axisType===W&&Y,dataStartIndex:S,dataEndIndex:A}))))},{}),ae=nRn(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")],ne=tRn(le),te=m(w,ba(ba({},X),{},{dataStartIndex:S,dataEndIndex:A,updateId:E,graphicalItems:G,stackGroups:Y,offset:ae}));return ba(ba({formattedGraphicalItems:te,graphicalItems:G,offset:ae,stackGroups:Y},ne),X)},g=function(y){function v(b){var w,S,A;return F6n(this,v),A=B6n(this,v,[b]),uc(A,"eventEmitterSymbol",Symbol("rechartsEventEmitter")),uc(A,"accessibilityManager",new j6n),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=axn(E),P=y2(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&&C9e.emit(A9e,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,Y=A.state,X=Y.offset,ae=Y.tooltipTicks;if(!X)return;if(typeof R=="function")G=R(ae,E);else if(R==="value"){G=-1;for(var le=0;le=0){var Fe,ke;if(W.dataKey&&!W.allowDuplicatedCategory){var Be=typeof W.dataKey=="function"?Le:"payload.".concat(W.dataKey.toString());Fe=qTe(le,Be,G),ke=ne&&te&&qTe(te,Be,G)}else Fe=le==null?void 0:le[V],ke=ne&&te&&te[V];if(ue||he){var Ne=E.props.activeIndex!==void 0?E.props.activeIndex:V;return[j.cloneElement(E,ba(ba(ba({},R.props),Ee),{},{activeIndex:Ne})),null,null]}if(!Gc(Fe))return[Se].concat(dW(A.renderActivePoints({item:R,activePoint:Fe,basePoint:ke,childIndex:V,isRange:ne})))}else{var Ae,Ce=(Ae=A.getItemByXY(A.state.activeCoordinate))!==null&&Ae!==void 0?Ae:{graphicalItem:Se},Ve=Ce.graphicalItem,ze=Ve.item,qe=ze===void 0?E:ze,dt=Ve.childIndex,Xe=ba(ba(ba({},R.props),Ee),{},{activeIndex:dt});return[j.cloneElement(qe,Xe),null,null]}return ne?[Se,null,null]:[Se,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:Zde,once:!0},ReferenceArea:{handler:A.renderReferenceElement},ReferenceLine:{handler:Zde},ReferenceDot:{handler:A.renderReferenceElement},XAxis:{handler:Zde},YAxis:{handler:Zde},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:YB("recharts"),"-clip"),A.throttleTriggeredAfterMouseMove=JKt(A.triggeredAfterMouseMove,(S=b.throttleDelay)!==null&&S!==void 0?S:1e3/60),A.state={},A}return q6n(v,y),z6n(v,[{key:"componentDidMount",value:function(){var w,S;this.addListener(),this.accessibilityManager.setDetails({container:this.container,offset:{left:(w=this.props.margin.left)!==null&&w!==void 0?w:0,top:(S=this.props.margin.top)!==null&&S!==void 0?S:0},coordinateList:this.state.tooltipTicks,mouseHandlerCallback:this.triggeredAfterMouseMove,layout:this.props.layout}),this.displayDefaultTooltip()}},{key:"displayDefaultTooltip",value:function(){var w=this.props,S=w.children,A=w.data,E=w.height,I=w.layout,P=$j(S,Cg);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=xYe(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},Y=this.state.formattedGraphicalItems.find(function(ae){var le=ae.item;return le.type.name==="Scatter"});Y&&(G=ba(ba({},G),Y.props.points[R].tooltipPosition),O=Y.props.points[R].tooltipPayload);var X={activeTooltipIndex:R,isTooltipActive:!0,activeLabel:D,activePayload:O,activeCoordinate:G};this.setState(X),this.renderCursor(P),this.accessibilityManager.setIndex(R)}}}},{key:"getSnapshotBeforeUpdate",value:function(w,S){if(!this.props.accessibilityLayer)return null;if(this.state.tooltipTicks!==S.tooltipTicks&&this.accessibilityManager.setDetails({coordinateList:this.state.tooltipTicks}),this.props.layout!==w.layout&&this.accessibilityManager.setDetails({layout:this.props.layout}),this.props.margin!==w.margin){var 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){HWe([$j(w.children,Cg)],[$j(this.props.children,Cg)])||this.displayDefaultTooltip()}},{key:"componentWillUnmount",value:function(){this.removeListener(),this.throttleTriggeredAfterMouseMove.cancel()}},{key:"getTooltipEventType",value:function(){var w=$j(this.props.children,Cg);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=PNn(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=qkt(this.state,this.props.data,this.props.layout,R);if(W!=="axis"&&O&&U){var G=CP(O).scale,Y=CP(U).scale,X=G&&G.invert?G.invert(I.chartX):null,ae=Y&&Y.invert?Y.invert(I.chartY):null;return ba(ba({},I),{},{xValue:X,yValue:ae},V)}return V?ba(ba({},I),V):null}},{key:"inRange",value:function(w,S){var 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=CP(U);return hNt({x:I,y:P},V)}return null}},{key:"parseEventsOfWrapper",value:function(){var w=this.props.children,S=this.getTooltipEventType(),A=$j(w,Cg),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=VTe(this.props,this.handleOuterEvent);return ba(ba({},I),E)}},{key:"addListener",value:function(){C9e.on(A9e,this.handleReceiveSyncEvent)}},{key:"removeListener",value:function(){C9e.removeListener(A9e,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:Kr,color:"text-foreground"},{label:"Total Emails Sent",value:l,icon:Yn,color:"text-green-600"},{label:"Avg Open Rate",value:`${h}%`,icon:Ca,color:"text-blue-600"},{label:"Avg Click Rate",value:`${m}%`,icon:cb,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),y=x.slice(0,6).map(b=>({name:b.name,value:b.sent})),v=a.map(b=>{var w;return{name:b.name.length>20?b.name.slice(0,20)+"…":b.name,agent:((w=i.get(b.user_id))==null?void 0:w.name)||"Unknown",openRate:b.sent_count>0?+(b.open_count/b.sent_count*100).toFixed(1):0,clickRate:b.sent_count>0?+(b.click_count/b.sent_count*100).toFixed(1):0,sent:b.sent_count,date:b.sent_at?en(new Date(b.sent_at),"MMM d"):""}});return e.jsx("div",{className:"space-y-6",children:a.length===0?e.jsx(je,{children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center py-12 text-center",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 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(Ie,{className:"p-4 text-center",children:[e.jsx(b.icon,{className:`h-5 w-5 mx-auto mb-1 ${b.color}`}),e.jsx("p",{className:"text-2xl font-bold",children:b.value}),e.jsx("p",{className:"text-xs text-muted-foreground",children:b.label})]})},b.label))}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-base",children:"Open & Click Rates by Campaign"})}),e.jsx(Ie,{children:e.jsx("div",{className:"h-[280px]",children:e.jsx(N_,{width:"100%",height:"100%",children:e.jsxs(LK,{data:v,children:[e.jsx(Ab,{dataKey:"date",fontSize:11}),e.jsx(Eb,{fontSize:11,unit:"%"}),e.jsx(Cg,{formatter:b=>`${b}%`}),e.jsx(Fw,{dataKey:"openRate",fill:"hsl(220, 70%, 50%)",name:"Open Rate",radius:[2,2,0,0]}),e.jsx(Fw,{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(Ie,{children:e.jsx("div",{className:"h-[280px]",children:e.jsx(N_,{width:"100%",height:"100%",children:e.jsxs(CXt,{children:[e.jsx(f3,{data:y,dataKey:"value",nameKey:"name",cx:"50%",cy:"50%",outerRadius:100,label:({name:b,percent:w})=>`${b} (${(w*100).toFixed(0)}%)`,fontSize:11,children:y.map((b,w)=>e.jsx(ZB,{fill:Gkt[w%Gkt.length]},w))}),e.jsx(Cg,{})]})})})})]})]}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-base",children:"Send Volume Trend"})}),e.jsx(Ie,{children:e.jsx("div",{className:"h-[240px]",children:e.jsx(N_,{width:"100%",height:"100%",children:e.jsxs(Hat,{data:v,children:[e.jsx(Ab,{dataKey:"date",fontSize:11}),e.jsx(Eb,{fontSize:11}),e.jsx(Cg,{}),e.jsx(DL,{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(Ie,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b text-left text-muted-foreground",children:[e.jsx("th",{className:"pb-2 font-medium",children:"Agent"}),e.jsx("th",{className:"pb-2 font-medium text-center",children:"Campaigns"}),e.jsx("th",{className:"pb-2 font-medium text-center",children:"Sent"}),e.jsx("th",{className:"pb-2 font-medium text-center",children:"Opens"}),e.jsx("th",{className:"pb-2 font-medium text-center",children:"Clicks"}),e.jsx("th",{className:"pb-2 font-medium text-center",children:"Open Rate"})]})}),e.jsx("tbody",{children:x.map(b=>e.jsxs("tr",{className:"border-b last:border-0 hover:bg-muted/30",children:[e.jsx("td",{className:"py-2.5 font-medium",children:b.name}),e.jsx("td",{className:"py-2.5 text-center",children:b.campaigns}),e.jsx("td",{className:"py-2.5 text-center",children:b.sent}),e.jsx("td",{className:"py-2.5 text-center",children:b.opens}),e.jsx("td",{className:"py-2.5 text-center",children:b.clicks}),e.jsx("td",{className:"py-2.5 text-center",children:e.jsxs($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(Ie,{children:e.jsx("div",{className:"space-y-2",children:[...a].sort((b,w)=>{const S=b.sent_count>0?b.open_count/b.sent_count:0;return(w.sent_count>0?w.open_count/w.sent_count:0)-S}).slice(0,10).map((b,w)=>{const S=b.sent_count>0?(b.open_count/b.sent_count*100).toFixed(1):"0.0",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?en(new Date(b.sent_at),"MMM d, yyyy"):""," · ",b.sent_count," sent"]})]}),e.jsxs("div",{className:"flex gap-3 text-xs",children:[e.jsxs($e,{variant:"outline",className:"gap-1",children:[e.jsx(Ca,{className:"h-3 w-3"})," ",S,"%"]}),e.jsxs($e,{variant:"outline",className:"gap-1",children:[e.jsx(cb,{className:"h-3 w-3"})," ",A,"%"]})]})]},b.id)})})})]})]})})}const iRn=()=>{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 y=new Map;for(const A of m||[])y.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=y.get(A.app_slug);E&&(E.installs+=1,A.enabled&&(E.enabled+=1))}for(const A of x){const E=y.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 v=new Map;for(const A of f){if(!A.enabled)continue;const E=v.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),v.set(A.user_id,E)}for(const A of x){const E=v.get(A.user_id);E&&(E.events_30d+=1,A.event_type==="lead_capture"&&(E.leads_30d+=1))}const b=Array.from(v.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=v.get(E.id);I&&(I.name=E.name,I.email=E.email)}}const w=Array.from(y.values()),S=Array.from(v.values()).sort((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(Ie,{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-4",children:[e.jsxs(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(dl,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ie,{children:[e.jsx("div",{className:"text-2xl font-bold",children:o.installs}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Apps turned on across all agents"})]})]}),e.jsxs(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(Ie,{children:[e.jsx("div",{className:"text-2xl font-bold",children:o.activeAgents}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"At least one app enabled"})]})]}),e.jsxs(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(Ca,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ie,{children:[e.jsx("div",{className:"text-2xl font-bold",children:o.impressions30d}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Widget views on lead sites"})]})]}),e.jsxs(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(mn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ie,{children:[e.jsx("div",{className:"text-2xl font-bold",children:o.leads30d}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Total submissions"})]})]})]}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{children:"App Performance (last 30 days)"})}),e.jsx(Ie,{children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"App"}),e.jsx(Dt,{className:"text-right",children:"Installs"}),e.jsx(Dt,{className:"text-right",children:"Enabled"}),e.jsx(Dt,{className:"text-right",children:"Impressions"}),e.jsx(Dt,{className:"text-right",children:"Expands"}),e.jsx(Dt,{className:"text-right",children:"CTA Clicks"}),e.jsx(Dt,{className:"text-right",children:"Leads"}),e.jsx(Dt,{className:"text-right",children:"Conv. Rate"})]})}),e.jsxs(fi,{children:[r.map(u=>{const h=u.impressions>0?(u.lead_captures/u.impressions*100).toFixed(1):"—";return e.jsxs(En,{children:[e.jsx(_t,{className:"font-medium",children:u.app_name}),e.jsx(_t,{className:"text-right",children:u.installs}),e.jsx(_t,{className:"text-right",children:u.enabled}),e.jsx(_t,{className:"text-right",children:u.impressions}),e.jsx(_t,{className:"text-right",children:u.expands}),e.jsx(_t,{className:"text-right",children:u.cta_clicks}),e.jsx(_t,{className:"text-right font-semibold",children:u.lead_captures}),e.jsx(_t,{className:"text-right text-muted-foreground",children:h==="—"?"—":`${h}%`})]},u.app_slug)}),r.length===0&&e.jsx(En,{children:e.jsx(_t,{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(Ie,{children:[e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Agent"}),e.jsx(Dt,{children:"Email"}),e.jsx(Dt,{children:"Apps Enabled"}),e.jsx(Dt,{className:"text-right",children:"Events (30d)"}),e.jsx(Dt,{className:"text-right",children:"Leads (30d)"})]})}),e.jsxs(fi,{children:[i.slice(0,100).map(u=>e.jsxs(En,{children:[e.jsx(_t,{className:"font-medium",children:u.name||"—"}),e.jsx(_t,{className:"text-muted-foreground",children:u.email||"—"}),e.jsx(_t,{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(_t,{className:"text-right",children:u.events_30d}),e.jsx(_t,{className:"text-right font-semibold",children:u.leads_30d})]},u.user_id)),i.length===0&&e.jsx(En,{children:e.jsx(_t,{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."]})]})]})]})},oRn=()=>{const[s,t]=j.useState([]),[n,r]=j.useState([]),[a,i]=j.useState({}),[l,o]=j.useState(!0);j.useEffect(()=>{c()},[]);const c=async()=>{o(!0);try{const[{data:h},{data:m}]=await Promise.all([q.rpc("get_extension_usage_summary"),q.from("extension_usage_events").select("id, user_id, action, metadata, created_at").order("created_at",{ascending:!1}).limit(50)]),f=h||[],g=m||[];t(f),r(g);const x=Array.from(new Set(g.map(y=>y.user_id)));if(x.length){const{data:y}=await q.from("profiles").select("id, name, email").in("id",x),v={};(y||[]).forEach(b=>{v[b.id]={name:b.name,email:b.email}}),i(v)}}finally{o(!1)}},d=s.reduce((h,m)=>({users:h.users+1,contacts:h.contacts+Number(m.contacts_saved||0),listings:h.listings+Number(m.listings_imported||0),activities:h.activities+Number(m.activities_logged||0),events:h.events+Number(m.total_events||0)}),{users:0,contacts:0,listings:0,activities:0,events:0});if(l)return e.jsx(je,{children:e.jsx(Ie,{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})});const u=h=>{switch(h){case"contact_saved":return"Contact saved";case"listing_imported":return"Listing imported";case"activity_logged":return"Activity logged";case"template_used":return"Template used";case"paired":return"Extension paired";default:return h}};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-5",children:[e.jsxs(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(Ie,{children:[e.jsx("div",{className:"text-2xl font-bold",children:d.users}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Using extension"})]})]}),e.jsxs(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(Fz,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ie,{children:[e.jsx("div",{className:"text-2xl font-bold",children:d.events}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"All events"})]})]}),e.jsxs(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(Ie,{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(Ie,{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(eo,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Ie,{children:e.jsx("div",{className:"text-2xl font-bold",children:d.activities})})]})]}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{children:"Users by Extension Activity"})}),e.jsx(Ie,{children:s.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-8 text-center",children:"No extension usage yet. Once agents install and use the Chrome Extension, their activity will appear here."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"User"}),e.jsx(Dt,{className:"text-right",children:"Total"}),e.jsx(Dt,{className:"text-right",children:"Contacts"}),e.jsx(Dt,{className:"text-right",children:"Listings"}),e.jsx(Dt,{className:"text-right",children:"Activities"}),e.jsx(Dt,{children:"First Used"}),e.jsx(Dt,{children:"Last Used"})]})}),e.jsx(fi,{children:s.map(h=>e.jsxs(En,{children:[e.jsxs(_t,{children:[e.jsx("div",{className:"font-medium",children:h.name||"—"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:h.email})]}),e.jsx(_t,{className:"text-right font-medium",children:h.total_events}),e.jsx(_t,{className:"text-right",children:h.contacts_saved}),e.jsx(_t,{className:"text-right",children:h.listings_imported}),e.jsx(_t,{className:"text-right",children:h.activities_logged}),e.jsx(_t,{className:"text-xs text-muted-foreground",children:h.first_event_at?en(new Date(h.first_event_at),"MMM d, yyyy"):"—"}),e.jsx(_t,{className:"text-xs text-muted-foreground",children:h.last_event_at?en(new Date(h.last_event_at),"MMM d, h:mm a"):"—"})]},h.user_id))})]})})})]}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{children:"Recent Activity"})}),e.jsx(Ie,{children:n.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No recent events."}):e.jsx("div",{className:"space-y-2",children:n.map(h=>{const m=a[h.user_id];return e.jsxs("div",{className:"flex items-center justify-between border-b pb-2 last:border-0",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx($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:en(new Date(h.created_at),"MMM d, h:mm a")})]},h.id)})})})]})]})},lRn=()=>e.jsx(Vs,{title:"Analytics",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Analytics & Activity"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Platform-wide usage statistics and user activity"})]}),e.jsxs(ha,{defaultValue:"analytics",className:"space-y-4",children:[e.jsxs(ma,{children:[e.jsx(Zt,{value:"analytics",children:"Analytics"}),e.jsx(Zt,{value:"website-apps",children:"Website Apps"}),e.jsx(Zt,{value:"extension",children:"Chrome Extension"}),e.jsx(Zt,{value:"content",children:"Content"}),e.jsx(Zt,{value:"email-campaigns",children:"Email Campaigns"}),e.jsx(Zt,{value:"activity",children:"Activity"}),e.jsx(Zt,{value:"shares",children:"Shares"})]}),e.jsx(Xt,{value:"analytics",className:"space-y-4",children:e.jsx(mmn,{})}),e.jsx(Xt,{value:"website-apps",className:"space-y-4",children:e.jsx(iRn,{})}),e.jsx(Xt,{value:"extension",className:"space-y-4",children:e.jsx(oRn,{})}),e.jsx(Xt,{value:"content",className:"space-y-4",children:e.jsx(pmn,{})}),e.jsx(Xt,{value:"email-campaigns",className:"space-y-4",children:e.jsx(aRn,{})}),e.jsx(Xt,{value:"activity",className:"space-y-4",children:e.jsx(hmn,{})}),e.jsx(Xt,{value:"shares",className:"space-y-4",children:e.jsx(FWt,{})})]})]})});function cRn(){const s=Wt(),[t,n]=j.useState(!1),[r,a]=j.useState(null),[i,l]=j.useState({title:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,category_id:""}),[o,c]=j.useState(null),[d,u]=j.useState(""),[h,m]=j.useState([]),[f,g]=j.useState([]),[x,y]=j.useState([]),[v,b]=j.useState(!1),[w,S]=j.useState(null),[A,E]=j.useState(""),{data:I,isLoading:P}=st({queryKey:["brokerage-resources"],queryFn:async()=>{const{data:ke,error:Be}=await q.from("brokerage_resources").select("*").order("publish_date",{ascending:!1});if(Be)throw Be;return ke}}),{data:R}=st({queryKey:["brokerage-resource-pdfs"],queryFn:async()=>{const{data:ke,error:Be}=await q.from("brokerage_resource_pdfs").select("*").order("sort_order",{ascending:!0});if(Be)throw Be;return ke}}),{data:D}=st({queryKey:["brokerage-resource-videos"],queryFn:async()=>{const{data:ke,error:Be}=await q.from("brokerage_resource_videos").select("*").order("sort_order",{ascending:!0});if(Be)throw Be;return ke}}),{data:O}=st({queryKey:["brokerage-resource-links"],queryFn:async()=>{const{data:ke,error:Be}=await q.from("brokerage_resource_links").select("*").order("sort_order",{ascending:!0});if(Be)throw Be;return ke}}),{data:U,isLoading:W}=st({queryKey:["brokerage-resource-categories"],queryFn:async()=>{const{data:ke,error:Be}=await q.from("brokerage_resource_categories").select("*").order("sort_order",{ascending:!0});if(Be)throw Be;return ke}}),V=()=>{l({title:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,category_id:""}),c(null),u(""),m([]),g([]),y([]),a(null),E("")},G=ke=>{a(ke),l({title:ke.title,description:ke.description||"",publish_date:ke.publish_date.split("T")[0],is_published:ke.is_published,category_id:ke.category_id||""}),u(ke.preview_image_url||""),E("");const Be=(R==null?void 0:R.filter(Ce=>Ce.resource_id===ke.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 Ne=(D==null?void 0:D.filter(Ce=>Ce.resource_id===ke.id))||[];g(Ne.map(Ce=>({id:Ce.id,title:Ce.title,video_url:Ce.video_url,sort_order:Ce.sort_order})));const Ae=(O==null?void 0:O.filter(Ce=>Ce.resource_id===ke.id))||[];y(Ae.map(Ce=>({id:Ce.id,title:Ce.title,canva_share_link:Ce.canva_share_link,sort_order:Ce.sort_order}))),n(!0)},Y=ke=>{var Ne;const Be=(Ne=ke.target.files)==null?void 0:Ne[0];Be&&(c(Be),u(URL.createObjectURL(Be)))},X=()=>{m([...h,{name:"",file_url:"",sort_order:h.length}])},ae=ke=>{m(h.filter((Be,Ne)=>Ne!==ke))},le=(ke,Be,Ne)=>{const Ae=[...h];if(Be==="file"&&Ne instanceof File){const Ce=Ne.name.replace(/\.[^/.]+$/,"");Ae[ke]={...Ae[ke],file:Ne,file_size:Ne.size,name:Ae[ke].name||Ce}}else Ae[ke]={...Ae[ke],[Be]:Ne};m(Ae)},ne=()=>{g([...f,{title:"",video_url:"",sort_order:f.length}])},te=ke=>{g(f.filter((Be,Ne)=>Ne!==ke))},J=(ke,Be,Ne)=>{const Ae=[...f];Be==="file"&&Ne instanceof File?Ae[ke]={...Ae[ke],file:Ne}:Ae[ke]={...Ae[ke],[Be]:Ne},g(Ae)},ce=()=>{y([...x,{title:"",canva_share_link:"",sort_order:x.length}])},_e=ke=>{y(x.filter((Be,Ne)=>Ne!==ke))},he=(ke,Be,Ne)=>{const Ae=[...x];Ae[ke]={...Ae[ke],[Be]:Ne},y(Ae)},ue=async(ke,Be)=>{try{const Ne=await q.functions.invoke("bunny-upload",{body:{action:"create",title:ke.name}});if(Ne.error)throw Ne.error;const{videoId:Ae,uploadUrl:Ce,libraryId:Ve}=Ne.data,ze=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:Ae,libraryId:Ve}});if(ze.error)throw ze.error;const{uploadUrl:qe,apiKey:dt}=ze.data,Xe=new XMLHttpRequest;return Xe.open("PUT",qe,!0),Xe.setRequestHeader("AccessKey",dt),Xe.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)=>{Xe.onload=()=>Xe.status>=200&&Xe.status<300?at():rt(new Error("Upload failed")),Xe.onerror=()=>rt(new Error("Upload failed")),Xe.send(ke)}),`https://iframe.mediadelivery.net/embed/${Ve}/${Ae}`}catch(Ne){throw console.error("Bunny upload error:",Ne),Ne}},ve=mt({mutationFn:async ke=>{const{data:Be,error:Ne}=await q.from("brokerage_resource_categories").insert({name:ke,sort_order:(U==null?void 0:U.length)||0}).select().single();if(Ne)throw Ne;return Be},onSuccess:ke=>{s.invalidateQueries({queryKey:["brokerage-resource-categories"]}),l({...i,category_id:ke.id}),E(""),re.success("Category created")},onError:ke=>{re.error("Failed to create category: "+ke.message)}}),Ee=mt({mutationFn:async()=>{b(!0);let ke=(r==null?void 0:r.preview_image_url)||null;if(o){const Ae=o.name.split(".").pop(),Ce=`${Date.now()}.${Ae}`,{error:Ve}=await q.storage.from("brokerage-resources").upload(`previews/${Ce}`,o);if(Ve)throw Ve;const{data:ze}=q.storage.from("brokerage-resources").getPublicUrl(`previews/${Ce}`);ke=ze.publicUrl}const Be={title:i.title,description:i.description||null,preview_image_url:ke,publish_date:i.publish_date,is_published:i.is_published,category_id:i.category_id||null};let Ne;if(r){const{error:Ae}=await q.from("brokerage_resources").update(Be).eq("id",r.id);if(Ae)throw Ae;Ne=r.id;const Ce=(R==null?void 0:R.filter(Je=>Je.resource_id===r.id).map(Je=>Je.id))||[],Ve=h.filter(Je=>Je.id).map(Je=>Je.id),ze=Ce.filter(Je=>!Ve.includes(Je));ze.length>0&&await q.from("brokerage_resource_pdfs").delete().in("id",ze);const qe=(D==null?void 0:D.filter(Je=>Je.resource_id===r.id).map(Je=>Je.id))||[],dt=f.filter(Je=>Je.id).map(Je=>Je.id),Xe=qe.filter(Je=>!dt.includes(Je));Xe.length>0&&await q.from("brokerage_resource_videos").delete().in("id",Xe);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;Ne=Ae.id}for(let Ae=0;Ae{s.invalidateQueries({queryKey:["brokerage-resources"]}),s.invalidateQueries({queryKey:["brokerage-resource-pdfs"]}),s.invalidateQueries({queryKey:["brokerage-resource-videos"]}),s.invalidateQueries({queryKey:["brokerage-resource-links"]}),re.success(r?"Resource updated":"Resource created"),n(!1),V(),b(!1)},onError:ke=>{re.error("Failed to save resource: "+ke.message),b(!1)}}),Se=mt({mutationFn:async ke=>{const{error:Be}=await q.from("brokerage_resources").delete().eq("id",ke);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"]}),re.success("Resource deleted")},onError:ke=>{re.error("Failed to delete: "+ke.message)}}),Le=ke=>{if(ke.preventDefault(),!i.title){re.error("Please enter a title");return}Ee.mutate()},Fe=ke=>{const Be=(R==null?void 0:R.filter(Ce=>Ce.resource_id===ke).length)||0,Ne=(D==null?void 0:D.filter(Ce=>Ce.resource_id===ke).length)||0,Ae=(O==null?void 0:O.filter(Ce=>Ce.resource_id===ke).length)||0;return{pdfCount:Be,videoCount:Ne,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(Ie,{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(Ie,{children:e.jsx("div",{className:"text-2xl font-bold",children:(I==null?void 0:I.filter(ke=>ke.is_published).length)||0})})]})]}),e.jsxs($,{onClick:()=>{V(),n(!0)},children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Add Resource"]})]}),e.jsx(je,{children:e.jsx(Ie,{className:"p-0",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Title"}),e.jsx(Dt,{children:"Category"}),e.jsx(Dt,{children:"Content"}),e.jsx(Dt,{children:"Publish Date"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(fi,{children:P?e.jsx(En,{children:e.jsx(_t,{colSpan:6,className:"text-center py-8",children:"Loading..."})}):(I==null?void 0:I.length)===0?e.jsx(En,{children:e.jsx(_t,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No brokerage resources yet. Create your first one!"})}):I==null?void 0:I.map(ke=>{const{pdfCount:Be,videoCount:Ne,linkCount:Ae}=Fe(ke.id),Ce=U==null?void 0:U.find(Ve=>Ve.id===ke.category_id);return e.jsxs(En,{children:[e.jsx(_t,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[ke.preview_image_url?e.jsx("img",{src:ke.preview_image_url,alt:ke.title,className:"w-10 h-10 rounded object-cover"}):e.jsx("div",{className:"w-10 h-10 rounded bg-muted flex items-center justify-center",children:e.jsx(kx,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:ke.title}),ke.description&&e.jsx("div",{className:"text-sm text-muted-foreground line-clamp-1",children:ke.description})]})]})}),e.jsx(_t,{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(_t,{children:e.jsxs("div",{className:"flex items-center gap-3 text-sm text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Jr,{className:"h-3.5 w-3.5"}),Be]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ua,{className:"h-3.5 w-3.5"}),Ne]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Sd,{className:"h-3.5 w-3.5"}),Ae]})]})}),e.jsx(_t,{children:en(new Date(ke.publish_date),"MMM d, yyyy")}),e.jsx(_t,{children:e.jsx("span",{className:`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${ke.is_published?"bg-green-100 text-green-800":"bg-yellow-100 text-yellow-800"}`,children:ke.is_published?"Published":"Draft"})}),e.jsx(_t,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>{const Ve=(R==null?void 0:R.filter(dt=>dt.resource_id===ke.id))||[],ze=(D==null?void 0:D.filter(dt=>dt.resource_id===ke.id))||[],qe=(O==null?void 0:O.filter(dt=>dt.resource_id===ke.id))||[];S({...ke,pdfs:Ve,videos:ze,links:qe})},children:e.jsx(Ca,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>G(ke),children:e.jsx(pi,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:async()=>{await fo("Delete this resource?")&&Se.mutate(ke.id)},children:e.jsx(Hn,{className:"h-4 w-4 text-destructive"})})]})})]},ke.id)})})]})})}),e.jsx(zs,{open:t,onOpenChange:n,children:e.jsxs(Os,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(Bs,{children:r?"Edit Brokerage Resource":"Add Brokerage Resource"})}),e.jsxs("form",{onSubmit:Le,className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Preview Image"}),e.jsxs("div",{className:"flex items-center gap-4",children:[d?e.jsx("img",{src:d,alt:"Preview",className:"w-24 h-24 rounded object-cover"}):e.jsx("div",{className:"w-24 h-24 rounded bg-muted flex items-center justify-center",children:e.jsx(kx,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx(pe,{type:"file",accept:"image/*",onChange:Y})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"title",children:"Title *"}),e.jsx(pe,{id:"title",value:i.title,onChange:ke=>l({...i,title:ke.target.value}),placeholder:"Resource Title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{className:"flex items-center gap-2",children:[e.jsx(Ap,{className:"h-4 w-4"}),"Category"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(ms,{value:i.category_id,onValueChange:ke=>l({...i,category_id:ke}),children:[e.jsx(us,{className:"flex-1",children:e.jsx(fs,{placeholder:"Select a category"})}),e.jsx(hs,{children:U==null?void 0:U.map(ke=>e.jsx(Ge,{value:ke.id,children:ke.name},ke.id))})]}),i.category_id&&e.jsx($,{type:"button",variant:"ghost",size:"icon",onClick:()=>l({...i,category_id:""}),children:e.jsx(pr,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{placeholder:"Or create new category...",value:A,onChange:ke=>E(ke.target.value),className:"flex-1"}),e.jsxs($,{type:"button",variant:"outline",size:"sm",disabled:!A.trim()||ve.isPending,onClick:()=>ve.mutate(A.trim()),children:[e.jsx(dn,{className:"h-4 w-4 mr-1"}),"Add"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Description"}),e.jsx(Sk,{content:i.description,onChange:ke=>l({...i,description:ke}),placeholder:"Brief description of this resource",minHeight:"120px"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(pe,{id:"publish_date",type:"date",value:i.publish_date,onChange:ke=>l({...i,publish_date:ke.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Published"}),e.jsxs("div",{className:"flex items-center space-x-2 pt-2",children:[e.jsx(Sn,{checked:i.is_published,onCheckedChange:ke=>l({...i,is_published:ke})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:i.is_published?"Visible to brokerage managers":"Hidden from brokerage managers"})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(ee,{className:"flex items-center gap-2",children:[e.jsx(Jr,{className:"h-4 w-4"}),"PDF Documents (",h.length,")"]}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:X,children:[e.jsx(dn,{className:"h-4 w-4 mr-1"}),"Add PDF"]})]}),h.map((ke,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:ke.name,onChange:Ne=>le(Be,"name",Ne.target.value),className:"flex-1"}),e.jsx(pe,{type:"file",accept:".pdf",onChange:Ne=>{var Ce;const Ae=(Ce=Ne.target.files)==null?void 0:Ce[0];Ae&&le(Be,"file",Ae)},className:"flex-1"}),ke.file_url&&!ke.file&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Uploaded"}),e.jsx($,{type:"button",variant:"ghost",size:"icon",onClick:()=>ae(Be),children:e.jsx(pr,{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(ua,{className:"h-4 w-4"}),"Videos (",f.length,")"]}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:ne,children:[e.jsx(dn,{className:"h-4 w-4 mr-1"}),"Add Video"]})]}),f.map((ke,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:ke.title,onChange:Ne=>J(Be,"title",Ne.target.value),className:"flex-1"}),e.jsx($,{type:"button",variant:"ghost",size:"icon",onClick:()=>te(Be),children:e.jsx(pr,{className:"h-4 w-4"})})]}),e.jsx(pe,{type:"file",accept:"video/*",onChange:Ne=>{var Ce;const Ae=(Ce=Ne.target.files)==null?void 0:Ce[0];Ae&&J(Be,"file",Ae)}}),ke.uploadProgress!==void 0&&ke.uploadProgress>0&&e.jsx("div",{className:"w-full bg-muted rounded-full h-2",children:e.jsx("div",{className:"bg-primary h-2 rounded-full transition-all",style:{width:`${ke.uploadProgress}%`}})}),ke.video_url&&!ke.file&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Video uploaded"})]},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(dn,{className:"h-4 w-4 mr-1"}),"Add Link"]})]}),x.map((ke,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:ke.title,onChange:Ne=>he(Be,"title",Ne.target.value),className:"flex-1"}),e.jsx(pe,{placeholder:"Canva Share Link",value:ke.canva_share_link,onChange:Ne=>he(Be,"canva_share_link",Ne.target.value),className:"flex-1"}),e.jsx($,{type:"button",variant:"ghost",size:"icon",onClick:()=>_e(Be),children:e.jsx(pr,{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||v,children:Ee.isPending||v?"Saving...":r?"Update":"Create"})]})]})]})}),e.jsx(zs,{open:!!w,onOpenChange:()=>S(null),children:e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(Bs,{children:w==null?void 0:w.title})}),w&&e.jsxs("div",{className:"space-y-4",children:[w.preview_image_url&&e.jsx("img",{src:w.preview_image_url,alt:w.title,className:"w-full h-48 object-cover rounded-lg"}),w.description&&e.jsx("p",{className:"text-muted-foreground",children:w.description}),w.pdfs&&w.pdfs.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2 flex items-center gap-2",children:[e.jsx(Jr,{className:"h-4 w-4"}),"PDF Documents (",w.pdfs.length,")"]}),e.jsx("div",{className:"space-y-1",children:w.pdfs.map(ke=>e.jsx("a",{href:ke.file_url,target:"_blank",rel:"noopener noreferrer",className:"block p-2 border rounded hover:bg-muted",children:ke.name},ke.id))})]}),w.videos&&w.videos.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2 flex items-center gap-2",children:[e.jsx(ua,{className:"h-4 w-4"}),"Videos (",w.videos.length,")"]}),e.jsx("div",{className:"space-y-2",children:w.videos.map(ke=>e.jsx("div",{className:"p-2 border rounded",children:e.jsx("p",{className:"font-medium text-sm",children:ke.title})},ke.id))})]}),w.links&&w.links.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2 flex items-center gap-2",children:[e.jsx(Sd,{className:"h-4 w-4"}),"Canva Links (",w.links.length,")"]}),e.jsx("div",{className:"space-y-1",children:w.links.map(ke=>e.jsx("a",{href:ke.canva_share_link,target:"_blank",rel:"noopener noreferrer",className:"block p-2 border rounded hover:bg-muted",children:ke.title},ke.id))})]})]})]})})]})})}const AXt=[{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 dRn(){const[s,t]=j.useState([]),[n,r]=j.useState(!0),[a,i]=j.useState(!1),[l,o]=j.useState(!1),[c,d]=j.useState(null),[u,h]=j.useState(!1),[m,f]=j.useState(!1),[g,x]=j.useState(""),[y,v]=j.useState(""),[b,w]=j.useState(""),[S,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(""),[Y,X]=j.useState("");j.useEffect(()=>{ae()},[]);const ae=async()=>{try{const{data:ve,error:Ee}=await q.from("dashboard_banners").select("*").order("placement").order("sort_order");if(Ee)throw Ee;t(ve||[])}catch(ve){re.error("Failed to load banners: "+ve.message)}finally{r(!1)}},le=()=>{x(""),v(""),w(""),A(""),I("Learn More"),R("top"),O(""),W(!0),G(""),X(""),d(null)},ne=ve=>{d(ve),x(ve.title),v(ve.description||""),w(ve.image_url),A(ve.link_url||""),I(ve.link_text||"Learn More"),R(ve.placement),O(ve.section_after||""),W(ve.is_active),G(ve.start_date?en(new Date(ve.start_date),"yyyy-MM-dd'T'HH:mm"):""),X(ve.end_date?en(new Date(ve.end_date),"yyyy-MM-dd'T'HH:mm"):""),i(!0)},te=async ve=>{var Se;const Ee=(Se=ve.target.files)==null?void 0:Se[0];if(Ee){h(!0);try{const Le=Ee.name.split(".").pop(),Fe=`${Date.now()}.${Le}`,{error:ke}=await q.storage.from("banner-images").upload(Fe,Ee);if(ke)throw ke;const{data:{publicUrl:Be}}=q.storage.from("banner-images").getPublicUrl(Fe);w(Be),re.success("Image uploaded successfully")}catch(Le){re.error("Failed to upload image: "+Le.message)}finally{h(!1)}}},J=async()=>{if(!g.trim()||!b){re.error("Please fill in required fields (title and image)");return}f(!0);try{const ve={title:g.trim(),description:y.trim()||null,image_url:b,link_url:S.trim()||null,link_text:E.trim()||"Learn More",placement:P,section_after:P==="between"?D:null,is_active:U,start_date:V?new Date(V).toISOString():null,end_date:Y?new Date(Y).toISOString():null};if(c){const{error:Ee}=await q.from("dashboard_banners").update(ve).eq("id",c.id);if(Ee)throw Ee;re.success("Banner updated successfully")}else{const Ee=s.filter(Le=>Le.placement===P).length,{error:Se}=await q.from("dashboard_banners").insert({...ve,sort_order:Ee});if(Se)throw Se;re.success("Banner created successfully")}i(!1),le(),ae()}catch(ve){re.error("Failed to save banner: "+ve.message)}finally{f(!1)}},ce=async()=>{if(c)try{const{error:ve}=await q.from("dashboard_banners").delete().eq("id",c.id);if(ve)throw ve;re.success("Banner deleted successfully"),o(!1),d(null),ae()}catch(ve){re.error("Failed to delete banner: "+ve.message)}},_e=async ve=>{try{const{error:Ee}=await q.from("dashboard_banners").update({is_active:!ve.is_active}).eq("id",ve.id);if(Ee)throw Ee;re.success(ve.is_active?"Banner deactivated":"Banner activated"),ae()}catch(Ee){re.error("Failed to update banner: "+Ee.message)}},he=s.filter(ve=>ve.placement==="top"),ue=s.filter(ve=>ve.placement==="between");return n?e.jsx(Vs,{title:"Dashboard Management",children:e.jsx("div",{className:"flex items-center justify-center h-64",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary"})})}):e.jsxs(Vs,{title:"Dashboard Management",description:"Configure dashboard modules and banners",children:[e.jsxs("div",{className:"space-y-8",children:[e.jsxs(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(Gn,{children:"These banners appear in a rotating carousel at the top of the dashboard"})]}),e.jsxs(zs,{open:a&&P==="top",onOpenChange:ve=>{ve||le(),i(ve),ve&&R("top")},children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{onClick:()=>{le(),R("top")},children:[e.jsx(dn,{className:"mr-2 h-4 w-4"}),"Add Hero Banner"]})}),e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{children:[c?"Edit":"Create"," Banner"]}),e.jsx(Pr,{children:"Configure the banner's content and display settings"})]}),e.jsx(Wkt,{title:g,setTitle:x,description:y,setDescription:v,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:Y,setEndDate:X,handleImageUpload:te,uploading:u,showPlacementOptions:!1}),e.jsxs(Sr,{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(Ie,{children:he.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No hero banners yet. Add your first banner above."}):e.jsx("div",{className:"space-y-3",children:he.map(ve=>e.jsx(Kkt,{banner:ve,onEdit:()=>ne(ve),onDelete:()=>{d(ve),o(!0)},onToggleActive:()=>_e(ve)},ve.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(Gn,{children:"These banners appear between dashboard content sections"})]}),e.jsxs(zs,{open:a&&P==="between",onOpenChange:ve=>{ve||le(),i(ve),ve&&R("between")},children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{onClick:()=>{le(),R("between")},children:[e.jsx(dn,{className:"mr-2 h-4 w-4"}),"Add Section Banner"]})}),e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{children:[c?"Edit":"Create"," Section Banner"]}),e.jsx(Pr,{children:"Configure where this banner appears between sections"})]}),e.jsx(Wkt,{title:g,setTitle:x,description:y,setDescription:v,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:Y,setEndDate:X,handleImageUpload:te,uploading:u,showPlacementOptions:!0}),e.jsxs(Sr,{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(Ie,{children:ue.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No section banners yet. Add your first banner above."}):e.jsx("div",{className:"space-y-3",children:ue.map(ve=>e.jsx(Kkt,{banner:ve,onEdit:()=>ne(ve),onDelete:()=>{d(ve),o(!0)},onToggleActive:()=>_e(ve),showSection:!0},ve.id))})})]})]}),e.jsx(zs,{open:l,onOpenChange:o,children:e.jsxs(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Delete Banner"}),e.jsxs(Pr,{children:['Are you sure you want to delete "',c==null?void 0:c.title,'"? This action cannot be undone.']})]}),e.jsxs(Sr,{children:[e.jsx($,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx($,{variant:"destructive",onClick:ce,children:"Delete"})]})]})})]})}function Wkt({title:s,setTitle:t,description:n,setDescription:r,imageUrl:a,linkUrl:i,setLinkUrl:l,linkText:o,setLinkText:c,placement:d,setPlacement:u,sectionAfter:h,setSectionAfter:m,isActive:f,setIsActive:g,startDate:x,setStartDate:y,endDate:v,setEndDate:b,handleImageUpload:w,uploading:S,showPlacementOptions: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(Ls,{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:AXt.map(E=>e.jsx(Ge,{value:E.value,children:E.label},E.value))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{htmlFor:"startDate",className:"flex items-center gap-2",children:[e.jsx(Ta,{className:"h-4 w-4"}),"Start Date (optional)"]}),e.jsx(pe,{id:"startDate",type:"datetime-local",value:x,onChange:E=>y(E.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{htmlFor:"endDate",className:"flex items-center gap-2",children:[e.jsx(Ta,{className:"h-4 w-4"}),"End Date (optional)"]}),e.jsx(pe,{id:"endDate",type:"datetime-local",value:v,onChange:E=>b(E.target.value)})]})]}),e.jsx("div",{className:"flex items-center justify-between pt-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sn,{id:"isActive",checked:f,onCheckedChange:g}),e.jsx(ee,{htmlFor:"isActive",children:"Active"})]})})]})}function Kkt({banner:s,onEdit:t,onDelete:n,onToggleActive:r,showSection:a=!1}){var c;const i=(c=AXt.find(d=>d.value===s.section_after))==null?void 0:c.label,[l,o]=j.useState(null);return j.useEffect(()=>{(async()=>{const{count:u}=await q.from("content_engagement_logs").select("*",{count:"exact",head:!0}).eq("resource_id",s.id).eq("action_type","click_link");o(u??0)})()},[s.id]),e.jsxs("div",{className:"flex items-center gap-4 p-3 border rounded-lg bg-card hover:bg-accent/50 transition-colors",children:[e.jsx(Ug,{className:"h-5 w-5 text-muted-foreground cursor-grab"}),e.jsx("img",{src:s.image_url,alt:s.title,className:"w-24 h-14 object-cover rounded"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h4",{className:"font-medium truncate",children:s.title}),!s.is_active&&e.jsx($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(Fr,{className:"h-4 w-4"})})}),e.jsx($,{variant:"ghost",size:"icon",onClick:r,children:s.is_active?e.jsx(Ca,{className:"h-4 w-4"}):e.jsx($g,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:t,children:e.jsx(pi,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:n,children:e.jsx(Hn,{className:"h-4 w-4 text-destructive"})})]})]})}const Xde={open:{label:"Open",icon:da,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:Nu,color:"bg-muted-foreground"}},Ykt={general:"General Support",technology:"Technology Support",crm:"CRM Support",marketing:"Marketing Support"};function uRn(){var P,R;const{user:s}=bs(),t=Wt(),[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:y=[]}=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:Y}=await q.from("support_notification_settings").select("user_id, receive_notifications");if(Y)throw Y;const X=new Map((G==null?void 0:G.map(ae=>[ae.user_id,ae.receive_notifications]))||[]);return W.map(ae=>({...ae,receives_notifications:X.get(ae.id)||!1}))}}),{data:v=[]}=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"]}),re.success("Notification settings updated")},onError:()=>{re.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}),re.success("Status updated")},onError:()=>{re.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"]}),re.success("Ticket assigned")},onError:()=>{re.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([]),re.success("Reply sent!")},onError:()=>{re.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?(Xde[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:Ykt[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(Ie,{children:e.jsxs(ms,{value:n.status,onValueChange:D=>{w.mutate({ticketId:n.id,status:D}),r({...n,status:D})},children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"open",children:"Open"}),e.jsx(Ge,{value:"in_progress",children:"In Progress"}),e.jsx(Ge,{value:"resolved",children:"Resolved"}),e.jsx(Ge,{value:"closed",children:"Closed"})]})]})})]}),e.jsxs(je,{children:[e.jsx(St,{className:"pb-2",children:e.jsx(Et,{className:"text-sm",children:"Assigned To"})}),e.jsx(Ie,{children:e.jsxs(ms,{value:n.assigned_to||"unassigned",onValueChange:D=>{const O=D==="unassigned"?null:D;S.mutate({ticketId:n.id,assignedTo:O}),r({...n,assigned_to:O})},children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Unassigned"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"unassigned",children:"Unassigned"}),y.map(D=>e.jsx(Ge,{value:D.id,children:D.name},D.id))]})]})})]})]}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsxs(Gn,{children:["Created on ",en(new Date(n.created_at),"MMM d, yyyy 'at' h:mm a")]})}),e.jsx(Ie,{children:e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:n.description})})]}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-lg",children:"Conversation"})}),e.jsxs(Ie,{children:[e.jsx(uo,{className:"h-[300px] pr-4",children:v.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No replies yet"}):e.jsx("div",{className:"space-y-4",children:v.map(D=>{var O,U;return e.jsxs("div",{className:`p-4 rounded-lg ${D.is_admin_reply?"bg-primary/10 ml-4":"bg-muted mr-4"}`,children:[e.jsxs("div",{className:"flex justify-between items-start mb-2",children:[e.jsx("span",{className:"font-medium text-sm",children:D.is_admin_reply?`${((O=D.profiles)==null?void 0:O.name)||"Admin"} (Support)`:((U=D.profiles)==null?void 0:U.name)||"User"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:en(new Date(D.created_at),"MMM d, h:mm a")})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:D.content}),D.attachments&&D.attachments.length>0&&e.jsx(AWt,{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(Ls,{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(Kr,{className:"h-4 w-4"})})]}),e.jsx(CWt,{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(zs,{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(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Email Notification Settings"}),e.jsx(Pr,{children:"Choose which admins receive email notifications for new support tickets."})]}),e.jsx("div",{className:"space-y-4 mt-4",children:y.map(D=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(sl,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:D.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:D.email})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[D.receives_notifications?e.jsx(Uy,{className:"h-4 w-4 text-primary"}):e.jsx(YS,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(Sn,{checked:D.receives_notifications,onCheckedChange:O=>b.mutate({userId:D.id,enabled:O})})]})]},D.id))})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-4 items-center",children:[e.jsx(ha,{value:c,onValueChange:d,className:"w-auto",children:e.jsxs(ma,{children:[e.jsx(Zt,{value:"all",children:"All"}),e.jsx(Zt,{value:"open",children:"Open"}),e.jsx(Zt,{value:"in_progress",children:"In Progress"}),e.jsx(Zt,{value:"resolved",children:"Resolved"}),e.jsx(Zt,{value:"closed",children:"Closed"})]})}),e.jsxs(ms,{value:u,onValueChange:h,children:[e.jsx(us,{className:"w-[180px]",children:e.jsx(fs,{placeholder:"All Categories"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Categories"}),e.jsx(Ge,{value:"general",children:"General Support"}),e.jsx(Ge,{value:"technology",children:"Technology Support"}),e.jsx(Ge,{value:"crm",children:"CRM Support"}),e.jsx(Ge,{value:"marketing",children:"Marketing Support"})]})]})]}),e.jsx("div",{className:"mt-4",children:x?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading tickets..."}):g.length===0?e.jsx(je,{children:e.jsxs(Ie,{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=Xde[D.status].icon;return e.jsx(je,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>r(D),children:e.jsx(Ie,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-medium truncate",children:D.subject}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:[e.jsx($e,{variant:"outline",className:"text-xs",children:Ykt[D.category]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[(U=D.profiles)==null?void 0:U.name," • ",en(new Date(D.created_at),"MMM d, yyyy")]}),D.assigned_to&&e.jsxs($e,{variant:"secondary",className:"text-xs gap-1",children:[e.jsx(sl,{className:"h-3 w-3"}),((W=y.find(V=>V.id===D.assigned_to))==null?void 0:W.name)||"Assigned"]})]})]}),e.jsxs($e,{className:Xde[D.status].color,children:[e.jsx(O,{className:"h-3 w-3 mr-1"}),Xde[D.status].label]})]})})},D.id)})})})]})]})})}const EXt=Cb.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 hRn({content:s,onChange:t,variables:n}){const r=$6e({extensions:[U6e,V6e.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline"}}),H6e.configure({types:["heading","paragraph"]}),Knt,EXt],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(SE,{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(EE,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().toggleBulletList().run(),className:r.isActive("bulletList")?"bg-muted":"",children:e.jsx(T0,{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(u2,{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(FI,{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(DI,{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(OI,{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(CE,{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(OE,{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(DE,{className:"h-4 w-4"})}),e.jsx("div",{className:"flex-1"}),n.length>0&&e.jsxs($u,{children:[e.jsx(Uu,{asChild:!0,children:e.jsxs($,{type:"button",variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(hV,{className:"h-4 w-4"}),"Insert Variable"]})}),e.jsx(Au,{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(B6e,{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 mRn(){const s=Wt(),[t,n]=j.useState(null),[r,a]=j.useState(null),[i,l]=j.useState(""),[o,c]=j.useState(""),[d,u]=j.useState(""),[h,m]=j.useState(!0),[f,g]=j.useState("visual"),{data:x,isLoading:y}=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||[]}))}}),v=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"]}),re.success("Email template updated successfully"),n(null)},onError:A=>{re.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&&v.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(Ca,{className:"h-4 w-4 mr-2"}),"Preview"]}),e.jsxs($,{onClick:w,disabled:v.isPending,children:[e.jsx(tl,{className:"h-4 w-4 mr-2"}),v.isPending?"Saving...":"Save Changes"]})]}),e.jsxs(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(mn,{className:"h-5 w-5"}),t.name]}),e.jsxs(Gn,{className:"mt-1",children:["Template slug: ",e.jsx("code",{className:"bg-muted px-1 rounded",children:t.slug})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ee,{htmlFor:"active-toggle",children:"Active"}),e.jsx(Sn,{id:"active-toggle",checked:h,onCheckedChange:m})]})]})}),e.jsxs(Ie,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"description",children:"Description"}),e.jsx(Ls,{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(ha,{value:f,onValueChange:A=>g(A),children:e.jsxs(ma,{className:"h-8",children:[e.jsxs(Zt,{value:"visual",className:"text-xs px-3 h-6",children:[e.jsx(XN,{className:"h-3 w-3 mr-1"}),"Visual"]}),e.jsxs(Zt,{value:"html",className:"text-xs px-3 h-6",children:[e.jsx(CE,{className:"h-3 w-3 mr-1"}),"HTML"]})]})})]}),f==="visual"?e.jsx(hRn,{content:o,onChange:c,variables:t.available_variables}):e.jsx(Ls,{value:o,onChange:A=>c(A.target.value),className:"font-mono text-sm min-h-[400px]",placeholder:"HTML email body"})]})]})]})]}),e.jsx(zs,{open:!!r,onOpenChange:()=>a(null),children:e.jsxs(Os,{className:"max-w-3xl max-h-[90vh] overflow-auto",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Email Preview"}),e.jsxs(Pr,{children:["Subject: ",i.replace(/\{\{(\w+)\}\}/g,"[$1]")]})]}),e.jsx("div",{className:"border rounded-lg p-4 bg-white",children:e.jsx("div",{dangerouslySetInnerHTML:{__html:S(o,t.available_variables)}})})]})})]}):e.jsx(Vs,{title:"Email Templates",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Email Templates"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Manage and customize system email templates"})]}),y?e.jsx("div",{className:"grid gap-4",children:[...Array(4)].map((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(mn,{className:"h-5 w-5 text-muted-foreground"}),A.name,!A.is_active&&e.jsx($e,{variant:"secondary",children:"Inactive"})]}),e.jsx(Gn,{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(Ca,{className:"h-4 w-4 mr-2"}),"Preview"]}),e.jsxs($,{size:"sm",onClick:()=>b(A),children:[e.jsx(_p,{className:"h-4 w-4 mr-2"}),"Edit"]})]})]})}),e.jsx(Ie,{children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Subject:"}),e.jsx("code",{className:"bg-muted px-2 py-0.5 rounded text-sm",children: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(zs,{open:!!r&&!t,onOpenChange:()=>a(null),children:e.jsxs(Os,{className:"max-w-3xl max-h-[90vh] overflow-auto",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{children:["Email Preview: ",r==null?void 0:r.name]}),e.jsxs(Pr,{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 fRn(){const s=Wt(),[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:y=[],isLoading:v}=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),re.success(r?"Template updated":"Template created")},onError:()=>re.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"]}),re.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),re.success(i?"Category updated":"Category created")},onError:()=>re.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"]}),re.success("Category deleted")}}),E=()=>{a(null),m({title:"",subject:"",body:"",description:"",tone:"",category_id:"",is_active:!0}),c(!0)},I=D=>{a(D),m({title:D.title,subject:D.subject,body:D.body,description:D.description||"",tone:D.tone||"",category_id:D.category_id||"",is_active:D.is_active}),c(!0)},P=()=>{l(null),g({name:"",description:"",icon:"📧"}),u(!0)},R=D=>{l(D),g({name:D.name,description:D.description||"",icon:D.icon}),u(!0)};return e.jsx(Vs,{children:e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsx(Dm,{title:"Agent Email Templates",description:"Manage email templates that agents use when composing emails from Mission Control."}),e.jsxs(ha,{value:t,onValueChange:n,children:[e.jsxs(ma,{children:[e.jsxs(Zt,{value:"templates",className:"gap-2",children:[e.jsx(mn,{className:"h-4 w-4"})," Templates"]}),e.jsxs(Zt,{value:"categories",className:"gap-2",children:[e.jsx(kv,{className:"h-4 w-4"})," Categories"]})]}),e.jsxs(Xt,{value:"templates",className:"space-y-4",children:[e.jsx("div",{className:"flex justify-end",children:e.jsxs($,{onClick:E,className:"gap-2",children:[e.jsx(dn,{className:"h-4 w-4"})," Add Template"]})}),e.jsx(je,{children:e.jsx(Ie,{className:"p-0",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Template"}),e.jsx(Dt,{className:"hidden md:table-cell",children:"Category"}),e.jsx(Dt,{className:"hidden md:table-cell",children:"Tone"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(fi,{children:v?e.jsx(En,{children:e.jsx(_t,{colSpan:5,className:"text-center py-8",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin mx-auto"})})}):y.length===0?e.jsx(En,{children:e.jsx(_t,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No templates yet. Create your first one!"})}):y.map(D=>e.jsxs(En,{children:[e.jsx(_t,{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(_t,{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(_t,{className:"hidden md:table-cell",children:D.tone?e.jsx($e,{variant:"secondary",children:D.tone}):"—"}),e.jsx(_t,{children:e.jsx($e,{variant:D.is_active?"default":"secondary",children:D.is_active?"Active":"Inactive"})}),e.jsx(_t,{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 fo("Delete this template?")&&w.mutate(D.id)},children:e.jsx(Hn,{className:"h-4 w-4"})})]})})]},D.id))})]})})})]}),e.jsxs(Xt,{value:"categories",className:"space-y-4",children:[e.jsx("div",{className:"flex justify-end",children:e.jsxs($,{onClick:P,className:"gap-2",children:[e.jsx(dn,{className:"h-4 w-4"})," Add Category"]})}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:x.map(D=>e.jsxs(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 fo("Delete this category?")&&A.mutate(D.id)},children:e.jsx(Hn,{className:"h-3.5 w-3.5"})})]})]})}),e.jsxs(Ie,{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:D.description||"No description"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:[y.filter(O=>O.category_id===D.id).length," templates"]})]})]},D.id))})]})]}),e.jsx(zs,{open:o,onOpenChange:c,children:e.jsxs(Os,{className:"sm:max-w-[700px] max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(Bs,{children:r?"Edit Template":"New Template"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Title"}),e.jsx(pe,{value:h.title,onChange:D=>m(O=>({...O,title:D.target.value})),placeholder:"e.g. Quick Check-in"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Category"}),e.jsxs(ms,{value:h.category_id,onValueChange:D=>m(O=>({...O,category_id:D})),children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Select category"})}),e.jsx(hs,{children:x.map(D=>e.jsxs(Ge,{value:D.id,children:[D.icon," ",D.name]},D.id))})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Subject Line"}),e.jsx(pe,{value:h.subject,onChange:D=>m(O=>({...O,subject:D.target.value})),placeholder:"e.g. Hey {{first_name}}, just checking in!"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Use ","{{first_name}}",", ","{{last_name}}",", ","{{full_name}}"," for merge variables"]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Email Body"}),e.jsx(Ls,{value:h.body,onChange:D=>m(O=>({...O,body:D.target.value})),rows:12,placeholder:"Write your email template...",className:"resize-y"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Description (internal)"}),e.jsx(pe,{value:h.description,onChange:D=>m(O=>({...O,description:D.target.value})),placeholder:"Short description for admin reference"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Tone"}),e.jsx(pe,{value:h.tone,onChange:D=>m(O=>({...O,tone:D.target.value})),placeholder:"e.g. Warm & Casual"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sn,{checked:h.is_active,onCheckedChange:D=>m(O=>({...O,is_active:D}))}),e.jsx(ee,{children:"Active"})]})]}),e.jsxs(Sr,{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(zs,{open:d,onOpenChange:u,children:e.jsxs(Os,{className:"sm:max-w-[450px]",children:[e.jsx(Us,{children:e.jsx(Bs,{children:i?"Edit Category":"New Category"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-[60px_1fr] gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Icon"}),e.jsx(pe,{value:f.icon,onChange:D=>g(O=>({...O,icon:D.target.value})),className:"text-center text-lg"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Name"}),e.jsx(pe,{value:f.name,onChange:D=>g(O=>({...O,name:D.target.value})),placeholder:"e.g. Check-in & Stay in Touch"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Description"}),e.jsx(pe,{value:f.description,onChange:D=>g(O=>({...O,description:D.target.value})),placeholder:"Brief description of this category"})]})]}),e.jsxs(Sr,{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 pRn=({brokerageId:s})=>{var Pa,ii,$i;const{toast:t}=Bi(),n=Xn(),[r,a]=j.useState([]),[i,l]=j.useState(!0),[o,c]=j.useState(""),[d,u]=j.useState("all"),[h,m]=j.useState(new Set),[f,g]=j.useState(!1),[x,y]=j.useState({}),[v,b]=j.useState(!1),[w,S]=j.useState(!1),[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,Y]=j.useState(null),[X,ae]=j.useState(!1),[le,ne]=j.useState(!1),[te,J]=j.useState(!1),[ce,_e]=j.useState(""),[he,ue]=j.useState(!1),[ve,Ee]=j.useState([]),[Se,Le]=j.useState(!1),[Fe,ke]=j.useState(!1),[Be,Ne]=j.useState(null),[Ae,Ce]=j.useState({name:"",phone:"",email:""}),[Ve,ze]=j.useState(!1),[qe,dt]=j.useState(!1),[Xe,at]=j.useState(null),[rt,Ke]=j.useState("asc"),[Je,pt]=j.useState(!1),[gt,ss]=j.useState(null),[Yt,ts]=j.useState(!1),[ys,Bt]=j.useState(null),[Ft,as]=j.useState(""),[kt,Ks]=j.useState(!1),[wt,gs]=j.useState(null);j.useEffect(()=>{Xs(),Is(),ks()},[s]);const ks=async()=>{try{const{data:Rn}=await q.from("partnership_programs").select("id, name, enabled").eq("brokerage_id",s).maybeSingle();if(!Rn||!Rn.enabled){P(null),D([]);return}const{data:xa}=await q.from("partnership_packages").select("id, name, description, sort_order").eq("program_id",Rn.id).order("sort_order",{ascending:!0});P({id:Rn.id,name:Rn.name}),D(xa||[]),xa&&xa.length>0&&U(xa[0].id)}catch(Rn){console.error("Error loading partnership packages:",Rn)}},Is=async()=>{try{const{data:Rn,error:xa}=await q.from("brokerage_manager_assignments").select("user_id").eq("brokerage_id",s);if(xa)throw xa;Ee((Rn==null?void 0:Rn.map(Ya=>Ya.user_id))||[])}catch(Rn){console.error("Error loading brokerage managers:",Rn)}},Xs=async()=>{try{l(!0);const{data:Rn,error:xa}=await q.functions.invoke("get-brokerage-agents",{body:{brokerageId:s}});if(xa)throw xa;const Ya=Rn.agents||[];if(a(Ya),Ya.length>0){const ho=Ya.map(zd=>zd.id),{data:Tc}=await q.from("agent_assistant_assignments").select("agent_id, assistant_id").in("agent_id",ho);if(Tc&&Tc.length>0){const zd=Tc.map(ti=>ti.assistant_id),{data:Nl}=await q.from("profiles").select("id, name, email").in("id",zd),Ho={};for(const ti of Tc){const Xr=Nl==null?void 0:Nl.find(Eo=>Eo.id===ti.assistant_id);Xr&&(Ho[ti.agent_id]={name:Xr.name||"",email:Xr.email||""})}y(Ho)}else y({})}}catch(Rn){console.error("Error loading agents:",Rn),t({title:"Error",description:"Failed to load agents",variant:"destructive"})}finally{l(!1)}},ds=async()=>{var Rn;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(),Ya=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${xa==null?void 0:xa.access_token}`},body:JSON.stringify({...A,brokerageId:s,partnershipPackageId:I&&O!=="none"?O:void 0})}),ho=await Ya.json();if(!Ya.ok)throw new Error(ho.error||"Failed to create agent");t({title:"Success",description:`Agent ${A.email} created successfully`}),E({email:"",name:"",password:"",phone:""}),U(((Rn=R[0])==null?void 0:Rn.id)||"none"),b(!1),Xs()}catch(xa){console.error("Error creating agent:",xa),t({title:"Error",description:xa.message||"Failed to create agent",variant:"destructive"})}finally{S(!1)}},Ss=async Rn=>{try{const{data:{session:xa}}=await q.auth.getSession(),Ya=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${xa==null?void 0:xa.access_token}`},body:JSON.stringify({userId:Rn})}),ho=await Ya.json();if(!Ya.ok)throw new Error(ho.error||"Failed to resend welcome email");t({title:"Success",description:"Welcome email sent successfully"})}catch(xa){console.error("Error resending welcome email:",xa),t({title:"Error",description:xa.message||"Failed to resend welcome email",variant:"destructive"})}},yn=async(Rn,xa)=>{try{const{error:Ya}=await q.functions.invoke("send-password-reset",{body:{email:Rn,redirectTo:"https://dashboard.relevelup.com/profile?reset=true"}});if(Ya)throw Ya;t({title:"Password Reset Sent",description:`Password reset email sent to ${xa}`})}catch(Ya){console.error("Error sending password reset:",Ya),t({title:"Error",description:Ya.message||"Failed to send password reset email",variant:"destructive"})}},Js=Rn=>{Y(Rn),V(!0)},Ut=Rn=>{Ne(Rn),Ce({name:Rn.name,phone:Rn.phone||"",email:Rn.email}),ke(!0)},hn=async()=>{if(!Be)return;if(!Ae.name.trim()){t({title:"Error",description:"Name is required",variant:"destructive"});return}const Rn=Ae.email.trim().toLowerCase()!==Be.email.toLowerCase();ze(!0);try{if(Rn){if(!Ae.email.trim())throw new Error("Email is required");dt(!0);const{data:{session:Ya}}=await q.auth.getSession(),ho=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/update-agent-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Ya==null?void 0:Ya.access_token}`},body:JSON.stringify({agentId:Be.id,newEmail:Ae.email.trim(),brokerageId:s})}),Tc=await ho.json();if(dt(!1),!ho.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"}),ke(!1),Ne(null),Xs()}catch(xa){console.error("Error updating agent:",xa),t({title:"Error",description:xa.message||"Failed to update agent",variant:"destructive"})}finally{ze(!1),dt(!1)}},hr=async()=>{if(!ce){t({title:"Error",description:"Please select an agent to promote",variant:"destructive"});return}ue(!0);try{const{data:{session:Rn}}=await q.auth.getSession(),xa=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Rn==null?void 0:Rn.access_token}`},body:JSON.stringify({userId:ce,role:"brokerage_manager",action:"add",brokerageId:s})}),Ya=await xa.json();if(!xa.ok)throw new Error(Ya.error||"Failed to add brokerage manager");t({title:"Success",description:"Brokerage manager added successfully"}),J(!1),_e(""),Is()}catch(Rn){console.error("Error adding brokerage manager:",Rn),t({title:"Error",description:Rn.message||"Failed to add brokerage manager",variant:"destructive"})}finally{ue(!1)}},Rs=async Rn=>{try{const{data:{session:xa}}=await q.auth.getSession(),Ya=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${xa==null?void 0:xa.access_token}`},body:JSON.stringify({userId:Rn,role:"brokerage_manager",action:"remove",brokerageId:s})}),ho=await Ya.json();if(!Ya.ok)throw new Error(ho.error||"Failed to remove brokerage manager");t({title:"Success",description:"Brokerage manager role removed"}),Is()}catch(xa){console.error("Error removing brokerage manager:",xa),t({title:"Error",description:xa.message||"Failed to remove brokerage manager",variant:"destructive"})}},jr=Rn=>ve.includes(Rn),kr=Rn=>{Bt(Rn),as(""),ts(!0)},$n=async()=>{if(!(!ys||!Ft)){if(Ft.length<6){t({title:"Error",description:"Password must be at least 6 characters",variant:"destructive"});return}Ks(!0);try{const{data:{session:Rn}}=await q.auth.getSession(),xa=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/update-agent-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Rn==null?void 0:Rn.access_token}`},body:JSON.stringify({agentId:ys.id,brokerageId:s,action:"set_password",newPassword:Ft})}),Ya=await xa.json();if(!xa.ok)throw new Error(Ya.error||"Failed to set password");t({title:"Success",description:`Password set for ${ys.name}`}),ts(!1),Bt(null),as("")}catch(Rn){console.error("Error setting password:",Rn),t({title:"Error",description:Rn.message||"Failed to set password",variant:"destructive"})}finally{Ks(!1)}}},kn=async Rn=>{gs(Rn.id);try{const{data:{session:xa}}=await q.auth.getSession(),Ya=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/update-agent-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${xa==null?void 0:xa.access_token}`},body:JSON.stringify({agentId:Rn.id,brokerageId:s,action:"claim_account"})}),ho=await Ya.json();if(!Ya.ok)throw new Error(ho.error||"Failed to claim account");t({title:"Success",description:`Account claimed for ${Rn.name}`}),Xs()}catch(xa){console.error("Error claiming account:",xa),t({title:"Error",description:xa.message||"Failed to claim account",variant:"destructive"})}finally{gs(null)}},Fn=async()=>{if(G){ae(!0);try{const{data:{session:Rn}}=await q.auth.getSession(),xa=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/remove-agent",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Rn==null?void 0:Rn.access_token}`},body:JSON.stringify({userId:G.id,brokerageId:s})}),Ya=await xa.json();if(!xa.ok)throw new Error(Ya.error||"Failed to remove agent");t({title:"Success",description:`${G.name} has been removed from your brokerage`}),V(!1),Y(null),Xs()}catch(Rn){console.error("Error removing agent:",Rn),t({title:"Error",description:Rn.message||"Failed to remove agent",variant:"destructive"})}finally{ae(!1)}}},bn=Rn=>{const xa=Rn.trim().split(" ");return xa.length>1?xa[xa.length-1].toLowerCase():Rn.toLowerCase()},xs=Rn=>{Xe===Rn?Ke(rt==="asc"?"desc":"asc"):(at(Rn),Ke("asc"))},Lr=Rn=>Xe!==Rn?e.jsx(zy,{className:"ml-1 h-4 w-4"}):rt==="asc"?e.jsx(Zf,{className:"ml-1 h-4 w-4"}):e.jsx(Dg,{className:"ml-1 h-4 w-4"}),Or=r.filter(Rn=>{if(d==="active"&&!Rn.claimed||d==="pending"&&Rn.claimed)return!1;if(!o)return!0;const xa=o.toLowerCase();return Rn.name.toLowerCase().includes(xa)||Rn.email.toLowerCase().includes(xa)}),la=[...Or].sort((Rn,xa)=>{if(!Xe)return 0;let Ya=0;return Xe==="name"?Ya=bn(Rn.name).localeCompare(bn(xa.name)):Xe==="status"&&(Ya=Rn.claimed===xa.claimed?0:Rn.claimed?-1:1),rt==="asc"?Ya:-Ya});Or.filter(Rn=>Rn.claimed&&!jr(Rn.id));const Qn=Rn=>{m(xa=>{const Ya=new Set(xa);return Ya.has(Rn)?Ya.delete(Rn):Ya.add(Rn),Ya})},Cr=()=>{h.size===la.length?m(new Set):m(new Set(la.map(Rn=>Rn.id)))},Un=()=>{m(new Set)},dr=async()=>{const Rn=Array.from(h);if(Rn.length===0)return;g(!0);let xa=0,Ya=0;try{const{data:{session:ho}}=await q.auth.getSession();for(const Tc of Rn)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${ho==null?void 0:ho.access_token}`},body:JSON.stringify({userId:Tc})})).ok?xa++:Ya++}catch{Ya++}xa>0?t({title:"Success",description:`Welcome emails sent to ${xa} agent${xa>1?"s":""}${Ya>0?` (${Ya} failed)`:""}`}):t({title:"Error",description:"Failed to send welcome emails",variant:"destructive"}),Un()}catch(ho){console.error("Error bulk sending welcome emails:",ho),t({title:"Error",description:ho.message||"Failed to send welcome emails",variant:"destructive"})}finally{g(!1)}};return i?e.jsx(je,{children:e.jsx(Ie,{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):e.jsxs(e.Fragment,{children:[e.jsxs(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(Gn,{children:"Manage your brokerage's agents"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{variant:"outline",onClick:()=>J(!0),children:[e.jsx(Tf,{className:"mr-2 h-4 w-4"}),"Add Brokerage Manager"]}),e.jsxs($,{variant:"outline",onClick:()=>ne(!0),children:[e.jsx(YN,{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(Ie,{children:[e.jsxs("div",{className:"mb-4 flex flex-col gap-4 sm:flex-row sm:items-center",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Zr,{className:"absolute left-3 top-3 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search agents...",value:o,onChange:Rn=>c(Rn.target.value),className:"pl-9"})]}),e.jsxs(ms,{value:d,onValueChange:Rn=>u(Rn),children:[e.jsx(us,{className:"w-[160px]",children:e.jsx(fs,{placeholder:"Filter by status"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Agents"}),e.jsx(Ge,{value:"active",children:"Active"}),e.jsx(Ge,{value:"pending",children:"Pending"})]})]})]}),h.size>0&&e.jsxs("div",{className:"mb-4 flex items-center gap-3 rounded-lg border bg-muted/50 p-3",children:[e.jsxs("span",{className:"text-sm font-medium",children:[h.size," agent",h.size>1?"s":""," selected"]}),e.jsx("div",{className:"flex-1"}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>{const xa=r.filter(Ya=>h.has(Ya.id)&&Ya.email).map(Ya=>({email:Ya.email,name:Ya.name}));sessionStorage.setItem("campaign_direct_recipients",JSON.stringify(xa)),n("/admin/email-campaigns/new?directMode=1",{state:{directRecipients:xa}})},disabled:f,children:[e.jsx(gm,{className:"mr-2 h-4 w-4"}),"Email Agents (",h.size,")"]}),e.jsxs($,{size:"sm",variant:"outline",onClick:dr,disabled:f,children:[e.jsx(mn,{className:"mr-2 h-4 w-4"}),f?"Sending...":"Resend Welcome Email"]}),e.jsx($,{size:"sm",variant:"ghost",onClick:Un,children:"Clear"})]}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{children:[e.jsx(Dt,{className:"w-[40px]",children:e.jsx(ai,{checked:la.length>0&&h.size===la.length,onCheckedChange:Cr,"aria-label":"Select all"})}),e.jsx(Dt,{children:e.jsxs($,{variant:"ghost",size:"sm",className:"-ml-3 h-8 hover:bg-transparent",onClick:()=>xs("name"),children:["Name (Last)",Lr("name")]})}),e.jsx(Dt,{children:"Email"}),e.jsx(Dt,{children:e.jsxs($,{variant:"ghost",size:"sm",className:"-ml-3 h-8 hover:bg-transparent",onClick:()=>xs("status"),children:["Status",Lr("status")]})}),e.jsx(Dt,{children:"Actions"})]})}),e.jsx(fi,{children:la.length===0?e.jsx(En,{children:e.jsx(_t,{colSpan:5,className:"text-center text-muted-foreground",children:"No agents found"})}):la.map(Rn=>e.jsxs(En,{children:[e.jsx(_t,{children:e.jsx(ai,{checked:h.has(Rn.id),onCheckedChange:()=>Qn(Rn.id),"aria-label":`Select ${Rn.name}`})}),e.jsx(_t,{className:"font-medium",children:Rn.name}),e.jsx(_t,{children:Rn.email}),e.jsx(_t,{children:e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[Rn.claimed?e.jsx($e,{variant:"default",children:"Active"}):e.jsx($e,{variant:"secondary",children:"Pending"}),jr(Rn.id)&&e.jsxs($e,{variant:"outline",className:"border-primary text-primary",children:[e.jsx(Rm,{className:"mr-1 h-3 w-3"}),"Manager"]}),x[Rn.id]&&e.jsxs($e,{variant:"outline",className:"text-xs",children:[e.jsx(Yn,{className:"mr-1 h-3 w-3"}),"Asst: ",x[Rn.id].name||x[Rn.id].email]})]})}),e.jsx(_t,{children:e.jsxs("div",{className:"flex items-center gap-1 flex-wrap",children:[e.jsx($,{size:"sm",variant:"ghost",onClick:()=>{ss(Rn),pt(!0)},title:"Send celebration",className:"text-yellow-500 hover:text-yellow-600 hover:bg-yellow-50",children:e.jsx(Cx,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>Ut(Rn),title:"Edit agent",children:e.jsx(pi,{className:"h-4 w-4"})}),!Rn.claimed&&e.jsxs(e.Fragment,{children:[e.jsx($,{size:"sm",variant:"ghost",onClick:()=>Ss(Rn.id),title:"Resend welcome email",children:e.jsx(mn,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>kn(Rn),title:"Claim account for agent",disabled:wt===Rn.id,className:"text-green-600 hover:text-green-700 hover:bg-green-50",children:e.jsx(m2,{className:"h-4 w-4"})})]}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>kr(Rn),title:"Set password",className:"text-blue-600 hover:text-blue-700 hover:bg-blue-50",children:e.jsx(pc,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>yn(Rn.email,Rn.name),title:"Send password reset email",children:e.jsx(GI,{className:"h-4 w-4"})}),jr(Rn.id)&&e.jsx($,{size:"sm",variant:"ghost",onClick:()=>Rs(Rn.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:()=>Js(Rn),className:"text-destructive hover:text-destructive",title:"Remove agent",children:e.jsx(Hn,{className:"h-4 w-4"})})]})})]},Rn.id))})]})})]})]}),e.jsx(zs,{open:v,onOpenChange:b,children:e.jsxs(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Add New Agent"}),e.jsx(Pr,{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:Rn=>E({...A,name:Rn.target.value}),placeholder:"John Doe"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"email",children:"Email"}),e.jsx(pe,{id:"email",type:"email",value:A.email,onChange:Rn=>E({...A,email:Rn.target.value}),placeholder:"john@example.com"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"phone",children:"Phone (optional)"}),e.jsx(pe,{id:"phone",type:"tel",value:A.phone,onChange:Rn=>E({...A,phone:Rn.target.value}),placeholder:"555-123-4567"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"password",children:"Temporary Password"}),e.jsx(pe,{id:"password",type:"password",value:A.password,onChange:Rn=>E({...A,password:Rn.target.value}),placeholder:"Temporary password"})]}),I&&R.length>0&&e.jsxs("div",{children:[e.jsxs(ee,{htmlFor:"package",children:[I.name," Package"]}),e.jsxs(ms,{value:O,onValueChange:U,children:[e.jsx(us,{id:"package",children:e.jsx(fs,{placeholder:"Choose a package"})}),e.jsxs(hs,{children:[R.map(Rn=>e.jsx(Ge,{value:Rn.id,children:Rn.name},Rn.id)),e.jsx(Ge,{value:"none",children:"No package (full access)"})]})]}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:O==="none"?"Agent gets unrestricted LevelUp access.":((Pa=R.find(Rn=>Rn.id===O))==null?void 0:Pa.description)||"Their welcome email will list what is included in this package."})]})]}),e.jsxs(Sr,{children:[e.jsx($,{variant:"outline",onClick:()=>b(!1),children:"Cancel"}),e.jsx($,{onClick:ds,disabled:w,children:w?"Creating...":"Create Agent"})]})]})}),e.jsx(zs,{open:W,onOpenChange:V,children:e.jsxs(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Remove Agent"}),e.jsxs(Pr,{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(Sr,{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(EWt,{open:le,onOpenChange:ne,fixedBrokerageId:s,onSuccess:Xs}),e.jsx(zs,{open:te,onOpenChange:J,children:e.jsxs(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Add Brokerage Manager"}),e.jsx(Pr,{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(Kd,{open:Se,onOpenChange:Le,children:[e.jsx(Yd,{asChild:!0,children:e.jsxs($,{variant:"outline",role:"combobox","aria-expanded":Se,className:"w-full justify-between",children:[ce?((ii=r.find(Rn=>Rn.id===ce))==null?void 0:ii.name)+" ("+(($i=r.find(Rn=>Rn.id===ce))==null?void 0:$i.email)+")":"Select an agent to promote...",e.jsx(Sw,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Od,{className:"w-full p-0",align:"start",children:e.jsxs(S2,{children:[e.jsx(C2,{placeholder:"Search by name or email..."}),e.jsxs(A2,{className:"max-h-[200px]",children:[e.jsx(E2,{children:"No eligible agents found."}),e.jsx(Dw,{children:r.filter(Rn=>!jr(Rn.id)).map(Rn=>e.jsxs(m1,{value:`${Rn.name} ${Rn.email}`,onSelect:()=>{_e(Rn.id),Le(!1)},children:[e.jsx(ca,{className:`mr-2 h-4 w-4 ${ce===Rn.id?"opacity-100":"opacity-0"}`}),Rn.name," (",Rn.email,")"]},Rn.id))})]})]})})]}),r.filter(Rn=>!jr(Rn.id)).length===0&&e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"All agents are already brokerage managers."})]})}),e.jsxs(Sr,{children:[e.jsx($,{variant:"outline",onClick:()=>J(!1),children:"Cancel"}),e.jsx($,{onClick:hr,disabled:he||!ce,children:he?"Adding...":"Add as Manager"})]})]})}),e.jsx(zs,{open:Fe,onOpenChange:ke,children:e.jsxs(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Edit Agent"}),e.jsxs(Pr,{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:Rn=>Ce({...Ae,name:Rn.target.value}),placeholder:"Agent name"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"edit-email",children:"Email"}),e.jsx(pe,{id:"edit-email",type:"email",value:Ae.email,onChange:Rn=>Ce({...Ae,email:Rn.target.value}),placeholder:"agent@example.com"}),Ae.email.trim().toLowerCase()!==(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:Rn=>Ce({...Ae,phone:Rn.target.value}),placeholder:"555-123-4567"})]})]}),e.jsxs(Sr,{children:[e.jsx($,{variant:"outline",onClick:()=>ke(!1),children:"Cancel"}),e.jsx($,{onClick:hn,disabled:Ve||qe,children:qe?"Updating email...":Ve?"Saving...":"Save Changes"})]})]})}),gt&&e.jsx(TWt,{open:Je,onOpenChange:Rn=>{pt(Rn),Rn||ss(null)},userId:gt.id,userName:gt.name}),e.jsx(zs,{open:Yt,onOpenChange:ts,children:e.jsxs(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Set Password"}),e.jsxs(Pr,{children:["Set a new password for ",ys==null?void 0:ys.name,". They will be able to log in with this password immediately."]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"new-password",children:"New Password"}),e.jsx(pe,{id:"new-password",type:"password",value:Ft,onChange:Rn=>as(Rn.target.value),placeholder:"Enter new password (min 6 characters)"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Make sure to communicate this password to the agent through a secure channel."})]}),e.jsxs(Sr,{children:[e.jsx($,{variant:"outline",onClick:()=>ts(!1),children:"Cancel"}),e.jsx($,{onClick:$n,disabled:kt||!Ft||Ft.length<6,children:kt?"Setting...":"Set Password"})]})]})})]})},gRn={academy_video:"Academy Video",template:"Template",toolbox:"Toolbox Resource",newsletter:"Newsletter",social_swag:"Social Swag",event:"Event"},xRn={view:"Viewed",click_canva:"Opened Canva",click_pdf:"Downloaded PDF",click_video:"Watched Video",click_link:"Clicked Link",register:"Registered"},yRn=s=>{switch(s){case"academy_video":return e.jsx(ua,{className:"h-4 w-4"});case"template":return e.jsx(Jr,{className:"h-4 w-4"});case"toolbox":return e.jsx(Jr,{className:"h-4 w-4"});case"newsletter":return e.jsx(QN,{className:"h-4 w-4"});case"social_swag":return e.jsx(Nn,{className:"h-4 w-4"});case"event":return e.jsx(Ta,{className:"h-4 w-4"});default:return e.jsx(Fr,{className:"h-4 w-4"})}},vRn=({brokerageId:s})=>{const{toast:t}=Bi(),[n,r]=j.useState([]),[a,i]=j.useState([]),[l,o]=j.useState([]),[c,d]=j.useState(!0),[u,h]=j.useState(null);j.useEffect(()=>{m()},[s]);const m=async()=>{try{d(!0);const{data:x,error:y}=await q.from("profiles").select("id, name, email").eq("brokerage_id",s);if(y)throw y;const v=x.map(O=>O.id),b=new Map(x.map(O=>[O.id,O]));if(v.length===0){r([]),i([]),o([]);return}const{data:w,error:S}=await q.from("activity_logs").select("*").in("user_id",v).order("launched_at",{ascending:!1});if(S)throw S;const 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",v).order("created_at",{ascending:!1});if(I)throw I;const P=(E||[]).map(O=>{var U,W;return{id:O.id,user_id:O.user_id,resource_type:O.resource_type,resource_id:O.resource_id,resource_title:O.resource_title,action_type:O.action_type,created_at:O.created_at,user_name:((U=b.get(O.user_id))==null?void 0:U.name)||"Unknown",user_email:((W=b.get(O.user_id))==null?void 0:W.email)||"Unknown"}});i(P);const R=new Map;x.forEach(O=>{R.set(O.id,{user_id:O.id,user_name:O.name,user_email:O.email,app_launches:0,content_views:0,last_activity:""})}),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(y=>y.user_id===x),g=x=>a.filter(y=>y.user_id===x);return c?e.jsx(je,{children:e.jsx(Ie,{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):e.jsxs(e.Fragment,{children:[e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{children:"Agent Activity"}),e.jsx(Gn,{children:"Track app usage and content engagement - click an agent for details"})]}),e.jsx(Ie,{children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Agent"}),e.jsx(Dt,{className:"text-center",children:"App Launches"}),e.jsx(Dt,{className:"text-center",children:"Content Views"}),e.jsx(Dt,{children:"Last Active"})]})}),e.jsx(fi,{children:l.length===0?e.jsx(En,{children:e.jsx(_t,{colSpan:4,className:"text-center text-muted-foreground",children:"No activity yet"})}):l.map(x=>e.jsxs(En,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>h({id:x.user_id,name:x.user_name,email:x.user_email}),children:[e.jsx(_t,{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(_t,{className:"text-center",children:e.jsxs($e,{variant:"outline",className:"gap-1",children:[e.jsx(zu,{className:"h-3 w-3"}),x.app_launches]})}),e.jsx(_t,{className:"text-center",children:e.jsxs($e,{variant:"secondary",className:"gap-1",children:[e.jsx(Jr,{className:"h-3 w-3"}),x.content_views]})}),e.jsx(_t,{className:"text-sm text-muted-foreground",children:x.last_activity&&hu(new Date(x.last_activity),{addSuffix:!0})})]},x.user_id))})]})})})]}),e.jsx(zs,{open:!!u,onOpenChange:x=>!x&&h(null),children:e.jsxs(Os,{className:"max-w-3xl max-h-[80vh] overflow-hidden flex flex-col",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{children:[u==null?void 0:u.name,"'s Activity"]}),e.jsx(Pr,{children:u==null?void 0:u.email})]}),e.jsxs(ha,{defaultValue:"content",className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(ma,{className:"grid w-full grid-cols-2",children:[e.jsx(Zt,{value:"content",children:"Content Engagement"}),e.jsx(Zt,{value:"apps",children:"App Launches"})]}),e.jsx(Xt,{value:"content",className:"flex-1 overflow-auto",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Resource"}),e.jsx(Dt,{children:"Type"}),e.jsx(Dt,{children:"Action"}),e.jsx(Dt,{children:"Time"})]})}),e.jsx(fi,{children:u&&g(u.id).length===0?e.jsx(En,{children:e.jsx(_t,{colSpan:4,className:"text-center text-muted-foreground",children:"No content engagement yet"})}):u&&g(u.id).map(x=>e.jsxs(En,{children:[e.jsx(_t,{className:"max-w-[200px] truncate font-medium",children:x.resource_title}),e.jsx(_t,{children:e.jsxs($e,{variant:"outline",className:"gap-1",children:[yRn(x.resource_type),gRn[x.resource_type]||x.resource_type]})}),e.jsx(_t,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:xRn[x.action_type]||x.action_type})}),e.jsx(_t,{className:"text-sm text-muted-foreground",children:hu(new Date(x.created_at),{addSuffix:!0})})]},x.id))})]})})}),e.jsx(Xt,{value:"apps",className:"flex-1 overflow-auto",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"App"}),e.jsx(Dt,{children:"Time"})]})}),e.jsx(fi,{children:u&&f(u.id).length===0?e.jsx(En,{children:e.jsx(_t,{colSpan:2,className:"text-center text-muted-foreground",children:"No app launches yet"})}):u&&f(u.id).map(x=>e.jsxs(En,{children:[e.jsx(_t,{children:e.jsx($e,{variant:"outline",children:x.app_name})}),e.jsx(_t,{className:"text-sm text-muted-foreground",children:hu(new Date(x.launched_at),{addSuffix:!0})})]},x.id))})]})})})]})]})})]})},bRn=({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:y}=await q.from("activity_logs").select("*",{count:"exact",head:!0}).in("user_id",d),v=new Date;v.setDate(v.getDate()-7);const{count:b}=await q.from("activity_logs").select("*",{count:"exact",head:!0}).in("user_id",d).gte("launched_at",v.toISOString()),w=new Date;w.setMonth(w.getMonth()-1);const{count:S}=await q.from("activity_logs").select("*",{count:"exact",head:!0}).in("user_id",d).gte("launched_at",w.toISOString());r({totalAgents:u,activeAgents:g,pendingAgents:x,totalLaunches:y||0,launchesThisWeek:b||0,launchesThisMonth:S||0})}catch(o){console.error("Error loading analytics:",o),t({title:"Error",description:"Failed to load analytics",variant:"destructive"})}finally{i(!1)}};return a?e.jsx(je,{children:e.jsx(Ie,{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):e.jsxs("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:[e.jsxs(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(Ie,{children:[e.jsx("div",{className:"text-2xl font-bold",children:n.totalAgents}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[n.activeAgents," active, ",n.pendingAgents," pending"]})]})]}),e.jsxs(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(Ie,{children:[e.jsx("div",{className:"text-2xl font-bold",children:n.activeAgents}),e.jsx("p",{className:"text-xs text-muted-foreground",children:n.totalAgents>0?`${Math.round(n.activeAgents/n.totalAgents*100)}% of total`:"0% of total"})]})]}),e.jsxs(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(da,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ie,{children:[e.jsx("div",{className:"text-2xl font-bold",children:n.pendingAgents}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Awaiting setup"})]})]}),e.jsxs(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(Ie,{children:[e.jsx("div",{className:"text-2xl font-bold",children:n.totalLaunches}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"All time"})]})]}),e.jsxs(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(Ie,{children:[e.jsx("div",{className:"text-2xl font-bold",children:n.launchesThisWeek}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Last 7 days"})]})]}),e.jsxs(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(Ie,{children:[e.jsx("div",{className:"text-2xl font-bold",children:n.launchesThisMonth}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Last 30 days"})]})]})]})},_Rn=({brokerageId:s})=>{const[t,n]=j.useState([]),[r,a]=j.useState(!0),[i,l]=j.useState(!1),[o,c]=j.useState(!1),[d,u]=j.useState({description:"",maxUses:""});j.useEffect(()=>{h()},[s]);const h=async()=>{try{const{data:v,error:b}=await q.from("invite_codes").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(b)throw b;n(v||[])}catch(v){console.error("Error loading invite codes:",v),re.error("Failed to load invite links")}finally{a(!1)}},m=()=>Math.random().toString(36).substring(2,8).toUpperCase(),f=async()=>{l(!0);try{const v=m(),{error:b}=await q.from("invite_codes").insert({code:v,description:d.description||null,max_uses:d.maxUses?parseInt(d.maxUses):null,brokerage_id:s,is_active:!0});if(b)throw b;re.success("Invite link created!"),c(!1),u({description:"",maxUses:""}),h()}catch(v){console.error("Error creating invite code:",v),re.error("Failed to create invite link")}finally{l(!1)}},g=async v=>{try{const{error:b}=await q.from("invite_codes").delete().eq("id",v);if(b)throw b;re.success("Invite link deleted"),n(t.filter(w=>w.id!==v))}catch(b){console.error("Error deleting invite code:",b),re.error("Failed to delete invite link")}},x=async(v,b)=>{try{const{error:w}=await q.from("invite_codes").update({is_active:!b}).eq("id",v);if(w)throw w;n(t.map(S=>S.id===v?{...S,is_active:!b}:S)),re.success(`Invite link ${b?"deactivated":"activated"}`)}catch(w){console.error("Error toggling invite code:",w),re.error("Failed to update invite link")}},y=v=>{const b=`${window.location.origin}/join?code=${v}`;navigator.clipboard.writeText(b),re.success("Link copied to clipboard!")};return r?e.jsx(je,{children:e.jsx(Ie,{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(Gn,{children:"Create shareable links for agents to join your brokerage"})]}),e.jsxs(zs,{open:o,onOpenChange:c,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{size:"sm",children:[e.jsx(dn,{className:"mr-2 h-4 w-4"}),"Create Link"]})}),e.jsxs(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Create Invite Link"}),e.jsx(Pr,{children:"Create a new invite link for agents to join your brokerage"})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"description",children:"Description (optional)"}),e.jsx(pe,{id:"description",placeholder:"e.g., New agent recruiting campaign",value:d.description,onChange:v=>u({...d,description:v.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"maxUses",children:"Max Uses (optional)"}),e.jsx(pe,{id:"maxUses",type:"number",placeholder:"Leave empty for unlimited",value:d.maxUses,onChange:v=>u({...d,maxUses:v.target.value})})]}),e.jsx($,{onClick:f,disabled:i,className:"w-full",children:i?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating..."]}):"Create Invite Link"})]})]})]})]}),e.jsx(Ie,{children:t.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(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(v=>e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border bg-card",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("code",{className:"text-sm font-mono bg-muted px-2 py-0.5 rounded",children:v.code}),e.jsx($e,{variant:v.is_active?"default":"secondary",children:v.is_active?"Active":"Inactive"})]}),v.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1 truncate",children:v.description}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[v.uses_count," uses",v.max_uses&&` / ${v.max_uses} max`]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($,{variant:"ghost",size:"sm",onClick:()=>y(v.code),title:"Copy link",children:e.jsx(Ha,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>x(v.id,v.is_active),title:v.is_active?"Deactivate":"Activate",children:v.is_active?"Disable":"Enable"}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>g(v.id),className:"text-destructive hover:text-destructive",title:"Delete",children:e.jsx(Hn,{className:"h-4 w-4"})})]})]},v.id))})})]})},wRn=({open:s,onOpenChange:t,referralCode:n,brokerageId:r,senderName:a,brokerageName:i,onInvitesSent:l})=>{const[o,c]=j.useState(""),[d,u]=j.useState([]),[h,m]=j.useState(""),[f,g]=j.useState(!1),x=S=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(S),y=()=>{const S=o.trim().toLowerCase();if(S&&x(S)&&!d.includes(S)){if(d.length>=10){re.error("Maximum 10 emails per invite");return}u([...d,S]),c("")}else S&&!x(S)?re.error("Please enter a valid email address"):d.includes(S)&&re.error("Email already added")},v=S=>{u(d.filter(A=>A!==S))},b=S=>{(S.key==="Enter"||S.key===",")&&(S.preventDefault(),y())},w=async()=>{if(d.length===0){re.error("Please add at least one email address");return}g(!0);try{const{data:S,error: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?re.success(`${S.successCount} invite${S.successCount>1?"s":""} sent successfully!`):re.warning(`${S.successCount} of ${S.totalCount} invites sent. Some failed.`),u([]),m(""),t(!1),l==null||l()}catch(S){console.error("Error sending invites:",S),re.error("Failed to send invites. Please try again.")}finally{g(!1)}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-[550px]",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(mn,{className:"h-5 w-5 text-primary"}),"Invite Broker Friends"]}),e.jsx(Pr,{children:"Send a personalized email invitation to broker owners you know. They'll receive a beautiful email highlighting LevelUp's features."})]}),e.jsxs("div",{className:"bg-gradient-to-r from-primary/10 to-primary/5 border border-primary/20 rounded-lg p-4 flex items-center gap-3",children:[e.jsx("div",{className:"bg-primary/20 rounded-full p-2",children:e.jsx(ul,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-sm",children:"Earn $25/month for each referral!"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"When they sign up and stay for 30 days, you save on your membership forever."})]})]}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"email",children:"Email Addresses (up to 10)"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{id:"email",type:"email",placeholder:"Enter email and press Enter",value:o,onChange:S=>c(S.target.value),onKeyDown:b,onBlur:y}),e.jsx($,{type:"button",variant:"secondary",onClick:y,children:"Add"})]}),d.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:d.map(S=>e.jsxs($e,{variant:"secondary",className:"flex items-center gap-1 pr-1",children:[S,e.jsx("button",{type:"button",onClick:()=>v(S),className:"ml-1 rounded-full p-0.5 hover:bg-muted",children:e.jsx(pr,{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(Ls,{id:"message",placeholder:"Add a personal note that will appear at the top of the email...",value:h,onChange:S=>m(S.target.value),rows:3,maxLength:500}),e.jsxs("p",{className:"text-xs text-muted-foreground text-right",children:[h.length,"/500 characters"]})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-4 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(Nn,{className:"h-4 w-4 text-primary"}),"What they'll receive:"]}),e.jsxs("ul",{className:"text-xs text-muted-foreground space-y-1",children:[e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-1 h-1 rounded-full bg-primary"}),"Beautiful branded email from you"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-1 h-1 rounded-full bg-primary"}),"Your personal message (if added)"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-1 h-1 rounded-full bg-primary"}),"Key LevelUp features for brokerages"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-1 h-1 rounded-full bg-primary"}),"Direct signup link with your referral code"]})]})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx($,{onClick:w,disabled:d.length===0||f,children:f?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent mr-2"}),"Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Kr,{className:"h-4 w-4 mr-2"}),"Send ",d.length>0&&`(${d.length})`," Invite",d.length!==1?"s":""]})})]})]})})},jRn=({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(Nu,{className:"h-3 w-3"}),"Expired"]});default:return e.jsxs($e,{variant:"secondary",className:"gap-1",children:[e.jsx(da,{className:"h-3 w-3"}),"Pending"]})}};return a?e.jsx("div",{className:"flex justify-center py-4",children:e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-primary border-t-transparent"})}):n.length===0?e.jsxs("div",{className:"text-center py-6 text-muted-foreground",children:[e.jsx(mn,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No invites sent yet"}),e.jsx("p",{className:"text-xs",children:"Start inviting broker friends to earn rewards!"})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium mb-3",children:"Recent Invites"}),n.map(c=>e.jsxs("div",{className:"flex items-center justify-between p-2.5 bg-muted/30 rounded-lg",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:c.recipient_email}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Sent ",en(new Date(c.sent_at),"MMM d, yyyy")]})]}),o(c.status)]},c.id))]})},NRn=()=>{const{brokerageId:s,user:t}=bs(),[n,r]=j.useState(null),[a,i]=j.useState(""),[l,o]=j.useState(""),[c,d]=j.useState([]),[u,h]=j.useState(!0),[m,f]=j.useState(!1),[g,x]=j.useState(0);j.useEffect(()=>{s&&y()},[s]);const y=async()=>{try{const[E,I]=await Promise.all([q.from("brokerages").select("name").eq("id",s).single(),t?q.from("profiles").select("name").eq("id",t.id).single():Promise.resolve({data:null})]);E.data&&i(E.data.name),I.data&&o(I.data.name||"A LevelUp Member");const{data:P}=await q.from("referral_codes").select("code").eq("brokerage_id",s).single();if(P)r(P.code);else{const D=`REF${s==null?void 0:s.slice(0,8).toUpperCase()}`;await q.from("referral_codes").insert({brokerage_id:s,code:D}),r(D)}const{data:R}=await q.from("referrals").select(` *, referred_user:profiles!referred_user_id(name, email), referred_brokerage:brokerages!referred_brokerage_id(name) `).eq("referrer_brokerage_id",s).order("created_at",{ascending:!1});d(R||[])}catch(E){console.error("Error fetching referral data:",E)}finally{h(!1)}},v=()=>{const E=`https://dashboard.relevelup.com/?ref=${n}`;navigator.clipboard.writeText(E),re.success("Referral link copied to clipboard!")},b=c.filter(E=>E.status==="qualified").length,w=c.filter(E=>E.status==="pending").length,S=b*25,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(ul,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-bold",children:"Referral Rewards Program"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Earn $25/month off your membership for every broker you refer"})]})]}),e.jsx("div",{className:"mt-4 bg-background/80 rounded-lg p-4 border",children:e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-4",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsxs("p",{className:"text-3xl font-bold text-primary",children:["$",S]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Monthly Savings"})]}),S>0&&e.jsxs("div",{className:"flex items-center gap-1 text-green-600",children:[e.jsx(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(Nn,{className:"h-5 w-5"}),e.jsx("span",{className:"font-bold",children:"FREE Membership Unlocked!"})]})]})})]})}),e.jsxs(Ie,{className:"pt-6 space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs($,{onClick:()=>f(!0),className:"w-full",size:"lg",children:[e.jsx(mn,{className:"h-4 w-4 mr-2"}),"Invite Broker Friends"]}),e.jsxs($,{onClick:v,variant:"outline",className:"w-full",size:"lg",children:[e.jsx(Ha,{className:"h-4 w-4 mr-2"}),"Copy Referral Link"]})]}),e.jsxs("div",{className:"p-4 bg-muted/50 rounded-lg",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Your Referral Link"}),e.jsxs("code",{className:"block px-3 py-2 bg-background rounded border text-sm break-all",children:["https://dashboard.relevelup.com/?ref=",n]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{className:"text-center p-4 bg-green-50 dark:bg-green-950/20 rounded-lg border border-green-200 dark:border-green-900",children:[e.jsx(nu,{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(da,{className:"h-5 w-5 mx-auto text-amber-600 mb-1"}),e.jsx("p",{className:"text-2xl font-bold text-amber-700 dark:text-amber-400",children:w}),e.jsx("p",{className:"text-xs text-amber-600 dark:text-amber-500",children:"Pending (30 days)"})]})]}),e.jsxs("div",{className:"bg-muted/30 rounded-lg p-4",children:[e.jsx("h4",{className:"font-semibold text-sm mb-3",children:"How It Works"}),e.jsxs("div",{className:"space-y-2 text-sm text-muted-foreground",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"bg-primary text-primary-foreground rounded-full w-5 h-5 flex items-center justify-center text-xs shrink-0",children:"1"}),e.jsx("p",{children:"Share your referral link or send an invite email to broker friends"})]}),e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"bg-primary text-primary-foreground rounded-full w-5 h-5 flex items-center justify-center text-xs shrink-0",children:"2"}),e.jsx("p",{children:"They sign up and subscribe to LevelUp"})]}),e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"bg-primary text-primary-foreground rounded-full w-5 h-5 flex items-center justify-center text-xs shrink-0",children:"3"}),e.jsx("p",{children:"After 30 days, you get $25/month off your membership - forever!"})]})]})]}),e.jsx(jRn,{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(wRn,{open:m,onOpenChange:f,referralCode:n||"",brokerageId:s||"",senderName:l||"A LevelUp Member",brokerageName:a,onInvitesSent:()=>x(E=>E+1)})]})},kRn=({brokerageId:s})=>{const t=Xn(),{teams:n,isLoading:r}=u3(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:y}=await q.from("innercircle_contacts").select("owner_user_id").in("owner_user_id",m),{data:v}=await q.from("deal_pipeline").select("owner_user_id").in("owner_user_id",m),{data:b}=await q.from("agent_videos").select("owner_user_id").in("owner_user_id",m).eq("is_deleted",!1),w=new Map;(y||[]).forEach(E=>{w.set(E.owner_user_id,(w.get(E.owner_user_id)||0)+1)});const S=new Map;(v||[]).forEach(E=>{S.set(E.owner_user_id,(S.get(E.owner_user_id)||0)+1)});const 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(Ie,{children:e.jsx(xn,{className:"h-24 w-full"})})]},u))});if(n.length===0)return e.jsx(je,{children:e.jsxs(Ie,{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(Ie,{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(Ie,{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(Ie,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(UI,{className:"h-4 w-4"})," Total Contacts"]}),e.jsx("p",{className:"text-2xl font-bold",children:c.toLocaleString()})]})}),e.jsx(je,{children:e.jsxs(Ie,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(kx,{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(Bg,{className:"h-3 w-3 text-amber-500"}),u.leader_name]})]})]}),e.jsx(Ie,{children:e.jsxs("div",{className:"grid grid-cols-3 gap-3 text-center",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-semibold",children:u.total_contacts.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Contacts"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-semibold",children:u.total_deals.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Deals"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-semibold",children:u.total_videos.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Videos"})]})]})})]},u.team_id))}),e.jsx("div",{className:"flex justify-end",children:e.jsx($,{variant:"outline",onClick:()=>t("/brokerage/teams"),children:"Manage Teams →"})})]})},SRn=()=>{const{user:s,isBrokerageManager:t,brokerageId:n,isAdmin:r,managedBrokerages:a,selectedBrokerageId:i,setSelectedBrokerageId:l}=bs(),o=Xn(),{toast:c}=Bi(),[d,u]=j.useState(""),[h,m]=j.useState(!0),f=i||(a.length>0?a[0].id:n);j.useEffect(()=>{if(!s||!t&&!r){o("/dashboard");return}!i&&a.length>0&&l(a[0].id),f?g():a.length===0&&!n&&m(!1)},[s,t,r,f,o,a,i]);const g=async()=>{if(!f){m(!1);return}try{const{data:x,error:y}=await q.from("brokerages").select("name").eq("id",f).single();if(y)throw y;u(x.name)}catch(x){console.error("Error loading brokerage info:",x),c({title:"Error",description:"Failed to load brokerage information",variant:"destructive"})}finally{m(!1)}};return h?e.jsx(Vs,{title:"Manage Brokerages",description:"Loading brokerage information...",children:e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):f?e.jsx(Vs,{title:d||"Manage Brokerages",description:"Brokerage Management Dashboard",children:e.jsxs("div",{className:"space-y-6",children:[a.length>1&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Managing:"}),e.jsxs(ms,{value:i||"",onValueChange:l,children:[e.jsxs(us,{className:"w-[280px]",children:[e.jsx(ji,{className:"mr-2 h-4 w-4"}),e.jsx(fs,{placeholder:"Select brokerage"})]}),e.jsx(hs,{children:a.map(x=>e.jsx(Ge,{value:x.id,children:x.name},x.id))})]})]}),e.jsxs(ha,{defaultValue:"agents",className:"space-y-4",children:[e.jsxs(ma,{className:"grid w-full grid-cols-4 md:grid-cols-8",children:[e.jsx(Zt,{value:"agents",children:"Agents"}),e.jsx(Zt,{value:"teams",children:"Teams"}),e.jsx(Zt,{value:"invite",children:"Invite Links"}),e.jsx(Zt,{value:"referrals",children:"Referrals"}),e.jsx(Zt,{value:"leaderboard",children:"Leaderboard"}),e.jsx(Zt,{value:"activity",children:"Activity"}),e.jsx(Zt,{value:"analytics",children:"Analytics"}),e.jsx(Zt,{value:"shares",children:"Shares"})]}),e.jsx(Xt,{value:"agents",className:"space-y-4",children:e.jsx(pRn,{brokerageId:f})}),e.jsx(Xt,{value:"teams",className:"space-y-4",children:e.jsx(kRn,{brokerageId:f})}),e.jsx(Xt,{value:"invite",className:"space-y-4",children:e.jsx(_Rn,{brokerageId:f})}),e.jsx(Xt,{value:"referrals",className:"space-y-4",children:e.jsx(NRn,{})}),e.jsx(Xt,{value:"leaderboard",className:"space-y-4",children:e.jsx(yHt,{brokerageId:f,title:`${d} Event Leaderboard`,showUserStats:!1})}),e.jsx(Xt,{value:"activity",className:"space-y-4",children:e.jsx(vRn,{brokerageId:f})}),e.jsx(Xt,{value:"analytics",className:"space-y-4",children:e.jsx(bRn,{brokerageId:f})}),e.jsx(Xt,{value:"shares",className:"space-y-4",children:e.jsx(FWt,{brokerageOnly:!0,brokerageId:f})})]})]})}):e.jsx(Vs,{title:"Manage Brokerages",description:"Brokerage Management",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(ji,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"No Brokerage Assigned"}),e.jsx("p",{className:"text-muted-foreground",children:"You don't have any brokerages to manage."})]})})};function CRn({brokerageId:s,canManage:t}){const{user:n}=bs(),[r,a]=j.useState([]),[i,l]=j.useState(!0),[o,c]=j.useState(!1),[d,u]=j.useState(null),[h,m]=j.useState(null),[f,g]=j.useState(!1),[x,y]=j.useState(""),[v,b]=j.useState(""),[w,S]=j.useState(!1),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]))||[]),Y=U.map(X=>({...X,author:G.get(X.created_by)||{name:"Unknown",avatar_url:null}}));a(Y)}else a([])}catch(D){console.error("Error fetching announcements:",D)}finally{l(!1)}};j.useEffect(()=>{A()},[s]);const E=()=>{y(""),b(""),S(!1),u(null)},I=D=>{D?(u(D),y(D.title),b(D.content),S(D.is_pinned)):E(),c(!0)},P=async()=>{if(!x.trim()||!v.trim()){re.error("Please fill in all fields");return}g(!0);try{if(d){const{error:D}=await q.from("brokerage_announcements").update({title:x.trim(),content:v.trim(),is_pinned:w,pinned_at:w?new Date().toISOString():null}).eq("id",d.id);if(D)throw D;re.success("Announcement updated")}else{const{error:D}=await q.from("brokerage_announcements").insert({brokerage_id:s,created_by:n==null?void 0:n.id,title:x.trim(),content:v.trim(),is_pinned:w,pinned_at:w?new Date().toISOString():null});if(D)throw D;re.success("Announcement created")}c(!1),E(),A()}catch(D){console.error("Error saving announcement:",D),re.error("Failed to save announcement")}finally{g(!1)}},R=async()=>{if(h)try{const{error:D}=await q.from("brokerage_announcements").delete().eq("id",h);if(D)throw D;re.success("Announcement deleted"),A()}catch(D){console.error("Error deleting announcement:",D),re.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(Ie,{children:e.jsx("div",{className:"animate-pulse space-y-3",children:e.jsx("div",{className:"h-20 bg-muted rounded"})})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(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(dn,{className:"h-4 w-4"}),"New"]})]}),e.jsx(Ie,{children:r.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No announcements yet"}):e.jsx("div",{className:"space-y-4",children:r.map(D=>{var O,U,W,V;return e.jsx("div",{className:`p-4 rounded-lg border ${D.is_pinned?"bg-primary/5 border-primary/20":"bg-muted/30"}`,children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[D.is_pinned&&e.jsx(LE,{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:en(new Date(D.created_at),"MMM d, yyyy")})]})]}),t&&e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>I(D),children:e.jsx(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(Hn,{className:"h-4 w-4"})})]})]})},D.id)})})})]}),e.jsx(zs,{open:o,onOpenChange:c,children:e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsx(Bs,{children:d?"Edit Announcement":"New Announcement"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"title",children:"Title"}),e.jsx(pe,{id:"title",value:x,onChange:D=>y(D.target.value),placeholder:"Announcement title..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"content",children:"Content"}),e.jsx(Ls,{id:"content",value:v,onChange:D=>b(D.target.value),placeholder:"Write your announcement...",rows:4})]}),e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sn,{id:"pinned",checked:w,onCheckedChange:S}),e.jsxs(ee,{htmlFor:"pinned",className:"flex items-center gap-1 cursor-pointer",children:[e.jsx(LE,{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 ARn({brokerageId:s,canManage:t=!1}){const{startImpersonation:n,isLoading:r}=uLe(),{user:a}=bs(),[i,l]=j.useState([]),[o,c]=j.useState(!0),[d,u]=j.useState(""),[h,m]=j.useState(new Set);j.useEffect(()=>{(async()=>{try{const{data:x,error:y}=await q.from("profiles").select("id, name, email, phone, avatar_url, title, bio, areas_served, years_experience, instagram_url, facebook_url, linkedin_url").eq("brokerage_id",s).order("name");if(y)throw y;if(l(x||[]),x&&x.length>0){const v=x.map(w=>w.id),{data:b}=await q.from("agent_assistant_assignments").select("agent_id").in("agent_id",v);b&&m(new Set(b.map(w=>w.agent_id)))}}catch(x){console.error("Error fetching agents:",x)}finally{c(!1)}})()},[s]);const f=i.filter(g=>{var x,y;return g.name.toLowerCase().includes(d.toLowerCase())||g.email.toLowerCase().includes(d.toLowerCase())||((x=g.title)==null?void 0:x.toLowerCase().includes(d.toLowerCase()))||((y=g.areas_served)==null?void 0:y.toLowerCase().includes(d.toLowerCase()))});return o?e.jsxs(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(Ie,{children:e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:[1,2,3,4].map(g=>e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-48 bg-muted rounded-lg"})},g))})})]}):e.jsxs(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(Zr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search agents...",value:d,onChange:g=>u(g.target.value),className:"pl-9"})]})]}),e.jsx(Ie,{children:f.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:d?"No agents match your search":"No agents in this brokerage yet"}):e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:f.map(g=>e.jsx(ERn,{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 ERn({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(ci,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate",children:s.areas_served})]}),s.years_experience&&e.jsxs("p",{className:"text-xs text-muted-foreground text-center",children:[s.years_experience," ",s.years_experience===1?"year":"years"," experience"]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-2",children:[n&&e.jsxs(iy,{children:[e.jsx(oy,{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(KI,{className:"h-4 w-4"})})}),e.jsxs(jx,{children:["Login as ",s.name]})]}),s.phone&&e.jsx($,{variant:"outline",size:"icon",className:"h-8 w-8",asChild:!0,children:e.jsx("a",{href:`tel:${s.phone}`,title:`Call ${s.name}`,children:e.jsx(Da,{className:"h-4 w-4"})})}),e.jsx($,{variant:"outline",size:"icon",className:"h-8 w-8",asChild:!0,children:e.jsx("a",{href:`mailto:${s.email}`,title:`Email ${s.name}`,children:e.jsx(mn,{className:"h-4 w-4"})})}),s.linkedin_url&&e.jsx($,{variant:"outline",size:"icon",className:"h-8 w-8",asChild:!0,children:e.jsx("a",{href:s.linkedin_url,target:"_blank",rel:"noopener noreferrer",title:"LinkedIn",children:e.jsx(dy,{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 TRn({brokerageId:s}){const[t,n]=j.useState([]),[r,a]=j.useState(!0);if(j.useEffect(()=>{(async()=>{try{const{data:c,error:d}=await q.from("profiles").select("id, name, avatar_url").eq("brokerage_id",s);if(d)throw d;if(!c||c.length===0){n([]),a(!1);return}const u=c.map(x=>x.id),{data:h,error:m}=await q.from("agent_attendance_stats").select("user_id, total_points").in("user_id",u).order("total_points",{ascending:!1});if(m)throw m;const f=new Map(c.map(x=>[x.id,x])),g=(h||[]).filter(x=>x.total_points>0).map(x=>{const y=f.get(x.user_id);return{user_id:x.user_id,total_points:x.total_points,name:(y==null?void 0:y.name)||"Unknown",avatar_url:(y==null?void 0:y.avatar_url)||null}});n(g)}catch(c){console.error("Error fetching leaderboard:",c)}finally{a(!1)}})()},[s]),r)return e.jsxs(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(Ie,{children:e.jsx("div",{className:"animate-pulse space-y-3",children:[1,2,3].map(o=>e.jsx("div",{className:"h-12 bg-muted rounded"},o))})})]});const i=o=>o===1?"text-yellow-500":o===2?"text-gray-400":o===3?"text-amber-600":"text-muted-foreground",l=o=>o<=3?e.jsx(TE,{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(Ie,{children:t.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No points earned yet. Attend events to earn points!"}):e.jsx("div",{className:"space-y-2",children:t.slice(0,10).map((o,c)=>{const d=o.name.split(" ").map(h=>h[0]).join("").toUpperCase().slice(0,2),u=c+1;return e.jsxs("div",{className:Pt("flex items-center gap-3 p-2 rounded-lg",u<=3&&"bg-muted/50"),children:[e.jsx("div",{className:"w-6 flex justify-center",children:l(u)}),e.jsxs(Oa,{className:"h-8 w-8",children:[e.jsx(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 MRn({brokerageId:s}){const t=Xn(),[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(Ie,{children:e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[1,2].map(o=>e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-32 bg-muted rounded-lg"})},o))})})]}):e.jsxs(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(dn,{className:"h-4 w-4"}),"Add Listing"]})]}),e.jsxs(Ie,{children:[n.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx(va,{className:"h-10 w-10 text-muted-foreground mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"No active listings from your brokerage yet"}),e.jsxs($,{size:"sm",onClick:()=>t("/mission-control/listings/new"),className:"gap-1",children:[e.jsx(dn,{className:"h-4 w-4"}),"Add Your First Listing"]})]}):e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:n.map(o=>e.jsxs("div",{onClick:()=>window.open(`https://listings.relevelup.com/${o.slug||o.id}`,"_blank"),className:"group cursor-pointer border rounded-lg overflow-hidden hover:shadow-md transition-shadow",children:[e.jsxs("div",{className:"relative h-24 bg-muted",children:[o.photos&&o.photos.length>0?e.jsx("img",{src:o.photos[0].photo_url,alt:o.property_address||"Listing",className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(va,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx("div",{className:"absolute top-2 left-2",children:e.jsx("span",{className:"text-[10px] font-medium bg-primary text-primary-foreground px-1.5 py-0.5 rounded uppercase",children:o.property_type.replace("_"," ")})})]}),e.jsxs("div",{className:"p-2.5",children:[e.jsx("p",{className:"font-semibold text-sm text-primary",children:l(o.price)}),e.jsx("p",{className:"text-xs text-muted-foreground truncate mt-0.5",children:o.property_address||"Address not available"}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:o.city}),o.agent&&e.jsxs("p",{className:"text-[10px] text-muted-foreground mt-1.5 truncate",children:["Listed by ",o.agent.name]})]})]},o.id))}),n.length>0&&e.jsxs($,{variant:"ghost",size:"sm",className:"w-full mt-3",onClick:()=>t("/mission-control/listings"),children:["View All Listings",e.jsx(Fr,{className:"h-3 w-3 ml-1"})]})]})]})}const PRn={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 IRn({brokerageId:s,canManage:t}){const{user:n}=bs(),{toast:r}=Bi(),{data:a,isLoading:i}=vsn(s),l=bsn(s),[o,c]=j.useState({...PRn}),[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 xHt(n.id,w,`brokerage-${b}`);g(b,S),r({title:"Image uploaded"})}catch(S){r({title:"Upload failed",description:S.message,variant:"destructive"})}finally{m(null)}}},y=async()=>{try{await l.mutateAsync({...Object.fromEntries(Object.entries(o).map(([b,w])=>[b,w||null])),...d}),r({title:"Brokerage brand saved",description:"Agents in this brokerage now inherit these settings."})}catch(b){r({title:"Could not save",description:b.message,variant:"destructive"})}},v=(b,w)=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:w}),e.jsxs("div",{className:"flex items-center gap-3",children:[o[b]&&e.jsx("img",{src:o[b],alt:w,className:"h-12 w-auto rounded border bg-background p-1"}),e.jsx("input",{ref:f[b],type:"file",accept:"image/*",className:"hidden",onChange:S=>{var 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(ji,{className:"h-5 w-5"}),"Brokerage Brand"]}),e.jsx(Gn,{children:t?"Every agent in this brokerage inherits these colors, logos and disclaimer wherever they leave their own brand blank — including AI-generated marketing through the LevelUp connector.":"These are your brokerage brand settings. Only a brokerage manager can change them."})]}),e.jsx(Ie,{className:"space-y-6",children:i?e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-sm",children:[e.jsx(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:[v("logo_url","Logo (light background)"),v("logo_dark_url","Logo (dark background)"),v("icon_mark_url","Icon mark")]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Heading font"}),e.jsx(pe,{disabled:!t,value:o.heading_font,placeholder:"Playfair Display",onChange:b=>g("heading_font",b.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Body font"}),e.jsx(pe,{disabled:!t,value:o.body_font,placeholder:"Inter",onChange:b=>g("body_font",b.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Legal brokerage name"}),e.jsx(pe,{disabled:!t,value:o.legal_name,placeholder:"Acme Realty, Inc.",onChange:b=>g("legal_name",b.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Brokerage license #"}),e.jsx(pe,{disabled:!t,value:o.license_number,placeholder:"DRE #01234567",onChange:b=>g("license_number",b.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"License state"}),e.jsx(pe,{disabled:!t,value:o.license_state,placeholder:"CA",onChange:b=>g("license_state",b.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Required disclaimer / compliance line"}),e.jsx(Ls,{disabled:!t,rows:2,value:o.compliance_line,placeholder:"Each office independently owned and operated. Information deemed reliable but not guaranteed.",onChange:b=>g("compliance_line",b.target.value)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Included in every brand kit so AI-generated marketing carries it automatically."})]}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:[["show_equal_housing","Include Equal Housing logo"],["show_realtor_logo","Include REALTOR® logo"],["lock_colors","Lock colors (agents cannot override)"],["lock_logo","Lock logo (agents cannot override)"]].map(([b,w])=>e.jsxs("div",{className:"flex items-center justify-between rounded-md border p-3",children:[e.jsx(ee,{className:"text-sm font-normal",children:w}),e.jsx(Sn,{disabled:!t,checked:d[b],onCheckedChange:S=>u(A=>({...A,[b]:S}))})]},b))}),t&&e.jsxs($,{onClick:y,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 TXt="brokerage-onboarding-docs",uE=s=>s.status==="approved"||s.status==="complete";function MXt(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 LRn(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 PXt(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(uE).length,overdue:u.filter(h=>!uE(h)&&h.due_date&&h.due_dateh.status==="submitted").length}})}})}function IXt(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 RRn(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 DRn(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 FRn(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 LXt(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 Qde(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 QRe(s){const t=Wt(),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:y,error:v}=await q.from("brokerage_onboarding_template_steps").select("*").eq("template_id",m).order("sort_order",{ascending:!0});if(v)throw v;const{data:b,error:w}=await q.from("brokerage_onboarding_assignments").insert({brokerage_id:s,agent_user_id:h,template_id:m,template_name:g.name,status:"in_progress",created_by:((S=f.user)==null?void 0:S.id)??null}).select().single();if(w)throw w;if(y!=null&&y.length){const A=new Date,E=y.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 Qde({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(),y=m==="approved"||m==="complete",{error:v}=await q.from("brokerage_onboarding_steps").update({status:m,review_note:f??null,completed_at:y?new Date().toISOString():null,completed_by:y?((b=x.user)==null?void 0:b.id)??null:null}).eq("id",h.id);if(v)throw v;return s&&await Qde({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(),y=m.name.replace(/[^a-zA-Z0-9._-]/g,"_"),v=`${s}/${f}/${h.id}/${Date.now()}-${y}`,{error:b}=await q.storage.from(TXt).upload(v,m,{upsert:!1,contentType:m.type||void 0});if(b)throw b;const{error:w}=await q.from("brokerage_onboarding_documents").insert({step_id:h.id,storage_path:v,file_name:m.name,file_size:m.size,file_type:m.type,version:g+1,uploaded_by:((S=x.user)==null?void 0:S.id)??null,review_status:"submitted"});if(w)throw w;return await q.from("brokerage_onboarding_steps").update({status:"submitted",review_note:null}).eq("id",h.id),s&&await Qde({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:y}=await q.auth.getUser(),{error:v}=await q.from("brokerage_onboarding_documents").update({review_status:f,review_note:g??null,reviewed_by:((w=y.user)==null?void 0:w.id)??null,reviewed_at:new Date().toISOString()}).eq("id",h.id);if(v)throw v;const b=f==="approved"?"approved":f==="changes_requested"?"changes_requested":"submitted";return await q.from("brokerage_onboarding_steps").update({status:b,review_note:g??null,completed_at:f==="approved"?new Date().toISOString():null}).eq("id",m.id),s&&await Qde({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 ORn(s){const t=Wt(),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 zRn(s){const{data:t,error:n}=await q.storage.from(TXt).createSignedUrl(s,300);if(n)throw n;return t.signedUrl}const BRn=s=>s==="document"?Jr:s==="form"?c_:Vj,$Rn=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"}}},yYe=({brokerageId:s,agentUserId:t,steps:n,documents:r,mode:a,displayMode:i="all"})=>{const{toast:l}=Bi(),{setStepStatus:o,uploadDocument:c,reviewDocument:d}=QRe(s),u=j.useRef({}),[h,m]=j.useState(null),[f,g]=j.useState(""),x=new Date().toISOString().slice(0,10),y=w=>r.filter(S=>S.step_id===w).sort((S,A)=>A.version-S.version),v=async(w,S)=>{try{await c.mutateAsync({step:w,file:S,agentUserId:t,existingVersions:y(w.id).length}),l({title:"Uploaded",description:`${S.name} is ready for review.`})}catch(A){l({title:"Upload failed",description:A.message,variant:"destructive"})}},b=async w=>{try{const S=await zRn(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=BRn(w.step_type),A=$Rn(w),E=y(w.id),I=E[0],P=!uE(w)&&w.due_date&&w.due_date0&&e.jsx("div",{className:"mt-3 space-y-1",children:E.map(D=>e.jsxs("div",{className:"flex flex-wrap items-center gap-2 rounded-md bg-muted/50 px-3 py-2 text-sm",children:[e.jsx(Jr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"min-w-0 flex-1 truncate",children:D.file_name}),e.jsxs($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(xi,{className:"mr-1 h-4 w-4"})," Open"]})]},D.id))})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[w.step_type!=="task"&&R&&e.jsxs(e.Fragment,{children:[e.jsx("input",{type:"file",className:"hidden",accept:".pdf,.png,.jpg,.jpeg,.heic,.doc,.docx",ref:D=>u.current[w.id]=D,onChange:D=>{var U;const O=(U=D.target.files)==null?void 0:U[0];O&&v(w,O),D.target.value=""}}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>{var D;return(D=u.current[w.id])==null?void 0:D.click()},children:[e.jsx(ni,{className:"mr-1 h-4 w-4"})," Upload"]})]}),w.step_type==="task"&&R&&!uE(w)&&e.jsxs($,{size:"sm",onClick:()=>o.mutate({step:w,status:"complete",agentUserId:t}),children:[e.jsx(Vj,{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(Nu,{className:"mr-1 h-4 w-4"})," Needs changes"]})]}),a==="manager"&&uE(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(Ax,{className:"mr-1 h-4 w-4"})," Revoke"]})]})]})},w.id)}),e.jsx(zs,{open:!!h,onOpenChange:w=>!w&&m(null),children:e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Request changes"})}),e.jsx(Ls,{rows:4,value:f,onChange:w=>g(w.target.value),placeholder:"Tell the agent what needs to be fixed…"}),e.jsxs(Sr,{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"})]})]})})]})},URn=()=>{const{user:s}=bs(),{data:t}=RRn(s==null?void 0:s.id),{data:n}=IXt(t==null?void 0:t.id);if(!t)return null;const r=(n==null?void 0:n.steps)||[],a=r.filter(uE).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(KN,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{children:[e.jsx(Et,{children:"Your onboarding"}),e.jsx(Gn,{children:t.template_name||"Onboarding checklist"})]})]}),e.jsxs("div",{className:"w-full max-w-[220px]",children:[e.jsx(Yi,{value:i}),e.jsxs("p",{className:"mt-1 text-right text-xs text-muted-foreground",children:[a," of ",r.length," complete"]})]})]})}),e.jsx(Ie,{children:e.jsx(yYe,{brokerageId:t.brokerage_id,agentUserId:t.agent_user_id,steps:r,documents:(n==null?void 0:n.documents)||[],mode:"agent"})})]})};function qRn(){const{user:s,isAdmin:t,isBrokerageManager:n}=bs(),r=Xn(),[a,i]=j.useState(!0),[l,o]=j.useState(null),[c,d]=j.useState(""),[u,h]=j.useState(0),[m,f]=j.useState(!1),[g,x]=j.useState(!1);return j.useEffect(()=>{(async()=>{if(s)try{const{data:v}=await q.from("profiles").select("brokerage_id").eq("id",s.id).maybeSingle();if(!(v!=null&&v.brokerage_id)){i(!1);return}o(v.brokerage_id);const{data:b}=await q.from("brokerages").select("name").eq("id",v.brokerage_id).maybeSingle();b&&d(b.name);const{count:w}=await q.from("profiles").select("id",{count:"exact",head:!0}).eq("brokerage_id",v.brokerage_id);if(h(w||0),t)f(!0),x(!0);else if(n){const{data:S}=await q.from("brokerage_manager_assignments").select("id").eq("user_id",s.id).eq("brokerage_id",v.brokerage_id).maybeSingle();f(!!S),x(!!S)}}catch(v){console.error("Error fetching brokerage info:",v)}finally{i(!1)}})()},[s,t,n]),a?e.jsx(Vs,{title:"My Brokerage",description:"Loading...",children:e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):l?e.jsx(Vs,{title:c||"My Brokerage",description:"Team Hub",children:e.jsxs("div",{className:"space-y-8",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2 bg-muted/50 rounded-lg px-4 py-2",children:[e.jsx(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(Xf,{className:"h-4 w-4 mr-2"}),"Brokerage Content"]}),e.jsxs($,{onClick:()=>r(`/mission-control/listings/new?brokerage=${l}`),children:[e.jsx(va,{className:"h-4 w-4 mr-2"}),"Add Listing"]})]})]}),e.jsx(URn,{}),e.jsx(IRn,{brokerageId:l,canManage:m}),e.jsx(CRn,{brokerageId:l,canManage:m}),e.jsx(ARn,{brokerageId:l,canManage:m}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[e.jsx(TRn,{brokerageId:l}),e.jsx(MRn,{brokerageId:l})]})]})}):e.jsx(Vs,{title:"My Brokerage",description:"Team Hub",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(ji,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"No Brokerage Assigned"}),e.jsx("p",{className:"text-muted-foreground",children:"You're not currently part of a brokerage team."})]})})}function VRn(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 HRn(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 Zkt={video:{icon:zu,label:"Video",color:"bg-red-500/10 text-red-600 dark:text-red-400"},pdf:{icon:Jr,label:"Document",color:"bg-blue-500/10 text-blue-600 dark:text-blue-400"},link:{icon:Wd,label:"Link",color:"bg-green-500/10 text-green-600 dark:text-green-400"},event:{icon:Ta,label:"Event",color:"bg-purple-500/10 text-purple-600 dark:text-purple-400"},graphic:{icon:yd,label:"Graphic",color:"bg-amber-500/10 text-amber-600 dark:text-amber-400"}};function GRn({item:s,canManage:t}){const[n,r]=j.useState(!1),[a,i]=j.useState(null),l=pWs(),o=Xn(),c=Zkt[s.content_type]||Zkt.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"?VRn(s.url):null,[s]);j.useEffect(()=>{u||!s.url||s.content_type!=="video"||!HRn(s.url)||fetch(`https://www.youtube.com/oembed?url=${encodeURIComponent(s.url)}&format=json`).then(g=>g.ok?g.json():null).then(g=>{g!=null&&g.thumbnail_url&&i(g.thumbnail_url)}).catch(()=>{})},[s.url,s.content_type,u]);const h=u||a,m=()=>{o(`/brokerage-content/${s.id}`)},f=async()=>{try{await l.mutateAsync(s.id),re.success("Content deleted")}catch{re.error("Failed to delete")}r(!1)};return e.jsxs(e.Fragment,{children:[e.jsxs(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(Ie,{className:"p-4",children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsxs($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:["📅 ",en(new Date(s.event_date),"MMM d, yyyy · h:mm a")]}),e.jsxs("p",{className:"text-[10px] text-muted-foreground mt-2",children:["Added ",en(new Date(s.created_at),"MMM d, yyyy")]})]}),t&&e.jsxs($u,{children:[e.jsx(Uu,{asChild:!0,onClick:g=>g.stopPropagation(),children:e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0",children:e.jsx(Jx,{className:"h-4 w-4"})})}),e.jsx(Au,{align:"end",children:e.jsxs(ja,{onClick:g=>{g.stopPropagation(),r(!0)},className:"text-destructive",children:[e.jsx(Hn,{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 WRn(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 Xkt=[{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 KRn({brokerageId:s,categories:t}){var J;const{user:n}=bs(),[r,a]=j.useState(!1),[i,l]=j.useState(!1),[o,c]=j.useState(""),[d,u]=j.useState("📁"),[h,m]=j.useState(!1);j.useRef(null);const[f,g]=j.useState("video"),[x,y]=j.useState(""),[v,b]=j.useState(""),[w,S]=j.useState(""),[A,E]=j.useState(""),[I,P]=j.useState(""),[R,D]=j.useState(""),[O,U]=j.useState(""),W=fWs(),V=gWs(s),G=xWs(),Y=yWs(s),X=()=>{g("video"),y(""),b(""),S(""),E(""),P(""),D(""),U("")},ae=async(ce,_e)=>{var ue;const he=(ue=ce.target.files)==null?void 0:ue[0];if(he){m(!0);try{const ve=he.name.split(".").pop(),Ee=`${s}/${Date.now()}-${Math.random().toString(36).slice(2)}.${ve}`,{error:Se}=await q.storage.from("brokerage-content").upload(Ee,he);if(Se)throw Se;const{data:{publicUrl:Le}}=q.storage.from("brokerage-content").getPublicUrl(Ee);_e==="file"?(E(Le),f==="graphic"&&!I&&P(Le)):P(Le),re.success("File uploaded")}catch(ve){re.error(ve.message||"Upload failed")}finally{m(!1)}}},le=async()=>{if(!x.trim()){re.error("Title is required");return}if(n)try{await W.mutateAsync({brokerage_id:s,category_id:O||null,content_type:f,title:x.trim(),description:v.trim()||null,url:w.trim()||null,file_url:A.trim()||null,thumbnail_url:I.trim()||null,event_date:R?new Date(R).toISOString():null,created_by:n.id}),re.success("Content added!"),X(),a(!1)}catch(ce){re.error(ce.message||"Failed to add content")}},ne=async()=>{if(o.trim())try{await V.mutateAsync({name:o.trim(),icon:d,sort_order:t.length}),c(""),u("📁"),re.success("Category created")}catch(ce){re.error(ce.message||"Failed to create category")}},te=async()=>{try{await Y.mutateAsync(),re.success("Default categories created")}catch{re.error("Failed to create defaults")}};return e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs(zs,{open:r,onOpenChange:a,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Add Content"]})}),e.jsxs(Os,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Add Brokerage Content"})}),e.jsxs("div",{className:"space-y-4 mt-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Content Type"}),e.jsxs(ms,{value:f,onValueChange:g,children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:Xkt.map(ce=>e.jsx(Ge,{value:ce.value,children:ce.label},ce.value))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(J=Xkt.find(ce=>ce.value===f))==null?void 0:J.hint})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Category"}),e.jsxs(ms,{value:O,onValueChange:U,children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Select category (optional)"})}),e.jsx(hs,{children:t.map(ce=>e.jsxs(Ge,{value:ce.id,children:[ce.icon," ",ce.name]},ce.id))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Title *"}),e.jsx(pe,{value:x,onChange:ce=>y(ce.target.value),placeholder:"Content title"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Description"}),e.jsx(Ls,{value:v,onChange:ce=>b(ce.target.value),placeholder:"Brief description...",rows:2})]}),["video","link","graphic","event"].includes(f)&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:f==="video"?"Video URL":f==="graphic"?"Canva / Image URL":f==="event"?"Event Link (Zoom, etc.)":"URL"}),e.jsx(pe,{value:w,onChange:ce=>{const _e=ce.target.value;if(S(_e),f==="video"&&!I){const he=WRn(_e);he&&P(he)}},placeholder:"https://..."})]}),["pdf","graphic"].includes(f)&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:f==="pdf"?"Upload PDF":"Upload Image"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pe,{type:"file",accept:f==="pdf"?".pdf,.doc,.docx":"image/*",onChange:ce=>ae(ce,"file"),disabled:h}),h&&e.jsx(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(pr,{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(dn,{className:"h-4 w-4 mr-2"}),"Add Content"]})]})]})]}),e.jsxs(zs,{open:i,onOpenChange:l,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",children:[e.jsx(Nd,{className:"h-4 w-4 mr-2"}),"Categories"]})}),e.jsxs(Os,{className:"max-w-md",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Manage Categories"})}),e.jsxs("div",{className:"space-y-4 mt-2",children:[t.length===0&&e.jsxs("div",{className:"text-center py-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"No categories yet"}),e.jsxs($,{variant:"outline",size:"sm",onClick:te,disabled:Y.isPending,children:[Y.isPending?e.jsx(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),re.success("Category deleted")},children:e.jsx(pr,{className:"h-4 w-4"})})]},ce.id)),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(pe,{value:d,onChange:ce=>u(ce.target.value),className:"w-14 text-center",maxLength:2}),e.jsx(pe,{value:o,onChange:ce=>c(ce.target.value),placeholder:"New category name",className:"flex-1",onKeyDown:ce=>ce.key==="Enter"&&ne()}),e.jsx($,{size:"sm",onClick:ne,disabled:!o.trim(),children:"Add"})]})]})]})]})]})}function YRn(){const{user:s,isAdmin:t,isBrokerageManager:n}=bs(),[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=[]}=uWs(i),{data:y=[],isLoading:v}=hWs(i,h),b=j.useMemo(()=>{if(!f.trim())return y;const w=f.toLowerCase();return y.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)})},[y,f]);return r?e.jsx(Vs,{title:"Brokerage Content",description:"Loading...",children:e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):i?e.jsx(Vs,{title:`${o} Content`,description:"Brokerage Content Hub",children:e.jsxs("div",{className:"space-y-6",children:[d&&i&&e.jsx(KRn,{brokerageId:i,categories:x}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(Zr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search content...",value:f,onChange:w=>g(w.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx($,{variant:h===null?"default":"outline",size:"sm",onClick:()=>m(null),children:"All"}),x.map(w=>e.jsxs($,{variant:h===w.id?"default":"outline",size:"sm",onClick:()=>m(w.id),children:[e.jsx("span",{className:"mr-1",children:w.icon}),w.name]},w.id))]})]}),v?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):b.length===0?e.jsx(je,{className:"bg-muted/30 border-dashed",children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(kv,{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(GRn,{item:w,canManage:d},w.id))})]})}):e.jsx(Vs,{title:"Brokerage Content",description:"Content Hub",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(ji,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"No Brokerage Assigned"}),e.jsx("p",{className:"text-muted-foreground",children:"You're not currently part of a brokerage team."})]})})}const Qkt={video:{icon:zu,label:"Video",color:"bg-red-500/10 text-red-600 dark:text-red-400"},pdf:{icon:Jr,label:"Document",color:"bg-blue-500/10 text-blue-600 dark:text-blue-400"},link:{icon:Wd,label:"Link",color:"bg-green-500/10 text-green-600 dark:text-green-400"},event:{icon:Ta,label:"Event",color:"bg-purple-500/10 text-purple-600 dark:text-purple-400"},graphic:{icon: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 XRn(s){try{const t=new URL(s).hostname.replace("www.","");return["youtube.com","youtu.be","m.youtube.com"].includes(t)}catch{return!1}}function QRn(s){try{return new URL(s).hostname.includes("vimeo.com")}catch{return!1}}function JRn(s){try{const t=s.match(/vimeo\.com\/(\d+)/);if(t)return`https://player.vimeo.com/video/${t[1]}`}catch{}return null}function eDn(){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(ji,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold",children:"Content not found"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"This content may have been removed."}),e.jsx($,{asChild:!0,className:"mt-4",children:e.jsx(wr,{to:"/brokerage-content",children:"Back to Content"})})]})});const r=Qkt[t.content_type]||Qkt.link,a=r.icon,i=t.url||t.file_url,l=i&&XRn(i)?ZRn(i):null,o=i&&QRn(i)?JRn(i):null,c=l||o;return e.jsx(Vs,{title:t.title,children:e.jsxs("div",{className:"space-y-6 max-w-4xl mx-auto",children:[e.jsx($,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(wr,{to:"/brokerage-content",children:[e.jsx(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 ",en(new Date(t.created_at),"MMMM d, yyyy")]})]}),e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:t.title}),c&&e.jsx(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(Ie,{className:"pt-6",children:e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:t.description})})}),t.content_type==="event"&&t.event_date&&e.jsx(je,{children:e.jsxs(Ie,{className:"pt-6 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-md bg-primary/10",children:e.jsx(Ta,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:"Event Date"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:en(new Date(t.event_date),"EEEE, MMMM d, yyyy · h:mm a")})]})]})}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[t.file_url&&e.jsx($,{asChild:!0,size:"lg",children:e.jsxs("a",{href:t.file_url,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(xi,{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(Fr,{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 WMe={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 tDn(s="open"){const{user:t}=bs();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 sDn(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 nDn(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 rDn(){const s=Wt(),{user:t,brokerageId:n}=bs();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 aDn(){const s=Wt(),{user:t}=bs();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 iDn(){const s=Wt();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 oDn(){const s=Wt();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 lDn(){const s=Wt();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 cDn(){const s=Wt();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 dDn(){const{user:s,brokerageId:t}=bs(),n=Wt(),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 uDn(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 hDn(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 mDn({req:s,onClick:t}){var i;const n=WMe[s.request_type],r=uDn(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(Ie,{className:"p-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs($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(da,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{children:r})]}),a&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ci,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"line-clamp-1",children:a})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(nu,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{children:hDn(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 fDn(){var c;const s=Xn(),{brokerageId:t}=bs(),[n,r]=j.useState("open"),{data:a=[],isLoading:i}=tDn(n),l=dDn(),o=((c=l.data)==null?void 0:c.email_enabled)??!0;return t?e.jsx(Vs,{title:"Help Board",description:"Ask a teammate to cover an open house, showing, or shift.",children:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsx(ha,{value:n,onValueChange:d=>r(d),children:e.jsxs(ma,{children:[e.jsx(Zt,{value:"open",children:"Open"}),e.jsx(Zt,{value:"mine",children:"My Posts"}),e.jsx(Zt,{value:"my_claims",children:"My Claims"}),e.jsx(Zt,{value:"filled",children:"Filled"})]})}),e.jsxs($,{onClick:()=>s("/brokerage/help-board/new"),className:"gap-2",children:[e.jsx(dn,{className:"h-4 w-4"})," Post Request"]})]}),e.jsx(je,{className:"bg-muted/30 border-dashed",children:e.jsxs(Ie,{className:"flex items-center justify-between py-3 px-5",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[o?e.jsx(Uy,{className:"h-4 w-4 text-primary"}):e.jsx(YS,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"email-notif",className:"text-sm font-medium cursor-pointer",children:"Email me when teammates post new help requests"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"You can still browse the board either way."})]})]}),e.jsx(Sn,{id:"email-notif",checked:o,disabled:l.isLoading||l.isSaving,onCheckedChange:d=>l.setEmailEnabled(d)})]})}),i?e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):a.length===0?e.jsx(je,{className:"bg-muted/30 border-dashed",children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(s4,{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(mDn,{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(s4,{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 pDn(){const s=Xn(),{toast:t}=Bi(),n=rDn(),[r,a]=j.useState("open_house"),[i,l]=j.useState(""),[o,c]=j.useState(""),[d,u]=j.useState(""),[h,m]=j.useState(""),[f,g]=j.useState(""),[x,y]=j.useState(""),[v,b]=j.useState(""),[w,S]=j.useState(""),[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",Y=r!=="general",X=(le,ne)=>!le||!ne?null:`${le}T${ne}: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 ne=X(d,h),te=X(d,f);await n.mutateAsync({request_type:r,title:i.trim(),description:o.trim()||null,event_start_at:ne,event_end_at:te,address:G&&x.trim()||null,city:G&&v.trim()||null,state:G&&w.trim()||null,zip:G&&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(ne){t({title:"Could not post",description:(ne==null?void 0:ne.message)??"Something went wrong.",variant:"destructive"})}};return e.jsx(Vs,{title:"Post a Help Request",description:"Ask a teammate to cover for you",children:e.jsxs("div",{className:"max-w-2xl mx-auto",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>s("/brokerage/help-board"),className:"mb-4 gap-2",children:[e.jsx(Va,{className:"h-4 w-4"})," Back to board"]}),e.jsx("form",{onSubmit:ae,children:e.jsx(je,{children:e.jsxs(Ie,{className:"p-6 space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"What do you need help with?"}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:Object.keys(WMe).map(le=>{const ne=WMe[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:ne.emoji}),e.jsx("div",{className:"font-medium text-sm mt-1",children:ne.label}),e.jsx("div",{className:"text-xs text-muted-foreground line-clamp-1",children:ne.description})]},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(Ls,{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})]}),Y&&e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"date",children:"Date"}),e.jsx(pe,{id:"date",type:"date",value:d,onChange: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=>y(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:v,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 ne=R===le.val;return e.jsxs("button",{type:"button",onClick:()=>D(le.val),className:`text-left p-3 rounded-lg border-2 transition ${ne?"border-primary bg-primary/5":"border-border hover:border-primary/40"}`,children:[e.jsx("div",{className:"font-medium text-sm",children: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 gDn(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 T9e(s){return s?s.split(" ").map(t=>t[0]).slice(0,2).join("").toUpperCase():"?"}function xDn(){var I,P,R,D,O,U,W,V;const{id:s}=Wi(),t=Xn(),{user:n}=bs(),{toast:r}=Bi(),{data:a,isLoading:i}=sDn(s),{data:l=[]}=nDn(s),o=aDn(),c=iDn(),d=oDn(),u=lDn(),h=cDn(),[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=WMe[a.request_type],x=gDn(a.event_start_at,a.event_end_at),y=[a.address,a.city,a.state,a.zip].filter(Boolean).join(", "),v=(n==null?void 0:n.id)===a.requester_user_id,b=l.find(G=>G.claimant_user_id===(n==null?void 0:n.id)),w=l.find(G=>G.status==="accepted"),S=a.status==="open",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(Ie,{className:"p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs($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:T9e((P=a.requester)==null?void 0:P.name)})]}),e.jsx("span",{children:((R=a.requester)==null?void 0:R.name)||"Teammate"})]})]}),e.jsx("h1",{className:"text-2xl font-bold",children:a.title}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3 pt-2",children:[x&&e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(da,{className:"h-4 w-4 text-primary mt-0.5"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"When"}),e.jsx("div",{children:x})]})]}),y&&e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(ci,{className:"h-4 w-4 text-primary mt-0.5"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Where"}),e.jsx("div",{children:y})]})]}),e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(nu,{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(HI,{className:"h-4 w-4 text-primary mt-0.5"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"MLS"}),e.jsx("div",{children:a.mls_number})]})]})]}),a.description&&e.jsxs("div",{className:"pt-3 border-t",children:[e.jsx("h3",{className:"text-xs uppercase tracking-wide font-semibold text-muted-foreground mb-2",children:"Notes"}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:a.description})]}),a.compensation_notes&&e.jsxs("p",{className:"text-sm text-muted-foreground italic",children:["💰 ",a.compensation_notes]})]})}),!v&&S&&!b&&e.jsx(je,{children:e.jsxs(Ie,{className:"p-6 space-y-3",children:[e.jsx("h3",{className:"font-semibold",children:"Offer to cover this"}),e.jsx(Ls,{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"]})]})}),!v&&b&&e.jsx(je,{className:"border-primary/30 bg-primary/5",children:e.jsxs(Ie,{className:"p-4 flex items-center gap-3",children:[e.jsx(ca,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{className:"text-sm",children:[e.jsxs("div",{className:"font-medium capitalize",children:["Your offer: ",b.status]}),e.jsxs("div",{className:"text-muted-foreground",children:[b.status==="pending"&&"Waiting for the requester to pick.",b.status==="accepted"&&"You're confirmed — see contact info below.",b.status==="declined"&&"They went with someone else this time."]})]})]})}),w&&(v||w.claimant_user_id===(n==null?void 0:n.id))&&e.jsx(je,{className:"border-primary/30",children:e.jsxs(Ie,{className:"p-6",children:[e.jsx("h3",{className:"font-semibold mb-3",children:"Confirmed coverage"}),e.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[e.jsxs(Oa,{className:"h-10 w-10",children:[e.jsx(Ii,{src:((D=w.claimant)==null?void 0:D.avatar_url)||void 0}),e.jsx(za,{children:T9e((O=w.claimant)==null?void 0:O.name)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:(U=w.claimant)==null?void 0:U.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Covering this request"})]})]}),e.jsxs("div",{className:"space-y-1.5 text-sm",children:[((W=w.claimant)==null?void 0:W.email)&&e.jsxs("a",{href:`mailto:${w.claimant.email}`,className:"flex items-center gap-2 text-primary hover:underline",children:[e.jsx(mn,{className:"h-4 w-4"})," ",w.claimant.email]}),((V=w.claimant)==null?void 0:V.phone)&&e.jsxs("a",{href:`tel:${w.claimant.phone}`,className:"flex items-center gap-2 text-primary hover:underline",children:[e.jsx(Da,{className:"h-4 w-4"})," ",w.claimant.phone]})]})]})}),v&&e.jsx(je,{children:e.jsxs(Ie,{className:"p-6 space-y-3",children:[e.jsxs("h3",{className:"font-semibold",children:["Interested agents (",l.length,")"]}),l.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No claims yet. Hang tight — your teammates were just notified."}),l.map(G=>{var Y,X,ae,le,ne;return e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg border",children:[e.jsxs(Oa,{className:"h-10 w-10",children:[e.jsx(Ii,{src:((Y=G.claimant)==null?void 0:Y.avatar_url)||void 0}),e.jsx(za,{children:T9e((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(ca,{className:"h-3.5 w-3.5"})," Pick ",((ne=(le=G.claimant)==null?void 0:le.name)==null?void 0:ne.split(" ")[0])||"them"]}),e.jsxs($,{size:"sm",variant:"ghost",onClick:()=>d.mutate({claim_id:G.id,request_id:a.id}),disabled:d.isPending,className:"gap-1",children:[e.jsx(pr,{className:"h-3.5 w-3.5"})," Pass"]})]})]})]},G.id)}),v&&S&&e.jsx("div",{className:"pt-3 border-t flex justify-end",children:e.jsx($,{variant:"ghost",size:"sm",onClick:()=>u.mutate(a.id),disabled:u.isPending,children:"Cancel request"})}),v&&a.status==="filled"&&e.jsx("div",{className:"pt-3 border-t flex justify-end",children:e.jsx($,{size:"sm",onClick:()=>h.mutate(a.id),disabled:h.isPending,children:"Mark complete"})})]})})]})})}function RXt({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(Zr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(pe,{value:n,onChange:u=>r(u.target.value),placeholder:"Search graphics...",className:"pl-8 h-9"})]}),c.length>1&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:c.map(u=>e.jsx("button",{onClick:()=>i(u),className:`px-2.5 py-1 rounded-full text-xs font-medium transition-colors ${a===u?"bg-primary text-primary-foreground":"bg-muted hover:bg-muted/70 text-muted-foreground"}`,children:u==="all"?"All":u},u))}),e.jsx(uo,{style:{maxHeight:t},className:"rounded-md border",children:o?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(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 yDn=[{key:"search",label:"Search for Properties",icon:Zr,defaultText:"Search for Properties",placeholder:"https://your-website.com/search",helper:"Link to your home search page"},{key:"call",label:"Call Agent",icon:Da,defaultText:"Call Me",hrefPrefix:"tel:",placeholder:"+15555551234",helper:"Your phone number"},{key:"email",label:"Email Agent",icon:mn,defaultText:"Email Me",hrefPrefix:"mailto:",placeholder:"you@email.com",helper:"Your email address"},{key:"schedule",label:"Schedule a Call",icon:Ta,defaultText:"Schedule a Call",placeholder:"https://calendly.com/you",helper:"Link to your booking page"},{key:"listings",label:"View My Listings",icon:va,defaultText:"View My Listings",placeholder:"https://your-website.com/listings",helper:"Link to your listings page"},{key:"valuation",label:"Get Home Value",icon:nu,defaultText:"Get My Home Value",placeholder:"https://your-website.com/home-value",helper:"Link to your home valuation page"},{key:"openhouse",label:"See Open Houses",icon:ci,defaultText:"See Open Houses",placeholder:"https://your-website.com/open-houses",helper:"Link to your open houses page"},{key:"forward",label:"Forward to a Friend",icon:Fd,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 Jkt(s){const t=s.match(/(?:youtube\.com\/(?:watch\?v=|embed\/|v\/)|youtu\.be\/)([A-Za-z0-9_-]{11})/);return t?t[1]:null}function vDn(s){const t=s.match(/vimeo\.com\/(?:video\/)?(\d+)/);return t?t[1]:null}function Wat({html:s,onChange:t}){const{user:n}=bs(),r=j.useRef(null),a=j.useRef(""),i=j.useRef(t);i.current=t;const[l,o]=j.useState("desktop"),c=j.useRef(null),[d,u]=j.useState(!1),[h,m]=j.useState(""),[f,g]=j.useState(""),x=j.useRef(null),y=()=>{var kt;const Ft=(kt=r.current)==null?void 0:kt.contentDocument,as=Ft==null?void 0:Ft.getSelection();as&&as.rangeCount>0&&(Ft!=null&&Ft.body.contains(as.anchorNode))&&(x.current=as.getRangeAt(0).cloneRange())},v=()=>{var gs;const Ft=c.current,as=(gs=r.current)==null?void 0:gs.contentDocument;if(!Ft||!as)return;let kt=h.trim();kt&&!/^(https?:|mailto:|tel:|#|\/)/i.test(kt)&&(kt="https://"+kt),Ft.setAttribute("href",kt),Ft.setAttribute("target","_blank");const Ks=f.trim();Ks&&Ks!==(Ft.textContent||"").trim()&&(Ft.textContent=Ks);const wt=` `+as.documentElement.outerHTML;a.current=wt,i.current(wt),u(!1)};j.useEffect(()=>{var kt,Ks;const Ft=r.current;if(!Ft||a.current===s)return;const as=()=>{const wt=Ft.contentDocument;if(!wt)return;wt.open(),wt.write(s||""),wt.close(),a.current=s;const gs=wt.body;if(!gs)return;gs.setAttribute("contenteditable","true"),gs.style.outline="none",gs.style.minHeight="400px",gs.style.cursor="text";const ks=()=>{const Xs=` `+wt.documentElement.outerHTML;a.current=Xs,i.current(Xs)};gs.addEventListener("input",ks),gs.addEventListener("blur",ks),gs.addEventListener("mouseup",y),gs.addEventListener("keyup",y),wt.addEventListener("selectionchange",y);const Is=Xs=>{var hn;const ds=Xs.target,Ss=ds==null?void 0:ds.closest("a");if(Ss){if(Xs.metaKey||Xs.ctrlKey||Xs.shiftKey)return;Xs.preventDefault(),Xs.stopPropagation(),c.current=Ss,m(Ss.getAttribute("href")||""),g((Ss.textContent||"").trim()),u(!0);return}const yn=wt.getSelection();if(!yn)return;const Js=(hn=wt.caretRangeFromPoint)==null?void 0:hn.call(wt,Xs.clientX,Xs.clientY),Ut=Js==null?void 0:Js.startContainer;if(Ut&&Ut.nodeType===Node.TEXT_NODE){const hr=Ut.textContent||"",Rs=Js.startOffset,jr=hr.lastIndexOf("[",Rs),kr=hr.indexOf("]",Rs);if(jr!==-1&&kr!==-1&&kr>jr){const $n=wt.createRange();$n.setStart(Ut,jr),$n.setEnd(Ut,kr+1),yn.removeAllRanges(),yn.addRange($n),x.current=$n.cloneRange()}}};gs.addEventListener("click",Is,!0)};((kt=Ft.contentDocument)==null?void 0:kt.readyState)==="complete"||(Ks=Ft.contentDocument)!=null&&Ks.body?as():Ft.addEventListener("load",as,{once:!0})},[s]);const b=(Ft,as)=>{var wt;const kt=(wt=r.current)==null?void 0:wt.contentDocument;if(!kt)return;kt.body.focus(),kt.execCommand(Ft,!1,as);const Ks=` `+kt.documentElement.outerHTML;a.current=Ks,i.current(Ks)},w=()=>{const Ft=window.prompt("Enter URL (https://...)");Ft&&b("createLink",Ft)},S=(Ft,as)=>{var wt;const kt=(wt=r.current)==null?void 0:wt.contentDocument;if(!kt)return;if(kt.body.focus(),as==="cursor"&&x.current&&kt.body.contains(x.current.startContainer)){const gs=kt.getSelection();if(gs){gs.removeAllRanges(),gs.addRange(x.current),kt.execCommand("insertHTML",!1,Ft);const ks=` `+kt.documentElement.outerHTML;a.current=ks,i.current(ks);return}}as==="top"?kt.body.insertAdjacentHTML("afterbegin",Ft):kt.body.insertAdjacentHTML("beforeend",Ft);const Ks=` `+kt.documentElement.outerHTML;a.current=Ks,i.current(Ks)},[A,E]=j.useState(!1),[I,P]=j.useState(null),[R,D]=j.useState(""),[O,U]=j.useState(""),[W,V]=j.useState("#406E71"),[G,Y]=j.useState("cursor"),X=Ft=>{P(Ft),D(Ft.defaultText),U(""),E(!0)},ae=()=>{if(!I)return;const Ft=O.trim();if(!I.isForward&&!Ft)return;let as=Ft;if(I.isForward){const gs=Ft||"",ks=encodeURIComponent("You should see this newsletter"),Is=encodeURIComponent(gs?`I thought you'd like this — take a look: ${gs} `:`I thought you'd like this newsletter — take a look! `);as=`mailto:?subject=${ks}&body=${Is}`}else I.hrefPrefix==="tel:"?as="tel:"+Ft.replace(/[^0-9+]/g,""):I.hrefPrefix==="mailto:"?as="mailto:"+Ft:/^https?:\/\//i.test(Ft)||(as="https://"+Ft);const kt=(R||I.defaultText).replace(/[<>]/g,""),Ks=W||"#406E71",wt=`
${kt}

 

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

 

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

 

`.trim();S(kt,dt),Be(!1)},{data:ss,isLoading:Yt}=st({queryKey:["newsletter-editor-videos",n==null?void 0:n.id],enabled:!!(n!=null&&n.id)&&le,queryFn:async()=>{const{data:Ft,error:as}=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(as)throw as;return Ft||[]}}),ts=Ft=>{Ft.share_token&&(J(`https://video.relevelup.com/share/video/${Ft.share_token}`),_e(`https://video.relevelup.com/thumb/${Ft.share_token}`),ue(Ft.title||"Watch the video"))},ys=l==="mobile"?390:"100%",Bt=l==="mobile"?390:void 0;return e.jsxs("div",{className:"rounded-md border overflow-hidden bg-background",children:[e.jsxs("div",{className:"flex items-center gap-1 border-b bg-muted/40 px-2 py-1.5 flex-wrap",children:[e.jsx($,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>b("bold"),title:"Bold",children:e.jsx(SE,{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(EE,{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(s7,{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(T0,{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(u2,{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(OE,{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(DE,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"w-px h-5 bg-border mx-1"}),e.jsxs($u,{children:[e.jsx(Uu,{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(Au,{align:"start",className:"w-56 bg-popover z-50",children:[e.jsx(jL,{children:"Insert a call-to-action"}),e.jsx(I0,{}),yDn.map(Ft=>{const as=Ft.icon;return e.jsxs(ja,{onClick:()=>X(Ft),children:[e.jsx(as,{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:Le,children:[e.jsx(ua,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-xs font-medium",children:"Video"})]}),e.jsx("div",{className:"ml-auto flex items-center gap-2",children:e.jsxs(kV,{type:"single",value:l,onValueChange:Ft=>Ft&&o(Ft),size:"sm",className:"h-7",children:[e.jsx(x7,{value:"desktop",className:"h-7 px-2",title:"Desktop preview",children:e.jsx(XN,{className:"h-3.5 w-3.5"})}),e.jsx(x7,{value:"mobile",className:"h-7 px-2",title:"Mobile preview",children:e.jsx(x1,{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:ys,maxWidth:Bt,height:480,border:l==="mobile"?"1px solid hsl(var(--border))":"none",borderRadius:l==="mobile"?12:0,boxShadow:l==="mobile"?"0 4px 12px rgba(0,0,0,0.08)":"none"}})}),e.jsx(zs,{open:d,onOpenChange:u,children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Edit link"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"link-edit-text",children:"Button / link text"}),e.jsx(pe,{id:"link-edit-text",value:f,onChange:Ft=>g(Ft.target.value),placeholder:"Click here"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"link-edit-href",children:"Where should this link go?"}),e.jsx(pe,{id:"link-edit-href",value:h,onChange:Ft=>m(Ft.target.value),placeholder:"https://your-website.com/...",autoFocus:!0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Use https://… for a web page, mailto:you@email.com for email, or tel:+15555551234 for a phone number."})]})]}),e.jsxs(Sr,{children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>u(!1),children:"Cancel"}),e.jsx($,{type:"button",onClick:v,disabled:!h.trim(),children:"Save link"})]})]})}),e.jsx(zs,{open:A,onOpenChange:E,children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsx(Us,{children:e.jsxs(Bs,{children:["Insert ",(I==null?void 0:I.label)||"CTA Button"]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"cta-text",children:"Button text"}),e.jsx(pe,{id:"cta-text",value:R,onChange:Ft=>D(Ft.target.value),placeholder:I==null?void 0:I.defaultText})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"cta-value",children:I==null?void 0:I.helper}),e.jsx(pe,{id:"cta-value",value:O,onChange:Ft=>U(Ft.target.value),placeholder:I==null?void 0:I.placeholder,autoFocus:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"cta-color",children:"Button color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pe,{id:"cta-color",type:"color",value:W,onChange:Ft=>V(Ft.target.value),className:"h-9 w-16 p-1 cursor-pointer"}),e.jsx(pe,{value:W,onChange:Ft=>V(Ft.target.value),className:"flex-1"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Position"}),e.jsxs(vw,{value:G,onValueChange:Ft=>Y(Ft),className:"flex gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(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(Dg,{className:"h-3.5 w-3.5"}),"Bottom of newsletter"]})]})]})]}),e.jsx("div",{className:"rounded-md border bg-muted/30 p-4 flex justify-center",children:e.jsx("div",{style:{backgroundColor:W,color:"#ffffff",borderRadius:6,padding:"14px 28px",fontFamily:"Arial, sans-serif",fontWeight:600,fontSize:16},children:R||(I==null?void 0:I.defaultText)})})]}),e.jsxs(Sr,{children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>E(!1),children:"Cancel"}),e.jsx($,{type:"button",onClick:ae,disabled:!(I!=null&&I.isForward)&&!O.trim(),children:"Insert Button"})]})]})}),e.jsx(zs,{open:le,onOpenChange:ne,children:e.jsxs(Os,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Insert Video Block"})}),e.jsxs(ha,{defaultValue:"library",className:"space-y-3",children:[e.jsxs(ma,{className:"grid w-full grid-cols-3",children:[e.jsx(Zt,{value:"library",children:"My Library"}),e.jsx(Zt,{value:"url",children:"From URL"}),e.jsx(Zt,{value:"record",children:"Record New"})]}),e.jsxs(Xt,{value:"library",className:"space-y-3 mt-2",children:[Yt?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..."]}):!ss||ss.length===0?e.jsxs("div",{className:"text-center py-8 text-sm text-muted-foreground border rounded-md",children:[e.jsx(ua,{className:"h-8 w-8 mx-auto mb-2 opacity-40"}),e.jsx("p",{children:"No videos in your library yet."}),e.jsx("p",{className:"text-xs mt-1",children:'Record one in the "Record New" tab.'})]}):e.jsx("div",{className:"grid grid-cols-2 gap-2 max-h-72 overflow-y-auto pr-1",children:ss.map(Ft=>{const as=te.includes(Ft.share_token||"___"),kt=Ft.share_token?`https://video.relevelup.com/thumb/${Ft.share_token}`:Ft.thumbnail_url||"";return e.jsxs("button",{type:"button",onClick:()=>ts(Ft),className:`group text-left rounded-md border-2 overflow-hidden transition-all ${as?"border-primary ring-2 ring-primary/30":"border-transparent hover:border-primary/40"}`,children:[e.jsxs("div",{className:"aspect-video bg-muted relative",children:[kt?e.jsx("img",{src:kt,alt:Ft.title||"Video",className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:e.jsx(ua,{className:"h-6 w-6"})}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx("div",{className:"rounded-full bg-black/60 w-9 h-9 flex items-center justify-center",children:e.jsx(zu,{className:"h-4 w-4 text-white fill-white"})})})]}),e.jsx("div",{className:"p-1.5",children:e.jsx("p",{className:"text-xs font-medium line-clamp-1",children:Ft.title||"Untitled"})})]},Ft.id)})}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"vid-title-lib",className:"text-xs",children:"Caption (optional)"}),e.jsx(pe,{id:"vid-title-lib",value:he,onChange:Ft=>ue(Ft.target.value),placeholder:"Watch the video"})]})]}),e.jsxs(Xt,{value:"url",className:"space-y-3 mt-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"vid-url",children:"Video URL"}),e.jsx(pe,{id:"vid-url",value:te,onChange:Ft=>J(Ft.target.value),placeholder:"https://youtube.com/watch?v=... or Vimeo link"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"YouTube & Vimeo thumbnails are detected automatically."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"vid-title",children:"Caption (optional)"}),e.jsx(pe,{id:"vid-title",value:he,onChange:Ft=>ue(Ft.target.value),placeholder:"Watch the video"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"vid-thumb",children:"Custom thumbnail URL (optional)"}),e.jsx(pe,{id:"vid-thumb",value:ce,onChange:Ft=>_e(Ft.target.value),placeholder:"https://... (only if not YouTube/Vimeo)"})]})]}),e.jsx(Xt,{value:"record",className:"mt-2",children:e.jsxs("div",{className:"rounded-md border bg-muted/30 p-5 text-center space-y-3",children:[e.jsx(ua,{className:"h-10 w-10 mx-auto text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Record a quick video"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:`Record a personal intro, market update, or property tour. When you're done, it'll show up in "My Library" and you can pick it from there.`})]}),e.jsx($,{type:"button",onClick:()=>{window.open("/mission-control/video/record","_blank")},children:"Open Video Recorder"}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Opens in a new tab — come back here when you're done."})]})})]}),e.jsxs("div",{className:"space-y-2 pt-2 border-t",children:[e.jsx(ee,{children:"Position"}),e.jsxs(vw,{value:ve,onValueChange:Ft=>Ee(Ft),className:"flex gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(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(Dg,{className:"h-3.5 w-3.5"}),"Bottom"]})]})]})]}),Se&&e.jsxs("div",{className:"rounded-md border bg-muted/30 p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Preview"}),e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:Se,alt:"thumbnail",className:"w-full rounded-md",style:{maxHeight:180,objectFit:"cover"},onError:Ft=>{Ft.target.style.opacity="0.3"}}),e.jsx("div",{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 rounded-full bg-black/65 text-white flex items-center justify-center",style:{width:56,height:56,fontSize:24},children:"▶"})]})]}),e.jsxs(Sr,{children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>ne(!1),children:"Cancel"}),e.jsx($,{type:"button",onClick:Fe,disabled:!te.trim(),children:"Insert Video"})]})]})}),e.jsx(zs,{open:ke,onOpenChange:Be,children:e.jsxs(Os,{className:"sm:max-w-md max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Insert Image"})}),e.jsxs(ha,{defaultValue:"library",className:"space-y-3",children:[e.jsxs(ma,{className:"grid w-full grid-cols-3",children:[e.jsx(Zt,{value:"library",children:"Library"}),e.jsx(Zt,{value:"upload",children:"Upload"}),e.jsx(Zt,{value:"url",children:"From URL"})]}),e.jsx(Xt,{value:"library",className:"mt-2",children:e.jsx(RXt,{maxHeight:"380px",onSelect:Ft=>{Ae(Ft.image_url),Ce||Ve(Ft.title)}})}),e.jsxs(Xt,{value:"upload",className:"space-y-3 mt-2",children:[e.jsx("input",{ref:Ke,type:"file",accept:"image/png,image/jpeg,image/webp,image/gif",className:"hidden",onChange:Ft=>{var kt;const as=(kt=Ft.target.files)==null?void 0:kt[0];as&&pt(as),Ft.target.value=""}}),Ne?e.jsxs("div",{className:"rounded-md border overflow-hidden bg-muted/30",children:[e.jsx("img",{src:Ne,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(Xt,{value:"url",className:"space-y-3 mt-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"img-url",children:"Image URL"}),e.jsx(pe,{id:"img-url",value:Ne,onChange:Ft=>Ae(Ft.target.value),placeholder:"https://..."})]}),Ne&&/^https?:\/\//i.test(Ne)&&e.jsx("div",{className:"rounded-md border overflow-hidden bg-muted/30",children:e.jsx("img",{src:Ne,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=>Ve(Ft.target.value),placeholder:"Describe the image"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Size"}),e.jsxs(vw,{value:ze,onValueChange:Ft=>qe(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(vw,{value:dt,onValueChange:Ft=>Xe(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(Dg,{className:"h-3.5 w-3.5"}),"Bottom"]})]})]})]})]}),e.jsxs(Sr,{children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>Be(!1),children:"Cancel"}),e.jsx($,{type:"button",onClick:gt,disabled:!Ne.trim()||at,children:"Insert Image"})]})]})})]})}const eSt="newsletter-content",bDn="inline-images";function _Dn(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)??NDn()),x((n==null?void 0:n.is_template)??!1),v((n==null?void 0:n.share_scope)??"private"))},[s,n]);const I=async()=>{if(a){if(!c.trim()){re.error("Please enter a title");return}if(!m.trim()){re.error("Newsletter content is empty");return}w(!0);try{const P=await wDn(m);P!==m&&f(P);const R={user_id:a.id,title:c.trim(),description:u.trim()||null,html_content:P,is_template:g,share_scope:y,shared_team_id:y==="team"?E:null,shared_brokerage_id:y==="brokerage"?o:null};if(y==="team"&&!E){re.error("You must be a team leader to share with a team"),w(!1);return}if(y==="brokerage"&&!l){re.error("Only brokerage managers can share to a brokerage"),w(!1);return}if(y==="global"&&!i){re.error("Only admins can publish global starter templates"),w(!1);return}let D;if(n!=null&&n.id?{error:D}=await q.from("agent_custom_newsletters").update(R).eq("id",n.id):{error:D}=await q.from("agent_custom_newsletters").insert(R),D)throw D;re.success(n!=null&&n.id?"Saved":"Newsletter created"),r==null||r(),t(!1)}catch(P){re.error(P.message||"Failed to save")}finally{w(!1)}}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-6xl h-[92vh] flex flex-col p-0",children:[e.jsx(Us,{className:"px-6 pt-6 pb-3 border-b",children:e.jsx(Bs,{children:n!=null&&n.id?"Edit Newsletter":"Create Newsletter"})}),e.jsxs("div",{className:"flex-1 overflow-y-auto px-6 py-4 space-y-4",children:[e.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"acn-title",children:"Title *"}),e.jsx(pe,{id:"acn-title",value:c,onChange:P=>d(P.target.value),placeholder:"e.g. June Market Update"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"acn-desc",children:"Description (optional)"}),e.jsx(pe,{id:"acn-desc",value:u,onChange:P=>h(P.target.value),placeholder:"Short summary"})]})]}),e.jsxs("div",{className:"flex items-center gap-3 rounded-lg border bg-muted/30 px-4 py-3",children:[e.jsx(Sn,{id:"acn-template",checked:g,onCheckedChange:x}),e.jsx(ee,{htmlFor:"acn-template",className:"cursor-pointer",children:"Save as reusable template"}),e.jsx("span",{className:"text-xs text-muted-foreground ml-auto",children:"Templates can be duplicated and reused for future newsletters"})]}),(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(vw,{value:y,onValueChange:P=>v(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(Wat,{html:m,onChange:f})]})]}),e.jsxs(Sr,{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 NDn(){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 Kat=/\[[^\]\[<>]{2,80}\]/g,kDn=/^\[\s*(?:\/?\s*if\b[^\]]*|endif|else|x-apple-[\w-]*|data-[\w-]*|object [^\]]*|cdata[^\]]*)\s*\]$/i;function Yat(s){return!kDn.test(s)}function SDn(s){return(s.match(Kat)||[]).filter(Yat)}function tSt(s){const t=s.toLowerCase();return t.charAt(0).toUpperCase()+t.slice(1)}function CDn(s){const t=[],n=new RegExp(Kat.source,"g");let r;for(;(r=n.exec(s))!==null;)Yat(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 · ${tSt(h)}`:`Date ${i[l.token]}`:(m=tSt(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 ADn({html:s,onChange:t,originalHtml:n}){const r=j.useMemo(()=>CDn(s),[s]),[a,i]=j.useState({}),[l,o]=j.useState([]),c=j.useRef(null);c.current===null&&s&&(c.current=n??s);const d=j.useRef(!1);j.useEffect(()=>{if(d.current){d.current=!1;return}i({}),o([])},[s]);const u=()=>{const v=new RegExp(Kat.source,"g");let b=0;const w=s.replace(v,S=>{if(!Yat(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 v=l[l.length-1];v&&(o(b=>b.slice(0,-1)),d.current=!0,i(v.values),t(v.html))},m=()=>{const v=c.current;!v||v===s||(o([]),d.current=!0,i({}),t(v))},f=l.length>0,g=!!c.current&&c.current!==s,x=e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs($,{type:"button",size:"sm",variant:"outline",onClick:h,disabled:!f,children:[e.jsx(ree,{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(Ax,{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 y=r.filter(v=>(a[v.index]||"").trim()).length;return e.jsxs("div",{className:"rounded-xl border border-amber-500/40 bg-amber-500/5 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(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:[y,"/",r.length," ready"]})]}),e.jsx("div",{className:"grid grid-cols-1 gap-4",children:r.map(v=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:v.label}),e.jsx(pe,{value:a[v.index]||"",placeholder:v.hint,className:"h-10 text-sm",onChange:b=>i(w=>({...w,[v.index]:b.target.value})),onKeyDown:b=>{b.key==="Enter"&&(b.preventDefault(),u())}})]},v.index))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs($,{type:"button",size:"sm",onClick:u,children:[e.jsx(Gq,{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 e9(){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 EDn(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 Zat(){const s=Wt(),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 TDn(){const s=Wt();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 MDn(){const s=Wt();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 DXt(){const s=Wt();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 PDn(){const s=Wt();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 Tie(){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 Xat(){const{user:s}=bs();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 FXt(){const s=Wt(),{user:t}=bs();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 OXt(){const s=Wt();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 sSt=s=>s.replace(/&/g,"&").replace(//g,">").replace(/"/g,""");function nSt(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 IDn(s,t,n,r){const a=t.trim()?`
${sSt(t).replace(/\n/g,"
")}
`:"",i=n.trim()?`
${sSt(n).replace(/\n/g,"
")}
`:"",l=r?`
${r}
`:"";return`${a} ${s} ${i} ${l}`}function LDn(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 RDn=["free","act now","click here","limited time","urgent","$$$","100% free","guarantee","no obligation","risk-free","winner","cash bonus","make money","earn extra","amazing"];function DDn(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=RDn.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 Qat({open:s,onOpenChange:t,newsletterId:n,newsletterTitle:r,htmlCode:a}){const{user:i}=bs();gy();const{isReady:l,settings:o}=l6(),{data:c}=sie(),[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,y]=j.useState("all"),[v,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,Y]=j.useState(new Set),[X,ae]=j.useState(""),[le,ne]=j.useState(!1),[te,J]=j.useState(!1),[ce,_e]=j.useState(!1),[he,ue]=j.useState({sent:0,failed:0,total:0,currentName:""}),[ve,Ee]=j.useState(!0),[Se,Le]=j.useState(!1),[Fe,ke]=j.useState([]),[Be,Ne]=j.useState(!1),[Ae,Ce]=j.useState(new Set),[Ve,ze]=j.useState("now"),[qe,dt]=j.useState(""),{data:Xe=[]}=e9(),{data:at=[]}=Tie(),{data:rt=[]}=Xat(),{data:Ke=[],isLoading:Je}=st({queryKey:["newsletter-send-contacts",h],enabled:!!h&&s,queryFn:async()=>{const bn=[];let xs=0;const Lr=1e3;for(;;){const{data:Or,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+Lr-1);if(la)throw la;if(!Or||Or.length===0||(bn.push(...Or),Or.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:ss}=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}}),Yt=!!(ss!=null&&ss.mls_provider_id),ts=(ss==null?void 0:ss.mls_agent_id)||(ss==null?void 0:ss.mls_agent_key)||null,{data:ys=[],isLoading:Bt}=st({queryKey:["newsletter-agent-listings",h,ts],enabled:!!h&&!!ts&&Be,staleTime:60*1e3,queryFn:async()=>{if(!ts)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",ts).eq("standard_status","Active").order("modification_timestamp",{ascending:!1}).limit(30);return bn||[]}}),{data:Ft=[],isLoading:as}=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 Lr=xs.map(Cr=>Cr.id),{data:Or}=await q.from("listing_photos").select("listing_id, photo_url, is_primary, sort_order").in("listing_id",Lr),la=new Map,Qn=new Map;for(const Cr of Or||[])Cr.is_primary&&!la.has(Cr.listing_id)&&la.set(Cr.listing_id,Cr.photo_url),Qn.has(Cr.listing_id)||Qn.set(Cr.listing_id,Cr.photo_url);return xs.map(Cr=>({...Cr,_photo:la.get(Cr.id)||Qn.get(Cr.id)||""}))}}),{data:kt=!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}}),Ks=j.useMemo(()=>{const bn=new Set(pt);return Ke.filter(xs=>xs.email&&xs.email.includes("@")&&!bn.has(xs.email.toLowerCase()))},[Ke,pt]),wt=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]),ks=j.useMemo(()=>{var bn;if(x==="all")return Ks;if(x==="tags")return wt?Ks.filter(xs=>wt.has(xs.id)):[];if(x==="smartlists"){if(!gs)return[];const xs=(((bn=gs.filters)==null?void 0:bn.search)||"").toLowerCase().trim();return xs?Ks.filter(Lr=>`${Lr.first_name||""} ${Lr.last_name||""}`.toLowerCase().includes(xs)||(Lr.email||"").toLowerCase().includes(xs)):Ks}return Ks.filter(xs=>G.has(xs.id))},[x,Ks,wt,gs,G]),Is=j.useMemo(()=>{if(!X.trim())return Ks;const bn=X.toLowerCase();return Ks.filter(xs=>`${xs.first_name||""} ${xs.last_name||""}`.toLowerCase().includes(bn))},[Ks,X]);j.useEffect(()=>{s&&(b(""),S(`Hi {{first_name}}, Sharing this month's update — hope you find something useful!`),E(`As always, reach out anytime if I can help. Talk soon!`),P(a||""),g("light"),y("all"),U([]),V(null),Y(new Set),ae(""),ne(!1),D(!0),Ee(!0),ke([]),ze("now"),dt(""),ue({sent:0,failed:0,total:0,currentName:""}))},[s,r,a]);const Xs=l,ds=j.useMemo(()=>SDn(I||a||""),[I,a]),Ss=!!(v.trim()&&Xs&&ks.length>0&&!te&&ds.length===0),yn=bn=>{const xs=I||a,Lr=R&&(m!=null&&m.email_signature)?m.email_signature:null;let Or;return f==="light"?Or=IDn(xs,w,A,Lr):Or=Lr?`${xs}
${Lr}
`:xs,ve&&(Or+=LDn(m??null,gt??null,bn.email)),nSt(Or,bn,m??null,(gt==null?void 0:gt.name)??null)},Js=j.useMemo(()=>yn({first_name:"Friend",last_name:"",email:"preview@example.com",phone:"",address:"",city:"",state:"",zip:""}),[f,w,A,I,a,R,m,ve,gt]),Ut=j.useMemo(()=>DDn(v,f==="advanced"||f==="visual"?I:a),[v,f,I,a]),hn=async()=>{Le(!0),ke([]);try{const bn=f==="advanced"||f==="visual"?I:a,{data:xs,error:Lr}=await q.functions.invoke("generate-newsletter-subjects",{body:{newsletterTitle:r,bodyHtml:bn,currentSubject:v}});if(Lr)throw Lr;const Or=xs==null?void 0:xs.subjects;if(!Array.isArray(Or)||Or.length===0)throw new Error("No subjects returned");ke(Or)}catch(bn){const xs=(bn==null?void 0:bn.message)||"Failed to generate subjects";xs.includes("credits exhausted")||xs.includes("402")?re.error("AI credits exhausted. Please add credits to your workspace."):xs.includes("Rate limit")||xs.includes("429")?re.error("Rate limit hit — try again in a moment."):re.error(xs)}finally{Le(!1)}},hr=bn=>bn?"$"+Number(bn).toLocaleString("en-US"):"",Rs=()=>{var Qn,Cr;if(Ae.size===0){re.error("Pick at least one listing first.");return}const bn=(ss==null?void 0:ss.subdomain_slug)||"",xs=bn?`https://${bn}.relevelup.com`:"https://relevelup.com",Lr=[];for(const Un of ys){const dr=`mls:${Un.listing_key}`;if(!Ae.has(dr))continue;const Pa=Array.isArray(Un.photos)&&Un.photos.length>0?typeof Un.photos[0]=="string"?Un.photos[0]:((Qn=Un.photos[0])==null?void 0:Qn.MediaURL)||((Cr=Un.photos[0])==null?void 0:Cr.url)||"":"",ii=Un.bedrooms?`${Un.bedrooms} bd`:"",$i=Un.bathrooms_total?`${Un.bathrooms_total} ba`:"",Rn=Un.living_area?`${Number(Un.living_area).toLocaleString()} sqft`:"";Lr.push({url:`${xs}/listings/${Un.listing_key}`,photo:Pa,price:hr(Un.list_price),addr:`${Un.address||""}${Un.city?", "+Un.city:""}`,stats:[ii,$i,Rn].filter(Boolean).join(" • ")})}for(const Un of Ft){const dr=`ex:${Un.id}`;if(!Ae.has(dr))continue;const Pa=Un.bedrooms?`${Un.bedrooms} bd`:"",ii=Un.bathrooms?`${Un.bathrooms} ba`:"",$i=Un.square_footage?`${Number(Un.square_footage).toLocaleString()} sqft`:"";Lr.push({url:`https://listings.relevelup.com/${Un.slug||Un.id}`,photo:Un._photo||"",price:hr(Un.price),addr:`${Un.property_address||""}${Un.city?", "+Un.city:""}`,stats:[Pa,ii,$i].filter(Boolean).join(" • ")})}const la=`

Featured Listings

${Lr.map(Un=>`
${Un.photo?`${Un.addr}`:""}
${Un.price}
${Un.addr}
${Un.stats}
`.trim()).join(` `)}
`.trim();P(Un=>(Un||a||"")+` `+la),g("visual"),Ce(new Set),Ne(!1),re.success(`Added ${Lr.length} listing${Lr.length===1?"":"s"} to your newsletter.`)},jr=()=>yn({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}}"),kr=()=>nSt(v,{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}}"),$n=()=>{if(ds.length>0){re.error(`Fill in ${ds.length} template field${ds.length===1?"":"s"} before sending.`);return}if(Ss){if(Ve==="later"){if(!qe){re.error("Pick a date and time to schedule.");return}const bn=new Date(qe).getTime();if(Number.isNaN(bn)||bn{if(!(!Ss||!i)){_e(!1),J(!0),ue({sent:0,failed:0,total:ks.length,currentName:"Preparing campaign…"});try{const xs=`${((o==null?void 0:o.display_name)||"ReLevelUp").toLowerCase().replace(/[^a-z]/g,".")}@send.relevelup.com`,Lr=jr(),Or=kr(),la=Ve==="later",{data:Qn,error:Cr}=await q.from("email_campaigns").insert({user_id:h||i.id,name:`Newsletter: ${r}`,subject:Or,body_html:Lr,from_email:xs,reply_to_email:(o==null?void 0:o.reply_to_email)||null,total_recipients:ks.length,status:la?"scheduled":"draft",scheduled_at:la?new Date(qe).toISOString():null}).select("id").single();if(Cr)throw Cr;ue(dr=>({...dr,currentName:"Adding recipients…"}));const Un=ks.map(dr=>({campaign_id:Qn.id,contact_id:dr.id,email:dr.email,name:[dr.first_name,dr.last_name].filter(Boolean).join(" ")||null,status:"pending"}));for(let dr=0;dr({...$i,sent:Math.min(dr+Pa.length,Un.length)}))}if(la){const{error:dr}=await q.functions.invoke("ses-schedule-campaign",{body:{action:"schedule",campaign_id:Qn.id}});if(dr)throw dr;re.success(`Newsletter scheduled for ${new Date(qe).toLocaleString()}.`)}else{const{error:dr}=await q.functions.invoke("ses-send-campaign",{body:{action:"send_campaign",campaign_id:Qn.id}});if(dr)throw dr;re.success(`Sending to ${ks.length} contact${ks.length===1?"":"s"}! Open & click tracking will appear in Sent Emails.`)}t(!1)}catch(bn){console.error("Newsletter send failed:",bn),re.error(`Failed to send: ${bn.message||"Unknown error"}`)}finally{J(!1)}}},Fn=bn=>{Y(xs=>{const Lr=new Set(xs);return Lr.has(bn)?Lr.delete(bn):Lr.add(bn),Lr})};return e.jsxs(zs,{open:s,onOpenChange:bn=>!te&&t(bn),children:[e.jsxs(Os,{className:"max-w-5xl max-h-[92vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(Kr,{className:"h-5 w-5"})," Send Newsletter"]})}),!Xs&&e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border-2 border-destructive/40 bg-destructive/10 p-4 text-sm",children:[e.jsx(ll,{className:"h-5 w-5 text-destructive shrink-0 mt-0.5"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-semibold text-destructive",children:"Set up Mass Email first"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"You need to verify your sender email before you can send newsletters. It only takes a minute — we'll send a verification email to confirm you own the address."}),e.jsx($,{size:"sm",className:"mt-3",onClick:()=>{window.open("/mission-control/integrations#mass-email","_blank")},children:"Set up Mass Email →"})]})]}),e.jsxs("div",{className:"grid lg:grid-cols-2 gap-6",children:[e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{children:"Subject"}),e.jsxs($,{type:"button",variant:"ghost",size:"sm",className:"h-7 gap-1 text-xs",onClick:hn,disabled:Se,title:"Generate subject lines with AI",children:[Se?e.jsx(Ct,{className:"h-3 w-3 animate-spin"}):e.jsx(Nn,{className:"h-3 w-3"}),"AI Suggestions"]})]}),e.jsx(pe,{value:v,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),ke([])},className:"w-full text-left text-sm px-2 py-1.5 rounded hover:bg-primary/10 transition-colors",children:[e.jsx(Nn,{className:"h-3 w-3 inline-block mr-1.5 text-primary"}),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}}"})]})]}),Ut.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(eV,{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:Ut.map((bn,xs)=>e.jsx("li",{children:bn},xs))})]}),(Yt||kt)&&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:Yt&&kt?"Pick from your live MLS listings or your Listing Exchange listings.":Yt?"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:()=>Ne(!0),children:"Choose listings"})]}),e.jsx(ADn,{html:I||a||"",originalHtml:a||"",onChange:P}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Editing"}),e.jsxs(ha,{value:f,onValueChange:bn=>g(bn),children:[e.jsxs(ma,{className:"grid grid-cols-3 w-full",children:[e.jsxs(Zt,{value:"visual",children:[e.jsx(ey,{className:"h-3 w-3 mr-1"}),"Visual"]}),e.jsxs(Zt,{value:"light",children:[e.jsx(Jr,{className:"h-3 w-3 mr-1"}),"Quick edit"]}),e.jsxs(Zt,{value:"advanced",children:[e.jsx(t4,{className:"h-3 w-3 mr-1"}),"HTML"]})]}),e.jsx(Xt,{value:"visual",className:"mt-3",children:e.jsx(Wat,{html:I,onChange:P})}),e.jsxs(Xt,{value:"light",className:"space-y-3 mt-3",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs text-muted-foreground",children:"Personal intro (above newsletter)"}),e.jsx(Ls,{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(Ls,{value:A,onChange:bn=>E(bn.target.value),rows:3,placeholder:"Talk soon!"})]})]}),e.jsxs(Xt,{value:"advanced",className:"mt-3",children:[e.jsx(ee,{className:"text-xs text-muted-foreground",children:"Edit full HTML"}),e.jsx(Ls,{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(Sn,{checked:R&&!!(m!=null&&m.email_signature),disabled:!(m!=null&&m.email_signature),onCheckedChange:D})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:"Include unsubscribe footer"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Adds your brokerage info and a one-click unsubscribe link. Strongly recommended for deliverability."})]}),e.jsx(Sn,{checked:ve,onCheckedChange:Ee})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Recipients"}),e.jsxs(ha,{value:x,onValueChange:bn=>y(bn),children:[e.jsxs(ma,{className:"grid grid-cols-4 w-full",children:[e.jsxs(Zt,{value:"all",children:[e.jsx(Yn,{className:"h-3 w-3 mr-1"}),"All"]}),e.jsxs(Zt,{value:"tags",children:[e.jsx(Ap,{className:"h-3 w-3 mr-1"}),"Tags"]}),e.jsxs(Zt,{value:"smartlists",children:[e.jsx(MJ,{className:"h-3 w-3 mr-1"}),"Lists"]}),e.jsxs(Zt,{value:"individual",children:[e.jsx(sl,{className:"h-3 w-3 mr-1"}),"Pick"]})]}),e.jsx(Xt,{value:"all",className:"mt-3",children:e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-4 text-sm",children:["Send to ",e.jsx("strong",{children:Ks.length})," contact",Ks.length===1?"":"s"," with a valid, non-suppressed email."]})}),e.jsxs(Xt,{value:"tags",className:"mt-3 space-y-2",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Select one or more tags"}),e.jsx(uo,{className:"h-40 rounded-lg border p-2",children:Xe.length===0?e.jsx("p",{className:"text-xs text-muted-foreground p-2",children:"No tags yet. Add tags to contacts to use this option."}):Xe.map(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(Lr=>xs?[...Lr,bn.id]:Lr.filter(Or=>Or!==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(Xt,{value:"smartlists",className:"mt-3 space-y-2",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Pick a saved smart list"}),e.jsx(uo,{className:"h-40 rounded-lg border p-2",children: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(Xt,{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:()=>Y(new Set),children:"Clear"})]}),e.jsxs(uo,{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&&Is.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground p-2",children:"No matching contacts."}),Is.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)),Is.length>200&&e.jsx("p",{className:"text-xs text-muted-foreground p-2",children:"Showing first 200 — refine search to see more."})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsxs($e,{variant:"secondary",className:"gap-1",children:[e.jsx(Vr,{className:"h-3 w-3"})," ",ks.length," recipient",ks.length===1?"":"s"]}),Xs&&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:()=>ne(bn=>!bn),children:le?e.jsxs(e.Fragment,{children:[e.jsx($g,{className:"h-3 w-3 mr-1"}),"Hide"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ca,{className:"h-3 w-3 mr-1"}),"Show"]})})]}),le?e.jsx("div",{className:"rounded-lg border overflow-hidden bg-white",children:e.jsx("iframe",{title:"newsletter-preview",srcDoc:Js,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 ",he.currentName||"..."]}),e.jsxs("span",{className:"text-muted-foreground",children:[he.sent+he.failed," / ",he.total]})]}),e.jsx(Yi,{value:he.total?(he.sent+he.failed)/he.total*100:0}),he.failed>0&&e.jsxs("p",{className:"text-xs text-destructive",children:[he.failed," failed"]})]}),e.jsxs("div",{className:"space-y-3 pt-2 border-t",children:[e.jsxs("div",{className:"rounded-lg border bg-muted/20 p-3 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(da,{className:"h-4 w-4"})," When to send"]}),e.jsxs(vw,{value:Ve,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(Cu,{className:"h-3.5 w-3.5"})," Schedule for later"]})]}),Ve==="later"&&e.jsx(pe,{type:"datetime-local",value:qe,onChange:bn=>dt(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:ds.length>0?`${ds.length} template field${ds.length===1?"":"s"} still need${ds.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:$n,disabled:!Ss,children:te?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"h-4 w-4 mr-1 animate-spin"}),"Working…"]}):Ve==="later"?e.jsxs(e.Fragment,{children:[e.jsx(Cu,{className:"h-4 w-4 mr-1"}),"Schedule for ",ks.length]}):e.jsxs(e.Fragment,{children:[e.jsx(Kr,{className:"h-4 w-4 mr-1"}),"Send to ",ks.length]})})]})]})]})]}),e.jsx(fc,{open:ce,onOpenChange:_e,children:e.jsxs(sc,{children:[e.jsxs(nc,{children:[e.jsx(ac,{children:Ve==="later"?"Schedule newsletter?":"Send newsletter?"}),e.jsxs(ic,{children:[Ve==="later"?"Schedule ":"Send ",e.jsxs("span",{className:"font-medium text-foreground",children:['"',v,'"']})," to"," ",e.jsxs("span",{className:"font-medium text-foreground",children:[ks.length," contact",ks.length===1?"":"s"]}),Ve==="later"&&qe?` for ${new Date(qe).toLocaleString()}`:"","? Suppressed and unsubscribed contacts are skipped automatically."]})]}),e.jsxs(rc,{children:[e.jsx(oc,{children:"Cancel"}),e.jsx(Yl,{onClick:kn,children:Ve==="later"?e.jsxs(e.Fragment,{children:[e.jsx(Cu,{className:"h-4 w-4 mr-1"}),"Schedule"]}):e.jsxs(e.Fragment,{children:[e.jsx(Kr,{className:"h-4 w-4 mr-1"}),"Send to ",ks.length]})})]})]})}),e.jsx(zs,{open:Be,onOpenChange:Ne,children:e.jsxs(Os,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(va,{className:"h-5 w-5"})," Choose listings to insert"]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Pick up to 6 listings. They'll be added as an email-safe grid."}),(Bt||as)&&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…"]}),!Bt&&!as&&ys.length===0&&Ft.length===0&&e.jsx("div",{className:"rounded-lg border bg-muted/30 p-6 text-center text-sm text-muted-foreground",children:"No listings found. Add a listing on the Listing Exchange or connect your MLS to get started."}),ys.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wide text-muted-foreground",children:"From your MLS"}),e.jsx("div",{className:"grid grid-cols-2 gap-3",children:ys.map(bn=>{var la,Qn;const xs=`mls:${bn.listing_key}`,Lr=Ae.has(xs),Or=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)||((Qn=bn.photos[0])==null?void 0:Qn.url)||"":"";return e.jsxs("button",{type:"button",onClick:()=>{Ce(Cr=>{const Un=new Set(Cr);return Un.has(xs)?Un.delete(xs):Un.size<6?Un.add(xs):re.error("Max 6 listings per newsletter"),Un})},className:`relative rounded-lg border-2 overflow-hidden text-left transition-all ${Lr?"border-primary ring-2 ring-primary/30":"border-border hover:border-primary/50"}`,children:[Or&&e.jsx("img",{src:Or,alt:"",className:"w-full h-32 object-cover"}),e.jsxs("div",{className:"p-2",children:[e.jsx("div",{className:"text-sm font-semibold text-primary",children: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}`:""]})]}),Lr&&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}`,Lr=Ae.has(xs);return e.jsxs("button",{type:"button",onClick:()=>{Ce(Or=>{const la=new Set(Or);return la.has(xs)?la.delete(xs):la.size<6?la.add(xs):re.error("Max 6 listings per newsletter"),la})},className:`relative rounded-lg border-2 overflow-hidden text-left transition-all ${Lr?"border-primary ring-2 ring-primary/30":"border-border hover:border-primary/50"}`,children:[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}`:""]})]}),Lr&&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(Sr,{children:[e.jsx($,{variant:"outline",onClick:()=>Ne(!1),children:"Cancel"}),e.jsxs($,{onClick:Rs,disabled:Ae.size===0,children:["Insert ",Ae.size>0?Ae.size:""," listing",Ae.size===1?"":"s"]})]})]})}),e.jsx(w6e,{open:d,onOpenChange:u,hasPending:!!(c!=null&&c.hasPendingSes),pendingEmails:c==null?void 0:c.pendingEmails})]})}function FDn(){const{user:s}=bs(),t=Wt(),[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))??[],y=(m==null?void 0:m.filter(I=>I.user_id===(s==null?void 0:s.id)&&I.is_template))??[],v=(m==null?void 0:m.filter(I=>I.user_id!==(s==null?void 0:s.id)&&I.is_template&&(I.share_scope==="team"||I.share_scope==="brokerage"||I.share_scope==="global")))??[],b=(m==null?void 0:m.filter(I=>I.share_scope==="global"&&I.is_template))??[],w=n==="starters"?b:n==="mine"?x:n==="templates"?y:v.filter(I=>I.share_scope!=="global"),S=async I=>{if(!s)return;const{error:P}=await q.from("agent_custom_newsletters").insert({user_id:s.id,title:`${I.title} (Copy)`,description:I.description,html_content:I.html_content,is_template:!1,share_scope:"private"});if(P){re.error(P.message);return}re.success('Duplicated to "My Newsletters"'),g(),r("mine")},A=async I=>{const{error:P}=await q.from("agent_custom_newsletters").delete().eq("id",I);if(P){re.error(P.message);return}re.success("Deleted"),h(null),g()},E=I=>I.share_scope==="global"?e.jsxs($e,{variant:"secondary",className:"gap-1",children:[e.jsx(Nn,{className:"h-3 w-3"}),"Starter"]}):I.share_scope==="brokerage"?e.jsxs($e,{variant:"secondary",className:"gap-1",children:[e.jsx(ji,{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(pc,{className:"h-3 w-3"}),"Private"]});return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs($,{variant:n==="starters"?"default":"outline",size:"sm",onClick:()=>r("starters"),className:"gap-1.5",children:[e.jsx(Nn,{className:"h-3.5 w-3.5"}),"Starter Templates (",b.length,")"]}),e.jsxs($,{variant:n==="mine"?"default":"outline",size:"sm",onClick:()=>r("mine"),children:["My Newsletters (",x.length,")"]}),e.jsxs($,{variant:n==="templates"?"default":"outline",size:"sm",onClick:()=>r("templates"),children:["My Templates (",y.length,")"]}),e.jsxs($,{variant:n==="shared"?"default":"outline",size:"sm",onClick:()=>r("shared"),children:["Shared with Me (",v.filter(I=>I.share_scope!=="global").length,")"]})]}),e.jsxs($,{onClick:()=>{o(null),i(!0)},children:[e.jsx(dn,{className:"h-4 w-4 mr-1.5"})," Create Newsletter"]})]}),f&&e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(3)].map((I,P)=>e.jsx(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(Nn,{className:"h-4 w-4 text-primary mt-0.5 shrink-0"}),e.jsxs("span",{children:["Click ",e.jsx("strong",{children:"Use"}),' on any starter to copy it into your "My Newsletters" — then edit, send, or save as your own template.']})]}),!f&&w.length===0&&e.jsx(je,{children:e.jsxs(Ie,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(Jr,{className:"h-10 w-10 mx-auto mb-3 opacity-50"}),n==="starters"&&e.jsx("p",{children:"No starter templates available yet."}),n==="mine"&&e.jsx("p",{children:`You haven't created any newsletters yet. Try a Starter Template or click "Create Newsletter"!`}),n==="templates"&&e.jsx("p",{children:`You haven't saved any templates yet. Toggle "Save as reusable template" when creating a newsletter.`}),n==="shared"&&e.jsx("p",{children:"No team or brokerage templates have been shared with you yet."})]})}),!f&&w.length>0&&e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:w.map(I=>{const P=I.user_id===(s==null?void 0:s.id);return e.jsxs(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(Ie,{className:"p-3 space-y-2",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold line-clamp-1",children:I.title}),I.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1",children:I.description}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:["Updated ",en(new Date(I.updated_at||I.created_at),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex gap-1.5 flex-wrap",children:[e.jsxs($,{size:"sm",onClick:()=>d(I),className:"flex-1 min-w-[80px]",children:[e.jsx(Kr,{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(Ha,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"sm",variant:"outline",onClick:()=>h(I.id),children:e.jsx(Hn,{className:"h-3.5 w-3.5"})})]}):e.jsxs($,{size:"sm",variant:"outline",onClick:()=>S(I),children:[e.jsx(Ha,{className:"h-3.5 w-3.5 mr-1"})," Use"]})]})]})]},I.id)})}),e.jsx(jDn,{open:a,onOpenChange:i,initial:l,onSaved:g}),c&&e.jsx(Qat,{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 ODn(){const s=Xn(),[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},y=A=>{var E;return((E=h==null?void 0:h.videos)==null?void 0:E.filter(I=>I.newsletter_id===A).length)||0},v=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)+y(A)+v(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(ha,{defaultValue:"custom",className:"space-y-4",children:[e.jsxs(ma,{children:[e.jsx(Zt,{value:"custom",children:"Build & Send"}),e.jsx(Zt,{value:"curated",children:"Curated Monthly"})]}),e.jsx(Xt,{value:"custom",className:"mt-2",children:e.jsx(FDn,{})}),e.jsxs(Xt,{value:"curated",className:"space-y-6 mt-2",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(Zr,{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(Qf,{className:"h-4 w-4"})}),e.jsx($,{variant:r==="list"?"secondary":"outline",size:"icon",onClick:()=>a("list"),className:"rounded-full",children:e.jsx(T0,{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(Ie,{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(Jr,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("div",{className:"text-muted-foreground mb-4",children:t?"No newsletters match your search":"No newsletters available yet"}),t&&e.jsx($,{variant:"outline",onClick:()=>n(""),children:"Clear Search"})]}),!c&&w&&w.length>0&&e.jsx("div",{className:r==="grid"?"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6":"space-y-3",children:w.map(A=>{const E=b(A.id),I=g(A.id),P=x(A.id),R=y(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(Jr,{className:"h-16 w-16"})})}),e.jsxs(Ie,{className:"p-4 space-y-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1",children:A.title}),e.jsxs("div",{className:"flex items-center gap-1.5 mt-1 text-xs text-muted-foreground",children:[e.jsx(Ta,{className:"h-3 w-3"}),en(new Date(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(xi,{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(zu,{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(qy,{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(Kr,{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(Jr,{className:"h-10 w-10"})})}),e.jsxs(Ie,{className:"p-4 flex-1 flex flex-col justify-center gap-2",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1",children:A.title}),e.jsxs("div",{className:"flex items-center gap-1.5 mt-0.5 text-xs text-muted-foreground",children:[e.jsx(Ta,{className:"h-3 w-3"}),en(new Date(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(qy,{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(Kr,{className:"h-4 w-4 mr-1.5"}),"Send"]})})]})},A.id)})})]})]}),(i==null?void 0:i.html_code)&&e.jsx(Qat,{open:!!i,onOpenChange:A=>!A&&l(null),newsletterId:i.id,newsletterTitle:i.title,htmlCode:i.html_code})]})})}function zDn({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(Ie,{className:"p-4 space-y-2",children:[i.title&&e.jsx("h4",{className:"font-semibold text-foreground",children:i.title}),i.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:i.description})]})]},l))},r)})})}function BDn(){const{id:s}=Wi(),t=Xn(),{user:n}=bs(),{toast:r}=Bi(),a=Wt(),{trackEngagement:i}=hK(),[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:y}=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:v}=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=y==null?void 0:y.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(zu,{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:en(new Date(u.publish_date),"MMMM d, yyyy")})]}),u.description&&e.jsx("div",{className:"text-lg text-muted-foreground prose prose-sm max-w-none dark:prose-invert [&_p]:mb-4 [&_p:last-child]:mb-0 whitespace-pre-line",dangerouslySetInnerHTML:{__html:u.description}}),e.jsx(zDn,{rows:u.content_blocks||[]}),e.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[e.jsx(pK,{resourceType:"newsletter",resourceId:u.id,resourceTitle:u.title}),e.jsxs($,{variant:b?"default":"outline",size:"sm",onClick:()=>w.mutate(),children:[e.jsx(Jo,{className:`h-4 w-4 mr-1 ${b?"fill-current":""}`}),(y==null?void 0:y.length)||0," ",(y==null?void 0:y.length)===1?"Like":"Likes"]}),u.html_code&&e.jsxs($,{size:"sm",className:"bg-gradient-to-r from-[#2a4c64] to-[#406E71] text-white hover:opacity-90",onClick:()=>d(!0),children:[e.jsx(Kr,{className:"h-4 w-4 mr-1"}),"Send Newsletter"]})]}),u.html_code&&e.jsx(Qat,{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(Ie,{className:"space-y-2",children:x.map(I=>e.jsxs("a",{href:I.canva_share_link,target:"_blank",rel:"noopener noreferrer",onClick:()=>i("newsletter",u.id,u.title,"click_canva"),className:"flex items-center gap-3 p-3 rounded-lg hover:bg-muted transition-colors",children:[e.jsx(yd,{className:"h-5 w-5 text-purple-500"}),e.jsx("span",{className:"font-medium",children:I.title}),e.jsx(Fr,{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(Ie,{className:"space-y-2",children:m.map(I=>e.jsxs("a",{href:I.drive_url,target:"_blank",rel:"noopener noreferrer",onClick:()=>i("newsletter",u.id,u.title,"click_link"),className:"flex items-center gap-3 p-3 rounded-lg hover:bg-muted transition-colors",children:[e.jsx(Fr,{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(Ie,{className:"space-y-2",children:f.map(I=>e.jsxs("a",{href:I.file_url,target:"_blank",rel:"noopener noreferrer",onClick:()=>i("newsletter",u.id,u.title,"click_pdf"),className:"flex items-center gap-3 p-3 rounded-lg hover:bg-muted transition-colors",children:[e.jsx(Jr,{className:"h-5 w-5 text-red-500"}),e.jsx("span",{className:"font-medium flex-1",children:I.name}),e.jsx(xi,{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(Ie,{className:"space-y-6",children:g.map(I=>e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium",children:I.title}),E(I.video_url)]},I.id))})]}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsxs(Et,{className:"text-lg",children:["Comments (",(v==null?void 0:v.length)||0,")"]})}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Ls,{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(Kr,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"space-y-4",children:v==null?void 0:v.map(I=>{var P,R,D;return e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Oa,{className:"h-8 w-8",children:e.jsx(za,{children:((R=(P=I.profiles)==null?void 0:P.name)==null?void 0:R[0])||"U"})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"font-medium text-sm",children:((D=I.profiles)==null?void 0:D.name)||"User"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:en(new Date(I.created_at),"MMM d, yyyy")}),I.user_id===(n==null?void 0:n.id)&&e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>A.mutate(I.id),children:e.jsx(Hn,{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 $Dn({rows:s,onChange:t}){const[n,r]=j.useState(null),[a,i]=j.useState(null),l=()=>{t([...s,{columns:[{title:"",description:""},{title:"",description:""},{title:"",description:""}]}])},o=h=>{t(s.filter((m,f)=>f!==h))},c=(h,m,f,g)=>{const x=[...s];x[h]={...x[h],columns:x[h].columns.map((y,v)=>v===m?{...y,[f]:g}:y)},t(x)},d=async(h,m,f)=>{var y;const g=(y=f.target.files)==null?void 0:y[0];if(!g)return;const x=`${h}-${m}`;r(x);try{const v=`content-blocks/${Date.now()}-${g.name}`,{error:b}=await q.storage.from("newsletter-content").upload(v,g);if(!b){const{data:w}=q.storage.from("newsletter-content").getPublicUrl(v);c(h,m,"image_url",w.publicUrl)}}finally{r(null)}},u=(h,m)=>{c(h,m,"image_url","")};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{className:"text-base font-medium",children:"Content Blocks (3-Column Rows)"}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:l,children:[e.jsx(dn,{className:"mr-1 h-3 w-3"})," Add Row"]})]}),s.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No content block rows yet. Add a row to create a 3-column layout."}),s.map((h,m)=>e.jsxs(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(pr,{className:"h-4 w-4"})}),e.jsxs(Ie,{className:"p-4 pt-3",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(Ug,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:["Row ",m+1]})]}),e.jsx("div",{className:"grid grid-cols-3 gap-3",children:h.columns.map((f,g)=>{const x=`${m}-${g}`;return e.jsxs("div",{className:"space-y-2 border border-border/50 rounded-md p-3 bg-muted/20",children:[e.jsxs("span",{className:"text-xs text-muted-foreground font-medium",children:["Column ",g+1]}),f.image_url?e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:f.image_url,alt:"",className:"w-full h-20 object-cover rounded"}),e.jsx($,{type:"button",variant:"destructive",size:"icon",className:"absolute top-1 right-1 h-5 w-5 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>u(m,g),children:e.jsx(pr,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"grid grid-cols-2 gap-1.5",children:[e.jsx(pe,{type:"file",accept:"image/*",className:"hidden",id:`block-img-${x}`,onChange:y=>d(m,g,y)}),e.jsx($,{type:"button",variant:"outline",size:"sm",className:"text-xs h-8",disabled:n===x,asChild:!0,children:e.jsx("label",{htmlFor:`block-img-${x}`,className:"cursor-pointer",children:n===x?"...":e.jsxs(e.Fragment,{children:[e.jsx(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(d2,{className:"h-3 w-3 mr-1"})," Library"]})]}),e.jsx(pe,{placeholder:"Title",value:f.title,onChange:y=>c(m,g,"title",y.target.value),className:"h-8 text-sm"}),e.jsx(Ls,{placeholder:"Description",value:f.description,onChange:y=>c(m,g,"description",y.target.value),className:"text-sm min-h-[60px] resize-none"})]},g)})})]})]},m)),e.jsx(zs,{open:!!a,onOpenChange:h=>!h&&i(null),children:e.jsxs(Os,{className:"sm:max-w-2xl",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Choose a Graphic"})}),e.jsx(RXt,{onSelect:h=>{a&&(c(a.row,a.col,"image_url",h.image_url),i(null))}})]})})]})}function UDn(){const{toast:s}=Bi(),t=Wt(),[n,r]=j.useState(!1),[a,i]=j.useState(null),[l,o]=j.useState({title:"",description:"",publish_date:en(new Date,"yyyy-MM-dd'T'HH:mm"),is_published:!1}),[c,d]=j.useState(null),[u,h]=j.useState(null),[m,f]=j.useState([]),[g,x]=j.useState([]),[y,v]=j.useState([]),[b,w]=j.useState([]),[S,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:ve,error:Ee}=await q.from("newsletter_content").select("*").order("publish_date",{ascending:!1});if(Ee)throw Ee;return ve}}),V=mt({mutationFn:async ve=>{const{data:Ee,error:Se}=await q.from("newsletter_content").insert({title:ve.title,description:ve.description||null,preview_image_url:ve.preview_image_url,publish_date:ve.publish_date,is_published:ve.is_published,content_blocks:ve.content_blocks,html_code:ve.html_code}).select().single();if(Se)throw Se;return Ee},onSuccess:async ve=>{await X(ve.id),t.invalidateQueries({queryKey:["admin-newsletters"]}),s({title:"Newsletter created successfully"}),ve.is_published&&Khn(ve.title,ve.id),ne()},onError:ve=>{s({title:"Error creating newsletter",description:ve.message,variant:"destructive"})}}),G=mt({mutationFn:async ve=>{const{error:Ee}=await q.from("newsletter_content").update({title:ve.title,description:ve.description||null,preview_image_url:ve.preview_image_url,publish_date:ve.publish_date,is_published:ve.is_published,content_blocks:ve.content_blocks,html_code:ve.html_code}).eq("id",ve.id);if(Ee)throw Ee;return ve.id},onSuccess:async ve=>{await X(ve),t.invalidateQueries({queryKey:["admin-newsletters"]}),s({title:"Newsletter updated successfully"}),ne()},onError:ve=>{s({title:"Error updating newsletter",description:ve.message,variant:"destructive"})}}),Y=mt({mutationFn:async ve=>{const{error:Ee}=await q.from("newsletter_content").delete().eq("id",ve);if(Ee)throw Ee},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-newsletters"]}),s({title:"Newsletter deleted successfully"})},onError:ve=>{s({title:"Error deleting newsletter",description:ve.message,variant:"destructive"})}}),X=async ve=>{await q.from("newsletter_drive_links").delete().eq("newsletter_id",ve),await q.from("newsletter_pdfs").delete().eq("newsletter_id",ve),await q.from("newsletter_videos").delete().eq("newsletter_id",ve),await q.from("newsletter_canva_links").delete().eq("newsletter_id",ve);for(const Ee of P){const Se=`${ve}/${Date.now()}-${Ee.file.name}`,{error:Le}=await q.storage.from("newsletter-content").upload(Se,Ee.file);if(!Le){const{data:Fe}=q.storage.from("newsletter-content").getPublicUrl(Se);g.push({name:Ee.name,file_url:Fe.publicUrl,file_size:Ee.file.size,sort_order:g.length})}}m.length>0&&await q.from("newsletter_drive_links").insert(m.map((Ee,Se)=>({newsletter_id:ve,title:Ee.title,drive_url:Ee.drive_url,sort_order:Se}))),g.length>0&&await q.from("newsletter_pdfs").insert(g.map((Ee,Se)=>({newsletter_id:ve,name:Ee.name,file_url:Ee.file_url,file_size:Ee.file_size||null,sort_order:Se}))),y.length>0&&await q.from("newsletter_videos").insert(y.map((Ee,Se)=>({newsletter_id:ve,title:Ee.title,video_url:Ee.video_url,sort_order:Se}))),b.length>0&&await q.from("newsletter_canva_links").insert(b.map((Ee,Se)=>({newsletter_id:ve,title:Ee.title,canva_share_link:Ee.canva_share_link,sort_order:Se})))},ae=async ve=>{i(ve),o({title:ve.title,description:ve.description||"",publish_date:en(new Date(ve.publish_date),"yyyy-MM-dd'T'HH:mm"),is_published:ve.is_published}),h(ve.preview_image_url),A(ve.content_blocks||[]),I(ve.html_code||"");const[Ee,Se,Le,Fe]=await Promise.all([q.from("newsletter_drive_links").select("*").eq("newsletter_id",ve.id).order("sort_order"),q.from("newsletter_pdfs").select("*").eq("newsletter_id",ve.id).order("sort_order"),q.from("newsletter_videos").select("*").eq("newsletter_id",ve.id).order("sort_order"),q.from("newsletter_canva_links").select("*").eq("newsletter_id",ve.id).order("sort_order")]);f(Ee.data||[]),x(Se.data||[]),v(Le.data||[]),w(Fe.data||[]),R([]),r(!0)},le=async ve=>{const[Ee,Se,Le,Fe]=await Promise.all([q.from("newsletter_drive_links").select("*").eq("newsletter_id",ve.id).order("sort_order"),q.from("newsletter_pdfs").select("*").eq("newsletter_id",ve.id).order("sort_order"),q.from("newsletter_videos").select("*").eq("newsletter_id",ve.id).order("sort_order"),q.from("newsletter_canva_links").select("*").eq("newsletter_id",ve.id).order("sort_order")]);i(null),o({title:`${ve.title} (Copy)`,description:ve.description||"",publish_date:en(new Date,"yyyy-MM-dd'T'HH:mm"),is_published:!1}),h(ve.preview_image_url),A(ve.content_blocks||[]),I(ve.html_code||""),f((Ee.data||[]).map(({id:ke,...Be})=>Be)),x((Se.data||[]).map(({id:ke,...Be})=>Be)),v((Le.data||[]).map(({id:ke,...Be})=>Be)),w((Fe.data||[]).map(({id:ke,...Be})=>Be)),R([]),r(!0)},ne=()=>{r(!1),i(null),o({title:"",description:"",publish_date:en(new Date,"yyyy-MM-dd'T'HH:mm"),is_published:!1}),d(null),h(null),f([]),x([]),v([]),w([]),A([]),I(""),R([])},te=async ve=>{var Se;const Ee=(Se=ve.target.files)==null?void 0:Se[0];Ee&&(d(Ee),h(URL.createObjectURL(Ee)))},J=async()=>{if(!l.title){s({title:"Title is required",variant:"destructive"});return}O(!0);let ve=u;if(c){const Ee=`previews/${Date.now()}-${c.name}`,{error:Se}=await q.storage.from("newsletter-content").upload(Ee,c);if(!Se){const{data:Le}=q.storage.from("newsletter-content").getPublicUrl(Ee);ve=Le.publicUrl}}a?G.mutate({id:a.id,...l,preview_image_url:ve,content_blocks:S,html_code:E||null}):V.mutate({...l,preview_image_url:ve,content_blocks:S,html_code:E||null}),O(!1)},ce=()=>f([...m,{title:"",drive_url:"",sort_order:m.length}]),_e=()=>v([...y,{title:"",video_url:"",sort_order:y.length}]),he=()=>w([...b,{title:"",canva_share_link:"",sort_order:b.length}]),ue=ve=>{const Ee=ve.target.files;if(!Ee)return;const Se=Array.from(Ee).map(Le=>({file:Le,name:Le.name.replace(/\.[^/.]+$/,"")}));R([...P,...Se])};return e.jsx(Vs,{title:"Newsletter Content",description:"Manage monthly newsletter templates and resources",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(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(Ie,{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(Ie,{children:e.jsx("div",{className:"text-2xl font-bold",children:(U==null?void 0:U.filter(ve=>ve.is_published).length)||0})})]})]}),e.jsxs(zs,{open:n,onOpenChange:ve=>!ve&&ne(),children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{onClick:()=>r(!0),children:[e.jsx(dn,{className:"mr-2 h-4 w-4"})," Add Newsletter"]})}),e.jsxs(Os,{className:"max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(Bs,{children:a?"Edit Newsletter":"Add Newsletter"})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Title *"}),e.jsx(pe,{value:l.title,onChange:ve=>o({...l,title:ve.target.value}),placeholder:"Newsletter title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Publish Date"}),e.jsx(pe,{type:"datetime-local",value:l.publish_date,onChange:ve=>o({...l,publish_date:ve.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Description"}),e.jsx(Sk,{content:l.description,onChange:ve=>o({...l,description:ve}),placeholder:"Newsletter description",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Preview Image"}),e.jsxs("div",{className:"flex items-center gap-4",children:[u&&e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:u,alt:"Preview",className:"h-20 w-32 object-cover rounded-md"}),e.jsx($,{type:"button",variant:"destructive",size:"icon",className:"absolute -top-2 -right-2 h-5 w-5 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>{d(null),h(null)},children:e.jsx(pr,{className:"h-3 w-3"})})]}),e.jsxs("div",{children:[e.jsx(pe,{type:"file",accept:"image/*",onChange:te,className:"hidden",id:"preview-upload"}),e.jsx($,{variant:"outline",asChild:!0,children:e.jsxs("label",{htmlFor:"preview-upload",className:"cursor-pointer",children:[e.jsx(ni,{className:"mr-2 h-4 w-4"})," Upload Image"]})})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sn,{checked:l.is_published,onCheckedChange:ve=>o({...l,is_published:ve})}),e.jsx(ee,{children:"Published"})]}),e.jsx($Dn,{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:ve=>I(ve.target.value),rows:10,placeholder:"...",className:"w-full font-mono text-xs rounded-md border border-input bg-background px-3 py-2 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Supports merge tags: ",e.jsx("code",{children:"{{first_name}}"}),", ",e.jsx("code",{children:"{{last_name}}"}),", ",e.jsx("code",{children:"{{full_name}}"}),", ",e.jsx("code",{children:"{{agent_name}}"}),", ",e.jsx("code",{children:"{{agent_email}}"}),", ",e.jsx("code",{children:"{{agent_phone}}"}),"."]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{className:"text-base font-medium",children:"Canva Links"}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:he,children:[e.jsx(dn,{className:"mr-1 h-3 w-3"})," Add Canva Link"]})]}),b.map((ve,Ee)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(pe,{placeholder:"Link title",value:ve.title,onChange:Se=>{const Le=[...b];Le[Ee].title=Se.target.value,w(Le)},className:"w-1/3"}),e.jsx(pe,{placeholder:"Canva share link",value:ve.canva_share_link,onChange:Se=>{const Le=[...b];Le[Ee].canva_share_link=Se.target.value,w(Le)},className:"flex-1"}),e.jsx($,{type:"button",variant:"ghost",size:"icon",onClick:()=>w(b.filter((Se,Le)=>Le!==Ee)),children:e.jsx(pr,{className:"h-4 w-4"})})]},Ee))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{className:"text-base font-medium",children:"Google Drive Links"}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:ce,children:[e.jsx(dn,{className:"mr-1 h-3 w-3"})," Add Link"]})]}),m.map((ve,Ee)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(pe,{placeholder:"Link title",value:ve.title,onChange:Se=>{const Le=[...m];Le[Ee].title=Se.target.value,f(Le)},className:"w-1/3"}),e.jsx(pe,{placeholder:"Google Drive URL",value:ve.drive_url,onChange:Se=>{const Le=[...m];Le[Ee].drive_url=Se.target.value,f(Le)},className:"flex-1"}),e.jsx($,{type:"button",variant:"ghost",size:"icon",onClick:()=>f(m.filter((Se,Le)=>Le!==Ee)),children:e.jsx(pr,{className:"h-4 w-4"})})]},Ee))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{className:"text-base font-medium",children:"PDF Files"}),e.jsxs("div",{children:[e.jsx(pe,{type:"file",accept:".pdf",multiple:!0,onChange:ue,className:"hidden",id:"pdf-upload"}),e.jsx($,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("label",{htmlFor:"pdf-upload",className:"cursor-pointer",children:[e.jsx(ni,{className:"mr-1 h-3 w-3"})," Upload PDF"]})})]})]}),g.map((ve,Ee)=>e.jsxs("div",{className:"flex gap-2 items-center bg-muted/50 p-2 rounded",children:[e.jsx(Jr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"flex-1 text-sm",children:ve.name}),e.jsx($,{type:"button",variant:"ghost",size:"icon",onClick:()=>x(g.filter((Se,Le)=>Le!==Ee)),children:e.jsx(pr,{className:"h-4 w-4"})})]},`existing-${Ee}`)),P.map((ve,Ee)=>e.jsxs("div",{className:"flex gap-2 items-center bg-muted/50 p-2 rounded",children:[e.jsx(Jr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(pe,{value:ve.name,onChange:Se=>{const Le=[...P];Le[Ee].name=Se.target.value,R(Le)},className:"flex-1 h-8",placeholder:"PDF name"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"(new)"}),e.jsx($,{type:"button",variant:"ghost",size:"icon",onClick:()=>R(P.filter((Se,Le)=>Le!==Ee)),children:e.jsx(pr,{className:"h-4 w-4"})})]},`pending-${Ee}`))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{className:"text-base font-medium",children:"Video Links"}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:_e,children:[e.jsx(dn,{className:"mr-1 h-3 w-3"})," Add Video"]})]}),y.map((ve,Ee)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(pe,{placeholder:"Video title",value:ve.title,onChange:Se=>{const Le=[...y];Le[Ee].title=Se.target.value,v(Le)},className:"w-1/3"}),e.jsx(pe,{placeholder:"Video URL",value:ve.video_url,onChange:Se=>{const Le=[...y];Le[Ee].video_url=Se.target.value,v(Le)},className:"flex-1"}),e.jsx($,{type:"button",variant:"ghost",size:"icon",onClick:()=>v(y.filter((Se,Le)=>Le!==Ee)),children:e.jsx(pr,{className:"h-4 w-4"})})]},Ee))]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e.jsx($,{variant:"outline",onClick:ne,children:"Cancel"}),e.jsx($,{onClick:J,disabled:D||V.isPending||G.isPending,children:D?"Uploading...":a?"Update":"Create"})]})]})]})]})]}),e.jsx(je,{children:e.jsx(Ie,{className:"p-0",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Name"}),e.jsx(Dt,{children:"Publish Date"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(fi,{children:W?e.jsx(En,{children:e.jsx(_t,{colSpan:4,className:"text-center py-8",children:"Loading..."})}):(U==null?void 0:U.length)===0?e.jsx(En,{children:e.jsx(_t,{colSpan:4,className:"text-center py-8 text-muted-foreground",children:"No newsletters yet. Create your first one!"})}):U==null?void 0:U.map(ve=>e.jsxs(En,{children:[e.jsx(_t,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[ve.preview_image_url?e.jsx("img",{src:ve.preview_image_url,alt:ve.title,className:"w-10 h-10 rounded object-cover"}):e.jsx("div",{className:"w-10 h-10 rounded bg-muted flex items-center justify-center",children:e.jsx(Jr,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:ve.title}),ve.description&&e.jsx("div",{className:"text-sm text-muted-foreground line-clamp-1",children:ve.description.replace(/<[^>]*>/g,"")})]})]})}),e.jsx(_t,{children:en(new Date(ve.publish_date),"MMM d, yyyy")}),e.jsx(_t,{children:e.jsx("span",{className:`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${ve.is_published?"bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400":"bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400"}`,children:ve.is_published?"Published":"Draft"})}),e.jsx(_t,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>ae(ve),title:"Edit",children:e.jsx(pi,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>le(ve),title:"Duplicate",children:e.jsx(Ha,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",title:"Delete",onClick:async()=>{await fo("Are you sure you want to delete this newsletter?")&&Y.mutate(ve.id)},children:e.jsx(Hn,{className:"h-4 w-4"})})]})})]},ve.id))})]})})})]})})}const qDn={status:"all",billing:"all",role:"all",brokerage:"all",joinedWithinDays:null};function VDn({brokerages:s}){var A;const{toast:t}=Bi(),[n,r]=j.useState(qDn),[a,i]=j.useState(""),[l,o]=j.useState(""),[c,d]=j.useState(""),[u,h]=j.useState(null),[m,f]=j.useState(!1),[g,x]=j.useState(!1),[y,v]=j.useState(null),b=(E,I)=>r(P=>({...P,[E]:I}));j.useEffect(()=>{const E=setTimeout(async()=>{f(!0);try{const{data:I,error:P}=await q.functions.invoke("admin-broadcast-sms",{body:{action:"preview",filters:n,sms_body:a||"Sample message"}});if(P)throw P;h(I)}catch{h(null)}finally{f(!1)}},450);return()=>clearTimeout(E)},[n,a]);const w=async()=>{if(!c||!a.trim()){t({title:"Add a test number and message",variant:"destructive"});return}x(!0);const{data:E,error:I}=await q.functions.invoke("admin-broadcast-sms",{body:{action:"test",to:c,sms_body:a}});if(x(!1),I||E!=null&&E.error){t({title:"Test failed",description:(E==null?void 0:E.error)||(I==null?void 0:I.message),variant:"destructive"});return}t({title:"Test text sent",description:`Sent to ${c}`})},S=async()=>{const E=(u==null?void 0:u.count)||0;if(!(!a.trim()||E===0||!await fo({title:"Send text broadcast?",description:`This will text ${E} member${E===1?"":"s"} who have a recorded SMS opt-in. Texts cannot be recalled.`,confirmText:"Send broadcast"}))){x(!0),v({total:E,sent:0,failed:0});try{const{data:P,error:R}=await q.functions.invoke("admin-broadcast-sms",{body:{action:"queue",name:l||a.slice(0,60),sms_body:a,filters:n}});if(R||P!=null&&P.error)throw new Error((P==null?void 0:P.error)||(R==null?void 0:R.message));let D=0,O=0,U=P.total,W=0;for(;U>0&&W++<400;){const{data:V,error:G}=await q.functions.invoke("admin-broadcast-sms",{body:{action:"process",broadcast_id:P.broadcast_id,limit:40}});if(G||V!=null&&V.error)throw new Error((V==null?void 0:V.error)||(G==null?void 0:G.message));if(V.deferred){t({title:"Paused for quiet hours",description:V.reason});break}D+=V.sent||0,O+=V.failed||0,U=V.remaining||0,v({total:E,sent:D,failed:O})}t({title:"Broadcast complete",description:`${D} sent${O?`, ${O} failed`:""}.`})}catch(P){t({title:"Broadcast failed",description:P.message,variant:"destructive"})}finally{x(!1)}}};return e.jsxs("div",{className:"grid gap-6 lg:grid-cols-[340px_1fr]",children:[e.jsx("div",{className:"space-y-4",children:e.jsxs(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(Gn,{children:"Only members with a recorded consent date and source are included. Opted-out and undeliverable numbers are always excluded."})]}),e.jsxs(Ie,{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Account status"}),e.jsxs(ms,{value:n.status,onValueChange:E=>b("status",E),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All members"}),e.jsx(Ge,{value:"active",children:"Signed in before"}),e.jsx(Ge,{value:"pending",children:"Never signed in"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Billing"}),e.jsxs(ms,{value:n.billing,onValueChange:E=>b("billing",E),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All"}),e.jsx(Ge,{value:"trial",children:"On trial"}),e.jsx(Ge,{value:"paid",children:"Paid"}),e.jsx(Ge,{value:"grandfathered",children:"Grandfathered"}),e.jsx(Ge,{value:"canceled",children:"Canceled / past due"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Role"}),e.jsxs(ms,{value:n.role,onValueChange:E=>b("role",E),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All roles"}),e.jsx(Ge,{value:"user",children:"Agents"}),e.jsx(Ge,{value:"brokerage_manager",children:"Brokerage managers"}),e.jsx(Ge,{value:"coach",children:"Coaches"}),e.jsx(Ge,{value:"admin",children:"Admins"})]})]})]}),!!(s!=null&&s.length)&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Brokerage"}),e.jsxs(ms,{value:n.brokerage,onValueChange:E=>b("brokerage",E),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All brokerages"}),e.jsx(Ge,{value:"none",children:"No brokerage"}),s.map(E=>e.jsx(Ge,{value:E.id,children:E.name},E.id))]})]})]}),e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"SMS-eligible members"}),e.jsx("span",{className:"text-lg font-semibold",children:m?e.jsx(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(da,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),e.jsx("span",{children:"Outside the 9:00 AM – 8:00 PM ET sending window. Queued texts will be held and resumed instead of sent now."})]})]})]})}),e.jsx("div",{className:"space-y-4",children:e.jsxs(je,{children:[e.jsxs(St,{className:"pb-3",children:[e.jsxs(Et,{className:"flex items-center gap-2 text-base",children:[e.jsx(eo,{className:"h-4 w-4"})," Text message"]}),e.jsxs(Gn,{children:["Merge tags: ",e.jsx("code",{children:"{{first_name}}"})," ",e.jsx("code",{children:"{{name}}"}),'. The LevelUp prefix and "Reply STOP to opt out" are added automatically.']})]}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"sms-broadcast-name",className:"text-xs",children:"Internal name"}),e.jsx(pe,{id:"sms-broadcast-name",value:l,onChange:E=>o(E.target.value),placeholder:"August member update"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"sms-broadcast-body",className:"text-xs",children:"Message"}),e.jsx(Ls,{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"]})]}),y&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(Yi,{value:y.total?(y.sent+y.failed)/y.total*100:0}),e.jsxs("div",{className:"flex items-center gap-4 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Vr,{className:"h-3 w-3"})," ",y.sent," sent"]}),y.failed>0&&e.jsxs("span",{className:"flex items-center gap-1 text-destructive",children:[e.jsx(ll,{className:"h-3 w-3"})," ",y.failed," failed"]}),e.jsxs("span",{children:["of ",y.total]})]})]}),e.jsxs($,{onClick:S,disabled:g||!a.trim()||!(u!=null&&u.count),className:"w-full",children:[g?e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Kr,{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 M9e={status:"all",billing:"all",role:"all",brokerage:"all",joinedWithinDays:null,respectOptOut:!0,program:"all",programStatus:"active"},HDn=["{{first_name}}","{{name}}","{{email}}"];function GDn(s){return`${s||'

Your email preview will appear here…

'}`}function WDn(){var Ke;const{toast:s}=Bi(),{user:t}=bs(),n=Wt(),[r,a]=j.useState("filters"),[i,l]=j.useState([]),[o,c]=j.useState(""),[d,u]=j.useState([]),[h,m]=j.useState(!1),[f,g]=j.useState(""),[x,y]=j.useState(!1),[v,b]=j.useState(M9e),[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,Y]=j.useState("rich"),[X,ae]=j.useState(""),[le,ne]=j.useState(""),[te,J]=j.useState(""),[ce,_e]=j.useState(!1),[he,ue]=j.useState(null),ve=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:Se}=st({queryKey:["broadcast-programs"],queryFn:async()=>{const{data:Je}=await q.from("programs").select("id, name").order("created_at",{ascending:!1});return Je||[]}}),{data:Le}=st({queryKey:["admin-broadcasts"],queryFn:async()=>{const{data:Je,error:pt}=await q.from("admin_broadcasts").select("*").order("created_at",{ascending:!1}).limit(30);if(pt)throw pt;return Je}}),{data:Fe}=st({queryKey:["admin-broadcast-templates"],queryFn:async()=>{const{data:Je,error:pt}=await q.from("admin_broadcast_templates").select("*").order("updated_at",{ascending:!1});if(pt)throw pt;return Je}}),ke=async Je=>{E(!0);try{const{data:pt,error:gt}=await q.functions.invoke("admin-broadcast",{body:{action:"preview",filters:Je}});if(gt)throw gt;if(pt!=null&&pt.error)throw new Error(pt.error);S(pt)}catch(pt){s({title:"Could not load audience",description:pt.message,variant:"destructive"})}finally{E(!1)}};j.useEffect(()=>{if(r!=="filters")return;const Je=setTimeout(()=>ke(v),400);return()=>clearTimeout(Je)},[v,r]),j.useEffect(()=>{if(r!=="manual")return;const Je=setTimeout(async()=>{m(!0);try{const{data:pt,error:gt}=await q.functions.invoke("admin-broadcast",{body:{action:"search_members",query:o}});if(gt)throw gt;u((pt==null?void 0:pt.members)||[])}catch{u([])}finally{m(!1)}},350);return()=>clearTimeout(Je)},[o,r]);const Be=(Je,pt)=>b(gt=>({...gt,[Je]:pt})),Ne=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:v},Ce=Je=>l(pt=>pt.some(gt=>gt.email.toLowerCase()===Je.email.toLowerCase())?pt.filter(gt=>gt.email.toLowerCase()!==Je.email.toLowerCase()):[...pt,Je]),Ve=async()=>{const Je=(f||I||R).trim();if(!Je||!ve.trim()){s({title:"Add a template name and content first",variant:"destructive"});return}y(!0);try{const{error:pt}=await q.from("admin_broadcast_templates").insert({created_by:t.id,name:Je,subject:R,body_html:ve,editor_mode:G,from_email:O||null,reply_to_email:W||null,filters:v});if(pt)throw pt;g(""),s({title:"Template saved",description:`"${Je}" is available for future sends.`}),n.invalidateQueries({queryKey:["admin-broadcast-templates"]})}catch(pt){s({title:"Could not save template",description:pt.message,variant:"destructive"})}finally{y(!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 pt=Je.editor_mode==="html"?"html":"rich";Y(pt),pt==="html"?ne(Je.body_html||""):ae(Je.body_html||""),Je.filters&&Object.keys(Je.filters).length&&b({...M9e,...Je.filters}),s({title:"Template loaded",description:"Edit and send when ready."})},qe=async Je=>{if(!await fo(`Delete template "${Je.name}"?`))return;const{error:pt}=await q.from("admin_broadcast_templates").delete().eq("id",Je.id);if(pt){s({title:"Delete failed",description:pt.message,variant:"destructive"});return}n.invalidateQueries({queryKey:["admin-broadcast-templates"]})},dt=j.useMemo(()=>!!R.trim()&&!!ve.trim()&&!!O.trim()&&Ne>0,[R,ve,O,Ne]),Xe=async()=>{if(!te||!R.trim()||!ve.trim()){s({title:"Add a subject, content and test address first",variant:"destructive"});return}try{const{data:Je,error:pt}=await q.functions.invoke("admin-broadcast",{body:{action:"test",to:te,subject:R,html:ve,from_email:O,reply_to:W||void 0}});if(pt)throw pt;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=Ne;if(await fo({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})){_e(!0),ue({total:Je,sent:0,failed:0});try{const{data:gt,error:ss}=await q.functions.invoke("admin-broadcast",{body:{action:"queue",name:I||R,subject:R,html:ve,from_email:O,reply_to:W||void 0,...Ae()}});if(ss)throw ss;if(gt!=null&>.error)throw new Error(gt.error);let Yt=0,ts=0,ys=gt.total,Bt=0;for(;ys>0;){const{data:Ft,error:as}=await q.functions.invoke("admin-broadcast",{body:{action:"process",broadcast_id:gt.broadcast_id,limit:40}});if(as)throw as;if(Ft!=null&&Ft.error)throw new Error(Ft.error);if(Yt+=Ft.sent,ts+=Ft.failed,ys=Ft.remaining,ue({total:gt.total,sent:Yt,failed:ts}),Ft.throttled){const kt=Math.min(Math.max(Number(Ft.retry_after_ms)||15e3,5e3),45e3);await new Promise(Ks=>setTimeout(Ks,kt));continue}if(Ft.sent===0&&Ft.failed===0){if(++Bt>=3)break;await new Promise(kt=>setTimeout(kt,5e3))}else Bt=0}s({title:"Broadcast complete",description:`${Yt} sent${ts?`, ${ts} failed`:""}`}),n.invalidateQueries({queryKey:["admin-broadcasts"]})}catch(gt){s({title:"Send failed",description:gt.message,variant:"destructive"})}finally{_e(!1)}}},rt=async Je=>{_e(!0);try{const{data:pt,error:gt}=await q.functions.invoke("admin-broadcast",{body:{action:"retry_failed",broadcast_id:Je}});if(gt)throw gt;if(pt!=null&&pt.error)throw new Error(pt.error);let ss=0,Yt=0,ts=pt.requeued,ys=0;for(ue({total:ts,sent:0,failed:0});ts>0;){const{data:Bt,error:Ft}=await q.functions.invoke("admin-broadcast",{body:{action:"process",broadcast_id:Je,limit:25}});if(Ft)throw Ft;if(Bt!=null&&Bt.error)throw new Error(Bt.error);if(ss+=Bt.sent,Yt+=Bt.failed,ts=Bt.remaining,ue({total:pt.requeued,sent:ss,failed:Yt}),Bt.throttled){await new Promise(as=>setTimeout(as,Math.min(Math.max(Number(Bt.retry_after_ms)||15e3,5e3),45e3)));continue}if(Bt.sent===0&&Bt.failed===0){if(++ys>=3)break;await new Promise(as=>setTimeout(as,5e3))}else ys=0}s({title:"Retry complete",description:`${ss} sent${Yt?`, ${Yt} still failed`:""}`}),n.invalidateQueries({queryKey:["admin-broadcasts"]})}catch(pt){s({title:"Retry failed",description:pt.message,variant:"destructive"})}finally{_e(!1)}};return e.jsx(Vs,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-8",children:[e.jsx(Dm,{title:"Member Broadcasts",description:"Send a one-off email to a filtered slice of LevelUp members"}),e.jsxs(ha,{defaultValue:"compose",className:"space-y-6",children:[e.jsxs(ma,{children:[e.jsxs(Zt,{value:"compose",className:"gap-2",children:[e.jsx(mn,{className:"h-4 w-4"})," Compose"]}),e.jsxs(Zt,{value:"sms",className:"gap-2",children:[e.jsx(eo,{className:"h-4 w-4"})," Text (SMS)"]}),e.jsxs(Zt,{value:"templates",className:"gap-2",children:[e.jsx(c2,{className:"h-4 w-4"})," Templates"]}),e.jsxs(Zt,{value:"history",className:"gap-2",children:[e.jsx(Aw,{className:"h-4 w-4"})," History"]})]}),e.jsx(Xt,{value:"sms",className:"space-y-6",children:e.jsx(VDn,{brokerages:Ee})}),e.jsx(Xt,{value:"compose",className:"space-y-6",children:e.jsxs("div",{className:"grid gap-6 lg:grid-cols-[340px_1fr]",children:[e.jsx("div",{className:"space-y-4",children:e.jsxs(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(Ie,{className:"space-y-4 pt-5",children:[e.jsx(ha,{value:r,onValueChange:Je=>a(Je),children:e.jsxs(ma,{className:"grid w-full grid-cols-2",children:[e.jsxs(Zt,{value:"filters",className:"gap-1.5 text-xs",children:[e.jsx(Yn,{className:"h-3.5 w-3.5"})," Filters"]}),e.jsxs(Zt,{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(Zr,{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(pr,{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 pt=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 ${pt?"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})]}),pt&&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:v.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:v.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:v.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:v.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:v.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"}),(Se||[]).map(Je=>e.jsx(Ge,{value:Je.id,children:Je.name},Je.id))]})]})]}),v.program!=="all"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Enrollment status"}),e.jsxs(ms,{value:v.programStatus,onValueChange: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:v.joinedWithinDays?String(v.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(Sn,{checked:v.respectOptOut,onCheckedChange:Je=>Be("respectOptOut",Je)})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx($,{variant:"ghost",size:"sm",onClick:()=>b(M9e),children:"Reset"}),e.jsxs($,{variant:"outline",size:"sm",className:"gap-2",onClick:()=>ke(v),disabled:A,children:[A?e.jsx(Ct,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(ro,{className:"h-3.5 w-3.5"}),"Refresh"]})]}),(Ke=w==null?void 0:w.sample)!=null&&Ke.length?e.jsxs("div",{className:"rounded-lg bg-muted/40 p-3",children:[e.jsx("p",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Sample recipients"}),e.jsx("div",{className:"space-y-1",children:w.sample.map(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(Gn,{children:["Personalize with merge tags: ",HDn.join(" ")]})]}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Internal name"}),e.jsx(pe,{value:I,onChange: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(ha,{value:G,onValueChange:Je=>Y(Je),children:[e.jsxs(ma,{children:[e.jsxs(Zt,{value:"rich",className:"gap-2",children:[e.jsx(Nn,{className:"h-3.5 w-3.5"})," Rich text"]}),e.jsxs(Zt,{value:"html",className:"gap-2",children:[e.jsx(CE,{className:"h-3.5 w-3.5"})," Paste HTML"]})]}),e.jsx(Xt,{value:"rich",className:"mt-3",children:e.jsx(Sk,{content:X,onChange:ae,minHeight:"320px",placeholder:"Write your message…"})}),e.jsxs(Xt,{value:"html",className:"mt-3 space-y-2",children:[e.jsx(Ls,{value:le,onChange:Je=>ne(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(Ca,{className:"h-4 w-4"})," Preview"]}),e.jsx($e,{variant:"secondary",children:G==="html"?"Raw HTML":"Rich text"})]}),e.jsx(Ie,{children:e.jsx("iframe",{title:"Email preview",srcDoc:GDn(ve),className:"h-[420px] w-full rounded-lg border bg-white"})})]}),e.jsx(je,{children:e.jsxs(Ie,{className:"space-y-4 pt-6",children:[he&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsxs("span",{children:[he.sent+he.failed," of ",he.total," processed"]}),e.jsxs("span",{className:"text-muted-foreground",children:[he.sent," sent",he.failed?` • ${he.failed} failed`:""]})]}),e.jsx(Yi,{value:he.total?(he.sent+he.failed)/he.total*100:0})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Send a test to"}),e.jsx(pe,{value:te,onChange:Je=>J(Je.target.value),className:"w-64"})]}),e.jsx($,{variant:"outline",onClick:Xe,disabled:ce,children:"Send test"}),e.jsx("div",{className:"flex-1"}),e.jsxs($,{onClick:at,disabled:!dt||ce,size:"lg",className:"gap-2",children:[ce?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Kr,{className:"h-4 w-4"}),ce?"Sending…":`Send to ${Ne} member${Ne===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:Ve,disabled:x,children:[x?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(BI,{className:"h-4 w-4"}),"Save template"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Saves the subject, content, sender and current filters for reuse later."})]})]})})]})]})}),e.jsx(Xt,{value:"templates",className:"space-y-3",children:(Fe||[]).length===0?e.jsx(je,{children:e.jsxs(Ie,{className:"flex flex-col items-center py-14 text-center",children:[e.jsx(c2,{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(Ie,{className:"flex flex-wrap items-center justify-between gap-4 py-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"truncate text-sm font-semibold",children: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 ",en(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:()=>qe(Je),children:e.jsx(Hn,{className:"h-3.5 w-3.5"})})]})]})},Je.id))}),e.jsx(Xt,{value:"history",className:"space-y-3",children:(Le||[]).length===0?e.jsx(je,{children:e.jsxs(Ie,{className:"flex flex-col items-center py-14 text-center",children:[e.jsx(mn,{className:"mb-3 h-10 w-10 text-muted-foreground"}),e.jsx("p",{className:"font-medium",children:"No broadcasts sent yet"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Your sent member emails will show up here."})]})}):(Le||[]).map(Je=>e.jsx(je,{children:e.jsxs(Ie,{className:"flex flex-wrap items-center justify-between gap-4 py-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"truncate text-sm font-semibold",children: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(ll,{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:[en(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 KDn=["Headers","Footers","Seasonal","Holidays","Market Updates","Just Sold","Just Listed","Open House","Buyer Tips","Seller Tips","Testimonials","CTAs & Buttons","Dividers","General"];function YDn(){const s=Wt(),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||[]}}),y=j.useMemo(()=>{const O=new Set(KDn);return g.forEach(U=>O.add(U.category)),Array.from(O).sort()},[g]),v=j.useMemo(()=>{const O=n.trim().toLowerCase();return g.filter(U=>a!=="all"&&U.category!==a?!1:O?U.title.toLowerCase().includes(O)||(U.description||"").toLowerCase().includes(O)||U.tags.some(W=>W.toLowerCase().includes(O)):!0)},[g,n,a]),b=()=>{f({title:"",description:"",image_url:"",category:"General",tags:"",is_active:!0,is_featured:!1}),o(null)},w=()=>{b(),d(!0)},S=O=>{o(O),f({title:O.title,description:O.description||"",image_url:O.image_url,category:O.category,tags:O.tags.join(", "),is_active:O.is_active,is_featured:O.is_featured}),d(!0)},A=async O=>{var U;if(!O.type.startsWith("image/")){re.error("Please choose an image file");return}if(O.size>15*1024*1024){re.error("Image must be under 15MB");return}h(!0);try{const W=((U=O.name.split(".").pop())==null?void 0:U.toLowerCase())||"png",V=`graphics-library/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${W}`,{error:G}=await q.storage.from("newsletter-content").upload(V,O,{cacheControl:"31536000",upsert:!1,contentType:O.type});if(G)throw G;const{data:Y}=q.storage.from("newsletter-content").getPublicUrl(V);f(X=>({...X,image_url:Y.publicUrl,title:X.title||O.name.replace(/\.[^.]+$/,"").replace(/[-_]/g," ")})),re.success("Uploaded")}catch(W){re.error(W.message||"Upload failed")}finally{h(!1),t.current&&(t.current.value="")}},E=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:()=>{re.success(l?"Updated":"Graphic added to library"),s.invalidateQueries({queryKey:["admin-newsletter-graphics"]}),s.invalidateQueries({queryKey:["newsletter-graphics-picker"]}),d(!1),b()},onError:O=>re.error(O.message||"Save failed")}),I=mt({mutationFn:async O=>{const{error:U}=await q.from("newsletter_graphics").delete().eq("id",O);if(U)throw U},onSuccess:()=>{re.success("Deleted"),s.invalidateQueries({queryKey:["admin-newsletter-graphics"]}),s.invalidateQueries({queryKey:["newsletter-graphics-picker"]})},onError:O=>re.error(O.message||"Delete failed")}),P=async O=>{const{error:U}=await q.from("newsletter_graphics").update({is_active:!O.is_active}).eq("id",O.id);U?re.error(U.message):(s.invalidateQueries({queryKey:["admin-newsletter-graphics"]}),s.invalidateQueries({queryKey:["newsletter-graphics-picker"]}))},R=async O=>{const{error:U}=await q.from("newsletter_graphics").update({is_featured:!O.is_featured}).eq("id",O.id);U?re.error(U.message):(s.invalidateQueries({queryKey:["admin-newsletter-graphics"]}),s.invalidateQueries({queryKey:["newsletter-graphics-picker"]}))},D=O=>{navigator.clipboard.writeText(O),re.success("URL copied")};return e.jsxs(Vs,{children:[e.jsxs("div",{className:"p-4 md:p-6 max-w-7xl mx-auto space-y-5",children:[e.jsx(Dm,{title:"Newsletter Graphics Library",description:"Upload branded graphics agents can drop into their newsletters and email campaigns."}),e.jsx(je,{children:e.jsxs(Ie,{className:"p-4 flex flex-col md:flex-row gap-3 md:items-center",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Zr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{value:n,onChange:O=>r(O.target.value),placeholder:"Search graphics by title, tag, description...",className:"pl-9"})]}),e.jsxs(ms,{value:a,onValueChange:i,children:[e.jsx(us,{className:"w-full md:w-56",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All categories"}),y.map(O=>e.jsx(Ge,{value:O,children:O},O))]})]}),e.jsxs($,{onClick:w,className:"gap-1.5 whitespace-nowrap",children:[e.jsx(Sv,{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"})}):v.length===0?e.jsx(je,{children:e.jsxs(Ie,{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(Sv,{className:"h-4 w-4"})," Upload First Graphic"]})]})}):e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4",children:v.map(O=>e.jsxs(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(Ie,{className:"p-3 space-y-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm truncate",children:O.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:O.category})]}),O.tags.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1",children:O.tags.slice(0,3).map(U=>e.jsx($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(Ha,{className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sn,{checked:O.is_active,onCheckedChange:()=>P(O)}),e.jsx($,{size:"icon",variant:"ghost",className:"h-7 w-7 text-destructive hover:text-destructive",onClick:async()=>{await fo(`Delete "${O.title}"?`)&&I.mutate(O.id)},children:e.jsx(Hn,{className:"h-3.5 w-3.5"})})]})]})]})]},O.id))})]}),e.jsx(zs,{open:c,onOpenChange:d,children:e.jsxs(Os,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(Bs,{children:l?"Edit Graphic":"Add New Graphic"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Image"}),e.jsx("input",{ref:t,type:"file",accept:"image/*",className:"hidden",onChange:O=>{var W;const U=(W=O.target.files)==null?void 0:W[0];U&&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(pr,{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(Ls,{id:"g-desc",value:m.description,onChange:O=>f(U=>({...U,description:O.target.value})),placeholder:"Short note about when to use this graphic",rows:2})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Category"}),e.jsxs(ms,{value:m.category,onValueChange:O=>f(U=>({...U,category:O})),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:y.map(O=>e.jsx(Ge,{value:O,children:O},O))})]})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"g-tags",children:"Tags (comma-separated)"}),e.jsx(pe,{id:"g-tags",value:m.tags,onChange:O=>f(U=>({...U,tags:O.target.value})),placeholder:"fall, autumn, banner"})]})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-md border p-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Featured"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show at top of the picker"})]}),e.jsx(Sn,{checked:m.is_featured,onCheckedChange:O=>f(U=>({...U,is_featured:O}))})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-md border p-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Active"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Visible to agents"})]}),e.jsx(Sn,{checked:m.is_active,onCheckedChange:O=>f(U=>({...U,is_active:O}))})]})]}),e.jsxs(Sr,{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 rSt={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}=bs(),{toast:t}=Bi(),n=Xn(),r=Wt(),[a,i]=j.useState(""),[l,o]=j.useState("popular"),[c,d]=j.useState(!1),[u,h]=j.useState(""),[m,f]=j.useState(""),[g,x]=j.useState(!1),{data:y=[],isLoading:v}=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(Y=>Y.user_id))||[])],{data:D}=await q.from("profiles").select("id, name").in("id",R),O=new Map((D==null?void 0:D.map(Y=>[Y.id,Y]))||[]);let U=[];if(s){const{data:Y}=await q.from("wishlist_votes").select("item_id").eq("user_id",s.id);U=(Y==null?void 0:Y.map(X=>X.item_id))||[]}const W=(I==null?void 0:I.map(Y=>Y.id))||[],{data:V}=await q.from("wishlist_comments").select("item_id").in("item_id",W),G=new Map;return V==null||V.forEach(Y=>{G.set(Y.item_id,(G.get(Y.item_id)||0)+1)}),I==null?void 0:I.map(Y=>{const X=O.get(Y.user_id),ae=(X==null?void 0:X.name)||"Unknown";return{...Y,user_name:ae,user_initials:ae.split(" ").map(le=>le[0]).join("").toUpperCase().slice(0,2),has_voted:U.includes(Y.id),comment_count:G.get(Y.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=y.find(R=>R.id===E.itemId),P=((I==null?void 0:I.vote_count)||0)+1;q.functions.invoke("wishlist-notify",{body:{itemId:E.itemId,voteCount:P}}).catch(console.error)}},onError:E=>{t({title:"Error",description:E.message,variant:"destructive"})}}),S=y.filter(E=>E.title.toLowerCase().includes(a.toLowerCase())||E.description.toLowerCase().includes(a.toLowerCase())),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(JS,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-5xl font-bold",children:"Wishlist"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Share ideas and vote on what we build next"})]})]}),e.jsxs(zs,{open:c,onOpenChange:d,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{className:"gap-2",children:[e.jsx(dn,{className:"h-4 w-4"}),"Add Idea"]})}),e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Submit a New Idea"})}),e.jsxs("div",{className:"space-y-4 pt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"title",children:"Title"}),e.jsx(pe,{id:"title",placeholder:"Give your idea a clear title...",value:u,onChange:E=>h(E.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"description",children:"Description"}),e.jsx(Ls,{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(Zr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search ideas...",value:a,onChange:E=>i(E.target.value),className:"pl-10"})]}),e.jsx("div",{className:"flex gap-2",children:e.jsx(ha,{value:l,onValueChange:E=>o(E),children:e.jsxs(ma,{children:[e.jsx(Zt,{value:"popular",children:"Most Popular"}),e.jsx(Zt,{value:"latest",children:"Latest"}),e.jsx(Zt,{value:"trending",children:"Trending"})]})})})]}),e.jsx("div",{className:"flex items-center gap-2 mb-4",children:e.jsx($,{variant:g?"default":"outline",size:"sm",onClick:()=>x(!g),children:g?"Show All Ideas":"My Ideas"})}),v?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(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(JS,{className:"h-12 w-12 text-muted-foreground mx-auto mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No ideas yet"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Be the first to submit an idea!"}),e.jsxs($,{onClick:()=>d(!0),children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Add Idea"]})]}):e.jsx("div",{className:"space-y-3",children:S.map(E=>e.jsx("div",{className:"bg-card border rounded-lg p-4 hover:shadow-md transition-shadow cursor-pointer",onClick:()=>n(`/wishlist/${E.id}`),children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsxs("button",{onClick:I=>{I.stopPropagation(),w.mutate({itemId:E.id,hasVoted:E.has_voted||!1})},className:Pt("flex flex-col items-center justify-center min-w-[50px] py-2 px-3 rounded-lg border transition-colors",E.has_voted?"bg-primary/10 border-primary text-primary":"bg-muted/50 border-border hover:bg-muted"),children:[e.jsx(Zf,{className:Pt("h-4 w-4",E.has_voted&&"fill-current")}),e.jsx("span",{className:"text-sm font-semibold",children:E.vote_count})]}),e.jsx(Oa,{className:"h-10 w-10 bg-primary/20",children:e.jsx(za,{className:"bg-primary/20 text-primary text-sm font-medium",children:E.user_initials})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("h3",{className:"font-semibold text-foreground",children:E.title}),e.jsx($e,{className:Pt("text-xs",rSt[E.status].color),children:rSt[E.status].label})]}),e.jsx("p",{className:"text-muted-foreground text-sm line-clamp-2",children:E.description}),e.jsxs("div",{className:"flex items-center gap-3 mt-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:E.user_name}),e.jsx("span",{children:"•"}),e.jsx("span",{children:new Date(E.created_at).toLocaleDateString()})]})]}),e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(eo,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm",children:E.comment_count})]})]})},E.id))})]})})}const aSt={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 XDn(){const{itemId:s}=Wi(),t=Xn(),{user:n}=bs(),{toast:r}=Bi(),a=Wt(),[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:y,error:v}=await q.from("user_roles").select("role").eq("user_id",n.id).eq("role","admin").maybeSingle();return!v&&!!y},enabled:!!n}),{data:c,isLoading:d}=st({queryKey:["wishlist-item",s],queryFn:async()=>{const{data:y,error:v}=await q.from("wishlist_items").select("*").eq("id",s).single();if(v)throw v;const{data:b}=await q.from("profiles").select("name").eq("id",y.user_id).single();let w=!1;if(n){const{data:S}=await q.from("wishlist_votes").select("id").eq("item_id",s).eq("user_id",n.id).maybeSingle();w=!!S}return{...y,user_name:(b==null?void 0:b.name)||"Unknown",user_initials:((b==null?void 0:b.name)||"U").split(" ").map(S=>S[0]).join("").toUpperCase().slice(0,2),has_voted:w}}}),{data:u=[],isLoading:h}=st({queryKey:["wishlist-comments",s],queryFn:async()=>{const{data:y,error:v}=await q.from("wishlist_comments").select("*").eq("item_id",s).order("created_at",{ascending:!0});if(v)throw v;const b=[...new Set((y==null?void 0:y.map(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 y==null?void 0:y.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 y=>{if(y){const{error:v}=await q.from("wishlist_votes").delete().eq("item_id",s).eq("user_id",n.id);if(v)throw v;return{wasAdded:!1}}else{const{error:v}=await q.from("wishlist_votes").insert({item_id:s,user_id:n.id});if(v)throw v;return{wasAdded:!0}}},onSuccess:async y=>{if(a.invalidateQueries({queryKey:["wishlist-item",s]}),a.invalidateQueries({queryKey:["wishlist-items"]}),y!=null&&y.wasAdded&&c){const v=(c.vote_count||0)+1;q.functions.invoke("wishlist-notify",{body:{itemId:s,voteCount:v}}).catch(console.error)}},onError:y=>{r({title:"Error",description:y.message,variant:"destructive"})}}),f=mt({mutationFn:async y=>{const{error:v}=await q.from("wishlist_comments").insert({item_id:s,user_id:n.id,content:y});if(v)throw v},onSuccess:()=>{a.invalidateQueries({queryKey:["wishlist-comments",s]}),l(""),r({title:"Comment added!"})},onError:y=>{r({title:"Error",description:y.message,variant:"destructive"})}}),g=mt({mutationFn:async y=>{const{error:v}=await q.from("wishlist_comments").delete().eq("id",y);if(v)throw v},onSuccess:()=>{a.invalidateQueries({queryKey:["wishlist-comments",s]}),r({title:"Comment deleted"})},onError:y=>{r({title:"Error",description:y.message,variant:"destructive"})}}),x=()=>{i.trim()&&f.mutate(i.trim())};return d?e.jsx(Vs,{title:"Wishlist",children:e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsx(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",aSt[c.status].color),children:aSt[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(UTe,{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(Kr,{className:"h-4 w-4"})})]}),h?e.jsx("div",{className:"space-y-4",children:[1,2].map(y=>e.jsx(xn,{className:"h-20 w-full"},y))}):u.length===0?e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No comments yet. Be the first to share your thoughts!"}):e.jsx("div",{className:"space-y-4",children:u.map(y=>e.jsxs("div",{className:"flex gap-3 p-3 bg-muted/30 rounded-lg",children:[e.jsx(Oa,{className:"h-8 w-8",children:e.jsx(za,{className:"bg-primary/20 text-primary text-xs",children:y.user_initials})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-medium text-sm",children:y.user_name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(y.created_at).toLocaleDateString()})]}),e.jsx(Rrt,{content:y.content,className:"text-sm text-foreground"})]}),(n==null?void 0:n.id)===y.user_id&&e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground hover:text-destructive",onClick:()=>g.mutate(y.id),children:e.jsx(Hn,{className:"h-4 w-4"})})]},y.id))})]})]})}):e.jsx(Vs,{title:"Wishlist",children:e.jsxs("div",{className:"max-w-3xl mx-auto text-center py-12",children:[e.jsx("p",{className:"text-muted-foreground",children:"Item not found"}),e.jsx($,{variant:"link",onClick:()=>t("/wishlist"),children:"Go back to Wishlist"})]})})}const iSt={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"}},oSt=["open","under_review","planned","in_progress","launched","declined"];function QDn(){const{toast:s}=Bi(),t=Xn(),n=Wt(),[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:v,error:b}=await q.from("wishlist_items").select("*").order("vote_count",{ascending:!1});if(b)throw b;const w=[...new Set((v==null?void 0:v.map(R=>R.user_id))||[])],{data:S}=await q.from("profiles").select("id, name, email").in("id",w),A=new Map((S==null?void 0:S.map(R=>[R.id,R]))||[]),E=(v==null?void 0:v.map(R=>R.id))||[],{data:I}=await q.from("wishlist_comments").select("item_id").in("item_id",E),P=new Map;return I==null||I.forEach(R=>{P.set(R.item_id,(P.get(R.item_id)||0)+1)}),v==null?void 0:v.map(R=>{const D=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:v,status:b})=>{const{error:w}=await q.from("wishlist_items").update({status:b}).eq("id",v);if(w)throw w},onSuccess:()=>{n.invalidateQueries({queryKey:["admin-wishlist-items"]}),s({title:"Status updated!"})},onError:v=>{s({title:"Error",description:v.message,variant:"destructive"})}}),g=mt({mutationFn:async v=>{const{error:b}=await q.from("wishlist_items").delete().eq("id",v);if(b)throw b},onSuccess:()=>{n.invalidateQueries({queryKey:["admin-wishlist-items"]}),c(!1),u(null),s({title:"Item deleted!"})},onError:v=>{s({title:"Error",description:v.message,variant:"destructive"})}}),x=h.filter(v=>{const b=v.title.toLowerCase().includes(r.toLowerCase())||v.description.toLowerCase().includes(r.toLowerCase())||v.user_name.toLowerCase().includes(r.toLowerCase()),w=i==="all"||v.status===i;return b&&w}),y={total:h.length,open:h.filter(v=>v.status==="open").length,inProgress:h.filter(v=>v.status==="in_progress").length,launched:h.filter(v=>v.status==="launched").length,highVotes:h.filter(v=>v.vote_count>=10).length};return e.jsx(Vs,{title:"Admin - Wishlist",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>t("/admin"),children:e.jsx(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:y.total})]}),e.jsxs("div",{className:"bg-card border rounded-lg p-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Open"}),e.jsx("p",{className:"text-2xl font-bold text-blue-600",children:y.open})]}),e.jsxs("div",{className:"bg-card border rounded-lg p-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"In Progress"}),e.jsx("p",{className:"text-2xl font-bold text-orange-600",children:y.inProgress})]}),e.jsxs("div",{className:"bg-card border rounded-lg p-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Launched"}),e.jsx("p",{className:"text-2xl font-bold text-green-600",children:y.launched})]}),e.jsxs("div",{className:"bg-card border rounded-lg p-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"10+ Votes"}),e.jsx("p",{className:"text-2xl font-bold text-primary",children:y.highVotes})]})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Zr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search ideas, users...",value:r,onChange:v=>a(v.target.value),className:"pl-10"})]}),e.jsxs(ms,{value:i,onValueChange:v=>l(v),children:[e.jsx(us,{className:"w-[180px]",children:e.jsx(fs,{placeholder:"Filter by status"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Statuses"}),oSt.map(v=>e.jsx(Ge,{value:v,children:iSt[v].label},v))]})]})]}),m?e.jsx("div",{className:"space-y-2",children:[1,2,3,4,5].map(v=>e.jsx(xn,{className:"h-16 w-full"},v))}):e.jsx("div",{className:"bg-card border rounded-lg overflow-hidden",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{children:[e.jsx(Dt,{className:"w-[60px]",children:"Votes"}),e.jsx(Dt,{children:"Title"}),e.jsx(Dt,{className:"hidden md:table-cell",children:"Submitted By"}),e.jsx(Dt,{className:"hidden sm:table-cell",children:"Comments"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"w-[100px]",children:"Actions"})]})}),e.jsx(fi,{children:x.length===0?e.jsx(En,{children:e.jsx(_t,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No items found"})}):x.map(v=>e.jsxs(En,{className:Pt(v.vote_count>=10&&"bg-primary/5"),children:[e.jsx(_t,{children:e.jsx($e,{variant:v.vote_count>=10?"default":"secondary",children:v.vote_count})}),e.jsx(_t,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium line-clamp-1",children:v.title}),e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-1",children:v.description})]})}),e.jsx(_t,{className:"hidden md:table-cell",children:e.jsxs("div",{children:[e.jsx("p",{className:"text-sm",children:v.user_name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:v.user_email})]})}),e.jsx(_t,{className:"hidden sm:table-cell",children:v.comment_count}),e.jsx(_t,{children:e.jsxs(ms,{value:v.status,onValueChange:b=>f.mutate({itemId:v.id,status:b}),children:[e.jsx(us,{className:"w-[140px] h-8",children:e.jsx(fs,{})}),e.jsx(hs,{children:oSt.map(b=>e.jsx(Ge,{value:b,children:iSt[b].label},b))})]})}),e.jsx(_t,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>window.open(`/wishlist/${v.id}`,"_blank"),children:e.jsx(Fr,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive",onClick:()=>{u(v.id),c(!0)},children:e.jsx(Hn,{className:"h-4 w-4"})})]})})]},v.id))})]})}),e.jsx(zs,{open:o,onOpenChange:c,children:e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Delete Wishlist Item"})}),e.jsx("p",{className:"text-muted-foreground",children:"Are you sure you want to delete this idea? This will also delete all votes and comments."}),e.jsxs("div",{className:"flex justify-end gap-2 mt-4",children:[e.jsx($,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx($,{variant:"destructive",onClick:()=>d&&g.mutate(d),disabled:g.isPending,children:g.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),"Deleting..."]}):"Delete"})]})]})})]})})}function JDn(){const{user:s}=bs(),[t,n]=j.useState([]),[r,a]=j.useState(!0),[i,l]=j.useState(!1),[o,c]=j.useState(null),[d,u]=j.useState(!1),[h,m]=j.useState(null),[f,g]=j.useState(""),[x,y]=j.useState(""),[v,b]=j.useState(""),[w,S]=j.useState(""),[A,E]=j.useState(""),[I,P]=j.useState(!1),[R,D]=j.useState(""),[O,U]=j.useState("once"),[W,V]=j.useState([]),[G,Y]=j.useState([]),[X,ae]=j.useState(!1),[le,ne]=j.useState(!1),[te,J]=j.useState([]),[ce,_e]=j.useState({total:0,dismissed:0});j.useEffect(()=>{he()},[]);const he=async()=>{const{data:rt,error:Ke}=await q.from("levelup_briefs").select("*").order("created_at",{ascending:!1});Ke?(re.error("Failed to fetch briefs"),console.error(Ke)):n(rt||[]),a(!1)},ue=()=>{g(""),y(""),b(""),S(""),E(""),P(!1),D(new Date().toISOString().slice(0,16)),U("once"),V([]),Y([]),c(null)},ve=()=>{ue(),l(!0)},Ee=async rt=>{c(rt),g(rt.title),y(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(pt=>({title:pt.title,url:pt.url})))||[]);const{data:Je}=await q.from("levelup_brief_polls").select("*").eq("brief_id",rt.id).order("sort_order");if(Je){const pt=[];for(const gt of Je){const{data:ss}=await q.from("levelup_brief_poll_options").select("*").eq("poll_id",gt.id).order("sort_order");pt.push({question:gt.question,poll_type:gt.poll_type,options:(ss==null?void 0:ss.map(Yt=>Yt.option_text))||[]})}Y(pt)}l(!0)},Se=async rt=>{var Je;const Ke=(Je=rt.target.files)==null?void 0:Je[0];if(Ke){ae(!0);try{const pt=await q.functions.invoke("bunny-upload",{body:{action:"create",title:Ke.name.replace(/\.[^/.]+$/,"")}});if(pt.error)throw pt.error;const{videoId:gt,libraryId:ss}=pt.data,Yt=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:gt}});if(Yt.error)throw Yt.error;const{uploadUrl:ts,apiKey:ys}=Yt.data,Bt=new XMLHttpRequest;await new Promise((as,kt)=>{Bt.upload.addEventListener("progress",Ks=>{if(Ks.lengthComputable){const wt=Math.round(Ks.loaded/Ks.total*100);console.log("Upload progress:",wt)}}),Bt.addEventListener("load",()=>{Bt.status>=200&&Bt.status<300?as():kt(new Error(`Upload failed with status ${Bt.status}`))}),Bt.addEventListener("error",()=>kt(new Error("Upload failed"))),Bt.open("PUT",ts),Bt.setRequestHeader("AccessKey",ys),Bt.send(Ke)});const Ft=`https://player.mediadelivery.net/embed/${ss}/${gt}`;b(Ft),re.success("Video uploaded successfully! It may take a few minutes to process.")}catch(pt){console.error("Upload error:",pt),re.error("Failed to upload video")}finally{ae(!1)}}},Le=async()=>{if(!f.trim()){re.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:v||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 pt of Je)await q.from("levelup_brief_poll_options").delete().eq("poll_id",pt.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:v||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,pt)=>({brief_id:rt,title:Je.title,url:Je.url,sort_order:pt}));await q.from("levelup_brief_links").insert(Ke)}for(let Ke=0;Ke0){const ss=Je.options.map((Yt,ts)=>({poll_id:pt.id,option_text:Yt,sort_order:ts}));await q.from("levelup_brief_poll_options").insert(ss)}}re.success(o?"Brief updated":"Brief created"),l(!1),ue(),he()}catch(rt){console.error("Error saving brief:",rt),re.error("Failed to save brief")}},Fe=async rt=>{if(await fo("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;re.success("Brief deleted"),he()}catch(Ke){console.error("Error deleting brief:",Ke),re.error("Failed to delete brief")}},ke=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);_e({total:Ke||0,dismissed:Je||0});const{data:pt}=await q.from("levelup_brief_polls").select("*").eq("brief_id",rt.id).order("sort_order");if(pt){const gt=[];for(const ss of pt){const{data:Yt}=await q.from("levelup_brief_poll_options").select("*").eq("poll_id",ss.id).order("sort_order"),{data:ts}=await q.from("levelup_brief_poll_responses").select("option_id, user_id").eq("poll_id",ss.id),ys=[...new Set((ts==null?void 0:ts.map(Ks=>Ks.user_id))||[])];let Bt={};if(ys.length>0){const{data:Ks}=await q.from("profiles").select("id, name, email").in("id",ys);Ks&&Ks.forEach(wt=>{Bt[wt.id]=wt.name||wt.email||"Unknown"})}const Ft=(ts||[]).map(Ks=>({optionId:Ks.option_id,userName:Bt[Ks.user_id]||"Unknown",userId:Ks.user_id})),as={};let kt=0;Yt&&Yt.forEach(Ks=>{const wt=(ts==null?void 0:ts.filter(gs=>gs.option_id===Ks.id).length)||0;as[Ks.id]=wt,kt+=wt}),gt.push({...ss,options:Yt||[],results:as,respondents:Ft,totalResponses:ss.poll_type==="single"?new Set(ts==null?void 0:ts.map(Ks=>Ks.user_id)).size:kt})}J(gt)}u(!0)},Be=()=>{V([...W,{title:"",url:""}])},Ne=(rt,Ke,Je)=>{const pt=[...W];pt[rt][Ke]=Je,V(pt)},Ae=rt=>{V(W.filter((Ke,Je)=>Je!==rt))},Ce=()=>{Y([...G,{question:"",poll_type:"single",options:["",""]}])},Ve=(rt,Ke)=>{const Je=[...G];Je[rt].question=Ke,Y(Je)},ze=(rt,Ke)=>{const Je=[...G];Je[rt].poll_type=Ke,Y(Je)},qe=rt=>{const Ke=[...G];Ke[rt].options.push(""),Y(Ke)},dt=(rt,Ke,Je)=>{const pt=[...G];pt[rt].options[Ke]=Je,Y(pt)},Xe=(rt,Ke)=>{const Je=[...G];Je[rt].options=Je[rt].options.filter((pt,gt)=>gt!==Ke),Y(Je)},at=rt=>{Y(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:ve,children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Create Brief"]})}),e.jsx(je,{children:e.jsx(Ie,{className:"p-0",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Title"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{children:"Frequency"}),e.jsx(Dt,{children:"Publish Date"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(fi,{children:r?e.jsx(En,{children:e.jsx(_t,{colSpan:5,className:"text-center py-8",children:"Loading..."})}):t.length===0?e.jsx(En,{children:e.jsx(_t,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No briefs created yet"})}):t.map(rt=>e.jsxs(En,{children:[e.jsx(_t,{className:"font-medium",children:rt.title}),e.jsx(_t,{children:e.jsx($e,{variant:rt.is_published?"default":"secondary",children:rt.is_published?"Published":"Draft"})}),e.jsx(_t,{className:"capitalize",children:rt.show_frequency.replace("_"," ")}),e.jsx(_t,{children:en(new Date(rt.publish_date),"MMM d, yyyy h:mm a")}),e.jsx(_t,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>ke(rt),children:e.jsx(Gl,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>Ee(rt),children:e.jsx(_p,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>Fe(rt.id),children:e.jsx(Hn,{className:"h-4 w-4 text-destructive"})})]})})]},rt.id))})]})})})]}),e.jsx(zs,{open:i,onOpenChange:l,children:e.jsxs(Os,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(Bs,{children:o?"Edit Brief":"Create New Brief"})}),e.jsxs(ha,{defaultValue:"content",className:"w-full",children:[e.jsxs(ma,{className:"grid w-full grid-cols-4",children:[e.jsx(Zt,{value:"content",children:"Content"}),e.jsx(Zt,{value:"media",children:"Media"}),e.jsx(Zt,{value:"links",children:"Links"}),e.jsx(Zt,{value:"polls",children:"Polls"})]}),e.jsxs(Xt,{value:"content",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Title *"}),e.jsx(pe,{value:f,onChange: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(Sk,{content:x,onChange:rt=>y(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(Sn,{checked:I,onCheckedChange:P}),e.jsx(ee,{children:"Publish immediately"})]})]}),e.jsxs(Xt,{value:"media",className:"space-y-6 mt-4",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"font-semibold text-sm text-foreground",children:"Video (optional)"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Upload Video to Bunny.net"}),e.jsx("div",{className:"flex gap-2",children:e.jsx(pe,{type:"file",accept:"video/*",onChange:Se,disabled:X})}),X&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Uploading..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Or paste embed URL"}),e.jsx(pe,{value:v,onChange:rt=>b(rt.target.value),placeholder:"https://iframe.mediadelivery.net/embed/..."})]}),v&&e.jsx("div",{className:"aspect-video rounded-lg overflow-hidden bg-muted",children:e.jsx("iframe",{src:v,className:"w-full h-full",allow:"autoplay; fullscreen",allowFullScreen:!0})})]}),e.jsxs("div",{className:"border-t pt-4 space-y-4",children:[e.jsx("h4",{className:"font-semibold text-sm text-foreground",children:"Graphic / Image (optional)"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Upload Image"}),e.jsx("div",{className:"flex gap-2",children:e.jsx(pe,{type:"file",accept:"image/*",onChange:async rt=>{var Je;const Ke=(Je=rt.target.files)==null?void 0:Je[0];if(Ke){ne(!0);try{const pt=Ke.name.split(".").pop(),gt=`brief-graphics/${Date.now()}.${pt}`,{error:ss}=await q.storage.from("banner-images").upload(gt,Ke,{upsert:!0});if(ss)throw ss;const{data:Yt}=q.storage.from("banner-images").getPublicUrl(gt);S(Yt.publicUrl),re.success("Image uploaded!")}catch(pt){console.error(pt),re.error("Failed to upload image")}finally{ne(!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(Xt,{value:"links",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(ee,{children:"Quick Links"}),e.jsxs($,{variant:"outline",size:"sm",onClick:Be,children:[e.jsx(dn,{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=>Ne(Ke,"title",Je.target.value),placeholder:"Link title",className:"flex-1"}),e.jsx(pe,{value:rt.url,onChange:Je=>Ne(Ke,"url",Je.target.value),placeholder:"https://...",className:"flex-[2]"}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>Ae(Ke),children:e.jsx(Hn,{className:"h-4 w-4 text-destructive"})})]},Ke)),W.length===0&&e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No links added yet"})]}),e.jsxs(Xt,{value:"polls",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(ee,{children:"Polls"}),e.jsxs($,{variant:"outline",size:"sm",onClick:Ce,children:[e.jsx(dn,{className:"h-4 w-4 mr-1"}),"Add Poll"]})]}),G.map((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=>Ve(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(Hn,{className:"h-4 w-4 text-destructive"})})]}),e.jsxs("div",{className:"space-y-2 pl-4",children:[rt.options.map((Je,pt)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{value:Je,onChange:gt=>dt(Ke,pt,gt.target.value),placeholder:`Option ${pt+1}`}),rt.options.length>2&&e.jsx($,{variant:"ghost",size:"icon",onClick:()=>Xe(Ke,pt),children:e.jsx(Hn,{className:"h-4 w-4 text-muted-foreground"})})]},pt)),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>qe(Ke),children:[e.jsx(dn,{className:"h-4 w-4 mr-1"}),"Add Option"]})]})]})},Ke)),G.length===0&&e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No polls added yet"})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 mt-4",children:[e.jsx($,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx($,{onClick:Le,children:o?"Update Brief":"Create Brief"})]})]})}),e.jsx(zs,{open:d,onOpenChange:u,children:e.jsxs(Os,{className:"max-w-2xl",children:[e.jsx(Us,{children:e.jsxs(Bs,{children:["Results: ",h==null?void 0:h.title]})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs(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(Ie,{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(Ie,{children:e.jsx("p",{className:"text-2xl font-bold",children:ce.dismissed})})]})]}),te.length>0?e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"font-semibold",children:"Poll Results"}),te.map(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,pt=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," (",pt,"%)"]})]}),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:`${pt}%`}})}),Je>0&&e.jsx("div",{className:"flex flex-wrap gap-1 pt-1",children:(rt.respondents||[]).filter(gt=>gt.optionId===Ke.id).map((gt,ss)=>e.jsx($e,{variant:"secondary",className:"text-xs font-normal",children:gt.userName},ss))})]},Ke.id)})})]},rt.id))]}):e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No polls in this brief"})]})]})})]})}const eFn=()=>{const{user:s}=bs(),{toast:t}=Bi(),n=Wt(),[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),v()},onError:A=>{t({title:"Error saving service",description:A.message,variant:"destructive"})}}),y=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"})}}),v=()=>{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(Ie,{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(Ie,{children:e.jsx("div",{className:"text-2xl font-bold",children:f.filter(A=>A.is_published).length})})]})]}),e.jsxs(zs,{open:r,onOpenChange:A=>{a(A),A||v()},children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{className:"gap-2",children:[e.jsx(dn,{className:"h-4 w-4"}),"Add Service"]})}),e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(Bs,{children:i?"Edit Service":"Add New Service"})}),e.jsxs("form",{onSubmit:S,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"name",children:"Name *"}),e.jsx(pe,{id:"name",value:o.name,onChange: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(Sk,{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(Sn,{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(pr,{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(Ie,{className:"p-0",children:g?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):f.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:'No services yet. Click "Add Service" to create your first one.'}):e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{children:[e.jsx(Dt,{className:"w-16",children:"Preview"}),e.jsx(Dt,{children:"Name"}),e.jsx(Dt,{children:"Signup Link"}),e.jsx(Dt,{children:"Publish Date"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(fi,{children:f.map(A=>e.jsxs(En,{children:[e.jsx(_t,{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(_t,{className:"font-medium",children:A.name}),e.jsx(_t,{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(Fr,{className:"h-3 w-3"}),"Link"]})}),e.jsx(_t,{children:new Date(A.publish_date).toLocaleDateString()}),e.jsx(_t,{children:e.jsx($e,{variant:A.is_published?"default":"secondary",children:A.is_published?"Published":"Draft"})}),e.jsx(_t,{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 fo("Are you sure you want to delete this service?")&&y.mutate(A.id)},children:e.jsx(Hn,{className:"h-4 w-4 text-destructive"})})]})})]},A.id))})]})})})]})})};function tFn(){const{toast:s}=Bi(),[t,n]=j.useState([]),[r,a]=j.useState(!0),[i,l]=j.useState(!1),[o,c]=j.useState(!1),[d,u]=j.useState({name:"",promotionCode:"",discountType:"percent",percentOff:"",amountOff:"",duration:"once",durationInMonths:""});j.useEffect(()=>{h()},[]);const h=async()=>{try{const{data:y,error:v}=await q.functions.invoke("stripe-manage-coupons",{body:{action:"list"}});if(v)throw v;n(y.coupons||[])}catch(y){console.error("Error fetching coupons:",y),s({title:"Error",description:"Failed to load coupons",variant:"destructive"})}finally{a(!1)}},m=async()=>{if(!d.name){s({title:"Error",description:"Please enter a coupon name",variant:"destructive"});return}if(d.discountType==="percent"&&!d.percentOff){s({title:"Error",description:"Please enter a percent off value",variant:"destructive"});return}if(d.discountType==="amount"&&!d.amountOff){s({title:"Error",description:"Please enter an amount off value",variant:"destructive"});return}if(d.duration==="repeating"&&!d.durationInMonths){s({title:"Error",description:"Please enter duration in months",variant:"destructive"});return}l(!0);try{const y={action:"create",name:d.name,duration:d.duration,promotion_code:d.promotionCode.trim()||void 0};d.discountType==="percent"?y.percent_off=parseFloat(d.percentOff):(y.amount_off=Math.round(parseFloat(d.amountOff)*100),y.currency="usd"),d.duration==="repeating"&&(y.duration_in_months=parseInt(d.durationInMonths));const{data:v,error:b}=await q.functions.invoke("stripe-manage-coupons",{body:y});if(b)throw b;s({title:"Success",description:"Coupon created successfully"}),c(!1),u({name:"",promotionCode:"",discountType:"percent",percentOff:"",amountOff:"",duration:"once",durationInMonths:""}),h()}catch(y){console.error("Error creating coupon:",y),s({title:"Error",description:y.message||"Failed to create coupon",variant:"destructive"})}finally{l(!1)}},f=async y=>{if(await fo("Are you sure you want to delete this coupon?"))try{const{error:v}=await q.functions.invoke("stripe-manage-coupons",{body:{action:"delete",couponId:y}});if(v)throw v;s({title:"Success",description:"Coupon deleted successfully"}),h()}catch(v){console.error("Error deleting coupon:",v),s({title:"Error",description:v.message||"Failed to delete coupon",variant:"destructive"})}},g=y=>y.percent_off?`${y.percent_off}% off`:y.amount_off?`$${(y.amount_off/100).toFixed(2)} off`:"N/A",x=y=>{switch(y.duration){case"once":return"Once";case"forever":return"Forever";case"repeating":return`${y.duration_in_months} months`;default:return y.duration}};return e.jsx(Vs,{title:"Subscription Discounts",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Dm,{title:"Subscription Discounts",description:"Create and manage discount coupons for subscriptions",children:e.jsxs(zs,{open:o,onOpenChange:c,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{children:[e.jsx(dn,{className:"mr-2 h-4 w-4"}),"Create Coupon"]})}),e.jsxs(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Create New Coupon"}),e.jsx(Pr,{children:"Create a discount coupon that can be applied to subscriptions"})]}),e.jsxs("div",{className:"space-y-4 pt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Promotion Code (what users will type)"}),e.jsx(pe,{placeholder:"e.g., BROKERAGE50",value:d.promotionCode,onChange:y=>u({...d,promotionCode:y.target.value.toUpperCase().replace(/[^A-Z0-9]/g,"")}),className:"font-mono uppercase"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Letters and numbers only. This is the code users enter at checkout."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Coupon Name (internal label)"}),e.jsx(pe,{placeholder:"e.g., 50% Off Brokerage Launch",value:d.name,onChange:y=>u({...d,name:y.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Discount Type"}),e.jsxs(ms,{value:d.discountType,onValueChange:y=>{const v=y==="amount"&&d.duration==="forever"?"once":d.duration;u({...d,discountType:y,duration:v})},children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"percent",children:e.jsxs("span",{className:"flex items-center",children:[e.jsx(Ew,{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(nu,{className:"mr-2 h-4 w-4"}),"Fixed Amount Off"]})})]})]})]}),d.discountType==="percent"?e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Percent Off"}),e.jsxs("div",{className:"relative",children:[e.jsx(pe,{type:"number",min:"1",max:"100",placeholder:"20",value:d.percentOff,onChange:y=>u({...d,percentOff:y.target.value})}),e.jsx("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground",children:"%"})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Amount Off (USD)"}),e.jsxs("div",{className:"relative",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground",children:"$"}),e.jsx(pe,{type:"number",min:"1",placeholder:"10.00",className:"pl-7",value:d.amountOff,onChange:y=>u({...d,amountOff:y.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Duration"}),e.jsxs(ms,{value:d.duration,onValueChange:y=>u({...d,duration:y}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"once",children:"Once (first payment only)"}),e.jsx(Ge,{value:"repeating",children:"Multiple months"}),e.jsxs(Ge,{value:"forever",disabled:d.discountType==="amount",children:["Forever ",d.discountType==="amount"&&"(% discounts only)"]})]})]}),d.discountType==="amount"&&e.jsx("p",{className:"text-xs text-muted-foreground",children:'Note: "Forever" duration is only available for percentage-based discounts.'})]}),d.duration==="repeating"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Number of Months"}),e.jsx(pe,{type:"number",min:"1",placeholder:"3",value:d.durationInMonths,onChange:y=>u({...d,durationInMonths:y.target.value})})]}),e.jsx($,{onClick:m,disabled:i,className:"w-full",children:i?e.jsxs(e.Fragment,{children:[e.jsx(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(Gn,{children:"Share coupon codes with users to give them discounts on subscriptions"})]}),e.jsx(Ie,{children:r?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(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(En,{children:[e.jsx(Dt,{children:"Promo Code"}),e.jsx(Dt,{children:"Name"}),e.jsx(Dt,{children:"Discount"}),e.jsx(Dt,{children:"Duration"}),e.jsx(Dt,{children:"Redemptions"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(fi,{children:t.map(y=>{var v;return e.jsxs(En,{children:[e.jsx(_t,{className:"font-mono font-medium",children:((v=y.promotion_codes)==null?void 0:v.length)>0?y.promotion_codes.join(", "):e.jsx("span",{className:"text-muted-foreground text-xs",children:"No promo code"})}),e.jsx(_t,{children:y.name||"-"}),e.jsx(_t,{children:g(y)}),e.jsx(_t,{children:x(y)}),e.jsx(_t,{children:y.times_redeemed}),e.jsx(_t,{children:e.jsx($e,{variant:y.valid?"default":"secondary",children:y.valid?"Active":"Inactive"})}),e.jsx(_t,{className:"text-right",children:e.jsx($,{variant:"ghost",size:"sm",onClick:()=>f(y.id),children:e.jsx(Hn,{className:"h-4 w-4 text-destructive"})})})]},y.id)})})]})})]}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{children:"How to Use Coupons"})}),e.jsxs(Ie,{className:"text-sm text-muted-foreground space-y-2",children:[e.jsx("p",{children:"1. Create a coupon above with your desired discount."}),e.jsx("p",{children:'2. Share the coupon code (shown in the "Code" column) with users.'}),e.jsx("p",{children:"3. Users can enter the code during checkout to receive the discount."}),e.jsx("p",{children:"4. Alternatively, you can create a promotion code in Stripe dashboard for public-facing promotions."})]})]})]})})}const P9e={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 sFn(){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:v,error:b}=await q.from("profiles").select(` *, brokerages:brokerage_id (id, name) `).order("created_at",{ascending:!1});if(b)throw b;return v}}),{data:h}=st({queryKey:["admin-brokerages-subscriptions"],queryFn:async()=>{const{data:v,error:b}=await q.from("brokerages").select("*").order("name");if(b)throw b;return await Promise.all((v||[]).map(async S=>{const{data: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:v,error:b}=await q.from("local_move_subscriptions").select("*").order("created_at",{ascending:!1});if(b)throw b;return v}}),f=v=>{if(v.is_grandfathered)return{status:"Grandfathered",badge:"Legacy",variant:"secondary"};if(v.brokerage_id&&!v.subscription_product_id)return{status:"Brokerage",badge:"Team Member",variant:"outline"};if(v.is_trial&&v.trial_expires_at)return new Date(v.trial_expires_at)>new Date?{status:"Trial",badge:"Active Trial",variant:"default"}:{status:"Trial Expired",badge:"Expired",variant:"destructive"};if(v.subscription_status==="active"||v.subscription_status==="trialing"){const b=P9e[v.subscription_product_id];return{status:(b==null?void 0:b.name)||"Active",badge:v.subscription_status==="trialing"?"Trial":"Active",variant:"default"}}return v.subscription_status==="canceled"||v.subscription_status==="past_due"?{status:"Canceled",badge:"Inactive",variant:"destructive"}:{status:"None",badge:"No Subscription",variant:"outline"}},g=c==null?void 0:c.filter(v=>{var w,S;if(!(((w=v.name)==null?void 0:w.toLowerCase().includes(s.toLowerCase()))||((S=v.email)==null?void 0:S.toLowerCase().includes(s.toLowerCase()))))return!1;if(a!=="all"){const A=v.subscription_source||"platform";if(a==="platform"&&A==="local_move_website"||a==="local_move_website"&&A!=="local_move_website")return!1}switch(f(v),n){case"active":return v.subscription_status==="active";case"trialing":return v.subscription_status==="trialing"||v.is_trial&&new Date(v.trial_expires_at)>new Date;case"grandfathered":return v.is_grandfathered;case"brokerage":return v.brokerage_id&&!v.subscription_product_id&&!v.is_grandfathered;case"expired":return v.subscription_status==="canceled"||v.subscription_status==="past_due"||v.is_trial&&new Date(v.trial_expires_at)<=new Date;case"none":return!v.subscription_status||v.subscription_status==="none";default:return!0}}),x={totalUsers:(c==null?void 0:c.length)||0,activeSubscriptions:(c==null?void 0:c.filter(v=>v.subscription_status==="active").length)||0,trials:(c==null?void 0:c.filter(v=>v.subscription_status==="trialing"||v.is_trial&&new Date(v.trial_expires_at)>new Date).length)||0,grandfathered:(c==null?void 0:c.filter(v=>v.is_grandfathered).length)||0,brokerageMembers:(c==null?void 0:c.filter(v=>v.brokerage_id&&!v.subscription_product_id&&!v.is_grandfathered).length)||0,individualSubscribers:(c==null?void 0:c.filter(v=>v.subscription_status==="active"&&v.subscription_product_id==="prod_Tc07cYplXUGNkm").length)||0,brokerageSubscribers:(c==null?void 0:c.filter(v=>v.subscription_status==="active"&&(v.subscription_product_id==="prod_Tc08MupgoVySDG"||v.subscription_product_id==="prod_Tc09N1tJ4RrAFn")).length)||0},y=v=>{window.open(`https://dashboard.stripe.com/customers/${v}`,"_blank")};return e.jsx(Vs,{title:"Subscription Management",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Dm,{title:"Subscription Management",description:"Track and manage all subscriptions",children:e.jsxs($,{onClick:()=>u(),variant:"outline",size:"sm",children:[e.jsx(ro,{className:"h-4 w-4 mr-2"}),"Refresh"]})}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-7 gap-4",children:[e.jsx(je,{children:e.jsxs(Ie,{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(Ie,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Nv,{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(Ie,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(da,{className:"h-4 w-4 text-blue-500"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Trials"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1 text-blue-600",children:x.trials})]})}),e.jsx(je,{className:"border-purple-500/50",children:e.jsxs(Ie,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Bg,{className:"h-4 w-4 text-purple-500"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Grandfathered"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1 text-purple-600",children:x.grandfathered})]})}),e.jsx(je,{className:"border-orange-500/50",children:e.jsxs(Ie,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ji,{className:"h-4 w-4 text-orange-500"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Brokerage Members"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1 text-orange-600",children:x.brokerageMembers})]})}),e.jsx(je,{children:e.jsxs(Ie,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(m2,{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(Ie,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ji,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Brokerage Subs"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:x.brokerageSubscribers})]})})]}),e.jsxs(ha,{defaultValue:"users",className:"space-y-4",children:[e.jsxs(ma,{children:[e.jsx(Zt,{value:"users",children:"All Users"}),e.jsx(Zt,{value:"brokerages",children:"Brokerages"}),e.jsxs(Zt,{value:"websites",className:"gap-2",children:[e.jsx(dl,{className:"h-4 w-4"}),"Website Subscriptions",m&&m.length>0&&e.jsx($e,{variant:"secondary",className:"ml-1",children:m.length})]})]}),e.jsxs(Xt,{value:"users",className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Zr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search by name or email...",value:s,onChange:v=>t(v.target.value),className:"pl-9"})]}),e.jsxs(ms,{value:a,onValueChange:v=>i(v),children:[e.jsx(us,{className:"w-[200px]",children:e.jsx(fs,{placeholder:"Source"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Sources"}),e.jsx(Ge,{value:"platform",children:"Platform"}),e.jsx(Ge,{value:"local_move_website",children:"Local Move Website"})]})]}),e.jsxs(ms,{value:n,onValueChange:v=>r(v),children:[e.jsx(us,{className:"w-[200px]",children:e.jsx(fs,{placeholder:"Filter by status"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Statuses"}),e.jsx(Ge,{value:"active",children:"Active Subscriptions"}),e.jsx(Ge,{value:"trialing",children:"Trials"}),e.jsx(Ge,{value:"grandfathered",children:"Grandfathered"}),e.jsx(Ge,{value:"brokerage",children:"Brokerage Members"}),e.jsx(Ge,{value:"expired",children:"Expired/Canceled"}),e.jsx(Ge,{value:"none",children:"No Subscription"})]})]})]}),e.jsx(je,{children:e.jsx(Ie,{className:"p-0",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"User"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{children:"Plan"}),e.jsx(Dt,{children:"Brokerage"}),e.jsx(Dt,{children:"End Date"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(fi,{children:d?e.jsx(En,{children:e.jsx(_t,{colSpan:6,className:"text-center py-8",children:"Loading subscriptions..."})}):(g==null?void 0:g.length)===0?e.jsx(En,{children:e.jsx(_t,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No users found"})}):g==null?void 0:g.map(v=>{var S,A;const b=f(v),w=P9e[v.subscription_product_id];return e.jsxs(En,{children:[e.jsx(_t,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:v.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:v.email})]})}),e.jsx(_t,{children:e.jsx($e,{variant:b.variant,children:b.badge})}),e.jsx(_t,{children:e.jsx("span",{className:"text-sm",children:v.is_grandfathered?"Legacy Access":v.brokerage_id&&!v.subscription_product_id?"Brokerage Subscription":(w==null?void 0:w.name)||b.status})}),e.jsx(_t,{children:(S=v.brokerages)!=null&&S.name?e.jsx("span",{className:"text-sm",children:v.brokerages.name}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"—"})}),e.jsx(_t,{children:v.subscription_end_date?e.jsx("span",{className:"text-sm",children:en(new Date(v.subscription_end_date),"MMM d, yyyy")}):v.trial_expires_at?e.jsxs("span",{className:"text-sm text-blue-600",children:["Trial: ",en(new Date(v.trial_expires_at),"MMM d, yyyy")]}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"—"})}),e.jsx(_t,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[v.stripe_customer_id&&e.jsx($,{variant:"ghost",size:"sm",onClick:()=>y(v.stripe_customer_id),children:e.jsx(Fr,{className:"h-4 w-4"})}),e.jsxs(zs,{children:[e.jsx(jl,{asChild:!0,children:e.jsx($,{variant:"outline",size:"sm",onClick:()=>o(v),children:"Details"})}),e.jsxs(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Subscription Details"}),e.jsxs(Pr,{children:[v.name," (",v.email,")"]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Status"}),e.jsx($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:v.is_grandfathered?"Grandfathered (Legacy)":v.brokerage_id&&!v.subscription_product_id?"Brokerage Subscription":(w==null?void 0:w.name)||"None"})]}),v.brokerage_id&&e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Brokerage"}),e.jsx("p",{className:"font-medium",children:((A=v.brokerages)==null?void 0:A.name)||"Unknown"})]}),v.subscription_end_date&&e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Current Period End"}),e.jsx("p",{className:"font-medium",children:en(new Date(v.subscription_end_date),"MMMM d, yyyy")})]}),v.trial_expires_at&&e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Trial Expires"}),e.jsx("p",{className:"font-medium",children:en(new Date(v.trial_expires_at),"MMMM d, yyyy")})]}),v.stripe_customer_id&&e.jsxs("div",{className:"col-span-2",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Stripe Customer ID"}),e.jsx("p",{className:"font-mono text-sm",children:v.stripe_customer_id})]})]}),v.stripe_customer_id&&e.jsxs($,{className:"w-full",onClick:()=>y(v.stripe_customer_id),children:[e.jsx(Fr,{className:"h-4 w-4 mr-2"}),"View in Stripe Dashboard"]})]})]})]})]})})]},v.id)})})]})})})]}),e.jsx(Xt,{value:"brokerages",className:"space-y-4",children:e.jsx("div",{className:"grid gap-4",children:h==null?void 0:h.map(v=>{var w,S;const b=(w=v.managers)==null?void 0:w.some(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(ji,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(Et,{className:"text-lg",children:v.name}),e.jsxs(Gn,{children:[v.agentCount," agents"]})]})]}),e.jsx($e,{variant:b?"default":"outline",children:b?"Active Subscription":"No Active Subscription"})]})}),e.jsx(Ie,{children:((S=v.managers)==null?void 0:S.length)>0?e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium text-muted-foreground",children:"Managers:"}),v.managers.map(A=>{const E=P9e[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"})})]},v.id)})})}),e.jsx(Xt,{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(dl,{className:"h-5 w-5 text-primary"}),"Local Move Website Subscriptions"]}),e.jsx(Gn,{children:"$249 setup fee + $99/mo subscriptions from TheLocalMove.com agent websites"})]}),e.jsx(Ie,{className:"p-0",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Agent"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{children:"Setup Fee"}),e.jsx(Dt,{children:"Monthly"}),e.jsx(Dt,{children:"Next Renewal"}),e.jsx(Dt,{children:"Started"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(fi,{children:m?m.length===0?e.jsx(En,{children:e.jsx(_t,{colSpan:7,className:"text-center py-8 text-muted-foreground",children:"No website subscriptions yet"})}):m.map(v=>e.jsxs(En,{children:[e.jsx(_t,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:v.agent_name||"—"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:v.agent_email})]})}),e.jsx(_t,{children:e.jsx($e,{variant:v.status==="active"?"default":v.status==="canceled"?"destructive":"outline",children:v.status})}),e.jsx(_t,{children:v.setup_fee_paid?e.jsxs($e,{variant:"secondary",children:["Paid · $",(v.setup_fee_amount_cents/100).toFixed(0)]}):e.jsx($e,{variant:"outline",children:"Unpaid"})}),e.jsxs(_t,{className:"font-medium",children:["$",(v.monthly_amount_cents/100).toFixed(0),"/mo"]}),e.jsx(_t,{children:v.current_period_end?e.jsx("span",{className:"text-sm",children:en(new Date(v.current_period_end),"MMM d, yyyy")}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"—"})}),e.jsx(_t,{children:e.jsx("span",{className:"text-sm",children:en(new Date(v.created_at),"MMM d, yyyy")})}),e.jsx(_t,{className:"text-right",children:v.stripe_customer_id&&e.jsx($,{variant:"ghost",size:"sm",onClick:()=>y(v.stripe_customer_id),children:e.jsx(Fr,{className:"h-4 w-4"})})})]},v.id)):e.jsx(En,{children:e.jsx(_t,{colSpan:7,className:"text-center py-8",children:"Loading…"})})})]})})]})})]})]})})}function nFn(){const[s,t]=j.useState([]),[n,r]=j.useState(!0),[a,i]=j.useState(""),[l,o]=j.useState("all"),[c,d]=j.useState({total:0,qualified:0,pending:0,cancelled:0,totalDiscounts:0});j.useEffect(()=>{u()},[]);const u=async()=>{try{const{data:g,error:x}=await q.from("referrals").select(` *, referrer_brokerage:brokerages!referrer_brokerage_id(name), referred_brokerage:brokerages!referred_brokerage_id(name), referred_user:profiles!referred_user_id(name, email) `).order("created_at",{ascending:!1});if(x)throw x;t(g||[]);const y=(g==null?void 0:g.filter(w=>w.status==="qualified").length)||0,v=(g==null?void 0:g.filter(w=>w.status==="pending").length)||0,b=(g==null?void 0:g.filter(w=>w.status==="cancelled").length)||0;d({total:(g==null?void 0:g.length)||0,qualified:y,pending:v,cancelled:b,totalDiscounts:y*25})}catch(g){console.error("Error fetching referrals:",g),re.error("Failed to load referrals")}finally{r(!1)}},h=async()=>{try{re.loading("Processing qualifications...");const{error:g}=await q.functions.invoke("process-referral-qualifications");if(g)throw g;re.dismiss(),re.success("Qualifications processed successfully"),u()}catch(g){re.dismiss(),console.error("Error processing qualifications:",g),re.error("Failed to process qualifications")}},m=s.filter(g=>{var v,b,w,S,A,E;const x=((b=(v=g.referrer_brokerage)==null?void 0:v.name)==null?void 0:b.toLowerCase().includes(a.toLowerCase()))||((S=(w=g.referred_brokerage)==null?void 0:w.name)==null?void 0:S.toLowerCase().includes(a.toLowerCase()))||((E=(A=g.referred_user)==null?void 0:A.email)==null?void 0:E.toLowerCase().includes(a.toLowerCase())),y=l==="all"||g.status===l;return x&&y}),f=g=>{switch(g){case"qualified":return e.jsxs($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(da,{className:"h-3 w-3 mr-1"}),"Pending"]});case"cancelled":return e.jsxs($e,{variant:"destructive",children:[e.jsx(Nu,{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(ro,{className:"h-4 w-4 mr-2"}),"Process Qualifications"]})}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-5 gap-4",children:[e.jsx(je,{children:e.jsx(Ie,{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(Ie,{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(Ie,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(da,{className:"h-5 w-5 text-amber-600"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:c.pending}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Pending"})]})]})})}),e.jsx(je,{children:e.jsx(Ie,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Nu,{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(Ie,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(nu,{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(Gn,{children:"View and manage all referral relationships"})]}),e.jsxs(Ie,{children:[e.jsxs("div",{className:"flex gap-4 mb-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Zr,{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(En,{children:[e.jsx(Dt,{children:"Referrer"}),e.jsx(Dt,{children:"Referred"}),e.jsx(Dt,{children:"Signup Date"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{children:"Qualified Date"}),e.jsx(Dt,{children:"Discount"})]})}),e.jsx(fi,{children:m.length===0?e.jsx(En,{children:e.jsx(_t,{colSpan:6,className:"text-center text-muted-foreground py-8",children:"No referrals found"})}):m.map(g=>{var x,y,v,b;return e.jsxs(En,{children:[e.jsx(_t,{className:"font-medium",children:((x=g.referrer_brokerage)==null?void 0:x.name)||"Unknown"}),e.jsx(_t,{children:e.jsxs("div",{children:[e.jsx("p",{children:((y=g.referred_brokerage)==null?void 0:y.name)||((v=g.referred_user)==null?void 0:v.name)||"Pending setup"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(b=g.referred_user)==null?void 0:b.email})]})}),e.jsx(_t,{children:en(new Date(g.signup_date),"MMM d, yyyy")}),e.jsx(_t,{children:f(g.status)}),e.jsx(_t,{children:g.qualified_date?en(new Date(g.qualified_date),"MMM d, yyyy"):"-"}),e.jsx(_t,{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 I9e=[{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"}],rFn=[{value:"brokerage_manager",label:"Brokerage Manager"},{value:"agent",label:"Agent"}];function aFn(){const[s,t]=j.useState([]),[n,r]=j.useState(!0),[a,i]=j.useState(!1),[l,o]=j.useState(null),[c,d]=j.useState({title:"",description:"",action_type:"view_template",target_role:"agent",is_active:!0});j.useEffect(()=>{u()},[]);const u=async()=>{try{const{data:b,error:w}=await q.from("onboarding_checklist_items").select("*").order("target_role").order("sort_order");if(w)throw w;t(b||[])}catch(b){console.error("Error fetching checklist items:",b),re.error("Failed to load checklist items")}finally{r(!1)}},h=()=>{o(null),d({title:"",description:"",action_type:"view_template",target_role:"agent",is_active:!0}),i(!0)},m=b=>{o(b),d({title:b.title,description:b.description||"",action_type:b.action_type,target_role:b.target_role,is_active:b.is_active}),i(!0)},f=async()=>{if(!c.title.trim()){re.error("Title is required");return}try{if(l){const{error:b}=await q.from("onboarding_checklist_items").update({title:c.title,description:c.description||null,action_type:c.action_type,target_role:c.target_role,is_active:c.is_active}).eq("id",l.id);if(b)throw b;re.success("Checklist item updated")}else{const b=s.filter(S=>S.target_role===c.target_role).reduce((S,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;re.success("Checklist item created")}i(!1),u()}catch(b){console.error("Error saving checklist item:",b),re.error("Failed to save checklist item")}},g=async b=>{if(await fo("Are you sure you want to delete this checklist item?"))try{const{error:w}=await q.from("onboarding_checklist_items").delete().eq("id",b);if(w)throw w;re.success("Checklist item deleted"),u()}catch(w){console.error("Error deleting checklist item:",w),re.error("Failed to delete checklist item")}},x=async b=>{try{const{error:w}=await q.from("onboarding_checklist_items").update({is_active:!b.is_active}).eq("id",b.id);if(w)throw w;re.success(b.is_active?"Item deactivated":"Item activated"),u()}catch(w){console.error("Error toggling item:",w),re.error("Failed to update item")}},y=s.filter(b=>b.target_role==="brokerage_manager"),v=s.filter(b=>b.target_role==="agent");return e.jsxs(Vs,{title:"Onboarding Checklist",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold",children:"Onboarding Checklist"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage checklist items shown to new users on their dashboard"})]}),e.jsxs($,{onClick:h,className:"gap-2",children:[e.jsx(dn,{className:"h-4 w-4"}),"Add Item"]})]}),e.jsxs(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(Ie,{children:y.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No checklist items for brokerage managers"}):e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{children:[e.jsx(Dt,{className:"w-12",children:"#"}),e.jsx(Dt,{children:"Title"}),e.jsx(Dt,{children:"Action Type"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(fi,{children:y.map((b,w)=>{var S;return e.jsxs(En,{children:[e.jsx(_t,{className:"text-muted-foreground",children:w+1}),e.jsx(_t,{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(_t,{children:e.jsx($e,{variant:"outline",children:((S=I9e.find(A=>A.value===b.action_type))==null?void 0:S.label)||b.action_type})}),e.jsx(_t,{children:e.jsx(Sn,{checked:b.is_active,onCheckedChange:()=>x(b)})}),e.jsx(_t,{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(Hn,{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(Ie,{children:v.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(En,{children:[e.jsx(Dt,{className:"w-12",children:"#"}),e.jsx(Dt,{children:"Title"}),e.jsx(Dt,{children:"Action Type"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(fi,{children:v.map((b,w)=>{var S;return e.jsxs(En,{children:[e.jsx(_t,{className:"text-muted-foreground",children:w+1}),e.jsx(_t,{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(_t,{children:e.jsx($e,{variant:"outline",children:((S=I9e.find(A=>A.value===b.action_type))==null?void 0:S.label)||b.action_type})}),e.jsx(_t,{children:e.jsx(Sn,{checked:b.is_active,onCheckedChange:()=>x(b)})}),e.jsx(_t,{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(Hn,{className:"h-4 w-4 text-destructive"})})]})})]},b.id)})})]})})]})]}),e.jsx(zs,{open:a,onOpenChange:i,children:e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsx(Bs,{children:l?"Edit Checklist Item":"Add Checklist Item"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"title",children:"Title *"}),e.jsx(pe,{id:"title",value:c.title,onChange:b=>d({...c,title:b.target.value}),placeholder:"e.g., Watch your first academy video"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"description",children:"Description"}),e.jsx(Ls,{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:rFn.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:I9e.map(b=>e.jsx(Ge,{value:b.value,children:b.label},b.value))})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sn,{id:"is_active",checked:c.is_active,onCheckedChange:b=>d({...c,is_active:b})}),e.jsx(ee,{htmlFor:"is_active",children:"Active"})]})]}),e.jsxs(Sr,{children:[e.jsx($,{variant:"outline",onClick:()=>i(!1),children:"Cancel"}),e.jsx($,{onClick:f,children:l?"Save Changes":"Create Item"})]})]})})]})}function iFn(){const[s,t]=j.useState(""),[n,r]=j.useState("all"),[a,i]=j.useState("name"),[l,o]=j.useState("asc"),[c,d]=j.useState(""),[u,h]=j.useState(""),[m,f]=j.useState(""),[g,x]=j.useState(""),{data:y}=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}}),v=async D=>{let U=[],W=0,V=!0;for(;V;){const{data:G,error:Y}=await D(W,W+1e3-1);if(Y)throw Y;G&&G.length>0?(U=[...U,...G],W+=1e3,V=G.length===1e3):V=!1}return U},{data:b,isLoading:w}=st({queryKey:["admin-agent-os-user-stats"],queryFn:async()=>{const D=await v((Ee,Se)=>q.from("profiles").select("id, name, email, brokerage_id, created_at").range(Ee,Se)),{data:O}=await q.from("brokerages").select("id, name"),U=new Map((O==null?void 0:O.map(Ee=>[Ee.id,Ee.name]))||[]),[{data:W},{data:V},{data:G},{data:Y},{data:X},{data:ae},{data: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")]),ne=new Map;W==null||W.forEach(Ee=>ne.set(Ee.owner_user_id,Ee.contact_count));const te=new Map;V==null||V.forEach(Ee=>te.set(Ee.owner_user_id,Ee.video_count));const J=new Map;G==null||G.forEach(Ee=>J.set(Ee.owner_user_id,Ee.popby_count));const ce=new Map;Y==null||Y.forEach(Ee=>ce.set(Ee.agent_id,Ee.listing_count));const _e=new Map;X==null||X.forEach(Ee=>_e.set(Ee.owner_user_id,Ee.deal_count));const he=new Map;ae==null||ae.forEach(Ee=>he.set(Ee.owner_user_id,{total:Ee.portal_count,active:Ee.active_portal_count}));const ue=new Map;return 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 Se=he.get(Ee.id),Le=ue.get(Ee.id);return{id:Ee.id,name:Ee.name||"Unknown",email:Ee.email||"",brokerage_id:Ee.brokerage_id,brokerage_name:Ee.brokerage_id&&U.get(Ee.brokerage_id)||null,contact_count:ne.get(Ee.id)||0,video_count:te.get(Ee.id)||0,popby_count:J.get(Ee.id)||0,listing_count:ce.get(Ee.id)||0,deal_count:_e.get(Ee.id)||0,portal_count:(Se==null?void 0:Se.total)||0,active_portal_count:(Se==null?void 0:Se.active)||0,card_count:(Le==null?void 0:Le.total)||0,sent_card_count:(Le==null?void 0:Le.sent)||0,total_card_views:(Le==null?void 0:Le.views)||0,created_at:Ee.created_at}})}}),S=j.useMemo(()=>{if(!b)return[];let D=b.filter(O=>{const U=s.toLowerCase(),W=!s||O.name.toLowerCase().includes(U)||O.email.toLowerCase().includes(U),V=n==="all"||n==="none"&&!O.brokerage_id||O.brokerage_id===n,G=parseInt(c)||0,Y=parseInt(u)||0,X=parseInt(m)||0,ae=parseInt(g)||0,le=O.contact_count>=G&&O.video_count>=Y&&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(Y=>[Y.name,Y.email,Y.brokerage_name||"None",Y.contact_count,Y.video_count,Y.popby_count,Y.listing_count,Y.deal_count,`${Y.portal_count} (${Y.active_portal_count})`,Y.card_count,Y.sent_card_count,Y.total_card_views]),U=[D.join(","),...O.map(Y=>Y.map(X=>`"${X}"`).join(","))].join(` `),W=new Blob([U],{type:"text/csv"}),V=URL.createObjectURL(W),G=document.createElement("a");G.href=V,G.download=`agent-os-user-stats-${new Date().toISOString().split("T")[0]}.csv`,G.click(),URL.revokeObjectURL(V)},I=j.useMemo(()=>S.length?S.reduce((D,O)=>({contacts:D.contacts+O.contact_count,videos:D.videos+O.video_count,popbys:D.popbys+O.popby_count,listings:D.listings+O.listing_count,deals:D.deals+O.deal_count,portals:D.portals+O.portal_count,activePortals:D.activePortals+O.active_portal_count,cards:D.cards+O.card_count,sentCards:D.sentCards+O.sent_card_count,cardViews:D.cardViews+O.total_card_views}),{contacts:0,videos:0,popbys:0,listings:0,deals:0,portals:0,activePortals:0,cards:0,sentCards:0,cardViews:0}):{contacts:0,videos:0,popbys:0,listings:0,deals:0,portals:0,activePortals:0,cards:0,sentCards:0,cardViews:0},[S]),P=j.useMemo(()=>S.length?{portals:S.filter(D=>D.portal_count>0).length,cards:S.filter(D=>D.card_count>0).length}:{portals:0,cards:0},[S]),R=({field:D,children:O})=>e.jsx(Dt,{className:"cursor-pointer hover:bg-muted/50 select-none",onClick:()=>A(D),children:e.jsxs("div",{className:"flex items-center gap-1",children:[O,e.jsx(zy,{className:`h-3 w-3 ${a===D?"text-primary":"text-muted-foreground"}`})]})});return e.jsx(bk,{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(i2,{className:"h-4 w-4 text-blue-500"}),"Client Portals"]})}),e.jsx(Ie,{children:e.jsxs("div",{className:"grid grid-cols-3 gap-4 text-center",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:P.portals}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Agents Using"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:I.portals}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Total Portals"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold text-emerald-600",children:I.activePortals}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Active Portals"})]})]})})]}),e.jsxs(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(mn,{className:"h-4 w-4 text-violet-500"}),"Card Studio"]})}),e.jsx(Ie,{children:e.jsxs("div",{className:"grid grid-cols-4 gap-3 text-center",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:P.cards}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Agents Using"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:I.cards}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Cards Created"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold text-emerald-600",children:I.sentCards}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Cards Sent"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold text-blue-600",children:I.cardViews}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Total Views"})]})]})})]})]}),e.jsxs(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(Gn,{children:"View all users and their Agent OS usage metrics"})]}),e.jsxs($,{variant:"outline",size:"sm",onClick:E,children:[e.jsx(xi,{className:"h-4 w-4 mr-2"}),"Export CSV"]})]})}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-6",children:[e.jsx("div",{className:"md:col-span-2",children:e.jsxs("div",{className:"relative",children:[e.jsx(Zr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search by name or email...",value:s,onChange:D=>t(D.target.value),className:"pl-9"})]})}),e.jsx("div",{children:e.jsxs(ms,{value:n,onValueChange:r,children:[e.jsxs(us,{children:[e.jsx(ji,{className:"h-4 w-4 mr-2 text-muted-foreground"}),e.jsx(fs,{placeholder:"Brokerage"})]}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Brokerages"}),e.jsx(Ge,{value:"none",children:"No Brokerage"}),y==null?void 0:y.map(D=>e.jsx(Ge,{value:D.id,children:D.name},D.id))]})]})}),e.jsx("div",{children:e.jsx(pe,{type:"number",placeholder:"Min contacts",value:c,onChange:D=>d(D.target.value),min:"0"})}),e.jsx("div",{children:e.jsx(pe,{type:"number",placeholder:"Min videos",value:u,onChange:D=>h(D.target.value),min:"0"})}),e.jsx("div",{children:e.jsx(pe,{type:"number",placeholder:"Min popbys",value:m,onChange:D=>f(D.target.value),min:"0"})})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-8 text-sm",children:[e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:S.length}),e.jsx("div",{className:"text-muted-foreground",children:"Users"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:I.contacts.toLocaleString()}),e.jsx("div",{className:"text-muted-foreground",children:"Contacts"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:I.videos.toLocaleString()}),e.jsx("div",{className:"text-muted-foreground",children:"Videos"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:I.popbys.toLocaleString()}),e.jsx("div",{className:"text-muted-foreground",children:"Popbys"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:I.listings.toLocaleString()}),e.jsx("div",{className:"text-muted-foreground",children:"Listings"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:I.deals.toLocaleString()}),e.jsx("div",{className:"text-muted-foreground",children:"Deals"})]}),e.jsxs("div",{className:"bg-blue-500/10 rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:I.portals.toLocaleString()}),e.jsx("div",{className:"text-muted-foreground",children:"Portals"})]}),e.jsxs("div",{className:"bg-violet-500/10 rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:I.cards.toLocaleString()}),e.jsx("div",{className:"text-muted-foreground",children:"Cards"})]})]}),w?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(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(En,{children:[e.jsx(R,{field:"name",children:"Name"}),e.jsx(Dt,{children:"Email"}),e.jsx(Dt,{children:"Brokerage"}),e.jsx(R,{field:"contact_count",children:"Contacts"}),e.jsx(R,{field:"video_count",children:"Videos"}),e.jsx(R,{field:"popby_count",children:"Popbys"}),e.jsx(R,{field:"listing_count",children:"Listings"}),e.jsx(R,{field:"deal_count",children:"Deals"}),e.jsx(R,{field:"portal_count",children:e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(i2,{className:"h-3 w-3 text-blue-500"}),"Portals"]})}),e.jsx(R,{field:"card_count",children:e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(mn,{className:"h-3 w-3 text-violet-500"}),"Cards"]})})]})}),e.jsx(fi,{children:S.length===0?e.jsx(En,{children:e.jsx(_t,{colSpan:10,className:"text-center py-8 text-muted-foreground",children:"No users found matching your filters"})}):S.map(D=>e.jsxs(En,{children:[e.jsx(_t,{className:"font-medium",children:D.name}),e.jsx(_t,{className:"text-muted-foreground",children:D.email}),e.jsx(_t,{children:D.brokerage_name?e.jsx($e,{variant:"secondary",children:D.brokerage_name}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(_t,{children:e.jsx($e,{variant:D.contact_count>0?"default":"outline",children:D.contact_count})}),e.jsx(_t,{children:e.jsx($e,{variant:D.video_count>0?"default":"outline",children:D.video_count})}),e.jsx(_t,{children:e.jsx($e,{variant:D.popby_count>0?"default":"outline",children:D.popby_count})}),e.jsx(_t,{children:e.jsx($e,{variant:D.listing_count>0?"default":"outline",children:D.listing_count})}),e.jsx(_t,{children:e.jsx($e,{variant:D.deal_count>0?"default":"outline",children:D.deal_count})}),e.jsx(_t,{children:D.portal_count>0?e.jsxs(iy,{children:[e.jsx(oy,{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(jx,{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(_t,{children:D.card_count>0?e.jsxs(iy,{children:[e.jsx(oy,{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(Kr,{className:"h-3 w-3"}),D.sent_card_count]}),D.total_card_views>0&&e.jsxs("span",{className:"flex items-center gap-0.5 text-xs text-muted-foreground",children:[e.jsx(Ca,{className:"h-3 w-3"}),D.total_card_views]})]})}),e.jsxs(jx,{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 oFn(){Bi(),Wt();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(ha,{value:s,onValueChange:t,children:[e.jsxs(ma,{className:"grid w-full grid-cols-9",children:[e.jsxs(Zt,{value:"user-analytics",className:"gap-2",children:[e.jsx(Gl,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Users"})]}),e.jsxs(Zt,{value:"relationship-types",className:"gap-2",children:[e.jsx(Yn,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Relationships"})]}),e.jsxs(Zt,{value:"action-types",className:"gap-2",children:[e.jsx(Da,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Actions"})]}),e.jsxs(Zt,{value:"scripts",className:"gap-2",children:[e.jsx(Jr,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Scripts"})]}),e.jsxs(Zt,{value:"video-scripts",className:"gap-2",children:[e.jsx(nf,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Video Scripts"})]}),e.jsxs(Zt,{value:"plans",className:"gap-2",children:[e.jsx(Ta,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Plans"})]}),e.jsxs(Zt,{value:"popbys",className:"gap-2",children:[e.jsx(ul,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Popbys"})]}),e.jsxs(Zt,{value:"settings",className:"gap-2",children:[e.jsx(Nd,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Settings"})]}),e.jsxs(Zt,{value:"feature-flags",className:"gap-2",children:[e.jsx(AE,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Flags"})]})]}),e.jsx(Xt,{value:"user-analytics",className:"mt-6",children:e.jsx(iFn,{})}),e.jsx(Xt,{value:"relationship-types",className:"mt-6",children:e.jsx(lFn,{types:r||[],isLoading:a})}),e.jsx(Xt,{value:"action-types",className:"mt-6",children:e.jsx(cFn,{types:i||[],isLoading:l})}),e.jsx(Xt,{value:"scripts",className:"mt-6",children:e.jsx(dFn,{scripts:o||[],actionTypes:i||[],isLoading:c})}),e.jsx(Xt,{value:"video-scripts",className:"mt-6",children:e.jsx(fFn,{})}),e.jsx(Xt,{value:"plans",className:"mt-6",children:e.jsx(uFn,{plans:d||[],actionTypes:i||[],scripts:o||[],isLoading:u})}),e.jsx(Xt,{value:"popbys",className:"mt-6",children:e.jsx(mFn,{items:h||[],isLoading:m})}),e.jsx(Xt,{value:"settings",className:"mt-6",children:e.jsx(pFn,{})}),e.jsx(Xt,{value:"feature-flags",className:"mt-6",children:e.jsx(hFn,{flags:n||[]})})]})]})})}function lFn({types:s,isLoading:t}){const{toast:n}=Bi(),r=Wt(),[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(Gn,{children:"Define the relationship categories for InnerCircle contacts"})]}),e.jsxs($,{onClick:()=>{i(null),o(!0)},children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Add Type"]})]}),e.jsx(Ie,{children:t?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(Ct,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{children:[e.jsx(Dt,{className:"w-12"}),e.jsx(Dt,{children:"Name"}),e.jsx(Dt,{children:"Description"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"w-24",children:"Actions"})]})}),e.jsx(fi,{children:s.map(u=>e.jsxs(En,{children:[e.jsx(_t,{children:e.jsx(Ug,{className:"h-4 w-4 text-muted-foreground cursor-grab"})}),e.jsx(_t,{className:"font-medium",children:u.name}),e.jsx(_t,{className:"text-muted-foreground",children:u.description}),e.jsx(_t,{children:e.jsx(Sn,{checked:u.active,onCheckedChange:()=>d(u)})}),e.jsx(_t,{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(zs,{open:l,onOpenChange:o,children:e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsxs(Bs,{children:[a?"Edit":"Add"," Relationship Type"]})}),e.jsxs("form",{onSubmit:u=>{u.preventDefault();const h=new FormData(u.currentTarget);c.mutate({id:a==null?void 0:a.id,name:h.get("name"),description:h.get("description"),icon:h.get("icon")})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"name",children:"Name"}),e.jsx(pe,{id:"name",name:"name",defaultValue:a==null?void 0:a.name,required:!0})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"description",children:"Description"}),e.jsx(Ls,{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(Sr,{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 cFn({types:s,isLoading:t}){const{toast:n}=Bi(),r=Wt(),[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(Gn,{children:"Define the types of touchpoint actions agents can take"})]}),e.jsxs($,{onClick:()=>{i(null),o(!0)},children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Add Action"]})]}),e.jsx(Ie,{children:t?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(Ct,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Name"}),e.jsx(Dt,{children:"Description"}),e.jsx(Dt,{children:"Color"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"w-24",children:"Actions"})]})}),e.jsx(fi,{children:s.map(u=>e.jsxs(En,{children:[e.jsx(_t,{className:"font-medium",children:u.name}),e.jsx(_t,{className:"text-muted-foreground",children:u.description}),e.jsx(_t,{children:u.color&&e.jsx("div",{className:"w-6 h-6 rounded",style:{backgroundColor:u.color}})}),e.jsx(_t,{children:e.jsx(Sn,{checked:u.active,onCheckedChange:()=>d(u)})}),e.jsx(_t,{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(zs,{open:l,onOpenChange:o,children:e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsxs(Bs,{children:[a?"Edit":"Add"," Action Type"]})}),e.jsxs("form",{onSubmit:u=>{u.preventDefault();const h=new FormData(u.currentTarget);c.mutate({id:a==null?void 0:a.id,name:h.get("name"),description:h.get("description"),icon:h.get("icon"),color:h.get("color")})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"name",children:"Name"}),e.jsx(pe,{id:"name",name:"name",defaultValue:a==null?void 0:a.name,required:!0})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"description",children:"Description"}),e.jsx(Ls,{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(Sr,{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 dFn({scripts:s,actionTypes:t,isLoading:n}){const{toast:r}=Bi(),a=Wt(),[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(Gn,{children:"Create and manage scripts for each action type"})]}),e.jsxs($,{onClick:()=>{l(null),c(!0)},children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Add Script"]})]}),e.jsx(Ie,{children:n?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(Ct,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Title"}),e.jsx(Dt,{children:"Action Type"}),e.jsx(Dt,{children:"Tone"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"w-24",children:"Actions"})]})}),e.jsx(fi,{children:s.map(h=>{var m;return e.jsxs(En,{children:[e.jsx(_t,{className:"font-medium",children:h.title}),e.jsx(_t,{children:e.jsx($e,{variant:"outline",children:((m=h.action_type)==null?void 0:m.name)||"Unknown"})}),e.jsx(_t,{className:"text-muted-foreground",children:h.tone}),e.jsx(_t,{children:e.jsx($e,{variant:h.active?"default":"secondary",children:h.active?"Active":"Inactive"})}),e.jsxs(_t,{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(Hn,{className:"h-4 w-4 text-destructive"})})]})]},h.id)})})]})}),e.jsx(zs,{open:o,onOpenChange:c,children:e.jsxs(Os,{className:"max-w-2xl",children:[e.jsx(Us,{children:e.jsxs(Bs,{children:[i?"Edit":"Add"," Script"]})}),e.jsxs("form",{onSubmit:h=>{h.preventDefault();const m=new FormData(h.currentTarget);d.mutate({id:i==null?void 0:i.id,title:m.get("title"),action_type_id:m.get("action_type_id"),tone:m.get("tone"),script_body:m.get("script_body"),active:!0})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"title",children:"Title"}),e.jsx(pe,{id:"title",name:"title",defaultValue:i==null?void 0:i.title,required:!0})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"action_type_id",children:"Action Type"}),e.jsxs(ms,{name:"action_type_id",defaultValue:i==null?void 0:i.action_type_id,children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Select action type"})}),e.jsx(hs,{children:t.map(h=>e.jsx(Ge,{value:h.id,children:h.name},h.id))})]})]})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"tone",children:"Tone (optional)"}),e.jsx(pe,{id:"tone",name:"tone",defaultValue:(i==null?void 0:i.tone)||"",placeholder:"e.g., Friendly, Professional, Casual"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"script_body",children:"Script Body"}),e.jsx(Ls,{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(Sr,{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 uFn({plans:s,actionTypes:t,scripts:n,isLoading:r}){const{toast:a}=Bi(),i=Wt(),[l,o]=j.useState(null),[c,d]=j.useState(!1),[u,h]=j.useState(null),[m,f]=j.useState(!1),[g,x]=j.useState(null),[y,v]=j.useState(null),{data:b}=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(Gn,{children:"Create annual touchpoint plans that agents can apply to their contacts"})]}),e.jsxs($,{onClick:()=>{o(null),d(!0)},children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Add Plan"]})]}),e.jsx(Ie,{children:r?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(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(Ie,{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(Gn,{children:"Configure the monthly touchpoint schedule. Select an action type for each month, then assign or create a script."})]}),e.jsx(Ie,{children:e.jsx("div",{className:"grid gap-3",children:Array.from({length:12},(R,D)=>D+1).map(R=>{const D=b==null?void 0:b.find(W=>W.month_number===R),O=D!=null&&D.default_script_id?P(D.default_script_id):null,U=n.filter(W=>W.action_type_id===(D==null?void 0:D.action_type_id)&&W.active);return e.jsxs("div",{className:"p-4 border rounded-lg space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"w-20 font-medium text-sm",children:["Month ",R]}),e.jsxs(ms,{value:(D==null?void 0:D.action_type_id)||"none",onValueChange:W=>{W==="none"&&D?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=>{v(null),S.mutate({id:D.id,default_script_id:W==="none"?null:W})},children:[e.jsx(us,{className:"w-56",children:e.jsx(fs,{placeholder:"Select script"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"none",children:"No default script"}),U.map(W=>e.jsxs(Ge,{value:W.id,children:[W.title," ",W.tone&&`(${W.tone})`]},W.id))]})]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>I(R,D.action_type_id,D.id),children:[e.jsx(dn,{className:"h-3 w-3 mr-1"}),"New Script"]}),O&&e.jsx($,{variant:"ghost",size:"sm",onClick:()=>v((y==null?void 0:y.id)===O.id?null:O),children:(y==null?void 0:y.id)===O.id?"Hide":"Preview"})]})]}),y&&(D==null?void 0:D.default_script_id)===y.id&&e.jsxs("div",{className:"ml-24 p-3 bg-muted rounded-lg text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx($e,{variant:"outline",children:y.title}),y.tone&&e.jsx($e,{variant:"secondary",children:y.tone})]}),e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:y.script_body})]})]},R)})})})]}),e.jsx(zs,{open:c,onOpenChange:d,children:e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsxs(Bs,{children:[l?"Edit":"Add"," Touchpoint Plan"]})}),e.jsxs("form",{onSubmit:R=>{R.preventDefault();const D=new FormData(R.currentTarget);w.mutate({id:l==null?void 0:l.id,name:D.get("name"),description:D.get("description"),active:!0})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"name",children:"Name"}),e.jsx(pe,{id:"name",name:"name",defaultValue:l==null?void 0:l.name,required:!0})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"description",children:"Description"}),e.jsx(Ls,{id:"description",name:"description",defaultValue:(l==null?void 0:l.description)||"",rows:3})]})]}),e.jsxs(Sr,{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(zs,{open:m,onOpenChange:f,children:e.jsxs(Os,{className:"max-w-2xl",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Create New Script"}),e.jsxs(Pr,{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(Ls,{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(Sr,{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 hFn({flags:s}){const{toast:t}=Bi(),n=Wt(),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(Gn,{children:"Control which features are enabled for members"})]}),e.jsx(Ie,{children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Flag"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{children:"Notes"}),e.jsx(Dt,{children:"Last Updated"})]})}),e.jsx(fi,{children:s.map(a=>e.jsxs(En,{children:[e.jsx(_t,{className:"font-mono text-sm",children:a.key}),e.jsx(_t,{children:e.jsx(Sn,{checked:a.enabled,onCheckedChange:i=>r(a,{enabled:i})})}),e.jsx(_t,{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(_t,{className:"text-muted-foreground text-sm",children:new Date(a.updated_at).toLocaleDateString()})]},a.id))})]})})]})}function mFn({items:s,isLoading:t}){const{toast:n}=Bi(),r=Wt(),[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(Gn,{children:"Manage global popby ideas that all agents can see"})]}),e.jsxs($,{onClick:()=>{i(null),o(!0)},children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Add Popby Idea"]})]}),e.jsx(Ie,{children:t?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(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(ul,{className:"h-12 w-12 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"No popby ideas yet. Add your first one!"})]}):e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Name"}),e.jsx(Dt,{children:"Description"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"w-24",children:"Actions"})]})}),e.jsx(fi,{children:s.map(h=>e.jsxs(En,{children:[e.jsx(_t,{className:"font-medium",children:h.name}),e.jsx(_t,{className:"text-muted-foreground",children:h.description}),e.jsx(_t,{children:e.jsx(Sn,{checked:h.is_active,onCheckedChange:()=>d(h)})}),e.jsx(_t,{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(Hn,{className:"h-4 w-4 text-destructive"})})]})})]},h.id))})]})}),e.jsx(zs,{open:l,onOpenChange:o,children:e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsxs(Bs,{children:[a?"Edit":"Add"," Popby Idea"]})}),e.jsxs("form",{onSubmit:h=>{h.preventDefault();const m=new FormData(h.currentTarget);c.mutate({id:a==null?void 0:a.id,name:m.get("name"),description:m.get("description")})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"name",children:"Name"}),e.jsx(pe,{id:"name",name:"name",defaultValue:a==null?void 0:a.name,required:!0,placeholder:"e.g., Homemade Cookies"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"description",children:"Description"}),e.jsx(Ls,{id:"description",name:"description",defaultValue:(a==null?void 0:a.description)||"",placeholder:"Brief description of the popby idea..."})]})]}),e.jsxs(Sr,{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 fFn(){var f;const{toast:s}=Bi(),t=Wt(),[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,y;if(g.id){const{error:v}=await q.from("video_scripts").update({title:g.title,script_text:g.script_text,category_id:g.category_id,tags:((x=g.tags)==null?void 0:x.split(",").map(b=>b.trim()).filter(Boolean))||[]}).eq("id",g.id);if(v)throw v}else{const{error:v}=await q.from("video_scripts").insert([{title:g.title,script_text:g.script_text,category_id:g.category_id||null,tags:((y=g.tags)==null?void 0:y.split(",").map(b=>b.trim()).filter(Boolean))||[]}]);if(v)throw v}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-video-scripts"]}),i(!1),r(null),s({title:"Video script saved!"})},onError:g=>s({title:"Error",description:g.message,variant:"destructive"})}),h=async g=>{await q.from("video_scripts").update({is_active:!g.is_active}).eq("id",g.id),t.invalidateQueries({queryKey:["admin-video-scripts"]})},m=async g=>{await fo("Delete this video script?")&&(await q.from("video_scripts").delete().eq("id",g),t.invalidateQueries({queryKey:["admin-video-scripts"]}),s({title:"Script deleted"}))};return e.jsxs(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(Gn,{children:"Manage teleprompter scripts for Quick Video Touch"})]}),e.jsxs($,{onClick:()=>{r(null),i(!0)},children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Add Script"]})]}),e.jsx(Ie,{children:d?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(Ct,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Title"}),e.jsx(Dt,{children:"Category"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"w-24",children:"Actions"})]})}),e.jsx(fi,{children:c==null?void 0:c.map(g=>{var x;return e.jsxs(En,{children:[e.jsx(_t,{className:"font-medium",children:g.title}),e.jsx(_t,{className:"text-muted-foreground",children:((x=g.category)==null?void 0:x.name)||"Uncategorized"}),e.jsx(_t,{children:e.jsx(Sn,{checked:g.is_active,onCheckedChange:()=>h(g)})}),e.jsxs(_t,{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(Hn,{className:"h-4 w-4"})})]})]},g.id)})})]})}),e.jsx(zs,{open:a,onOpenChange:i,children:e.jsxs(Os,{className:"max-w-2xl",children:[e.jsx(Us,{children:e.jsxs(Bs,{children:[n?"Edit":"Add"," Video Script"]})}),e.jsxs("form",{onSubmit:g=>{g.preventDefault();const x=new FormData(g.currentTarget);u.mutate({id:n==null?void 0:n.id,title:x.get("title"),script_text:x.get("script_text"),category_id:x.get("category_id")||null,tags:x.get("tags")})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"title",children:"Title"}),e.jsx(pe,{id:"title",name:"title",defaultValue:n==null?void 0:n.title,required:!0})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"category_id",children:"Category"}),e.jsxs(ms,{name:"category_id",defaultValue:(n==null?void 0:n.category_id)||"",children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Select category"})}),e.jsx(hs,{children:l==null?void 0:l.map(g=>e.jsx(Ge,{value:g.id,children:g.name},g.id))})]})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"script_text",children:"Script Text"}),e.jsx(Ls,{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(Sr,{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 pFn(){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(Ie,{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(ci,{className:"h-5 w-5"}),"Popby Map Settings"]}),e.jsx(Gn,{children:"Configure the map feature for popbys"})]}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"mapbox-token",children:"Mapbox Public Token"}),e.jsx(pe,{id:"mapbox-token",placeholder:"pk.eyJ1I...",value:t,onChange:c=>n(c.target.value)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Get your token at"," ",e.jsx("a",{href:"https://mapbox.com/",target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline",children:"mapbox.com"}),". This token will be used by all agents for the popby map feature."]})]}),e.jsxs($,{onClick:o,disabled:i,children:[i&&e.jsx(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 gFn=()=>{const[s,t]=j.useState(""),[n,r]=j.useState("grid"),a=Xn(),{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(Zr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search services...",value:s,onChange:c=>t(c.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex gap-2",children:[s&&e.jsx($,{variant:"outline",size:"sm",onClick:()=>t(""),children:"Clear"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{variant:n==="grid"?"secondary":"outline",size:"icon",onClick:()=>r("grid"),className:"rounded-full",children:e.jsx(Qf,{className:"h-4 w-4"})}),e.jsx($,{variant:n==="list"?"secondary":"outline",size:"icon",onClick:()=>r("list"),className:"rounded-full",children:e.jsx(T0,{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(Ie,{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(Nn,{className:"h-8 w-8"})})}),e.jsxs(Ie,{className:`p-4 flex flex-col ${n==="list"?"flex-1":""}`,children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 mb-1",children:c.name}),c.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 flex-1",children:zte(c.description)})]})]},c.id))})]})})},xFn=()=>{const{serviceId:s}=Wi(),t=Xn(),{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(Nn,{className:"h-16 w-16"})})})}),e.jsx(je,{children:e.jsxs(Ie,{className:"p-6 space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground mb-2",children:n.name}),e.jsxs("div",{className:"flex items-center text-sm text-muted-foreground",children:[e.jsx(Ta,{className:"h-4 w-4 mr-1"}),"Published ",en(new Date(n.publish_date),"MMMM d, yyyy")]})]}),n.description&&e.jsx("div",{className:"prose prose-sm max-w-none text-muted-foreground [&_a]:text-primary [&_a]:underline",dangerouslySetInnerHTML:{__html:n.description}}),e.jsx("div",{className:"pt-4 border-t",children:e.jsxs($,{size:"lg",className:"gap-2",onClick:()=>window.open(n.signup_link_url,"_blank"),children:[e.jsx(Fr,{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"]})]})})},eX=[{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 yFn(){const[s,t]=j.useState(eX[0].id),n=eX.find(r=>r.id===s)||eX[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(E4,{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:eX.map(r=>e.jsx(Ge,{value:r.id,children:r.name},r.id))})]})}),e.jsx("div",{className:"hidden md:block",children:e.jsx(ha,{value:s,onValueChange:t,className:"w-full",children:e.jsx(ma,{className:"w-full flex-wrap h-auto gap-1 bg-muted p-1",children:eX.map(r=>e.jsx(Zt,{value:r.id,className:"flex-1 min-w-[150px] text-xs lg:text-sm whitespace-normal h-auto py-2",children:r.name},r.id))})})}),e.jsx("div",{className:"flex justify-center",children:e.jsx("div",{className:"w-full max-w-[700px]",dangerouslySetInnerHTML:{__html:n.iframe}})})]})})}function vFn(s,t){const n={};return(s[s.length-1]===""?[...s,""]:s).join((n.padRight?" ":"")+","+(n.padLeft===!1?"":" ")).trim()}const bFn=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,_Fn=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,wFn={};function lSt(s,t){return(wFn.jsx?_Fn:bFn).test(s)}const jFn=/[ \t\n\f\r]/g;function NFn(s){return typeof s=="object"?s.type==="text"?cSt(s.value):!1:cSt(s)}function cSt(s){return s.replace(jFn,"")===""}class Mie{constructor(t,n,r){this.normal=n,this.property=t,r&&(this.space=r)}}Mie.prototype.normal={};Mie.prototype.property={};Mie.prototype.space=void 0;function zXt(s,t){const n={},r={};for(const a of s)Object.assign(n,a.property),Object.assign(r,a.normal);return new Mie(n,r,t)}function vYe(s){return s.toLowerCase()}class Hw{constructor(t,n){this.attribute=n,this.property=t}}Hw.prototype.attribute="";Hw.prototype.booleanish=!1;Hw.prototype.boolean=!1;Hw.prototype.commaOrSpaceSeparated=!1;Hw.prototype.commaSeparated=!1;Hw.prototype.defined=!1;Hw.prototype.mustUseProperty=!1;Hw.prototype.number=!1;Hw.prototype.overloadedBoolean=!1;Hw.prototype.property="";Hw.prototype.spaceSeparated=!1;Hw.prototype.space=void 0;let kFn=0;const ed=t9(),Py=t9(),bYe=t9(),wi=t9(),vf=t9(),_7=t9(),kj=t9();function t9(){return 2**++kFn}const _Ye=Object.freeze(Object.defineProperty({__proto__:null,boolean:ed,booleanish:Py,commaOrSpaceSeparated:kj,commaSeparated:_7,number:wi,overloadedBoolean:bYe,spaceSeparated:vf},Symbol.toStringTag,{value:"Module"})),L9e=Object.keys(_Ye);class Jat extends Hw{constructor(t,n,r,a){let i=-1;if(super(t,n),dSt(this,"space",a),typeof r=="number")for(;++i4&&n.slice(0,4)==="data"&&TFn.test(t)){if(t.charAt(4)==="-"){const i=t.slice(5).replace(uSt,IFn);r="data"+i.charAt(0).toUpperCase()+i.slice(1)}else{const i=t.slice(4);if(!uSt.test(i)){let l=i.replace(EFn,PFn);l.charAt(0)!=="-"&&(l="-"+l),t="data"+l}}a=Jat}return new a(r,t)}function PFn(s){return"-"+s.toLowerCase()}function IFn(s){return s.charAt(1).toUpperCase()}const LFn=zXt([BXt,SFn,qXt,VXt,HXt],"html"),eit=zXt([BXt,CFn,qXt,VXt,HXt],"svg");function RFn(s){return s.join(" ").trim()}var tit={},hSt=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,DFn=/\n/g,FFn=/^\s*/,OFn=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,zFn=/^:\s*/,BFn=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,$Fn=/^[;\s]*/,UFn=/^\s+|\s+$/g,qFn=` `,mSt="/",fSt="*",ZO="",VFn="comment",HFn="declaration";function GFn(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(DFn);x&&(n+=x.length);var y=g.lastIndexOf(qFn);r=~y?g.length-y:r+g.length}function i(){var g={line:n,column:r};return function(x){return x.position=new l(g),d(),x}}function l(g){this.start=g,this.end={line:n,column:r},this.source=t.source}l.prototype.content=s;function o(g){var x=new Error(t.source+":"+n+":"+r+": "+g);if(x.reason=g,x.filename=t.source,x.line=n,x.column=r,x.source=s,!t.silent)throw x}function c(g){var x=g.exec(s);if(x){var y=x[0];return a(y),s=s.slice(y.length),x}}function d(){c(FFn)}function u(g){var x;for(g=g||[];x=h();)x!==!1&&g.push(x);return g}function h(){var g=i();if(!(mSt!=s.charAt(0)||fSt!=s.charAt(1))){for(var x=2;ZO!=s.charAt(x)&&(fSt!=s.charAt(x)||mSt!=s.charAt(x+1));)++x;if(x+=2,ZO===s.charAt(x-1))return o("End of comment missing");var y=s.slice(2,x-2);return r+=2,a(y),s=s.slice(x),r+=2,g({type:VFn,comment:y})}}function m(){var g=i(),x=c(OFn);if(x){if(h(),!c(zFn))return o("property missing ':'");var y=c(BFn),v=g({type:HFn,property:pSt(x[0].replace(hSt,ZO)),value:y?pSt(y[0].replace(hSt,ZO)):ZO});return c($Fn),v}}function f(){var g=[];u(g);for(var x;x=m();)x!==!1&&(g.push(x),u(g));return g}return d(),f()}function pSt(s){return s?s.replace(UFn,ZO):ZO}var WFn=GFn,KFn=Sp&&Sp.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(tit,"__esModule",{value:!0});tit.default=ZFn;const YFn=KFn(WFn);function ZFn(s,t){let n=null;if(!s||typeof s!="string")return n;const r=(0,YFn.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 JRe={};Object.defineProperty(JRe,"__esModule",{value:!0});JRe.camelCase=void 0;var XFn=/^--[a-zA-Z0-9_-]+$/,QFn=/-([a-z])/g,JFn=/^[^-]+$/,eOn=/^-(webkit|moz|ms|o|khtml)-/,tOn=/^-(ms)-/,sOn=function(s){return!s||JFn.test(s)||XFn.test(s)},nOn=function(s,t){return t.toUpperCase()},gSt=function(s,t){return"".concat(t,"-")},rOn=function(s,t){return t===void 0&&(t={}),sOn(s)?s:(s=s.toLowerCase(),t.reactCompat?s=s.replace(tOn,gSt):s=s.replace(eOn,gSt),s.replace(QFn,nOn))};JRe.camelCase=rOn;var aOn=Sp&&Sp.__importDefault||function(s){return s&&s.__esModule?s:{default:s}},iOn=aOn(tit),oOn=JRe;function wYe(s,t){var n={};return!s||typeof s!="string"||(0,iOn.default)(s,function(r,a){r&&a&&(n[(0,oOn.camelCase)(r,t)]=a)}),n}wYe.default=wYe;var lOn=wYe;const cOn=ru(lOn),GXt=WXt("end"),sit=WXt("start");function WXt(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 dOn(s){const t=sit(s),n=GXt(s);if(t&&n)return{start:t,end:n}}function Wee(s){return!s||typeof s!="object"?"":"position"in s||"type"in s?xSt(s.position):"start"in s||"end"in s?xSt(s):"line"in s||"column"in s?jYe(s):""}function jYe(s){return ySt(s&&s.line)+":"+ySt(s&&s.column)}function xSt(s){return jYe(s&&s.start)+"-"+jYe(s&&s.end)}function ySt(s){return s&&typeof s=="number"?s:1}class T1 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=Wee(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}}T1.prototype.file="";T1.prototype.name="";T1.prototype.reason="";T1.prototype.message="";T1.prototype.stack="";T1.prototype.column=void 0;T1.prototype.line=void 0;T1.prototype.ancestors=void 0;T1.prototype.cause=void 0;T1.prototype.fatal=void 0;T1.prototype.place=void 0;T1.prototype.ruleId=void 0;T1.prototype.source=void 0;const nit={}.hasOwnProperty,uOn=new Map,hOn=/[A-Z]/g,mOn=new Set(["table","tbody","thead","tfoot","tr"]),fOn=new Set(["td","th"]),KXt="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function pOn(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=jOn(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=wOn(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"?eit:LFn,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},i=YXt(a,s,void 0);return i&&typeof i!="string"?i:a.create(s,a.Fragment,{children:i||void 0},void 0)}function YXt(s,t,n){if(t.type==="element")return gOn(s,t,n);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return xOn(s,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return vOn(s,t,n);if(t.type==="mdxjsEsm")return yOn(s,t);if(t.type==="root")return bOn(s,t,n);if(t.type==="text")return _On(s,t)}function gOn(s,t,n){const r=s.schema;let a=r;t.tagName.toLowerCase()==="svg"&&r.space==="html"&&(a=eit,s.schema=a),s.ancestors.push(t);const i=XXt(s,t.tagName,!1),l=NOn(s,t);let o=ait(s,t);return mOn.has(t.tagName)&&(o=o.filter(function(c){return typeof c=="string"?!NFn(c):!0})),ZXt(s,l,i,t),rit(l,o),s.ancestors.pop(),s.schema=r,s.create(t,i,l,n)}function xOn(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)}dne(s,t.position)}function yOn(s,t){if(t.data&&t.data.estree&&s.evaluater)return s.evaluater.evaluateProgram(t.data.estree);dne(s,t.position)}function vOn(s,t,n){const r=s.schema;let a=r;t.name==="svg"&&r.space==="html"&&(a=eit,s.schema=a),s.ancestors.push(t);const i=t.name===null?s.Fragment:XXt(s,t.name,!0),l=kOn(s,t),o=ait(s,t);return ZXt(s,l,i,t),rit(l,o),s.ancestors.pop(),s.schema=r,s.create(t,i,l,n)}function bOn(s,t,n){const r={};return rit(r,ait(s,t)),s.create(t,s.Fragment,r,n)}function _On(s,t){return t.value}function ZXt(s,t,n,r){typeof n!="string"&&n!==s.Fragment&&s.passNode&&(t.node=r)}function rit(s,t){if(t.length>0){const n=t.length>1?t:t[0];n&&(s.children=n)}}function wOn(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 jOn(s,t){return n;function n(r,a,i,l){const o=Array.isArray(i.children),c=sit(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 NOn(s,t){const n={};let r,a;for(a in t.properties)if(a!=="children"&&nit.call(t.properties,a)){const i=SOn(s,a,t.properties[a]);if(i){const[l,o]=i;s.tableCellAlignToStyle&&l==="align"&&typeof o=="string"&&fOn.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 kOn(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 dne(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 dne(s,t.position);else i=r.value===null?!0:r.value;n[a]=i}return n}function ait(s,t){const n=[];let r=-1;const a=s.passKeys?new Map:uOn;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?(Q4(s,s.length,0,t),s):t}const _St={}.hasOwnProperty;function LOn(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 TV(s){return s.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const d4=C6(/[A-Za-z]/),Qj=C6(/[\dA-Za-z]/),FOn=C6(/[#-'*+\--9=?A-Z^-~]/);function NYe(s){return s!==null&&(s<32||s===127)}const kYe=C6(/\d/),OOn=C6(/[\dA-Fa-f]/),zOn=C6(/[!-/:-@[-`{-~]/);function Fc(s){return s!==null&&s<-2}function Lw(s){return s!==null&&(s<0||s===32)}function nm(s){return s===-2||s===-1||s===32}const BOn=C6(new RegExp("\\p{P}|\\p{S}","u")),$On=C6(/\s/);function C6(s){return t;function t(n){return n!==null&&n>-1&&s.test(String.fromCharCode(n))}}function DK(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(v(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 GOn(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 jSt(s){if(s===null||Lw(s)||$On(s))return 1;if(BOn(s))return 2}function oit(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};NSt(h,-c),NSt(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=EN(d,[["enter",s[r][1],t],["exit",s[r][1],t]])),d=EN(d,[["enter",a,t],["enter",l,t],["exit",l,t],["enter",i,t]]),d=EN(d,oit(t.parser.constructs.insideSpan.null,s.slice(r+1,n),t)),d=EN(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=EN(d,[["enter",s[n][1],t],["exit",s[n][1],t]])):u=0,Q4(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(kSt,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 r8n(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 D9e={name:"codeIndented",tokenize:i8n},a8n={partial:!0,tokenize:o8n};function i8n(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(a8n,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 o8n(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 l8n={name:"codeText",previous:d8n,resolve:c8n,tokenize:u8n};function c8n(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&&tX(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),tX(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),tX(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 rQt(s,t,n,r,a,i,l,o,c){const d=c||Number.POSITIVE_INFINITY;let u=0;return h;function h(v){return v===60?(s.enter(r),s.enter(a),s.enter(i),s.consume(v),s.exit(i),m):v===null||v===32||v===41||NYe(v)?n(v):(s.enter(r),s.enter(l),s.enter(o),s.enter("chunkString",{contentType:"string"}),x(v))}function m(v){return v===62?(s.enter(i),s.consume(v),s.exit(i),s.exit(a),s.exit(r),t):(s.enter(o),s.enter("chunkString",{contentType:"string"}),f(v))}function f(v){return v===62?(s.exit("chunkString"),s.exit(o),m(v)):v===null||v===60||Fc(v)?n(v):(s.consume(v),v===92?g:f)}function g(v){return v===60||v===62||v===92?(s.consume(v),f):f(v)}function x(v){return!u&&(v===null||v===41||Lw(v))?(s.exit("chunkString"),s.exit(o),s.exit(l),s.exit(r),t(v)):u999||f===null||f===91||f===93&&!c||f===94&&!o&&"_hiddenFootnoteSupport"in l.parser.constructs?n(f):f===93?(s.exit(i),s.enter(a),s.consume(f),s.exit(a),s.exit(r),t):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 iQt(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 Kee(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 v8n={name:"definition",tokenize:_8n},b8n={partial:!0,tokenize:w8n};function _8n(s,t,n){const r=this;let a;return i;function i(f){return s.enter("definition"),l(f)}function l(f){return aQt.call(r,s,o,n,"definitionLabel","definitionLabelMarker","definitionLabelString")(f)}function o(f){return a=TV(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 Lw(f)?Kee(s,d)(f):d(f)}function d(f){return rQt(s,u,n,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(f)}function u(f){return s.attempt(b8n,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 w8n(s,t,n){return r;function r(o){return Lw(o)?Kee(s,a)(o):n(o)}function a(o){return iQt(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 j8n={name:"hardBreakEscape",tokenize:N8n};function N8n(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 k8n={name:"headingAtx",resolve:S8n,tokenize:C8n};function S8n(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"},Q4(s,r,n-r+1,[["enter",a,t],["enter",i,t],["exit",i,t],["exit",a,t]])),s}function C8n(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||Lw(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||Lw(u)?(s.exit("atxHeadingText"),o(u)):(s.consume(u),d)}}const A8n=["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"],CSt=["pre","script","style","textarea"],E8n={concrete:!0,name:"htmlFlow",resolveTo:P8n,tokenize:I8n},T8n={partial:!0,tokenize:R8n},M8n={partial:!0,tokenize:L8n};function P8n(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 I8n(s,t,n){const r=this;let a,i,l,o,c;return d;function d(ce){return u(ce)}function u(ce){return s.enter("htmlFlow"),s.enter("htmlFlowData"),s.consume(ce),h}function h(ce){return ce===33?(s.consume(ce),m):ce===47?(s.consume(ce),i=!0,x):ce===63?(s.consume(ce),a=3,r.interrupt?t:ne):d4(ce)?(s.consume(ce),l=String.fromCharCode(ce),y):n(ce)}function m(ce){return ce===45?(s.consume(ce),a=2,f):ce===91?(s.consume(ce),a=5,o=0,g):d4(ce)?(s.consume(ce),a=4,r.interrupt?t:ne):n(ce)}function f(ce){return ce===45?(s.consume(ce),r.interrupt?t:ne):n(ce)}function g(ce){const _e="CDATA[";return ce===_e.charCodeAt(o++)?(s.consume(ce),o===_e.length?r.interrupt?t:U:g):n(ce)}function x(ce){return d4(ce)?(s.consume(ce),l=String.fromCharCode(ce),y):n(ce)}function y(ce){if(ce===null||ce===47||ce===62||Lw(ce)){const _e=ce===47,he=l.toLowerCase();return!_e&&!i&&CSt.includes(he)?(a=1,r.interrupt?t(ce):U(ce)):A8n.includes(l.toLowerCase())?(a=6,_e?(s.consume(ce),v):r.interrupt?t(ce):U(ce)):(a=7,r.interrupt&&!r.parser.lazy[r.now().line]?n(ce):i?b(ce):w(ce))}return ce===45||Qj(ce)?(s.consume(ce),l+=String.fromCharCode(ce),y):n(ce)}function v(ce){return ce===62?(s.consume(ce),r.interrupt?t:U):n(ce)}function b(ce){return nm(ce)?(s.consume(ce),b):D(ce)}function w(ce){return ce===47?(s.consume(ce),D):ce===58||ce===95||d4(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||Qj(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||Lw(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),Y):ce===60&&a===1?(s.consume(ce),X):ce===62&&a===4?(s.consume(ce),te):ce===63&&a===3?(s.consume(ce),ne):ce===93&&a===5?(s.consume(ce),le):Fc(ce)&&(a===6||a===7)?(s.exit("htmlFlowData"),s.check(T8n,J,W)(ce)):ce===null||Fc(ce)?(s.exit("htmlFlowData"),W(ce)):(s.consume(ce),U)}function W(ce){return s.check(M8n,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 Y(ce){return ce===45?(s.consume(ce),ne):U(ce)}function X(ce){return ce===47?(s.consume(ce),l="",ae):U(ce)}function ae(ce){if(ce===62){const _e=l.toLowerCase();return CSt.includes(_e)?(s.consume(ce),te):U(ce)}return d4(ce)&&l.length<8?(s.consume(ce),l+=String.fromCharCode(ce),ae):U(ce)}function le(ce){return ce===93?(s.consume(ce),ne):U(ce)}function ne(ce){return ce===62?(s.consume(ce),te):ce===45&&a===2?(s.consume(ce),ne):U(ce)}function te(ce){return ce===null||Fc(ce)?(s.exit("htmlFlowData"),J(ce)):(s.consume(ce),te)}function J(ce){return s.exit("htmlFlow"),t(ce)}}function L8n(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 R8n(s,t,n){return r;function r(a){return s.enter("lineEnding"),s.consume(a),s.exit("lineEnding"),s.attempt(eDe,t,n)}}const D8n={name:"htmlText",tokenize:F8n};function F8n(s,t,n){const r=this;let a,i,l;return o;function o(ne){return s.enter("htmlText"),s.enter("htmlTextData"),s.consume(ne),c}function c(ne){return ne===33?(s.consume(ne),d):ne===47?(s.consume(ne),A):ne===63?(s.consume(ne),w):d4(ne)?(s.consume(ne),P):n(ne)}function d(ne){return ne===45?(s.consume(ne),u):ne===91?(s.consume(ne),i=0,g):d4(ne)?(s.consume(ne),b):n(ne)}function u(ne){return ne===45?(s.consume(ne),f):n(ne)}function h(ne){return ne===null?n(ne):ne===45?(s.consume(ne),m):Fc(ne)?(l=h,X(ne)):(s.consume(ne),h)}function m(ne){return ne===45?(s.consume(ne),f):h(ne)}function f(ne){return ne===62?Y(ne):ne===45?m(ne):h(ne)}function g(ne){const te="CDATA[";return ne===te.charCodeAt(i++)?(s.consume(ne),i===te.length?x:g):n(ne)}function x(ne){return ne===null?n(ne):ne===93?(s.consume(ne),y):Fc(ne)?(l=x,X(ne)):(s.consume(ne),x)}function y(ne){return ne===93?(s.consume(ne),v):x(ne)}function v(ne){return ne===62?Y(ne):ne===93?(s.consume(ne),v):x(ne)}function b(ne){return ne===null||ne===62?Y(ne):Fc(ne)?(l=b,X(ne)):(s.consume(ne),b)}function w(ne){return ne===null?n(ne):ne===63?(s.consume(ne),S):Fc(ne)?(l=w,X(ne)):(s.consume(ne),w)}function S(ne){return ne===62?Y(ne):w(ne)}function A(ne){return d4(ne)?(s.consume(ne),E):n(ne)}function E(ne){return ne===45||Qj(ne)?(s.consume(ne),E):I(ne)}function I(ne){return Fc(ne)?(l=I,X(ne)):nm(ne)?(s.consume(ne),I):Y(ne)}function P(ne){return ne===45||Qj(ne)?(s.consume(ne),P):ne===47||ne===62||Lw(ne)?R(ne):n(ne)}function R(ne){return ne===47?(s.consume(ne),Y):ne===58||ne===95||d4(ne)?(s.consume(ne),D):Fc(ne)?(l=R,X(ne)):nm(ne)?(s.consume(ne),R):Y(ne)}function D(ne){return ne===45||ne===46||ne===58||ne===95||Qj(ne)?(s.consume(ne),D):O(ne)}function O(ne){return ne===61?(s.consume(ne),U):Fc(ne)?(l=O,X(ne)):nm(ne)?(s.consume(ne),O):R(ne)}function U(ne){return ne===null||ne===60||ne===61||ne===62||ne===96?n(ne):ne===34||ne===39?(s.consume(ne),a=ne,W):Fc(ne)?(l=U,X(ne)):nm(ne)?(s.consume(ne),U):(s.consume(ne),V)}function W(ne){return ne===a?(s.consume(ne),a=void 0,G):ne===null?n(ne):Fc(ne)?(l=W,X(ne)):(s.consume(ne),W)}function V(ne){return ne===null||ne===34||ne===39||ne===60||ne===61||ne===96?n(ne):ne===47||ne===62||Lw(ne)?R(ne):(s.consume(ne),V)}function G(ne){return ne===47||ne===62||Lw(ne)?R(ne):n(ne)}function Y(ne){return ne===62?(s.consume(ne),s.exit("htmlTextData"),s.exit("htmlText"),t):n(ne)}function X(ne){return s.exit("htmlTextData"),s.enter("lineEnding"),s.consume(ne),s.exit("lineEnding"),ae}function ae(ne){return nm(ne)?Kf(s,le,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(ne):le(ne)}function le(ne){return s.enter("htmlTextData"),l(ne)}}const lit={name:"labelEnd",resolveAll:$8n,resolveTo:U8n,tokenize:q8n},O8n={tokenize:V8n},z8n={tokenize:H8n},B8n={tokenize:G8n};function $8n(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 sw={continuation:{tokenize:szn},exit:rzn,name:"list",tokenize:tzn},J8n={partial:!0,tokenize:azn},ezn={partial:!0,tokenize:nzn};function tzn(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:kYe(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(N3e,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 kYe(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(eDe,r.interrupt?n:u,s.attempt(J8n,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 szn(s,t,n){const r=this;return r.containerState._closeFlow=void 0,s.check(eDe,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(ezn,t,l)(o))}function l(o){return r.containerState._closeFlow=!0,r.interrupt=void 0,Kf(s,s.attempt(sw,t,n),"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(o)}}function nzn(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 rzn(s){s.exit(this.containerState.type)}function azn(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 ASt={name:"setextUnderline",resolveTo:izn,tokenize:ozn};function izn(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 ozn(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 lzn={tokenize:czn};function czn(s){const t=this,n=s.attempt(eDe,r,s.attempt(this.parser.constructs.flowInitial,a,Kf(s,s.attempt(this.parser.constructs.flow,a,s.attempt(f8n,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 dzn={resolveAll:lQt()},uzn=oQt("string"),hzn=oQt("text");function oQt(s){return{resolveAll:lQt(s==="text"?mzn: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 Szn(s,t){let n=-1;const r=[];let a;for(;++n0){const ys=ss.tokenStack[ss.tokenStack.length-1];(ys[1]||TSt).call(ss,void 0,ys[0])}for(gt.position={start:NM(pt.length>0?pt[0][1].start:{line:1,column:1,offset:0}),end:NM(pt.length>0?pt[pt.length-2][1].end:{line:1,column:1,offset:0})},ts=-1;++ts0&&(r.className=["language-"+a[0]]);let i={type:"element",tagName:"code",properties:r,children:[{type:"text",value:n}]};return t.meta&&(i.data={meta:t.meta}),s.patch(t,i),i=s.applyData(t,i),i={type:"element",tagName:"pre",properties:{},children:[i]},s.patch(t,i),i}function Bzn(s,t){const n={type:"element",tagName:"del",properties:{},children:s.all(t)};return s.patch(t,n),s.applyData(t,n)}function $zn(s,t){const n={type:"element",tagName:"em",properties:{},children:s.all(t)};return s.patch(t,n),s.applyData(t,n)}function Uzn(s,t){const n=typeof s.options.clobberPrefix=="string"?s.options.clobberPrefix:"user-content-",r=String(t.identifier).toUpperCase(),a=DK(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 qzn(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 Vzn(s,t){if(s.options.allowDangerousHtml){const n={type:"raw",value:t.value};return s.patch(t,n),s.applyData(t,n)}}function uQt(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 Hzn(s,t){const n=String(t.identifier).toUpperCase(),r=s.definitionById.get(n);if(!r)return uQt(s,t);const a={src:DK(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 Gzn(s,t){const n={src:DK(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 Wzn(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 Kzn(s,t){const n=String(t.identifier).toUpperCase(),r=s.definitionById.get(n);if(!r)return uQt(s,t);const a={href:DK(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 Yzn(s,t){const n={href:DK(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?Xzn(n):hQt(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 Qzn(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=sit(t.children[1]),c=GXt(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 n7n(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(ISt(t.slice(a),a>0,!1)),i.join("")}function ISt(s,t,n){let r=0,a=s.length;if(t){let i=s.codePointAt(r);for(;i===MSt||i===PSt;)r++,i=s.codePointAt(r)}if(n){let i=s.codePointAt(a-1);for(;i===MSt||i===PSt;)a--,i=s.codePointAt(a-1)}return a>r?s.slice(r,a):""}function i7n(s,t){const n={type:"text",value:a7n(String(t.value))};return s.patch(t,n),s.applyData(t,n)}function o7n(s,t){const n={type:"element",tagName:"hr",properties:{},children:[]};return s.patch(t,n),s.applyData(t,n)}const l7n={blockquote:Fzn,break:Ozn,code:zzn,delete:Bzn,emphasis:$zn,footnoteReference:Uzn,heading:qzn,html:Vzn,imageReference:Hzn,image:Gzn,inlineCode:Wzn,linkReference:Kzn,link:Yzn,listItem:Zzn,list:Qzn,paragraph:Jzn,root:e7n,strong:t7n,table:s7n,tableCell:r7n,tableRow:n7n,text:i7n,thematicBreak:o7n,toml:Jde,yaml:Jde,definition:Jde,footnoteDefinition:Jde};function Jde(){}const mQt=-1,tDe=0,Yee=1,KMe=2,cit=3,dit=4,uit=5,hit=6,fQt=7,pQt=8,{defineProperty:c7n}=Object,gQt=typeof self=="object"?self:globalThis,LSt=(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 gQt[s](t)},d7n=(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 tDe:case mQt:return n(l,a);case Yee:{const o=n([],a);for(const c of l)o.push(r(c));return o}case KMe:{const o=n({},a);for(const[c,d]of l){const u=r(c),h=r(d);u==="__proto__"?c7n(o,u,{value:h,configurable:!0,enumerable:!0,writable:!0}):o[u]=h}return o}case cit:return n(new Date(l),a);case dit:{const{source:o,flags:c}=l;return n(new RegExp(o,c),a)}case uit:{const o=n(new Map,a);for(const[c,d]of l)o.set(r(c),r(d));return o}case hit:{const o=n(new Set,a);for(const c of l)o.add(r(c));return o}case fQt:{const{name:o,message:c}=l;return n(typeof gQt[o]=="function"?LSt(o,c):new Error(c),a)}case pQt: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(LSt(i,l),a)};return r},RSt=s=>d7n(new Map,s)(0),FO="",{toString:u7n}={},{keys:h7n,is:m7n}=Object,sX=s=>{const t=typeof s;if(t!=="object"||!s)return[tDe,t];const n=u7n.call(s).slice(8,-1);switch(n){case"Array":return[Yee,FO];case"Object":return[KMe,FO];case"Date":return[cit,FO];case"RegExp":return[dit,FO];case"Map":return[uit,FO];case"Set":return[hit,FO];case"DataView":return[Yee,n]}return n.includes("Array")?[Yee,n]:s instanceof Error?[fQt,s.name||"Error"]:[KMe,n]},eue=([s,t])=>s===tDe&&(t==="function"||t==="symbol"),f7n=(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]=sX(l);switch(o){case tDe:{let u=l;switch(c){case"bigint":o=pQt,u=l.toString();break;case"number":if(!l&&m7n(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([mQt],l)}return a([o,u],l)}case Yee:{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 KMe:{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 h7n(l))(s||!eue(sX(l[m])))&&u.push([i(m),i(l[m])]);return h}case cit:return a([o,isNaN(l.getTime())?FO:l.toISOString()],l);case dit:{const{source:u,flags:h}=l;return a([o,{source:u,flags:h}],l)}case uit:{const u=[],h=a([o,u],l);for(const[m,f]of l)(s||!(eue(sX(m))||eue(sX(f))))&&u.push([i(m),i(f)]);return h}case hit:{const u=[],h=a([o,u],l);for(const m of l)(s||!eue(sX(m)))&&u.push(i(m));return h}}const{message:d}=l;return a([o,{name:c,message:d}],l)};return i},DSt=(s,{json:t,lossy:n}={})=>{const r=[];return f7n(!(t||n),!!t,new Map,r)(s),r},YMe=typeof structuredClone=="function"?(s,t)=>t&&("json"in t||"lossy"in t)?RSt(DSt(s,t)):structuredClone(s):(s,t)=>RSt(DSt(s,t));function p7n(s,t){const n=[{type:"text",value:"↩"}];return t>1&&n.push({type:"element",tagName:"sup",properties:{},children:[{type:"text",value:String(t)}]}),n}function g7n(s,t){return"Back to reference "+(s+1)+(t>1?"-"+t:"")}function x7n(s){const t=typeof s.options.clobberPrefix=="string"?s.options.clobberPrefix:"user-content-",n=s.options.footnoteBackContent||p7n,r=s.options.footnoteBackLabel||g7n,a=s.options.footnoteLabel||"Footnotes",i=s.options.footnoteLabelTagName||"h2",l=s.options.footnoteLabelProperties||{className:["sr-only"]},o=[];let c=-1;for(;++c0&&g.push({type:"text",value:" "});let b=typeof n=="string"?n:n(c,f);typeof b=="string"&&(b={type:"text",value:b}),g.push({type:"element",tagName:"a",properties:{href:"#"+t+"fnref-"+m+(f>1?"-"+f:""),dataFootnoteBackref:"",ariaLabel:typeof r=="string"?r:r(c,f),className:["data-footnote-backref"]},children:Array.isArray(b)?b:[b]})}const y=u[u.length-1];if(y&&y.type==="element"&&y.tagName==="p"){const b=y.children[y.children.length-1];b&&b.type==="text"?b.value+=" ":y.children.push({type:"text",value:" "}),y.children.push(...g)}else u.push(...g);const v={type:"element",tagName:"li",properties:{id:t+"fn-"+m},children:s.wrap(u,!0)};s.patch(d,v),o.push(v)}if(o.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:i,properties:{...YMe(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 xQt=function(s){if(s==null)return _7n;if(typeof s=="function")return sDe(s);if(typeof s=="object")return Array.isArray(s)?y7n(s):v7n(s);if(typeof s=="string")return b7n(s);throw new Error("Expected function, string, or object as test")};function y7n(s){const t=[];let n=-1;for(;++n":""))+")"})}return m;function m(){let f=yQt,g,x,y;if((!t||i(c,d,u[u.length-1]||void 0))&&(f=S7n(n(c,u)),f[0]===FSt))return f;if("children"in c&&c.children){const v=c;if(v.children&&f[0]!==N7n)for(x=(r?v.children.length:-1)+l,y=u.concat(v);x>-1&&x0&&n.push({type:"text",value:` `}),n}function OSt(s){let t=0,n=s.charCodeAt(t);for(;n===9||n===32;)t++,n=s.charCodeAt(t);return s.slice(t)}function zSt(s,t){const n=A7n(s,t),r=n.one(s,void 0),a=x7n(n),i=Array.isArray(r)?{type:"root",children:r}:r||{type:"root",children:[]};return a&&i.children.push({type:"text",value:` `},a),i}function I7n(s,t){return s&&"run"in s?async function(n,r){const a=zSt(n,{file:r,...t});await s.run(a,r)}:function(n,r){return zSt(n,{file:r,...s||t})}}function BSt(s){if(s)throw s}var k3e=Object.prototype.hasOwnProperty,bQt=Object.prototype.toString,$St=Object.defineProperty,USt=Object.getOwnPropertyDescriptor,qSt=function(t){return typeof Array.isArray=="function"?Array.isArray(t):bQt.call(t)==="[object Array]"},VSt=function(t){if(!t||bQt.call(t)!=="[object Object]")return!1;var n=k3e.call(t,"constructor"),r=t.constructor&&t.constructor.prototype&&k3e.call(t.constructor.prototype,"isPrototypeOf");if(t.constructor&&!n&&!r)return!1;var a;for(a in t);return typeof a>"u"||k3e.call(t,a)},HSt=function(t,n){$St&&n.name==="__proto__"?$St(t,n.name,{enumerable:!0,configurable:!0,value:n.newValue,writable:!0}):t[n.name]=n.newValue},GSt=function(t,n){if(n==="__proto__")if(k3e.call(t,n)){if(USt)return USt(t,n).value}else return;return t[n]},L7n=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 k5={basename:F7n,dirname:O7n,extname:z7n,join:B7n,sep:"/"};function F7n(s,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');Pie(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 O7n(s){if(Pie(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 z7n(s){Pie(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 B7n(...s){let t=-1,n;for(;++t0&&s.codePointAt(s.length-1)===47&&(n+="/"),t?"/"+n:n}function U7n(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 Pie(s){if(typeof s!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(s))}const q7n={cwd:V7n};function V7n(){return"/"}function EYe(s){return!!(s!==null&&typeof s=="object"&&"href"in s&&s.href&&"protocol"in s&&s.protocol&&s.auth===void 0)}function H7n(s){if(typeof s=="string")s=new URL(s);else if(!EYe(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 G7n(s)}function G7n(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];AYe(x)&&AYe(f)&&(f=O9e(!0,x,f)),r[m]=[d,f,...g]}}}}const Z7n=new mit().freeze();function U9e(s,t){if(typeof t!="function")throw new TypeError("Cannot `"+s+"` without `parser`")}function q9e(s,t){if(typeof t!="function")throw new TypeError("Cannot `"+s+"` without `compiler`")}function V9e(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 KSt(s){if(!AYe(s)||typeof s.type!="string")throw new TypeError("Expected node, got `"+s+"`")}function YSt(s,t,n){if(!n)throw new Error("`"+s+"` finished async. Use `"+t+"` instead")}function tue(s){return X7n(s)?s:new _Qt(s)}function X7n(s){return!!(s&&typeof s=="object"&&"message"in s&&"messages"in s)}function Q7n(s){return typeof s=="string"||J7n(s)}function J7n(s){return!!(s&&typeof s=="object"&&"byteLength"in s&&"byteOffset"in s)}const eBn="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",ZSt=[],XSt={allowDangerousHtml:!0},tBn=/^(https?|ircs?|mailto|xmpp)$/i,sBn=[{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 nBn(s){const t=rBn(s),n=aBn(s);return iBn(t.runSync(t.parse(n),n),s)}function rBn(s){const t=s.rehypePlugins||ZSt,n=s.remarkPlugins||ZSt,r=s.remarkRehypeOptions?{...s.remarkRehypeOptions,...XSt}:XSt;return Z7n().use(Dzn).use(n).use(I7n,r).use(t)}function aBn(s){const t=s.children||"",n=new _Qt;return typeof t=="string"&&(n.value=t),n}function iBn(s,t){const n=t.allowedElements,r=t.allowElement,a=t.components,i=t.disallowedElements,l=t.skipHtml,o=t.unwrapDisallowed,c=t.urlTransform||oBn;for(const u of sBn)Object.hasOwn(t,u.from)&&(""+u.from+(u.to?"use `"+u.to+"` instead":"remove it")+eBn+u.id,void 0);return vQt(s,d),pOn(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 R9e)if(Object.hasOwn(R9e,f)&&Object.hasOwn(u.properties,f)){const g=u.properties[f],x=R9e[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 oBn(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||tBn.test(s.slice(0,t))?s:""}const lBn={a:({href:s,children:t})=>{const n=s||"",r=n.startsWith("/"),a="inline-flex items-center gap-1 rounded-md bg-primary/10 px-1.5 py-0.5 font-medium text-primary no-underline transition-colors hover:bg-primary/20";return r?e.jsxs(wr,{to:n,className:a,children:[t,e.jsx(Lz,{className:"h-3 w-3"})]}):e.jsxs("a",{href:n,target:"_blank",rel:"noopener noreferrer",className:a,children:[t,e.jsx(Lz,{className:"h-3 w-3"})]})}},cBn=["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 dBn(){var h,m,f;const{user:s}=bs(),[t,n]=j.useState([]),[r,a]=j.useState(""),[i,l]=j.useState(!1),o=j.useRef(null),c=j.useRef(null),d=((h=s==null?void 0:s.user_metadata)==null?void 0:h.first_name)||((f=(m=s==null?void 0:s.user_metadata)==null?void 0:m.full_name)==null?void 0:f.split(" ")[0])||"";j.useEffect(()=>{var g;(g=c.current)==null||g.scrollTo({top:c.current.scrollHeight,behavior:"smooth"})},[t,i]);const u=async g=>{var b;const x=g.trim();if(!x||i)return;const y=[...t,{role:"user",content:x}];n([...y,{role:"assistant",content:""}]),a(""),l(!0);const v=new AbortController;o.current=v;try{const{data:w}=await q.auth.getSession(),S=(b=w.session)==null?void 0:b.access_token,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:y,agentName:d}),signal:v.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 Y=JSON.parse(G);Y.delta&&(R+=Y.delta,n(X=>{const ae=[...X];return ae[ae.length-1]={role:"assistant",content:R},ae}))}catch{}}}R||n(D=>{const O=[...D];return O[O.length-1]={role:"assistant",content:"I didn't catch that — mind asking again?"},O})}catch(w){w.name==="AbortError"?n(S=>S.filter((A,E)=>!(E===S.length-1&&!A.content))):(re.error(w.message||"The assistant is unavailable right now."),n(S=>S.slice(0,-1)))}finally{l(!1),o.current=null}};return e.jsx(Vs,{children:e.jsxs("div",{className:"mx-auto flex h-[calc(100vh-7rem)] w-full max-w-3xl flex-col p-4 md:p-6",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"flex h-10 w-10 items-center justify-center rounded-xl bg-primary/10",children:e.jsx(E4,{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(Ax,{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(E4,{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:cBn.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(nBn,{components:lBn,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(Ls,{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(j_,{className:"h-4 w-4"})}):e.jsx($,{size:"icon",disabled:!r.trim(),onClick:()=>u(r),children:e.jsx(Kr,{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 uBn({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 sue({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 hBn({agentName:s,todayDone:t,todayTotal:n,focusLine:r,weekDone:a,weekGoal:i,streak:l,staleCount:o,sphereCount:c,onEditGoal:d,onStaleClick:u,onSphereClick:h}){const m=new Date().getHours(),f=m<12?"Good morning":m<17?"Good afternoon":"Good evening",g=i>0?Math.min(100,Math.round(a/i*100)):0;return e.jsxs("div",{className:"grid gap-4 lg:grid-cols-[minmax(0,1.15fr)_minmax(0,1fr)]",children:[e.jsxs("div",{className:"relative overflow-hidden rounded-2xl border bg-gradient-to-br from-primary/[0.07] via-card to-card p-5 sm:p-6",children:[e.jsx("div",{className:"pointer-events-none absolute -right-16 -top-16 h-48 w-48 rounded-full bg-primary/10 blur-3xl"}),e.jsxs("div",{className:"relative flex flex-col-reverse items-start gap-5 sm:flex-row sm:items-center",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-primary",children:[f,s?`, ${s}`:""]}),e.jsx("h2",{className:"mt-1.5 text-xl font-semibold leading-snug sm:text-2xl",children:n===0?"Your day is clear — pick a few people to reconnect with.":t>=n?"Today's list is done. That's how referrals get built.":`${n-t} ${n-t===1?"touch":"touches"} left to stay on track.`}),e.jsxs("p",{className:"mt-2 flex items-start gap-1.5 text-sm text-muted-foreground",children:[e.jsx(Nn,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-primary"}),e.jsx("span",{children:r})]})]}),e.jsx(uBn,{done:t,total:n})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(sue,{icon:e.jsx(nh,{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(sue,{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(sue,{icon:e.jsx(da,{className:"h-3.5 w-3.5 text-amber-500"}),label:"Going cold",value:String(o),hint:"No contact in 90+ days",tone:o>0?"alert":"default",onClick:u}),e.jsx(sue,{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 QSt="agent-os-onboarding-completed",nue=[{icon:qg,iconColor:"text-white",bgGradient:"from-primary via-primary/80 to-purple-600",title:"Welcome to Agent OS",description:"You've unlocked a powerful new tool designed to help you build stronger relationships and close more deals. Agent OS is currently in beta, and we're excited for you to try it!",highlights:["Manage your most important relationships","Stay in touch with automated reminders","Track your transactions and goals","Maximize referrals from your sphere"]},{icon:eg,iconColor:"text-white",bgGradient:"from-pink-500 via-rose-500 to-red-500",title:"InnerCircle Home",description:"Your daily command center. See today's action items, track your momentum streak, and get a snapshot of your relationship health—all at a glance.",highlights:["Today's touchpoints and special dates","Momentum stats and streak tracking","Relationship health overview","Quick access to all features"]},{icon: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:ul,iconColor:"text-white",bgGradient:"from-orange-500 via-amber-500 to-yellow-500",title:"Popbys",description:"Pop-by visits are one of the most powerful ways to stay top-of-mind. Track your gift drop-offs and see who's due for a visit on the map.",highlights:["Track pop-by gift ideas","Set visit frequency by contact type","Log completed pop-bys","Map view for route planning"]},{icon: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"]}],mBn=()=>{const[s,t]=j.useState(!1),[n,r]=j.useState(0),[a,i]=j.useState(!1);j.useEffect(()=>{if(!localStorage.getItem(QSt)){const g=setTimeout(()=>t(!0),500);return()=>clearTimeout(g)}},[]);const l=()=>{n{r(n+1),i(!1)},150)):c()},o=()=>{c()},c=()=>{localStorage.setItem(QSt,"true"),t(!1)},d=nue[n],u=d.icon,h=n===nue.length-1,m=f=>{f||c(),t(f)};return e.jsx(zs,{open:s,onOpenChange:m,children:e.jsxs(Os,{className:"sm:max-w-lg overflow-hidden p-0 gap-0",children:[e.jsxs("div",{className:`relative bg-gradient-to-br ${d.bgGradient} p-8 pb-12 transition-all duration-500`,children:[e.jsxs("div",{className:"absolute inset-0 overflow-hidden",children:[e.jsx("div",{className:"absolute -top-4 -right-4 w-32 h-32 bg-white/10 rounded-full blur-2xl animate-pulse"}),e.jsx("div",{className:"absolute -bottom-8 -left-8 w-40 h-40 bg-white/10 rounded-full blur-3xl animate-pulse",style:{animationDelay:"1s"}}),e.jsx("div",{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-64 h-64 bg-white/5 rounded-full blur-3xl"})]}),e.jsxs("div",{className:`relative mx-auto flex h-20 w-20 items-center justify-center transition-all duration-300 ${a?"scale-75 opacity-0":"scale-100 opacity-100"}`,children:[e.jsx("div",{className:"absolute inset-0 bg-white/20 rounded-2xl blur-xl"}),e.jsx("div",{className:"relative flex h-20 w-20 items-center justify-center rounded-2xl bg-white/20 backdrop-blur-sm border border-white/30 shadow-2xl",children:e.jsx(u,{className:`h-10 w-10 ${d.iconColor} drop-shadow-lg`})})]}),n===0&&e.jsxs("div",{className:"absolute top-4 right-4 px-3 py-1 rounded-full bg-white/20 backdrop-blur-sm border border-white/30 text-white text-xs font-medium flex items-center gap-1.5",children:[e.jsx(Nn,{className:"h-3 w-3"}),"Beta"]})]}),e.jsxs("div",{className:"p-6 pt-4",children:[e.jsxs(Us,{className:"text-center sm:text-center pb-2",children:[e.jsx(Bs,{className:`text-2xl font-bold transition-all duration-300 ${a?"translate-y-2 opacity-0":"translate-y-0 opacity-100"}`,children:d.title}),e.jsx(Pr,{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(ca,{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:nue.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}=bs();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})},pBn=()=>{const s=Wt(),{user:t}=bs();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"})}})},gBn=()=>{const s=Wt();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"})}})},xBn=[{label:"1 week",days:7},{label:"2 weeks",days:14},{label:"1 month",days:30}];function nDe({open:s,onOpenChange:t,contactId:n,contactName:r}){const[a,i]=j.useState(null),l=pBn(),o=async()=>{a&&(await l.mutateAsync({contactId:n,days:a}),i(null),t(!1))},c=d=>en(Am(new Date,d),"MMM d, yyyy");return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(da,{className:"h-5 w-5"}),"Snooze Touch"]}),e.jsxs(Pr,{children:["Postpone the next scheduled touch for ",r,". Select how long to snooze."]})]}),e.jsx("div",{className:"space-y-3 py-4",children:xBn.map(d=>e.jsxs("button",{type:"button",onClick:()=>i(d.days),className:Pt("w-full flex items-center justify-between p-3 rounded-lg border transition-colors",a===d.days?"border-primary bg-primary/5":"border-border hover:border-primary/50 hover:bg-accent/50"),children:[e.jsx("span",{className:"font-medium",children:d.label}),e.jsxs("span",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[e.jsx(Ta,{className:"h-3.5 w-3.5"}),"Until ",c(d.days)]})]},d.days))}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx($,{onClick:o,disabled:!a||l.isPending,children:l.isPending?"Snoozing...":"Snooze Touch"})]})]})})}const yBn={Crown:Bg,FileText:Jr,Users:Yn,Globe:dl,Star:ei,Phone:Da,MessageSquare:eo,PenTool:IE,Video:ua,Gift:ul};function vBn({actions:s,onMarkComplete:t,onViewScript:n,isLoading:r,buildSmsLink:a,buildEmailLink:i,onGmailCompose:l}){const o=Xn(),[c,d]=j.useState("name"),[u,h]=j.useState("asc"),[m,f]=j.useState(null),[g,x]=j.useState(""),y=A=>{c===A?h(E=>E==="asc"?"desc":"asc"):(d(A),h("asc"))},v=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=>yBn[A||"Phone"]||Da,w=({field:A,children:E})=>e.jsxs($,{variant:"ghost",size:"sm",className:"h-8 -ml-3 font-medium",onClick:()=>y(A),children:[E,c===A?u==="asc"?e.jsx(Zf,{className:"ml-2 h-4 w-4"}):e.jsx(Dg,{className:"ml-2 h-4 w-4"}):e.jsx(zy,{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(En,{className:"bg-muted/50",children:[e.jsx(Dt,{className:"w-[180px]",children:e.jsx(w,{field:"name",children:"Contact"})}),e.jsx(Dt,{className:"w-[130px]",children:e.jsx(w,{field:"relationship_type",children:"Type"})}),e.jsx(Dt,{className:"w-[120px]",children:e.jsx(w,{field:"action_type",children:"Action"})}),e.jsx(Dt,{className:"w-[130px]",children:"Phone"}),e.jsx(Dt,{className:"w-[200px]",children:"Quick Actions"})]})}),e.jsx(fi,{children:v.map((A,E)=>{var U,W,V,G,Y,X;const I=A.isSpecialDate,P=A.specialDateType,R=I?P==="birthday"?Fg:va:b(((U=A.actionType)==null?void 0:U.icon)||null),D=A.contact.phone,O=A.contact.email;return e.jsxs(En,{className:Pt("hover:bg-muted/50 transition-colors",I&&P==="birthday"&&"bg-pink-50/50 dark:bg-pink-950/20",I&&P==="anniversary"&&"bg-purple-50/50 dark:bg-purple-950/20"),children:[e.jsx(_t,{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(_t,{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(_t,{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(Fg,{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(_t,{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(_t,{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(eo,{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(mn,{className:"h-3.5 w-3.5"})}):e.jsx("a",{href:i(A.contact.email,(G=A.script)==null?void 0:G.script_body,(Y=A.script)==null?void 0:Y.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(mn,{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",ne=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?${ne.toString()}`)},className:Pt("h-7 px-2 rounded text-xs font-semibold flex items-center gap-1 transition-colors",P==="birthday"?"bg-pink-500/15 hover:bg-pink-500/25 text-pink-600 dark:text-pink-400":"bg-purple-500/15 hover:bg-purple-500/25 text-purple-600 dark:text-purple-400"),title:`Send ${P==="birthday"?"Birthday":"Anniversary"} Card`,children:[e.jsx(mn,{className:"h-3.5 w-3.5"}),"Send Card"]}),e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-foreground",onClick:()=>S(A.contact.id,A.contact.first_name,A.contact.last_name),title:"Snooze",children:e.jsx(Av,{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(nDe,{open:!!m,onOpenChange:A=>!A&&f(null),contactId:m||"",contactName:g})]})}function bBn(){const s=Xn(),{data:t}=AUt(),{data:n}=tie(),r=b6e(),{isGmailConnected:a,gmailEmail:i}=gy(),[l,o]=j.useState(null),[c,d]=j.useState(!1),[u,h]=j.useState(new Set),m=Mg(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)||R4(I,m)&&rC(I,f))&&A.push({contact:E,type:"birthday",date:I,daysUntil:ub(I,m),dateStr:E.birthday})}if(E.home_anniversary){const I=g(E.home_anniversary);I&&(sf(I,m)||R4(I,m)&&rC(I,f))&&A.push({contact:E,type:"anniversary",date:I,daysUntil:ub(I,m),dateStr:E.home_anniversary})}if(E.wedding_anniversary){const I=g(E.wedding_anniversary);I&&(sf(I,m)||R4(I,m)&&rC(I,f))&&A.push({contact:E,type:"wedding_anniversary",date:I,daysUntil:ub(I,m),dateStr:E.wedding_anniversary})}}return A.sort((E,I)=>E.daysUntil-I.daysUntil),A},[t]),y=A=>A==="birthday"?"Birthday":A==="wedding_anniversary"?"Wedding Anniversary":"Home Anniversary",v=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:`${y(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(Ie,{className:"space-y-2",children:[x.length===0&&e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Fg,{className:"h-8 w-8 mx-auto mb-2 opacity-40"}),e.jsx("p",{className:"text-sm",children:"No birthdays or anniversaries in the next 30 days."}),e.jsx("p",{className:"text-xs mt-1",children:"Add dates to your contacts to see upcoming milestones here."})]}),x.map((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(Fg,{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:en(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(eo,{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(mn,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"Record video",onClick:()=>s(`/mission-control/video/record?contactId=${A.contact.id}`),children:e.jsx(ua,{className:"h-3.5 w-3.5"})}),e.jsxs($,{variant:"ghost",size:"sm",className:Pt("h-7 px-2 gap-1 text-xs",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(Nn,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Card"})]}),e.jsx($,{variant:"ghost",size:"icon",className:Pt("h-7 w-7",P&&"text-green-600"),title:"Log a touch",disabled:P||r.isPending,onClick:()=>v(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(Ca,{className:"h-3.5 w-3.5"})})]})]},`${I}-${E}`)})]})]}),a&&l&&e.jsx(kk,{open:c,onOpenChange:d,contact:l,gmailEmail:i})]})}function _Bn(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 y=u.find(v=>v.auth_user_id===x.user_id);y&&!y.contact_id&&x.contact_id&&(y.contact_id=x.contact_id),y&&!m[y.contact_id||""]&&x.name&&(m[y.contact_id||y.auth_user_id||""]={first_name:x.name.split(" ")[0],last_name:x.name.split(" ").slice(1).join(" ")||null,email:null,phone:x.phone})})}return u.map(g=>{var x,y;return{...g,contact_name:m[g.contact_id||g.auth_user_id||""]?`${m[g.contact_id||g.auth_user_id||""].first_name} ${m[g.contact_id||g.auth_user_id||""].last_name||""}`.trim():null,contact_email:((x=m[g.contact_id||g.auth_user_id||""])==null?void 0:x.email)||null,contact_phone:((y=m[g.contact_id||g.auth_user_id||""])==null?void 0:y.phone)||null}})},enabled:!!s,refetchInterval:6e4});j.useEffect(()=>{if(!s)return;const u=q.channel(`active-visitors-${s}`).on("postgres_changes",{event:"*",schema:"public",table:"lead_site_active_visitors",filter:`lead_site_id=eq.${s}`},h=>{h.eventType==="INSERT"?n(m=>m.find(g=>g.id===h.new.id)?m:[h.new,...m]):h.eventType==="UPDATE"?n(m=>m.map(f=>f.id===h.new.id?{...f,...h.new}:f)):h.eventType==="DELETE"&&n(m=>m.filter(f=>f.id!==h.old.id))}).subscribe(h=>{h==="SUBSCRIBED"&&a(!0)});return()=>{q.removeChannel(u)}},[s]);const o=r&&t.length>0?wBn([...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 wBn(s){const t=new Set;return s.filter(n=>t.has(n.id)?!1:(t.add(n.id),!0))}const jBn={property_view:{label:"Viewed",icon:Ca,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 NBn(){const{user:s}=bs(),t=Xn(),{isGmailConnected:n,gmailEmail:r}=gy(),{leadSite:a}=ng(),{count:i}=_Bn(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:v,error:b}=await q.rpc("get_lead_site_activity",{_user_id:s.id});if(b)throw b;return v},enabled:!!s,refetchInterval:6e4});if(h||!(u!=null&&u.has_site))return null;const m=(u.activities||[]).filter(v=>v.visitor_name&&v.visitor_name!=="Site Visitor"),f=m.filter(v=>v.activity_type==="new_lead"),g=(u.activities||[]).filter(v=>v.activity_type==="property_view").length,x=(u.activities||[]).filter(v=>v.activity_type==="saved_listing").length,y=v=>{if(v.visitor_email)if(n){const b=(v.visitor_name||"").split(" ");d({id:v.contact_id||"",first_name:b[0]||"",last_name:b.slice(1).join(" ")||null,email:v.visitor_email}),o(!0)}else window.location.href=`mailto:${v.visitor_email}`};return e.jsxs("section",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"p-1.5 bg-primary/10 rounded-lg",children:e.jsx(dl,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Website Activity"}),i>0&&e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 text-[11px] font-semibold",children:[e.jsxs("span",{className:"relative flex h-1.5 w-1.5",children:[e.jsx("span",{className:"animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75"}),e.jsx("span",{className:"relative inline-flex rounded-full h-1.5 w-1.5 bg-emerald-500"})]}),i," Live"]})]})]}),e.jsxs($,{variant:"ghost",size:"sm",className:"text-primary gap-1",onClick:()=>t("/mission-control/website-activity"),children:["View All",e.jsx(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(Ca,{className:"h-4 w-4 text-blue-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-bold text-blue-600 dark:text-blue-400",children:g}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Views"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 p-3 rounded-lg bg-rose-500/5 border border-rose-200 dark:border-rose-800",children:[e.jsx(Jo,{className:"h-4 w-4 text-rose-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-bold text-rose-600 dark:text-rose-400",children:x}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Saved"})]})]})]}),m.length>0?e.jsxs("div",{className:"space-y-2",children:[m.slice(0,5).map((v,b)=>{const w=jBn[v.activity_type],S=w.icon,A=hu(new Date(v.occurred_at),{addSuffix:!0});return e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border bg-card hover:shadow-sm transition-shadow",children:[e.jsx("div",{className:`p-1.5 rounded-md ${w.bgColor}`,children:e.jsx(S,{className:`h-3.5 w-3.5 ${w.color}`})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("button",{className:"font-medium text-sm text-primary hover:underline text-left truncate block",onClick:()=>{v.contact_id&&t(`/mission-control/contacts/${v.contact_id}`)},children:v.visitor_name}),e.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-muted-foreground",children:[e.jsx("span",{children:w.label}),v.mls_number&&e.jsxs("span",{children:["· MLS# ",v.mls_number]}),v.lead_type&&e.jsxs("span",{children:["· ",v.lead_type]}),e.jsxs("span",{children:["· ",A]})]})]}),e.jsxs("div",{className:"flex items-center gap-0.5 shrink-0",children:[v.visitor_email&&e.jsx($,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-primary",onClick:()=>y(v),children:e.jsx(mn,{className:"h-3.5 w-3.5"})}),v.visitor_phone&&e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-primary",onClick:()=>window.location.href=`tel:${v.visitor_phone}`,children:e.jsx(Da,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-primary",onClick:()=>window.location.href=`sms:${v.visitor_phone}`,children:e.jsx(eo,{className:"h-3.5 w-3.5"})})]}),v.contact_id&&e.jsx($,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>t(`/mission-control/contacts/${v.contact_id}`),children:e.jsx(Di,{className:"h-3.5 w-3.5"})})]})]},`${v.activity_type}-${v.occurred_at}-${b}`)}),m.length>5&&e.jsxs($,{variant:"outline",className:"w-full text-xs",onClick:()=>t("/mission-control/website-activity"),children:["View ",m.length-5," more activities",e.jsx(Qa,{className:"h-3.5 w-3.5 ml-1"})]})]}):e.jsx(je,{children:e.jsxs(Ie,{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(kk,{open:l,onOpenChange:o,contact:c,gmailEmail:r})]})}const JSt={Crown:Bg,FileText:Jr,Users:Yn,Globe:dl,Star:ei,Phone:Da,MessageSquare:eo,PenTool:IE,Video:ua,Gift:ul},kBn={"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 SBn(){var pt,gt,ss,Yt,ts,ys;const s=Xn(),{user:t}=bs(),{data:n}=qw(),{data:r}=EUt(),{data:a}=R_(),{data:i}=tie(),{data:l}=ent(),o=BHs(),c=_6e(),d=FHs(90),u=b6e(),[h,m]=j.useState(null),[f,g]=j.useState(null),[x,y]=j.useState(!1),[v,b]=j.useState(""),[w,S]=j.useState(!1),[A,E]=j.useState(""),[I,P]=j.useState(LUt()),[R,D]=j.useState("cards"),[O,U]=j.useState(!1),[W,V]=j.useState(null),[G,Y]=j.useState(null),[X,ae]=j.useState(""),{isGmailConnected:le,gmailEmail:ne}=gy(),te=()=>{const Bt=parseInt(A,10);if(isNaN(Bt)||Bt<1){_a({title:"Invalid goal",description:"Please enter a number greater than 0",variant:"destructive"});return}P(Bt),OHs(Bt),S(!1),_a({title:"Goal updated",description:`Weekly touch goal set to ${Bt}`})},J=()=>{E(I.toString()),S(!0)};j.useEffect(()=>{(async()=>{if(!(t!=null&&t.id))return;const{data:Ft}=await q.from("profiles").select("name").eq("id",t.id).single();Ft!=null&&Ft.name&&b(Ft.name.split(" ")[0])})()},[t==null?void 0:t.id]),j.useEffect(()=>{o.mutate()},[]);const ce=Mg(new Date),_e=Am(ce,7),he=Bt=>{if(!Bt)return null;const Ft=Bt.split(/[-/T]/);if(Ft.length<3)return null;const as=parseInt(Ft[1],10)-1,kt=parseInt(Ft[2],10);return isNaN(as)||isNaN(kt)?null:new Date(ce.getFullYear(),as,kt)},ue=(a==null?void 0:a.filter(Bt=>{const Ft=he(Bt.birthday),as=he(Bt.home_anniversary);return Ft&&sf(Ft,ce)||as&&sf(as,ce)}))||[],ve=(a==null?void 0:a.filter(Bt=>{if(!Bt.birthday&&!Bt.home_anniversary)return!1;const Ft=as=>{if(!as)return!1;const kt=he(as);return kt?R4(kt,ce)&&rC(kt,_e):!1};return Ft(Bt.birthday)||Ft(Bt.home_anniversary)}).slice(0,5))||[],Ee=[],Se=(i==null?void 0:i.find(Bt=>Bt.name==="Call"))||(i==null?void 0:i[0]);for(const Bt of ue){const Ft=he(Bt.birthday),as=he(Bt.home_anniversary),kt=Ft&&sf(Ft,ce),Ks=as&&sf(as,ce);kt&&Ee.push({contact:Bt,actionType:Se||{id:"special-date-birthday",name:"Birthday Call",icon:"Cake",color:"#EC4899",description:"Wish them happy birthday!",active:!0,sort_order:0,created_at:"",updated_at:""},planName:"🎂 Birthday Today!",relationshipTypeName:((ss=(gt=(pt=Bt.tags)==null?void 0:pt[0])==null?void 0:gt.relationship_type)==null?void 0:ss.name)||"",monthNumber:0,isSpecialDate:!0,specialDateType:"birthday"}),Ks&&Ee.push({contact:Bt,actionType:Se||{id:"special-date-anniversary",name:"Anniversary Call",icon:"Home",color:"#8B5CF6",description:"Celebrate their home anniversary!",active:!0,sort_order:0,created_at:"",updated_at:""},planName:"🏠 Home Anniversary!",relationshipTypeName:((ys=(ts=(Yt=Bt.tags)==null?void 0:Yt[0])==null?void 0:ts.relationship_type)==null?void 0:ys.name)||"",monthNumber:0,isSpecialDate:!0,specialDateType:"anniversary"})}const Fe=l!==void 0?l||[]:(a==null?void 0:a.slice(0,5).map((Bt,Ft)=>{var kt,Ks,wt;const as=i==null?void 0:i[Ft%((i==null?void 0:i.length)||1)];return as?{contact:Bt,actionType:as,planName:"Quick Touch",relationshipTypeName:((wt=(Ks=(kt=Bt.tags)==null?void 0:kt[0])==null?void 0:Ks.relationship_type)==null?void 0:wt.name)||"",monthNumber:0}:null}).filter(Boolean))||[],ke=[...Ee,...Fe],{data:Be}=uK(7),Ne=(Be||[]).filter(Bt=>sf(new Date(Bt.completed_at),ce)).length,Ae=Ne+ke.length,Ce=(a==null?void 0:a.length)??0,Ve=Ee.length>0?`${Ee.length} celebration${Ee.length===1?"":"s"} today — a card or a call goes a long way.`:d.count>0?`${d.count} people haven't heard from you in 90+ days. Start with one.`:ve.length>0?`${ve.length} milestone${ve.length===1?"":"s"} coming up this week — get ahead of them.`:"Consistency beats intensity. A few real conversations today is a win.",ze=async(Bt,Ft,as)=>{await u.mutateAsync({contactId:Bt,actionTypeId:Ft,scriptUsedId:as}),y(!1),g(null)},qe=Bt=>{Bt.script?(g(Bt),y(!0)):ze(Bt.contact.id,Bt.actionType.id)},dt=Bt=>JSt[Bt||"Phone"]||Da,Xe=Bt=>JSt[Bt||"Users"]||Yn,at=(Bt,Ft)=>Bt.replace(/\{\{FirstName\}\}/g,Ft.first_name).replace(/\{\{LastName\}\}/g,Ft.last_name||"").replace(/\{\{AgentName\}\}/g,v||"there"),rt=(Bt,Ft)=>({Call:`Thinking of you, ${Ft}!`,Text:`Quick hello, ${Ft}`,Email:`Checking in, ${Ft}`,"Handwritten Note":`A note for ${Ft}`,Video:`Video message for ${Ft}`,Gift:`Something special for you, ${Ft}`})[Bt]||`Hello ${Ft}!`,Ke=(Bt,Ft,as)=>{const kt=`sms:${Bt}`;if(Ft&&as){const Ks=at(Ft,as);return`${kt}?body=${encodeURIComponent(Ks)}`}return kt},Je=(Bt,Ft,as,kt,Ks)=>{const wt=`mailto:${Bt}`,gs=[];if(Ks){const ks=as||rt(kt||"Email",Ks.first_name);if(gs.push(`subject=${encodeURIComponent(ks)}`),Ft){const Is=at(Ft,Ks);gs.push(`body=${encodeURIComponent(Is)}`)}}return gs.length>0?`${wt}?${gs.join("&")}`:wt};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(ua,{className:"h-4 w-4"}),"Library"]}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>s("/mission-control/plans"),className:"gap-1.5",children:[e.jsx(Nd,{className:"h-4 w-4"}),"Plans"]})]})]}),e.jsx(hBn,{agentName:v,todayDone:Ne,todayTotal:Ae,focusLine:Ve,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(NBn,{}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between gap-2",children:[e.jsx("h2",{className:"text-sm font-semibold uppercase tracking-wide text-muted-foreground",children:"Your Sphere"}),e.jsxs("button",{onClick:()=>s("/mission-control/contacts"),className:"inline-flex items-center gap-1 text-xs font-medium text-primary hover:underline",children:["View all ",e.jsx(Di,{className:"h-3 w-3"})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:n==null?void 0:n.filter(Bt=>Bt.active).map(Bt=>{const Ft=Xe(Bt.icon),as=(r==null?void 0:r[Bt.id])||0,kt=h===Bt.id,Ks=kBn[Bt.name]||"bg-secondary text-secondary-foreground";return e.jsxs("button",{onClick:()=>{kt?(m(null),s("/mission-control/contacts")):(m(Bt.id),s(`/mission-control/contacts?type=${Bt.id}`))},className:` inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-sm transition-all ${kt?Ks:"bg-card hover:bg-accent"} `,children:[e.jsx(Ft,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"font-medium",children:Bt.name}),e.jsx("span",{className:`rounded-full px-1.5 py-0.5 text-[11px] tabular-nums ${kt?"bg-black/15":"bg-muted text-muted-foreground"}`,children:as})]},Bt.id)})})]}),e.jsxs("section",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"Today in Your InnerCircle"}),l!==void 0&&e.jsxs($e,{variant:"outline",className:"gap-1",children:[e.jsx(Nn,{className:"h-3 w-3"}),"Plan-based"]}),e.jsxs("div",{className:"ml-auto flex items-center gap-1 border rounded-lg p-0.5",children:[e.jsx($,{variant:R==="cards"?"secondary":"ghost",size:"sm",className:"h-7 px-2",onClick:()=>D("cards"),title:"Card view",children:e.jsx(Qf,{className:"h-4 w-4"})}),e.jsx($,{variant:R==="table"?"secondary":"ghost",size:"sm",className:"h-7 px-2",onClick:()=>D("table"),title:"Table view",children:e.jsx(T0,{className:"h-4 w-4"})})]})]}),e.jsx(je,{children:e.jsx(Ie,{className:"p-4",children:ke.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx("p",{children:"No actions scheduled for today."}),e.jsx("p",{className:"text-sm mt-1",children:"Add contacts and enable touchpoint plans to get started."}),e.jsx($,{variant:"outline",className:"mt-4",onClick:()=>s("/mission-control/plans"),children:"Manage Plans"})]}):R==="table"?e.jsx(vBn,{actions:ke,onMarkComplete:ze,onViewScript:qe,isLoading:u.isPending,buildSmsLink:Ke,buildEmailLink:Je,onGmailCompose:le?Bt=>{V(Bt),U(!0)}:void 0}):e.jsxs("div",{className:"flex gap-3 overflow-x-auto pb-2",children:[ke.map((Bt,Ft)=>{var Xs,ds,Ss,yn,Js,Ut,hn;const as=Bt.isSpecialDate,kt=Bt.specialDateType,Ks=as?kt==="birthday"?Fg:va:dt(((Xs=Bt.actionType)==null?void 0:Xs.icon)||null),wt=Bt.contact.phone,gs=Bt.contact.email,ks=as?kt==="birthday"?"#EC4899":"#8B5CF6":((ds=Bt.actionType)==null?void 0:ds.color)||"#3B82F6",Is=as?kt==="birthday"?"🎂 Birthday Today!":"🏠 Home Anniversary!":(Ss=Bt.actionType)==null?void 0:Ss.name;return e.jsxs("div",{className:`flex-shrink-0 w-[260px] border rounded-lg overflow-hidden ${as?"ring-2 ring-offset-2":""}`,style:as?{"--tw-ring-color":ks}:void 0,children:[e.jsxs("div",{className:"p-3 text-white flex items-center gap-2",style:{backgroundColor:ks},children:[e.jsx(Ks,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium text-sm",children:Is})]}),e.jsxs("div",{className:"p-3 space-y-2",children:[e.jsxs("button",{onClick:()=>s(`/mission-control/contacts/${Bt.contact.id}`),className:"font-medium text-sm hover:text-primary hover:underline transition-colors text-left",children:[Bt.contact.first_name," ",Bt.contact.last_name]}),e.jsxs("div",{className:"flex gap-1.5",children:[wt&&e.jsxs(e.Fragment,{children:[e.jsxs("a",{href:`tel:${Bt.contact.phone}`,className:"flex-1 flex items-center justify-center gap-1 px-2 py-1.5 bg-primary/10 hover:bg-primary/20 text-primary rounded text-xs font-medium transition-colors",title:"Call",children:[e.jsx(Da,{className:"h-3 w-3"}),"Call"]}),e.jsxs("a",{href:Ke(Bt.contact.phone,(yn=Bt.script)==null?void 0:yn.script_body,Bt.contact),className:"flex-1 flex items-center justify-center gap-1 px-2 py-1.5 bg-emerald-500/10 hover:bg-emerald-500/20 text-emerald-600 dark:text-emerald-400 rounded text-xs font-medium transition-colors",title:"Text",children:[e.jsx(eo,{className:"h-3 w-3"}),"Text"]})]}),gs&&(le?e.jsxs("button",{onClick:()=>{V({id:Bt.contact.id,first_name:Bt.contact.first_name,last_name:Bt.contact.last_name,email:Bt.contact.email}),U(!0)},className:"flex-1 flex items-center justify-center gap-1 px-2 py-1.5 bg-sky-500/10 hover:bg-sky-500/20 text-sky-600 dark:text-sky-400 rounded text-xs font-medium transition-colors",title:"Compose Email",children:[e.jsx(mn,{className:"h-3 w-3"}),"Email"]}):e.jsxs("a",{href:Je(Bt.contact.email,(Js=Bt.script)==null?void 0:Js.script_body,(Ut=Bt.script)==null?void 0:Ut.email_subject,(hn=Bt.actionType)==null?void 0:hn.name,Bt.contact),className:"flex-1 flex items-center justify-center gap-1 px-2 py-1.5 bg-sky-500/10 hover:bg-sky-500/20 text-sky-600 dark:text-sky-400 rounded text-xs font-medium transition-colors",title:"Email",children:[e.jsx(mn,{className:"h-3 w-3"}),"Email"]}))]}),as&&e.jsxs("button",{onClick:()=>{const hr=`${Bt.contact.first_name}${Bt.contact.last_name?" "+Bt.contact.last_name:""}`,Rs=kt==="birthday"?"birthday":"home_anniversary",jr=new URLSearchParams({cardType:Rs,contactId:Bt.contact.id,name:hr,...Bt.contact.address?{address:Bt.contact.address}:{},...kt==="anniversary"&&Bt.contact.home_anniversary?{date:Bt.contact.home_anniversary}:{}});s(`/mission-control/card-studio?${jr.toString()}`)},className:"w-full flex items-center justify-center gap-1.5 px-2 py-1.5 rounded text-xs font-semibold bg-gradient-to-r from-pink-500/15 to-violet-500/15 hover:from-pink-500/25 hover:to-violet-500/25 text-pink-600 dark:text-pink-400 transition-colors",children:[e.jsx(mn,{className:"h-3 w-3"}),"Send ",kt==="birthday"?"Birthday":"Anniversary"," Card"]}),!wt&&!gs&&e.jsx("p",{className:"text-xs text-muted-foreground italic",children:"No contact info"}),e.jsxs("div",{className:"flex gap-1 flex-wrap",children:[Bt.relationshipTypeName&&e.jsx($e,{variant:"secondary",className:"text-xs",children:Bt.relationshipTypeName}),Bt.monthNumber>0&&e.jsxs($e,{variant:"outline",className:"text-xs",children:["Month ",Bt.monthNumber]})]}),Bt.script&&e.jsx($,{size:"sm",variant:"outline",className:"w-full",onClick:()=>qe(Bt),children:"View Script"}),e.jsxs("div",{className:"flex gap-1.5",children:[e.jsxs($,{size:"sm",variant:"outline",className:"flex-1 gap-1",onClick:()=>{Y(Bt.contact.id),ae(`${Bt.contact.first_name} ${Bt.contact.last_name||""}`.trim())},children:[e.jsx(Av,{className:"h-3.5 w-3.5"}),"Snooze"]}),e.jsx($,{size:"sm",className:"flex-1",onClick:()=>{var hr;return ze(Bt.contact.id,Bt.actionType.id,(hr=Bt.script)==null?void 0:hr.id)},disabled:u.isPending,children:"Mark Complete"})]})]})]},Bt.contact.id+Ft)}),e.jsx("div",{className:"flex-shrink-0 w-[100px] border rounded-lg flex items-center justify-center",children:e.jsxs($u,{children:[e.jsx(Uu,{asChild:!0,children:e.jsxs($,{variant:"ghost",className:"h-full w-full",children:[e.jsx(l_,{className:"h-5 w-5 mr-2"}),"More"]})}),e.jsx(Au,{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(zs,{open:w,onOpenChange:S,children:e.jsxs(Os,{className:"sm:max-w-[360px]",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Set Weekly Goal"}),e.jsx(Pr,{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:Bt=>E(Bt.target.value),placeholder:"20",onKeyDown:Bt=>{Bt.key==="Enter"&&te()}})]}),e.jsx($,{onClick:te,className:"w-full",children:"Save Goal"})]})]})}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-6",children:[e.jsx(QUt,{}),e.jsx(bBn,{})]})]}),e.jsx(zs,{open:x,onOpenChange:y,children:e.jsxs(Os,{className:"max-w-md",children:[e.jsx(Us,{children:e.jsx(Bs,{className:"flex items-center gap-2",children:f&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:f.actionType.color||"#3B82F6"}}),f.actionType.name," Script"]})})}),f&&f.script&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:["For: ",e.jsxs("span",{className:"font-medium text-foreground",children:[f.contact.first_name," ",f.contact.last_name]})]}),e.jsx("div",{className:"bg-muted p-4 rounded-lg",children:e.jsx("p",{className:"whitespace-pre-wrap",children:at(f.script.script_body,f.contact)})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",className:"flex-1",onClick:()=>y(!1),children:"Close"}),e.jsx($,{className:"flex-1",onClick:()=>{var Bt;return ze(f.contact.id,f.actionType.id,(Bt=f.script)==null?void 0:Bt.id)},disabled:u.isPending,children:"Mark Complete"})]})]})]})}),e.jsx(mBn,{})]}),le&&W&&e.jsx(kk,{open:O,onOpenChange:U,contact:W,gmailEmail:ne}),e.jsx(nDe,{open:!!G,onOpenChange:Bt=>!Bt&&Y(null),contactId:G||"",contactName:X})]})}const ON=s=>(s||"").trim(),wQt=["Home","Vacation home","Work","Mailing","Rental"];function eCt(s){return s?!!(ON(s.address2)||ON(s.address2_city)):!1}function CBn(s){const t=ON(s==null?void 0:s.address),n=ON(s==null?void 0:s.city);return{line:t,city:n,state:ON(s==null?void 0:s.state),zip:ON(s==null?void 0:s.zip_code)||ON(s==null?void 0:s.zip),label:"Home",isSecondary:!1,hasAddress:!!(t||n)}}function TYe(s){const t=ON(s==null?void 0:s.address2),n=ON(s==null?void 0:s.address2_city);return{line:t,city:n,state:ON(s==null?void 0:s.address2_state),zip:ON(s==null?void 0:s.address2_zip),label:ON(s==null?void 0:s.address2_label)||"Second address",isSecondary:!0,hasAddress:!!(t||n)}}function nX(s){const t=TYe(s);return s!=null&&s.mail_to_secondary&&t.hasAddress?t:CBn(s)}function ABn(s){const t=[s.city,s.state].filter(Boolean).join(", ");return[s.line,[t,s.zip].filter(Boolean).join(" ")].filter(Boolean).join(", ")}const EBn=[{value:"bidirectional",label:"Two-Way",icon:zy,tooltip:"Sync contacts in both directions"},{value:"push_only",label:"Push Only",icon:Zf,tooltip:"Only push Agent OS → BoldTrail"},{value:"pull_only",label:"Pull Only",icon:Dg,tooltip:"Only pull BoldTrail → Agent OS"}];function ZMe({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(kV,{type:"single",value:s,onValueChange:a=>{a&&t(a)},className:"justify-start",children:EBn.map(a=>e.jsxs(iy,{children:[e.jsx(oy,{asChild:!0,children:e.jsxs(x7,{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(jx,{children:a.tooltip})]},a.value))})]})}function TBn(){const s=Wt(),[t,n]=j.useState(!1),[r,a]=j.useState(null),[i,l]=j.useState(!1),[o,c]=j.useState(!1),[d,u]=j.useState(null),[h,m]=j.useState(null),[f,g]=j.useState(0),x=j.useRef(!1),{data:y}=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}}),v=(y==null?void 0:y.sync_direction)||"bidirectional",b=d??v,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=>{re.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,Y=O.pull_total||0,X=O.update_total||0,ae=0,le=0,ne=0;for(;W!=="finalize"&&!x.current;){const ce=G+Y+X;W==="fetch_bt"?m("Fetching BoldTrail contacts..."):W==="analyze"?(m("Analyzing contacts..."),g(15)):W==="push"?(m(`Pushing contacts to BoldTrail... (${ae}/${G})`),g(ce>0?ae/ce*90:0)):W==="pull"?(m(`Pulling contacts from BoldTrail... (${le}/${Y})`),g(ce>0?(G+le)/ce*90:0)):W==="update"&&(m(`Updating existing contacts... (${ne}/${X})`),g(ce>0?(G+Y+ne)/ce*90:0));const{data:_e,error:he}=await q.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:W,offset:V,sync_log_id:U,sync_direction:b}});if(he)throw he;if(_e!=null&&_e.error)throw new Error(_e.error);const ue=_e;ae+=ue.chunk_pushed||0,le+=ue.chunk_pulled||0,ne+=ue.chunk_updated||0,ue.push_total!==void 0&&(G=ue.push_total||0),ue.pull_total!==void 0&&(Y=ue.pull_total||0),ue.update_total!==void 0&&(X=ue.update_total||0),ue.progress&&m(ue.progress),W=ue.next_phase,V=ue.next_offset}m("Finalizing sync..."),g(95);const{data:te,error:J}=await q.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"finalize",sync_log_id:U,sync_direction:b}});if(J)throw J;return g(100),te},onSuccess:R=>{m(null),g(0),n(!1),s.invalidateQueries({queryKey:["boldtrail-status"]}),s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),s.invalidateQueries({queryKey:["contacts-last-touch"]});const D=[`Pushed ${R.contacts_pushed||0}`,`pulled ${R.contacts_pulled||0}`,`updated ${R.contacts_updated||0}`,`skipped ${R.contacts_skipped||0} duplicates`];re.success(`Sync complete! ${D.join(", ")}.`)},onError:R=>{m(null),g(0),re.error(R.message||"Sync failed")}});if(!(y!=null&&y.connected))return null;const 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(iy,{children:[e.jsx(oy,{asChild:!0,children:e.jsx($,{variant:"outline",size:"icon",onClick:()=>w.mutate(),disabled:w.isPending,className:"shrink-0",children:w.isPending?e.jsx(ro,{className:"h-4 w-4 animate-spin"}):e.jsx(zy,{className:"h-4 w-4 text-emerald-600"})})}),e.jsx(jx,{children:"Sync with BoldTrail"})]}),e.jsx(zs,{open:t,onOpenChange:R=>{S.isPending||n(R)},children:e.jsxs(Os,{className:"sm:max-w-lg",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(zy,{className:"h-5 w-5 text-emerald-600"}),"Sync Preview"]}),e.jsx(Pr,{children:"Review what will happen when you sync your contacts."})]}),r&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(ZMe,{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(Dg,{className:"h-3 w-3"})," Pull to Agent OS"]})]}),e.jsxs("div",{className:"rounded-lg border p-3 text-center",children:[e.jsx("p",{className:"text-2xl font-bold text-amber-600",children:I}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(Yq,{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(Yq,{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(v1,{open:i,onOpenChange:l,children:[e.jsx(b1,{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(_1,{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(v1,{open:o,onOpenChange:c,children:[e.jsx(b1,{asChild:!0,children:e.jsxs($,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Dg,{className:"h-3 w-3 text-blue-600"}),E," contacts to pull from BoldTrail"]}),e.jsx(wl,{className:`h-3 w-3 transition-transform ${o?"rotate-180":""}`})]})}),e.jsx(_1,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[r.pull_preview.map((R,D)=>e.jsxs("div",{className:"px-3 py-1.5 text-xs flex justify-between",children:[e.jsx("span",{className:"font-medium",children:R.name||"No name"}),e.jsx("span",{className:"text-muted-foreground",children:R.email})]},D)),r.to_pull>20&&e.jsxs("div",{className:"px-3 py-1.5 text-xs text-muted-foreground text-center",children:["...and ",r.to_pull-20," more"]})]})})]}),!P&&!S.isPending&&e.jsx("div",{className:"text-center py-4 text-sm text-muted-foreground",children:"✅ Everything is already in sync! No contacts to transfer or update."}),S.isPending&&e.jsxs("div",{className:"space-y-2 py-2",children:[e.jsx(Yi,{value:f||10,className:"h-2"}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:h||"Sync in progress..."})]}),e.jsxs("div",{className:"flex gap-2 justify-end pt-2",children:[e.jsx($,{variant:"outline",onClick:()=>n(!1),disabled:S.isPending,children:"Cancel"}),e.jsxs($,{onClick:()=>S.mutate(),disabled:S.isPending||!P,className:"gap-2",children:[S.isPending?e.jsx(ro,{className:"h-4 w-4 animate-spin"}):e.jsx(zy,{className:"h-4 w-4"}),S.isPending?"Syncing...":"Sync Now"]})]})]})]})})]})}const MBn=[{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"}],PBn="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 XMe(s){return Object.entries(s).filter(([t,n])=>t!=="id"&&n!==null&&n!==void 0&&String(n).trim()!=="").length}function IBn(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 LBn(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(PBn).in("id",s);if(r)throw r;return n??[]}})}function jQt(){const s=Wt();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 tCt(s){return[s.first_name,s.last_name].filter(Boolean).join(" ")||"Unnamed contact"}function rue(s,t){const n=s==null?void 0:s[t];return n==null||String(n).trim()===""?null:String(n)}function NQt({open:s,onOpenChange:t,contactIds:n,onMerged:r}){const{data:a,isLoading:i}=LBn(n,s),l=jQt(),[o,c]=j.useState(null),[d,u]=j.useState({}),h=j.useMemo(()=>a??[],[a]);j.useEffect(()=>{if(!s){c(y=>y===null?y:null),u(y=>Object.keys(y).length===0?y:{});return}if(h.length&&!o){const y=[...h].sort((v,b)=>XMe(b)-XMe(v))[0];c(y.id)}},[s,h,o]),j.useEffect(()=>{u(y=>Object.keys(y).length===0?y:{})},[o]);const m=j.useMemo(()=>MBn.map(y=>{const v=h.map(w=>({id:w.id,value:rue(w,y.key)})).filter(w=>w.value!==null),b=Array.from(new Set(v.map(w=>w.value)));return{...y,values:v,distinct:b}}).filter(y=>y.distinct.length>1),[h]),f=h.find(y=>y.id===o)??null,g=async()=>{if(!f)return;const y={};for(const[v,b]of Object.entries(d)){const w=h.find(A=>A.id===b);if(!w)continue;const S=rue(w,v);S!==null&&S!==rue(f,v)&&(y[v]=w[v])}try{const v=await l.mutateAsync({primaryId:f.id,duplicateIds:h.filter(b=>b.id!==f.id).map(b=>b.id),overrides:y});v.failed.length?_a({title:`Merged ${v.merged} of ${v.merged+v.failed.length}`,description:v.failed[0].message,variant:"destructive"}):_a({title:`Merged into ${tCt(f)}`,description:"Nothing in their history was lost."}),t(!1),r==null||r()}catch(v){_a({title:"Could not merge",description:v.message,variant:"destructive"})}},x=n.length>10;return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-3xl max-h-[90vh] flex flex-col",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(Wz,{className:"h-4 w-4"}),"Merge contacts"]}),e.jsx(Pr,{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(uo,{className:"flex-1 -mx-2 px-2",children:e.jsxs("div",{className:"space-y-5 pb-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium",children:"Which record should we keep?"}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:h.map(y=>e.jsxs("button",{type:"button",onClick:()=>c(y.id),className:`rounded-lg border p-3 text-left transition-colors ${o===y.id?"border-primary bg-primary/5":"hover:bg-accent"}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"font-medium truncate",children:tCt(y)}),o===y.id&&e.jsx($e,{variant:"secondary",children:"Keep"})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:y.email||"No email"}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:y.phone||"No phone"}),y.created_at&&e.jsxs("p",{className:"mt-1 text-[11px] text-muted-foreground",children:["Added ",new Date(String(y.created_at)).toLocaleDateString()]})]},y.id))})]}),m.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-sm font-medium",children:"These details differ — pick what to keep"}),m.map(y=>{var b;const v=d[y.key]??(f&&rue(f,y.key)!==null?f.id:(b=y.values[0])==null?void 0:b.id);return e.jsxs("div",{className:"rounded-lg border p-3",children:[e.jsx("p",{className:"mb-2 text-xs uppercase tracking-wide text-muted-foreground",children:y.label}),e.jsx("div",{className:"flex flex-wrap gap-2",children:y.values.map(w=>e.jsx("button",{type:"button",onClick:()=>u(S=>({...S,[y.key]:w.id})),className:`rounded-md border px-2.5 py-1.5 text-sm transition-colors ${v===w.id?"border-primary bg-primary/10 font-medium":"hover:bg-accent text-muted-foreground"}`,children:w.value},w.id))})]},y.key)})]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["1 contact will be kept, ",h.length-1," will be removed. Nothing in their history is lost."]})]})}),e.jsxs(Sr,{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 RBn={email:"Same email",phone:"Same phone",name:"Same name"};function DBn(s){return[s.first_name,s.last_name].filter(Boolean).join(" ")||"Unnamed contact"}function FBn({open:s,onOpenChange:t}){const{data:n,isLoading:r,isError:a,error:i}=IBn(s),l=jQt(),[o,c]=j.useState(new Set),[d,u]=j.useState(null),[h,m]=j.useState(!1),f=j.useMemo(()=>(n??[]).filter(y=>y.contact_ids.length>1&&!o.has(y.contact_ids.join(","))),[n,o]),g=f.filter(y=>y.match_type!=="name"),x=async()=>{m(!0);let y=0,v=0;try{for(const b of g){const w=[...b.contacts].sort((E,I)=>XMe(I)-XMe(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)});y+=A.merged,v+=A.failed.length}_a({title:`Merged ${y} duplicate${y===1?"":"s"}`,description:v?`${v} could not be merged.`:"Name-only matches still need your review.",variant:v?"destructive":void 0})}catch(b){_a({title:"Could not finish merging",description:b.message,variant:"destructive"})}finally{m(!1)}};return e.jsxs(e.Fragment,{children:[e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"flex h-[90dvh] max-h-[90dvh] max-w-2xl flex-col overflow-hidden",children:[e.jsxs(Us,{className:"shrink-0",children:[e.jsx(Bs,{children:"Find duplicates"}),e.jsx(Pr,{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(y=>{const v=y.contact_ids.join(",");return e.jsxs("div",{className:"rounded-lg border p-3",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[e.jsx($e,{variant:"secondary",children:RBn[y.match_type]}),e.jsx("span",{className:"truncate text-xs text-muted-foreground",children:y.match_value}),e.jsxs("span",{className:"ml-auto text-xs text-muted-foreground",children:[y.contact_ids.length," records"]})]}),e.jsx("div",{className:"space-y-1",children:y.contacts.map(b=>e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 text-sm",children:[e.jsx("span",{className:"font-medium",children:DBn(b)}),b.email&&e.jsx("span",{className:"text-muted-foreground",children:b.email}),b.phone&&e.jsx("span",{className:"text-muted-foreground",children:b.phone}),b.created_at&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["added ",new Date(String(b.created_at)).toLocaleDateString()]})]},b.id))}),e.jsxs("div",{className:"mt-3 flex gap-2",children:[e.jsx($,{size:"sm",onClick:()=>u(y.contact_ids),children:"Review & merge"}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>c(b=>new Set(b).add(v)),children:"Not a duplicate"})]})]},`${y.match_type}-${v}`)})})}),e.jsxs(Sr,{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(Nn,{className:"mr-2 h-4 w-4"}),"Merge all safe matches (",g.length,")"]})]})]})}),e.jsx(NQt,{open:!!d,onOpenChange:y=>{y||u(null)},contactIds:d??[]})]})}const OBn=()=>{const{user:s}=bs();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})},rDe=s=>{const{user:t}=bs();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})},fit=()=>{const{user:s}=bs();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})},kQt=()=>{const{user:s}=bs();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})},zBn=()=>{const{data:s}=R_(),{data:t}=qw(),{data:n}=rDe(),{data:r}=kQt(),{data:a}=fit(),i=new Map;n==null||n.forEach(u=>{const h=i.get(u.contact_id);(!h||new Date(u.completed_at)>new Date(h))&&i.set(u.contact_id,u.completed_at)});const l=new Map;a==null||a.forEach(u=>l.set(u.relationship_type_id,u.frequency_days));const o=new Map;r==null||r.filter(u=>u.is_active).forEach(u=>{o.set(u.contact_id,u.frequency_days)});const c=Mg(new Date);return(s||[]).map(u=>{let h=90;if(o.has(u.id))h=o.get(u.id);else if(u.tags&&u.tags.length>0){const y=u.tags.map(v=>l.get(v.relationship_type_id)).filter(v=>v!==void 0);y.length>0&&(h=Math.min(...y))}const m=i.get(u.id)||null,f=m?dk(c,Mg(new Date(m))):null,g=f===null||f>=h,x=g&&f!==null?f-h:0;return{...u,lastPopby:m,daysSinceLastPopby:f,frequencyDays:h,isDue:g,daysOverdue:x}}).sort((u,h)=>h.daysOverdue-u.daysOverdue)},SQt=()=>zBn().filter(t=>t.isDue),BBn=()=>{const s=Wt(),{user:t}=bs();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"})}})},$Bn=()=>{const s=Wt(),{user:t}=bs();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"})}})},UBn=()=>{const s=Wt(),{user:t}=bs();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"})}})},qBn=()=>{const{data:s}=rDe(30),t=SQt(),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 VBn(){const{user:s}=bs();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 CQt(s){const{data:t}=VBn(),{data:n}=kQt(),{data:r}=fit(),{data:a}=fBn();return j.useMemo(()=>{const i=a==null?void 0:a.find(y=>y.contact_id===s.id),l=i?new Date(i.snoozed_until):null,o=Mg(new Date);if(l&&!rC(l,o))return{nextTouchDate:l,daysUntil:dk(l,o),status:"snoozed",frequencyDays:90,lastTouchDate:null,snoozedUntil:l};const d=((t==null?void 0:t.filter(y=>y.contact_id===s.id))||[]).sort((y,v)=>new Date(v.completed_at).getTime()-new Date(y.completed_at).getTime())[0],u=d?new Date(d.completed_at):null;let h=90;const m=n==null?void 0:n.find(y=>y.contact_id===s.id&&y.is_active);if(m)h=m.frequency_days;else if(s.tags&&s.tags.length>0){const y=s.tags.map(v=>{const b=r==null?void 0:r.find(w=>w.relationship_type_id===v.relationship_type_id);return b==null?void 0:b.frequency_days}).filter(v=>v!==void 0);y.length>0&&(h=Math.min(...y))}if(!u)return{nextTouchDate:null,daysUntil:null,status:"never-touched",frequencyDays:h,lastTouchDate:null,snoozedUntil:null};const f=Am(Mg(u),h),g=dk(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 sCt({contact:s}){const t=CQt(s),r=(()=>{switch(t.status){case"overdue":return{variant:"destructive",icon:ll,text:`${Math.abs(t.daysUntil)} days overdue`,className:""};case"due-soon":return{variant:"secondary",icon:da,text:t.daysUntil===0?"Due today":`Due in ${t.daysUntil} days`,className:"bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-400"};case"on-track":return{variant:"secondary",icon: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:Av,text:`Snoozed until ${en(t.snoozedUntil,"MMM d")}`,className:"bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-300"};case"never-touched":return{variant:"outline",icon:Ta,text:"Never touched",className:"border-dashed"}}})(),a=r.icon;return e.jsxs($e,{variant:r.variant,className:Pt("gap-1",r.className),children:[e.jsx(a,{className:"h-3 w-3"}),r.text]})}function HBn({contact:s,onLogTouch:t,onSnooze:n}){const r=CQt(s),a=gBn(),[i,l]=j.useState(!1),o=()=>{switch(r.status){case"overdue":return"text-destructive";case"due-soon":return"text-amber-600 dark:text-amber-400";case"on-track":return"text-emerald-600 dark:text-emerald-400";case"snoozed":return"text-slate-600 dark:text-slate-400";case"never-touched":return"text-muted-foreground"}},c=()=>{switch(r.status){case"overdue":return e.jsx(ll,{className:"h-5 w-5 text-destructive"});case"due-soon":return e.jsx(da,{className:"h-5 w-5 text-amber-600 dark:text-amber-400"});case"on-track":return e.jsx(Vr,{className:"h-5 w-5 text-emerald-600 dark:text-emerald-400"});case"snoozed":return e.jsx(Av,{className:"h-5 w-5 text-slate-600 dark:text-slate-400"});case"never-touched":return e.jsx(Ta,{className:"h-5 w-5 text-muted-foreground"})}},d=()=>{switch(r.status){case"overdue":return`${Math.abs(r.daysUntil)} days overdue`;case"due-soon":return r.daysUntil===0?"Due today!":`Due in ${r.daysUntil} days`;case"on-track":return`On track - ${r.daysUntil} days remaining`;case"snoozed":return`Snoozed for ${r.daysUntil} more days`;case"never-touched":return"No touches logged yet"}},u=async()=>{await a.mutateAsync(s.id)};return e.jsxs(e.Fragment,{children:[e.jsxs(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(Ta,{className:"h-4 w-4"}),"Next Touch"]})}),e.jsxs(Ie,{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[c(),e.jsx("span",{className:Pt("font-medium",o()),children:d()})]}),r.status==="snoozed"&&r.snoozedUntil&&e.jsxs("div",{className:"text-sm text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Snoozed until:"})," ",en(r.snoozedUntil,"MMMM d, yyyy")]}),r.status!=="snoozed"&&r.nextTouchDate&&e.jsxs("div",{className:"text-sm text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Scheduled:"})," ",en(r.nextTouchDate,"MMMM d, yyyy")]}),r.lastTouchDate&&e.jsxs("div",{className:"text-sm text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Last touch:"})," ",en(r.lastTouchDate,"MMM d, yyyy")]}),r.status!=="snoozed"&&e.jsxs("div",{className:"text-xs text-muted-foreground border-t pt-2",children:["Touch frequency: Every ",r.frequencyDays," days"]}),r.status==="snoozed"&&e.jsxs("div",{className:"flex gap-2 pt-1",children:[e.jsxs($,{size:"sm",variant:"outline",className:"flex-1",onClick:u,disabled:a.isPending,children:[e.jsx(pr,{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(Av,{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(nDe,{open:i,onOpenChange:l,contactId:s.id,contactName:`${s.first_name} ${s.last_name||""}`.trim()})]})}const H9e=768;function FK(){const[s,t]=j.useState(void 0);return j.useEffect(()=>{const n=window.matchMedia(`(max-width: ${H9e-1}px)`),r=()=>{t(window.innerWidthn.removeEventListener("change",r)},[]),!!s}function GBn(){const{user:s}=bs(),{hasLeadSite:t,leadSite:n}=ng(),{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 WBn={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"}},KBn={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 MYe({score:s,showScore:t=!1,showTooltip:n=!0,size:r="sm",className:a}){const i=WBn[s.status],l=KBn[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(bk,{children:e.jsxs(iy,{children:[e.jsx(oy,{asChild:!0,children:o}),e.jsx(jx,{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 YBn=[{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}],aue=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}=bs(),{toast:i}=Bi(),l=j.useRef(null),[o,c]=j.useState("upload"),[d,u]=j.useState([]),[h,m]=j.useState([]),[f,g]=j.useState({}),[x,y]=j.useState([]),[v,b]=j.useState([]),[w,S]=j.useState([]),[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:Le}=await q.from("contact_custom_tags").select("id, name, color").eq("owner_user_id",a.id).order("name");b(Le||[])})()},[s,a==null?void 0:a.id]);const G=Le=>{S(Fe=>Fe.includes(Le)?Fe.filter(ke=>ke!==Le):[...Fe,Le])},Y=async()=>{const Le=A.trim();if(!(!Le||!(a!=null&&a.id))){P(!0);try{const{data:Fe,error:ke}=await q.from("contact_custom_tags").insert({owner_user_id:a.id,name:Le}).select("id, name, color").single();if(ke)throw ke;Fe&&(b(Be=>[...Be,Fe].sort((Ne,Ae)=>Ne.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({}),y([]),S([]),E(""),D([]),V(null),l.current&&(l.current.value="")},ae=()=>{X(),t(!1)},le=Le=>{const Fe=Le.split(` `).map(Ve=>Ve.trim()).filter(Ve=>Ve);if(Fe.length===0)return{headers:[],data:[]};const ke=Ve=>{const ze=[];let qe="",dt=!1;for(let Xe=0;Xe0&&(Be[0]=Be[0].replace(/^\uFEFF/,""));const Ne=new Map,Ae=Be.map((Ve,ze)=>{let qe=(Ve||"").trim();qe||(qe=`Column ${ze+1}`);const dt=Ne.get(qe)||0;return Ne.set(qe,dt+1),dt===0?qe:`${qe} (${dt+1})`}),Ce=Fe.slice(1).map(ke);return{headers:Ae,data:Ce}},ne=Le=>{var Be;const Fe=(Be=Le.target.files)==null?void 0:Be[0];if(!Fe)return;const ke=new FileReader;ke.onload=Ne=>{var qe;const Ae=(qe=Ne.target)==null?void 0:qe.result,{headers:Ce,data:Ve}=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(Ve);const ze={};Ce.forEach(dt=>{const Xe=dt.toLowerCase().replace(/[_\s-]/g,"");Xe.includes("firstname")||Xe==="first"?ze.first_name=dt:Xe.includes("lastname")||Xe==="last"?ze.last_name=dt:Xe.includes("spouse")&&Xe.includes("email")?ze.spouse_email=dt:Xe.includes("spouse")||Xe.includes("partner")?ze.spouse_name=dt:Xe.includes("email")?ze.email=dt:Xe.includes("phone")||Xe.includes("mobile")||Xe.includes("cell")?ze.phone=dt:(Xe.includes("address")||Xe.includes("street"))&&(Xe.includes("2")||Xe.includes("second")||Xe.includes("secondary"))?ze.address2=dt:Xe.includes("address")||Xe.includes("street")?ze.address=dt:Xe==="city"?ze.city=dt:Xe==="state"||Xe==="province"?ze.state=dt:Xe==="zip"||Xe==="zipcode"||Xe==="postalcode"?ze.zip=dt:Xe.includes("company")||Xe.includes("organization")||Xe.includes("business")?ze.company_name=dt:Xe.includes("jobtitle")||Xe.includes("title")&&!Xe.includes("spouse")?ze.job_title=dt:Xe.includes("birthday")||Xe.includes("dob")||Xe.includes("birthdate")?ze.birthday=dt:Xe.includes("anniversary")||Xe.includes("homeanniversary")?ze.home_anniversary=dt:(Xe.includes("notes")||Xe.includes("comment"))&&(ze.notes=dt)}),g(ze),c("mapping")},ke.readAsText(Fe)},te=(Le,Fe)=>{g(ke=>{if(Fe==="none"){const{[Le]:Be,...Ne}=ke;return Ne}return{...ke,[Le]:Fe}})},J=Le=>{y(Fe=>Fe.includes(Le)?Fe.filter(ke=>ke!==Le):[...Fe,Le])},ce=async()=>{if(!(a!=null&&a.id))return;const{data:Le}=await q.from("innercircle_contacts").select("id, email, phone").eq("owner_user_id",a.id),Fe=new Set((Le||[]).filter(Ne=>Ne.email).map(Ne=>Ne.email.toLowerCase())),ke=new Set((Le||[]).filter(Ne=>Ne.phone).map(Ne=>Ne.phone.replace(/[^0-9]/g,""))),Be=h.map(Ne=>{const Ae=Xe=>{const at=f[Xe];if(!at)return"";const rt=d.indexOf(at);return rt>=0?(Ne[rt]||"").trim():""},Ce=Ae("first_name"),Ve=Ae("email"),ze=Ae("phone"),qe=Ce.length>0,dt=!!(Ve&&Fe.has(Ve.toLowerCase())||ze&&ke.has(ze.replace(/[^0-9]/g,"")));return{first_name:Ce,last_name:Ae("last_name"),email:Ve,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:qe,isDuplicate:dt,error:qe?void 0:"First name is required"}});D(Be),c("preview")},_e=Le=>{const Fe=Le.trim().split(/\s+/);return{first_name:Fe[0],last_name:Fe.length>1?Fe.slice(1).join(" "):null}},he=async()=>{if(!(a!=null&&a.id))return;const Le=R.filter(Ne=>Ne.isValid);if(Le.length===0){i({title:"No valid contacts",description:"There are no valid contacts to import.",variant:"destructive"});return}U(!0);let Fe=0,ke=0,Be=0;try{for(const Ne of Le)try{let Ae=null;if(Ne.email){const{data:ze}=await q.from("innercircle_contacts").select("id").eq("owner_user_id",a.id).eq("email",Ne.email).maybeSingle();Ae=ze}if(!Ae&&Ne.phone){const ze=Ne.phone.replace(/[^0-9]/g,""),{data:qe}=await q.from("innercircle_contacts").select("id, phone").eq("owner_user_id",a.id).not("phone","is",null);if(qe){const dt=qe.find(Xe=>Xe.phone&&Xe.phone.replace(/[^0-9]/g,"")===ze);dt&&(Ae={id:dt.id})}}const Ce={owner_user_id:a.id,first_name:Ne.first_name,last_name:Ne.last_name||null,email:Ne.email||null,phone:Ne.phone||null,address:Ne.address||null,city:Ne.city||null,state:Ne.state||null,zip:Ne.zip||null,address2_label:Ne.address2_label||null,address2:Ne.address2||null,address2_city:Ne.address2_city||null,address2_state:Ne.address2_state||null,address2_zip:Ne.address2_zip||null,spouse_name:Ne.spouse_name||null,spouse_email:Ne.spouse_email||null,company_name:Ne.company_name||null,job_title:Ne.job_title||null,birthday:aue(Ne.birthday),home_anniversary:aue(Ne.home_anniversary),notes:Ne.notes||null};let Ve=null;if(Ae){const{data:ze}=await q.from("innercircle_contacts").select("*").eq("id",Ae.id).single();if(ze){const qe={},dt=["last_name","email","phone","address","city","state","zip","address2_label","address2","address2_city","address2_state","address2_zip","spouse_name","spouse_email","company_name","job_title","birthday","home_anniversary","notes"];for(const Xe of dt){const at=ze[Xe],rt=Ce[Xe];(!at||at==="")&&rt&&(qe[Xe]=rt)}Object.keys(qe).length>0&&await q.from("innercircle_contacts").update(qe).eq("id",Ae.id)}Ve=Ae.id,ke++}else{const{data:ze,error:qe}=await q.from("innercircle_contacts").insert(Ce).select("id").single();qe?(console.error("Insert error for contact:",Ne.first_name,qe),Be++):ze?(Ve=ze.id,x.length>0&&await q.from("innercircle_contact_tags").insert(x.map(dt=>({contact_id:ze.id,relationship_type_id:dt}))),Fe++):Be++}if(Ve&&w.length>0&&await q.from("contact_custom_tag_assignments").upsert(w.map(ze=>({contact_id:Ve,tag_id:ze})),{onConflict:"contact_id,tag_id",ignoreDuplicates:!0}),Ve&&Ne.spouse_name){const ze=_e(Ne.spouse_name);let qe=null;if(Ne.spouse_email){const{data:Xe}=await q.from("innercircle_contacts").select("id").eq("owner_user_id",a.id).eq("email",Ne.spouse_email).maybeSingle();qe=Xe}if(!qe){const{data:Xe}=await q.from("innercircle_contacts").select("id").eq("owner_user_id",a.id).eq("first_name",ze.first_name).eq("last_name",ze.last_name||Ne.last_name||"").maybeSingle();qe=Xe}let dt=null;if(qe){dt=qe.id;const Xe=aue(Ne.home_anniversary);Xe&&await q.from("innercircle_contacts").update({home_anniversary:Xe}).eq("id",qe.id).is("home_anniversary",null)}else{const{data:Xe}=await q.from("innercircle_contacts").insert({owner_user_id:a.id,first_name:ze.first_name,last_name:ze.last_name||Ne.last_name||null,email:Ne.spouse_email||null,address:Ne.address||null,city:Ne.city||null,state:Ne.state||null,zip:Ne.zip||null,home_anniversary:aue(Ne.home_anniversary),spouse_name:`${Ne.first_name}${Ne.last_name?" "+Ne.last_name:""}`,spouse_email:Ne.email||null,notes:`Spouse of ${Ne.first_name} ${Ne.last_name||""} (imported via CSV)`.trim()}).select("id").single();Xe&&(dt=Xe.id,Fe++)}dt&&(await q.from("innercircle_contacts").update({spouse_contact_id:dt}).eq("id",Ve),await q.from("innercircle_contacts").update({spouse_contact_id:Ve}).eq("id",dt))}}catch(Ae){console.error("Error importing contact:",Ae),Be++}V({created:Fe,updated:ke,failed:Be}),c("result"),(Fe>0||ke>0)&&r(),i({title:"Import Complete",description:`${Fe} created, ${ke} updated${Be>0?`, ${Be} failed`:""}.`})}catch(Ne){console.error("Import error:",Ne),i({title:"Import Failed",description:Ne.message||"Failed to import contacts",variant:"destructive"})}finally{U(!1)}},ue=R.filter(Le=>Le.isValid).length,ve=R.filter(Le=>!Le.isValid).length,Ee=R.filter(Le=>Le.isValid&&Le.isDuplicate).length,Se=ue-Ee;return e.jsx(zs,{open:s,onOpenChange:ae,children:e.jsxs(Os,{className:"max-w-3xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(YN,{className:"h-5 w-5"}),"Import Contacts from CSV"]}),e.jsx(Pr,{children:"Upload a CSV file with your contacts. You can map columns and select relationship types."})]}),o==="upload"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-8 text-center",children:[e.jsx("input",{type:"file",accept:".csv,.txt",ref:l,onChange:ne,className:"hidden"}),e.jsx(ni,{className:"h-10 w-10 mx-auto text-muted-foreground mb-4"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Click to upload or drag and drop a CSV file"}),e.jsx($,{onClick:()=>{var Le;return(Le=l.current)==null?void 0:Le.click()},children:"Select CSV File"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-4 text-sm",children:[e.jsx("p",{className:"font-medium mb-2",children:"Supported Fields:"}),e.jsx("p",{className:"text-muted-foreground text-xs mb-3",children:"First Name, Last Name, Email, Phone, Street Address, City, State, Zip, Spouse Name, Spouse Email, Company, Job Title, Birthday, Home Anniversary, Notes"}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>{const Le=`First Name,Last Name,Email,Phone,Street Address,City,State,Zip,Spouse Name,Spouse Email,Company,Job Title,Birthday,Home Anniversary,Notes John,Doe,john@example.com,555-123-4567,123 Main St,Austin,TX,78701,Jane Doe,jane@example.com,ABC Realty,Real Estate Agent,1985-06-15,2020-03-22,Met at open house`,Fe=new Blob([Le],{type:"text/csv"}),ke=URL.createObjectURL(Fe),Be=document.createElement("a");Be.href=ke,Be.download="contact_import_template.csv",Be.click(),URL.revokeObjectURL(ke)},children:[e.jsx(xi,{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:YBn.map(Le=>e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs(ee,{className:"w-40 text-sm",children:[Le.label,Le.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsxs(ms,{value:f[Le.key]||"none",onValueChange:Fe=>te(Le.key,Fe),children:[e.jsx(us,{className:"w-48",children:e.jsx(fs,{placeholder:"Select column..."})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"none",children:"-- Not mapped --"}),d.map(Fe=>e.jsx(Ge,{value:Fe,children:Fe},Fe))]})]})]},Le.key))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(ee,{className:"text-base font-medium",children:"Apply Relationship Types (optional)"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:n.map(Le=>e.jsx($e,{variant:x.includes(Le.id)?"default":"outline",className:"cursor-pointer",onClick:()=>J(Le.id),children:Le.name},Le.id))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(ee,{className:"text-base font-medium",children:"Apply Tags to All Imported Contacts (optional)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Every contact in this CSV — both newly created and merged duplicates — will receive the selected tags."}),v.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:v.map(Le=>{const Fe=w.includes(Le.id);return e.jsxs($e,{variant:Fe?"default":"outline",className:"cursor-pointer gap-1",style:Fe&&Le.color?{backgroundColor:Le.color,borderColor:Le.color}:void 0,onClick:()=>G(Le.id),children:[Le.name,Fe&&e.jsx(pr,{className:"h-3 w-3"})]},Le.id)})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pe,{placeholder:"Create a new tag (e.g. Open House Oct 2026)",value:A,onChange:Le=>E(Le.target.value),onKeyDown:Le=>{Le.key==="Enter"&&(Le.preventDefault(),Y())},className:"max-w-xs"}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:Y,disabled:!A.trim()||I,children:[I?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(dn,{className:"h-4 w-4 mr-1"}),"Add Tag"]})]})]}),e.jsx("div",{className:"bg-muted/50 rounded-lg p-3 text-sm",children:e.jsxs("p",{className:"text-muted-foreground",children:["Preview: ",h.length," row(s) found in CSV"]})})]}),o==="preview"&&e.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-4 text-sm flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Vr,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{children:[Se," new"]})]}),Ee>0&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(ll,{className:"h-4 w-4"}),e.jsxs("span",{children:[Ee," existing (will merge gaps)"]})]}),ve>0&&e.jsxs("div",{className:"flex items-center gap-2 text-destructive",children:[e.jsx(ll,{className:"h-4 w-4"}),e.jsxs("span",{children:[ve," invalid"]})]})]}),Ee>0&&e.jsx("div",{className:"bg-muted/50 rounded-lg p-3 text-xs text-muted-foreground",children:"Duplicates matched by email or phone will only fill in missing fields — your existing data won't be overwritten."}),e.jsxs("div",{className:"flex-1 overflow-auto border rounded-lg",children:[e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{className:"bg-muted/30",children:[e.jsx(Dt,{children:"First Name"}),e.jsx(Dt,{children:"Last Name"}),e.jsx(Dt,{children:"Email"}),e.jsx(Dt,{children:"Phone"}),e.jsx(Dt,{children:"Status"})]})}),e.jsx(fi,{children:R.slice(0,100).map((Le,Fe)=>e.jsxs(En,{children:[e.jsx(_t,{children:Le.first_name}),e.jsx(_t,{children:Le.last_name}),e.jsx(_t,{children:Le.email}),e.jsx(_t,{children:Le.phone}),e.jsx(_t,{children:Le.isValid?Le.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:Le.error||"Invalid"})})]},Fe))})]}),R.length>100&&e.jsxs("p",{className:"text-sm text-muted-foreground text-center py-2",children:["Showing first 100 of ",R.length," contacts"]})]})]}),o==="result"&&W&&e.jsxs("div",{className:"space-y-4 py-4 text-center",children:[e.jsx(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(Sr,{children:[o==="upload"&&e.jsx($,{variant:"outline",onClick:ae,children:"Cancel"}),o==="mapping"&&e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"outline",onClick:X,children:"Back"}),e.jsx($,{onClick:ce,disabled:!f.first_name,children:"Continue"})]}),o==="preview"&&e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"outline",onClick:()=>c("mapping"),children:"Back"}),e.jsx($,{onClick:he,disabled:O||ue===0,children:O?e.jsxs(e.Fragment,{children:[e.jsx(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 XBn(){return"contacts"in navigator&&"ContactsManager"in window}function QBn(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 JBn({open:s,onOpenChange:t,onComplete:n}){const{user:r}=bs(),{data:a}=R_(),i=v6e(),l=j.useRef(null),[o,c]=j.useState("choose"),[d,u]=j.useState([]),[h,m]=j.useState(new Set),[f,g]=j.useState(0),[x,y]=j.useState(0),v=XBn(),b=j.useCallback(O=>{if(!a)return O;const U=new Set(a.filter(V=>V.email).map(V=>V.email.toLowerCase())),W=new Set(a.filter(V=>V.phone).map(V=>V.phone.replace(/\D/g,"")));return O.map(V=>{var X,ae;const G=(X=V.email)==null?void 0:X.toLowerCase(),Y=(ae=V.phone)==null?void 0:ae.replace(/\D/g,"");return G&&U.has(G)?{...V,isDuplicate:!0,duplicateField:"email"}:Y&&Y.length>=7&&W.has(Y)?{...V,isDuplicate:!0,duplicateField:"phone"}:V})},[a]),w=async()=>{try{const O=["name","email","tel","address"],U=await navigator.contacts.select(O,{multiple:!0});if(!U||U.length===0)return;const W=U.map(Y=>{var le,ne,te,J;const ae=(((le=Y.name)==null?void 0:le[0])||"").split(" ");return{first_name:ae[0]||"",last_name:ae.slice(1).join(" "),email:((ne=Y.email)==null?void 0:ne[0])||"",phone:((te=Y.tel)==null?void 0:te[0])||"",address:(J=Y.address)!=null&&J[0]?[Y.address[0].streetAddress,Y.address[0].city,Y.address[0].region,Y.address[0].postalCode].filter(Boolean).join(", "):""}}),V=b(W);u(V);const G=new Set;V.forEach((Y,X)=>{Y.isDuplicate||G.add(X)}),m(G),c("preview")}catch(O){console.error("Contact Picker error:",O),_a({title:"Could not access contacts",description:"Please try the file upload option instead.",variant:"destructive"})}},S=O=>{var V;const U=(V=O.target.files)==null?void 0:V[0];if(!U)return;const W=new FileReader;W.onload=G=>{var ne;const Y=(ne=G.target)==null?void 0:ne.result,X=QBn(Y);if(X.length===0){_a({title:"No contacts found",description:"The file didn't contain any valid contacts.",variant:"destructive"});return}const ae=b(X);u(ae);const 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++,y(Math.round(U/O.length*100))}catch(V){console.error(`Failed to import ${W.first_name} ${W.last_name}:`,V)}g(U),c("done")},E=O=>{m(U=>{const W=new Set(U);return W.has(O)?W.delete(O):W.add(O),W})},I=()=>{h.size===d.length?m(new Set):m(new Set(d.map((O,U)=>U)))},P=O=>{O||(c("choose"),u([]),m(new Set),g(0),y(0),o==="done"&&n()),t(O)},R=d.filter(O=>O.isDuplicate).length,D=h.size;return e.jsx(zs,{open:s,onOpenChange:P,children:e.jsxs(Os,{className:"sm:max-w-lg max-h-[90vh]",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(x1,{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(Pr,{children:"Add contacts from your phone directly into Agent OS."})]}),o==="choose"&&e.jsxs("div",{className:"space-y-4 pt-2",children:[v&&e.jsxs($,{onClick:w,className:"w-full h-auto py-4 flex flex-col items-center gap-2",children:[e.jsx(x1,{className:"h-6 w-6"}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"font-semibold",children:"Select from Phone"}),e.jsx("div",{className:"text-xs opacity-80",children:"Pick contacts directly from your device"})]})]}),e.jsxs("div",{className:"relative",children:[v&&e.jsx("div",{className:"absolute inset-0 flex items-center",children:e.jsx("span",{className:"w-full border-t"})}),v&&e.jsx("div",{className:"relative flex justify-center text-xs uppercase",children:e.jsx("span",{className:"bg-background px-2 text-muted-foreground",children:"or"})})]}),e.jsxs($,{variant:v?"outline":"default",onClick:()=>{var O;return(O=l.current)==null?void 0:O.click()},className:"w-full h-auto py-4 flex flex-col items-center gap-2",children:[e.jsx(ni,{className:"h-6 w-6"}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"font-semibold",children:"Upload Contact File"}),e.jsx("div",{className:"text-xs opacity-80",children:v?"Import a .vcf file exported from your Contacts app":"Export contacts from your phone as a .vcf file, then upload here"})]})]}),e.jsx("input",{ref:l,type:"file",accept:".vcf,.vcard",onChange:S,className:"hidden"}),!v&&e.jsxs("div",{className:"rounded-lg bg-muted p-3 text-sm text-muted-foreground space-y-2",children:[e.jsx("p",{className:"font-medium",children:"How to export contacts:"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-xs",children:"iPhone:"}),e.jsx("p",{className:"text-xs",children:'Open Contacts → select contacts → Share → choose "Export vCard"'})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-xs",children:"Android:"}),e.jsx("p",{className:"text-xs",children:"Open Contacts → Menu → Export → save as .vcf file"})]})]})]}),o==="preview"&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("span",{children:[d.length," contact",d.length!==1?"s":""," found",R>0&&e.jsxs("span",{className:"text-amber-600 ml-1",children:["(",R," already exist)"]})]}),e.jsx($,{variant:"ghost",size:"sm",onClick:I,children:h.size===d.length?"Deselect All":"Select All"})]}),e.jsx(uo,{className:"h-[350px] rounded-md border",children:e.jsx("div",{className:"divide-y",children:d.map((O,U)=>e.jsxs("div",{className:`flex items-start gap-3 p-3 cursor-pointer hover:bg-accent/50 transition-colors ${O.isDuplicate?"opacity-60":""}`,onClick:()=>E(U),children:[e.jsx(ai,{checked:h.has(U),onCheckedChange:()=>E(U),className:"mt-0.5"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"font-medium text-sm truncate",children:[O.first_name," ",O.last_name]}),O.isDuplicate&&e.jsxs($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(ca,{className:"h-6 w-6 text-emerald-600"})}),e.jsxs("div",{className:"text-center",children:[e.jsxs("p",{className:"font-semibold text-lg",children:[f," contact",f!==1?"s":""," imported!"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Your contacts are now in Agent OS and ready for touchpoint plans."})]}),e.jsx($,{onClick:()=>P(!1),className:"mt-2",children:"Done"})]})]})})}const PYe="mailStudioHandoff";function e9n(s){sessionStorage.setItem(PYe,JSON.stringify({...s,at:Date.now()}))}function ISr(){const s=sessionStorage.getItem(PYe);if(sessionStorage.removeItem(PYe),!s)return null;try{const t=JSON.parse(s);return Date.now()-(t.at||0)>10*60*1e3?null:t}catch{return null}}const t9n="/mission-control/direct-mail";function pit({build:s,label:t="Mail Studio",...n}){const{isAdmin:r}=bs(),a=Xn();return r?e.jsxs($,{variant:"outline",size:"sm",...n,onClick:()=>{const i=s();i&&(e9n(i),a(`${t9n}?handoff=1`))},children:[e.jsx(mn,{className:"mr-1.5 h-3.5 w-3.5"}),t]}):null}function s9n(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 n9n(){const{user:s}=bs();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 r9n(){const{user:s}=bs();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 AQt(){const{user:s}=bs(),t=Wt();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 EQt(s){return`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/track-video-share?t=${s}&e=open`}function TQt(s){return`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/track-video-share?t=${s}&e=click`}const a9n=100;function i9n({open:s,onOpenChange:t,contacts:n,isGmailConnected:r,isMassEmailReady:a,onSendComplete:i}){const l=Xn(),o=Sa(),c=AQt(),[d,u]=j.useState([]),[h,m]=j.useState(!1),[f,g]=j.useState(""),[x,y]=j.useState(null),[v,b]=j.useState(""),[w,S]=j.useState(""),[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>a9n;j.useEffect(()=>{s&&(y(null),g(""),P({done:0,total:0,failed:0}))},[s]),j.useEffect(()=>{!s||!o||(m(!0),q.from("agent_videos").select("id, title, share_token, thumbnail_url, playback_url, duration_seconds, created_at").eq("owner_user_id",o).eq("is_deleted",!1).eq("status","ready").order("created_at",{ascending:!1}).limit(50).then(({data:X})=>{u(X||[]),m(!1)}))},[s,o]),j.useEffect(()=>{if(!x)return;const X=x.title||"a quick video";b(`I recorded a video for you — ${X}`),S("Hey {{first_name}}! I recorded a quick video just for you. Click below to watch it:")},[x]);const U=d.filter(X=>!f||(X.title||"").toLowerCase().includes(f.toLowerCase())),W=(X,ae)=>{if(!x)return"";const le=x.share_token?`https://video.relevelup.com/share/video/${x.share_token}`:"",ne=x.share_token?`https://video.relevelup.com/thumb/${x.share_token}`:x.thumbnail_url||"",te=x.title||"Video Message",ce=w.replace(/\{\{first_name\}\}/gi,X).split(/\n\n+/).map(ue=>`

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

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

▶ Watch Video

${he}
`},V=async()=>{if(!x)return;E(!0),P({done:0,total:R.length,failed:0});let X=0,ae=0;for(const le of R)try{let ne;try{ne=(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(he){console.warn("Tracking record failed for",le.email,he)}const te=W(le.first_name,ne),J=v.replace(/\{\{first_name\}\}/gi,le.first_name),{data:ce,error:_e}=await q.functions.invoke("gmail-send",{body:{to:le.email,subject:J,body:te,contactId:le.id}});if(_e||!(ce!=null&&ce.success))throw new Error((ce==null?void 0:ce.error)||(_e==null?void 0:_e.message)||"Send failed");X+=1}catch(ne){console.error("Failed to send to",le.email,ne),ae+=1}finally{P({done:X+ae,total:R.length,failed:ae}),await new Promise(ne=>setTimeout(ne,250))}E(!1),ae===0?re.success(`Video sent to ${X} ${X===1?"contact":"contacts"}!`):re.warning(`Sent to ${X}, ${ae} failed. Check console for details.`),t(!1),i==null||i()},G=()=>{if(!x)return;const X=W("there",void 0);l("/admin/email-campaigns/new",{state:{directRecipients:R.map(ae=>({email:ae.email,name:`${ae.first_name} ${ae.last_name||""}`.trim()})),initialSubject:v,initialBodyHtml:X}}),t(!1)},Y=!!x&&!!v.trim()&&R.length>0&&(O?a:r);return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-[640px] max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(ua,{className:"h-5 w-5 text-primary"}),"Send Video to ",R.length," ",R.length===1?"Contact":"Contacts"]}),e.jsxs(Pr,{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(mn,{className:"h-3.5 w-3.5"}),"Sent individually via your connected Gmail"]}),D>0&&e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",D," skipped — no email)"]})]})]}),e.jsxs("div",{className:"space-y-4",children:[O&&!a&&e.jsxs("div",{className:"flex items-start gap-2 p-3 rounded-md bg-destructive/10 text-destructive text-sm",children:[e.jsx(ll,{className:"h-4 w-4 mt-0.5 shrink-0"}),e.jsxs("div",{children:["Mass Email is not set up yet. Verify a sender address in Integrations → Mass Email before sending to ",R.length," recipients."]})]}),!O&&!r&&e.jsxs("div",{className:"flex items-start gap-2 p-3 rounded-md bg-destructive/10 text-destructive text-sm",children:[e.jsx(ll,{className:"h-4 w-4 mt-0.5 shrink-0"}),e.jsx("div",{children:"Gmail isn't connected. Connect Gmail in Integrations to send videos."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{children:"Choose a video"}),e.jsxs($,{type:"button",variant:"ghost",size:"sm",className:"gap-1",onClick:()=>l("/innercircle/videos/record"),children:[e.jsx(dn,{className:"h-3.5 w-3.5"})," Record new"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Zr,{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:()=>y(X),className:`w-full flex items-center gap-3 p-2 rounded-md border text-left transition-colors ${ae?"border-primary bg-primary/5":"border-border hover:border-primary/50 hover:bg-accent/50"}`,children:[e.jsxs("div",{className:"w-16 h-10 rounded bg-muted flex items-center justify-center shrink-0 overflow-hidden relative",children:[X.thumbnail_url?e.jsx("img",{src:X.thumbnail_url,alt:"",className:"w-full h-full object-cover",referrerPolicy:"no-referrer"}):e.jsx(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(zu,{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:v,onChange:X=>b(X.target.value),placeholder:"I recorded a video for you"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(ee,{htmlFor:"bulk-video-message",children:["Personal message ",e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(use ","{{first_name}}"," to personalize)"]})]}),e.jsx(Ls,{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:!Y,className:"gap-2",children:[e.jsx(gm,{className:"h-4 w-4"}),"Continue in Mass Email"]}):e.jsxs($,{onClick:V,disabled:!Y||A,className:"gap-2",children:[A?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Kr,{className:"h-4 w-4"}),A?"Sending…":`Send to ${R.length}`]})]})]})]})})}function Iie(){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 o9n(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 l9n(){const s=Sa(),t=Wt();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 MQt(){const s=Wt();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 c9n(){const s=Wt();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 git(){const s=Sa(),t=Wt();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 PQt(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 d9n(){const s=Wt();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 u9n(){const s=Wt();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 h9n(){const s=Wt();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 m9n(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 f9n(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 xit(){const s=Wt();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 p9n(){const s=Wt();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 g9n=[{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"}],aDe={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"},x9n={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 y9n({open:s,onOpenChange:t,subject:n,body:r,ownerUserId:a,stepLabel:i}){const[l,o]=j.useState(!1),[c,d]=j.useState(""),[u,h]=j.useState(""),[m,f]=j.useState("desktop"),[g,x]=j.useState(""),[y,v]=j.useState(!1);j.useEffect(()=>{if(!s)return;let w=!1;return(async()=>{var S,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||re.error("Could not build preview")}finally{w||o(!1)}})(),()=>{w=!0}},[s,n,r,a]);const b=async()=>{if(g.trim()){v(!0);try{const{data:w,error:S}=await q.functions.invoke("process-drip-campaigns",{body:{action:"test_send",subject:n,body:r,to:g.trim(),owner_user_id:a||void 0}});if(S)throw S;w!=null&&w.success?re.success(`Test email sent to ${g.trim()}`):re.error((w==null?void 0:w.error)||"Could not send test email",{duration:1e4})}catch{re.error("Could not send test email")}finally{v(!1)}}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-3xl max-h-[92vh] flex flex-col p-0 gap-0",children:[e.jsxs(Us,{className:"p-5 pb-3 border-b shrink-0",children:[e.jsxs(Bs,{children:["Email preview",i?` — ${i}`:""]}),e.jsx(Pr,{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(XN,{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(x1,{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:y||!g.trim(),children:[y?e.jsx(Ct,{className:"h-4 w-4 mr-1.5 animate-spin"}):e.jsx(Kr,{className:"h-4 w-4 mr-1.5"}),"Send test"]})]})]})]})})}function s9({userId:s,onSelect:t,onSelectVideo:n,triggerLabel:r="Library",triggerSize:a="sm",triggerVariant:i="outline",triggerClassName:l}){const[o,c]=j.useState(!1),[d,u]=j.useState([]),[h,m]=j.useState(!1),[f,g]=j.useState("");j.useEffect(()=>{!o||!s||(m(!0),q.from("agent_videos").select("id, title, recipient_name, playback_url, thumbnail_url, created_at, duration_seconds").eq("owner_user_id",s).eq("is_deleted",!1).eq("status","ready").order("created_at",{ascending:!1}).limit(50).then(({data:y})=>{u(y||[]),m(!1)}))},[o,s]);const x=d.filter(y=>!f||(y.title||y.recipient_name||"").toLowerCase().includes(f.toLowerCase()));return e.jsxs(zs,{open:o,onOpenChange:c,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{variant:i,size:a,className:l||"gap-1.5 shrink-0",children:[e.jsx(nf,{className:"h-3.5 w-3.5"}),r]})}),e.jsxs(Os,{className:"max-w-lg max-h-[70vh] flex flex-col",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Select from Video Library"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Choose a video from your library"})]}),e.jsxs("div",{className:"relative mb-3",children:[e.jsx(Zr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search videos...",value:f,onChange:y=>g(y.target.value),className:"pl-10"})]}),e.jsx("div",{className:"flex-1 overflow-y-auto space-y-2 min-h-0",children:h?e.jsxs(e.Fragment,{children:[e.jsx(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(y=>e.jsxs("button",{onClick:()=>{t(y.playback_url||""),n==null||n(y),c(!1)},className:"w-full flex items-center gap-3 p-3 rounded-lg border border-border hover:border-primary/50 hover:bg-accent/50 transition-colors text-left",children:[e.jsx("div",{className:"w-16 h-10 rounded bg-muted flex items-center justify-center shrink-0 overflow-hidden",children:y.thumbnail_url?e.jsx("img",{src:y.thumbnail_url,alt:"",className:"w-full h-full object-cover",referrerPolicy:"no-referrer",onError:v=>{const b=v.currentTarget.parentElement;if(b){v.currentTarget.remove();const w=document.createElement("span");w.innerHTML="🎬",w.className="text-lg",b.appendChild(w)}}}):e.jsx(ua,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:y.title||y.recipient_name||"Untitled Video"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[y.duration_seconds?`${Math.round(y.duration_seconds)}s`:"",y.created_at?` · ${new Date(y.created_at).toLocaleDateString()}`:""]})]})]},y.id))})]})]})}function v9n(){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 b9n(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 _9n(){const{user:s}=bs();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 w9n(){const{user:s}=bs(),t=Wt();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 j9n(s){const{user:t}=bs();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 N9n(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 p3(){const{user:s}=bs(),t=Wt();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 k9n(){const s=Wt();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 S9n(){const s=Wt();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 iDe(){const{user:s}=bs();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 IQt(){const{data:s,isLoading:t}=iDe(),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 A6(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 E6(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 mk(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 C9n(){const{user:s}=bs(),t=Wt();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 LQt({open:s,onOpenChange:t,onUploadComplete:n}){const{data:r}=R_(),{data:a}=iDe(),i=p3(),l=j.useRef(null),[o,c]=j.useState(null),[d,u]=j.useState(""),[h,m]=j.useState(""),[f,g]=j.useState(""),[x,y]=j.useState(!1),[v,b]=j.useState(0),[w,S]=j.useState("idle"),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/")){re.error("Please select a video file");return}const V=W.size/(1024*1024);if(V>500){re.error("Video file must be less than 500MB");return}if(V>I){re.error(`Not enough storage. You have ${I.toFixed(1)} MB remaining.`);return}c(W),d||u(W.name.replace(/\.[^/.]+$/,""))},R=async()=>{if(!o){re.error("Please select a video file");return}y(!0),b(0),S("creating");try{const{data:U,error:W}=await q.functions.invoke("bunny-upload",{body:{action:"create",title:d||o.name,isAgentVideo:!0}});if(W)throw new Error(W.message);const{videoId:V,libraryId:G}=U;S("uploading");const{data:Y,error:X}=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:V,isAgentVideo:!0}});if(X)throw new Error(X.message);await new Promise((ne,te)=>{const J=new XMLHttpRequest;J.upload.addEventListener("progress",ce=>{if(ce.lengthComputable){const _e=Math.round(ce.loaded/ce.total*100);b(_e)}}),J.addEventListener("load",()=>{J.status>=200&&J.status<300?ne():te(new Error(`Upload failed with status ${J.status}`))}),J.addEventListener("error",()=>te(new Error("Upload failed"))),J.open("PUT",Y.uploadUrl),J.setRequestHeader("AccessKey",Y.apiKey),J.send(o)}),S("processing");const ae=o.size/(1024*1024),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"}),re.success("Video uploaded successfully! Processing may take a few minutes."),n==null||n(le),D()}catch(U){console.error("Upload error:",U),re.error(U instanceof Error?U.message:"Failed to upload video")}finally{y(!1),S("idle")}},D=()=>{x||(c(null),u(""),m(""),g(""),b(0),S("idle"),t(!1))},O=()=>{switch(w){case"creating":return"Preparing upload...";case"uploading":return`Uploading... ${v}%`;case"processing":return"Saving video...";default:return""}};return e.jsx(zs,{open:s,onOpenChange:D,children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Upload Video"}),e.jsx(Pr,{children:"Upload a video file from your device to your video library."})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Video File"}),o?e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-muted rounded-lg",children:[e.jsx(ua,{className:"h-8 w-8 text-primary flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:o.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(o.size/(1024*1024)).toFixed(1)," MB"]})]}),!x&&e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:U=>{U.stopPropagation(),c(null)},children:e.jsx(pr,{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(Ls,{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"?v:w==="processing"?100:10})]})]}),e.jsxs(Sr,{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 A9n=["🌱","💎","🏠","🔑","📧","💌","🎂","🥂","🤝","⭐","🎉","📞"],E9n={" ":" ","&":"&","<":"<",">":">",""":'"',"'":"'"},nCt=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=>E9n[t.toLowerCase()]||t).replace(/\n{3,}/g,` `).replace(/[ \t]+\n/g,` `).trim():s:"";function RQt({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}=o9n(o||void 0),{data:u,isLoading:h}=PQt(o||void 0),m=l9n(),f=MQt(),g=d9n(),[x,y]=j.useState(""),[v,b]=j.useState(""),[w,S]=j.useState("nurture"),[A,E]=j.useState("🌱"),[I,P]=j.useState("");j.useEffect(()=>{d?(y(d.name),b(d.description||""),S(d.category),E(d.icon),P(d.goal||"")):c||(y(""),b(""),S("nurture"),E("🌱"),P(""))},[d,c,s]);const R=x9n[w],D=async()=>{if(!x.trim()){re.error("Give your campaign a name");return}try{if(c&&o)await f.mutateAsync({id:o,name:x,description:v,category:w,icon:A,goal:I,cover_color:R}),re.success("Campaign updated");else{const U=await m.mutateAsync({name:x,description:v,category:w,icon:A,goal:I,cover_color:R});return re.success("Campaign created — now add your first step!"),a(U.id),l("steps"),U}}catch(U){re.error(U.message||"Failed to save")}},O=async()=>{if(!o){re.error("Save the campaign first, then add steps");return}const U=((u==null?void 0:u.length)||0)+1;try{await g.mutateAsync({campaign_id:o,step_order:U,channel:"email",subject:"",body:"",delay_type:"relative",delay_days:U===1?0:2,delay_hours:0})}catch{re.error("Failed to add step")}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-3xl max-h-[90vh] flex flex-col p-0 overflow-hidden",children:[e.jsx("div",{className:`bg-gradient-to-br ${R} p-5 text-white shrink-0`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("span",{className:"text-4xl drop-shadow-sm",children:A}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(Bs,{className:"text-lg font-bold text-white",children:c?"Edit Campaign":"Create New Campaign"}),e.jsx(Pr,{className:"text-white/85 text-xs mt-0.5",children:"Design a multi-step nurture sequence. Steps are sent in order with your chosen delays."})]})]})}),e.jsxs(ha,{value:i,onValueChange:U=>l(U),className:"flex-1 flex flex-col overflow-hidden min-h-0",children:[e.jsxs(ma,{className:"mx-5 mt-4 grid grid-cols-2 w-fit",children:[e.jsx(Zt,{value:"details",children:"Details"}),e.jsxs(Zt,{value:"steps",disabled:!c,children:["Steps ",u&&u.length>0&&e.jsx($e,{variant:"secondary",className:"ml-1.5 text-[10px]",children:u.length})]})]}),e.jsx(Xt,{value:"details",className:"flex-1 overflow-y-auto overscroll-contain mt-0 min-h-0 data-[state=inactive]:hidden",children:e.jsx("div",{children:e.jsxs("div",{className:"p-5 space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Campaign Name *"}),e.jsx(pe,{value:x,onChange:U=>y(U.target.value),placeholder:"e.g. New Buyer Lead — 7 Touch Nurture",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Description"}),e.jsx(Ls,{value:v,onChange:U=>b(U.target.value),placeholder:"What's this campaign for? When should you use it?",rows:2,className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Goal (optional)"}),e.jsx(pe,{value:I,onChange:U=>P(U.target.value),placeholder:"e.g. Book a buyer consultation within 14 days",className:"mt-1"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Category"}),e.jsxs(ms,{value:w,onValueChange:U=>S(U),children:[e.jsx(us,{className:"mt-1",children:e.jsx(fs,{})}),e.jsx(hs,{children:Object.entries(aDe).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:A9n.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(Xt,{value:"steps",className:"flex-1 overflow-y-auto overscroll-contain mt-0 min-h-0 data-[state=inactive]:hidden",children:e.jsx("div",{children:e.jsx("div",{className:"p-5 space-y-3",children:h?e.jsx("div",{className:"text-center text-sm text-muted-foreground py-8",children:"Loading steps…"}):!u||u.length===0?e.jsxs("div",{className:"text-center py-10 border border-dashed rounded-xl",children:[e.jsx(Nn,{className:"h-8 w-8 text-muted-foreground/40 mx-auto mb-2"}),e.jsx("p",{className:"text-sm font-medium mb-1",children:"No steps yet"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"Build your sequence — each step waits for its delay, then sends."}),e.jsxs($,{size:"sm",onClick:O,disabled:g.isPending,children:[e.jsx(dn,{className:"h-3.5 w-3.5 mr-1.5"})," Add first step"]})]}):e.jsxs(e.Fragment,{children:[u.map((U,W)=>e.jsx(T9n,{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(dn,{className:"h-3.5 w-3.5 mr-1.5"}),"Add another step"]})]})})})})]}),e.jsxs(Sr,{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 T9n({step:s,index:t,totalSteps:n}){const r=u9n(),a=h9n(),i=Sa(),[l,o]=j.useState(!1),[c,d]=j.useState(()=>({...s,body:nCt(s.body)})),[u,h]=j.useState(!1),[m,f]=j.useState(!1),[g,x]=j.useState(""),[y,v]=j.useState(!1),[b,w]=j.useState(!1);j.useEffect(()=>{d({...s,body:nCt(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}),re.success(`Step ${t+1} saved`)}catch{re.error("Failed to save step")}finally{h(!1)}},E=async()=>{if(await fo(`Delete step ${t+1}?`))try{await a.mutateAsync({id:s.id,campaign_id:s.campaign_id}),re.success("Step deleted")}catch{re.error("Failed to delete")}},I=R=>{d({...c,body:c.body+R})},P=()=>{if(c.delay_type==="calendar_anchor"){const D=c.anchor_field==="birthday"?"birthday":"home anniversary",O=c.anchor_offset_days||0;return O===0?`On their ${D}`:O<0?`${Math.abs(O)}d before ${D}`:`${O}d after ${D}`}if(t===0&&!c.delay_days&&!c.delay_hours)return"Sends immediately";const R=[];return c.delay_days&&R.push(`${c.delay_days}d`),c.delay_hours&&R.push(`${c.delay_hours}h`),t===0?`After ${R.join(" ")||"0"}`:`+${R.join(" ")||"0"}`};return e.jsxs("div",{className:"border rounded-lg bg-card overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-2 p-3 hover:bg-muted/30 cursor-pointer",onClick:()=>o(!l),children:[e.jsx("div",{className:"h-7 w-7 shrink-0 rounded-full bg-primary/10 text-primary flex items-center justify-center text-xs font-semibold",children:t+1}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[c.delay_type==="calendar_anchor"?e.jsx(Ta,{className:"h-3 w-3"}):e.jsx(da,{className:"h-3 w-3"}),e.jsx("span",{children:P()}),e.jsx("span",{children:"·"}),c.channel==="email"?e.jsx(mn,{className:"h-3 w-3"}):e.jsx(eo,{className:"h-3 w-3"}),e.jsx("span",{className:"capitalize",children:c.channel})]}),e.jsx("p",{className:"text-sm font-medium truncate mt-0.5",children:c.subject||e.jsx("span",{className:"text-muted-foreground italic",children:"No subject"})})]}),l?e.jsx(yb,{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(Ls,{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:"}),g9n.map(R=>e.jsx("button",{type:"button",onClick:()=>I(R.key),className:"text-[10px] px-1.5 py-0.5 rounded bg-primary/10 text-primary hover:bg-primary/20",children:R.label},R.key))]})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Video (optional)"}),c.video_url?e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[e.jsxs("div",{className:"flex-1 text-xs text-muted-foreground truncate bg-muted/50 rounded px-2 py-1.5 border border-input",children:[e.jsx(ua,{className:"h-3 w-3 inline mr-1 text-primary"}),c.video_url.length>50?c.video_url.slice(0,50)+"...":c.video_url]}),e.jsx($,{variant:"ghost",size:"sm",className:"h-7 text-xs text-destructive",onClick:()=>d({...c,video_url:null}),children:"Remove"})]}):e.jsxs("div",{className:"mt-1 flex items-center gap-1.5 flex-wrap",children:[e.jsx(s9,{userId:i||void 0,onSelect:R=>d({...c,video_url:R}),triggerSize:"sm",triggerClassName:"gap-1.5 flex-1 min-w-[120px]"}),e.jsxs($,{variant:"outline",size:"sm",className:"gap-1 text-xs flex-1 min-w-[120px]",onClick:()=>v(!0),children:[e.jsx(ni,{className:"h-3 w-3"})," Upload"]}),e.jsxs($,{variant:"ghost",size:"sm",className:"gap-1 text-xs text-muted-foreground flex-1 min-w-[120px]",onClick:()=>{x(""),f(!0)},children:[e.jsx(Sd,{className:"h-3 w-3"})," Paste URL"]}),e.jsx(LQt,{open:y,onOpenChange:v,onUploadComplete:R=>d({...c,video_url:R})}),e.jsx(zs,{open:m,onOpenChange:f,children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Add video URL"}),e.jsx(Pr,{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(Sr,{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(Hn,{className:"h-3.5 w-3.5 mr-1"})," Delete step"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[c.channel==="email"&&e.jsxs($,{variant:"outline",size:"sm",onClick:()=>w(!0),children:[e.jsx(Ca,{className:"h-3.5 w-3.5 mr-1.5"})," Preview"]}),e.jsxs($,{size:"sm",onClick: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(y9n,{open:b,onOpenChange:w,subject:c.subject||"",body:c.body||"",ownerUserId:i,stepLabel:`Step ${t+1}`})]})]})}function M9n({open:s,onOpenChange:t,contactIds:n,onSuccess:r}){const{data:a,isLoading:i}=Iie(),l=xit(),[o,c]=j.useState(""),[d,u]=j.useState(null),[h,m]=j.useState(!1),f=(a||[]).filter(y=>!y.is_starter),g=f.filter(y=>y.name.toLowerCase().includes(o.toLowerCase())||(y.description||"").toLowerCase().includes(o.toLowerCase())),x=async()=>{if(d)try{const y=await l.mutateAsync({campaignId:d,contactIds:n}),v=[`${y.enrolled} enrolled`];y.skipped>0&&v.push(`${y.skipped} skipped`),y.errors>0&&v.push(`${y.errors} errors`),re.success(v.join(" · ")),t(!1),u(null),r==null||r()}catch(y){re.error(y.message||"Failed to enroll contacts")}};return e.jsxs(zs,{open:s,onOpenChange:t,children:[e.jsxs(Os,{className:"max-w-md",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(Nn,{className:"h-4 w-4 text-primary"}),"Enroll in Drip Campaign"]}),e.jsxs(Pr,{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(Zr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search campaigns...",value:o,onChange:y=>c(y.target.value),className:"pl-9 h-9"})]}),e.jsx(uo,{className:"h-[320px] -mx-1 px-1",children:i?e.jsx("div",{className:"text-center py-8 text-sm text-muted-foreground",children:"Loading..."}):g.length===0?e.jsx("div",{className:"text-center py-8",children:f.length===0?e.jsxs(e.Fragment,{children:[e.jsx(Nn,{className:"h-8 w-8 text-muted-foreground/40 mx-auto mb-2"}),e.jsx("p",{className:"text-sm font-medium mb-1",children:"No campaigns yet"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"Build a custom drip campaign to nurture these contacts on autopilot."}),e.jsxs($,{size:"sm",onClick:()=>m(!0),children:[e.jsx(dn,{className:"h-3.5 w-3.5 mr-1.5"})," Create campaign"]})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"No campaigns match your search."})}):e.jsx("div",{className:"space-y-1.5",children:g.map(y=>e.jsxs("button",{onClick:()=>u(y.id),className:`w-full flex items-start gap-3 p-3 rounded-lg border text-left transition-all ${d===y.id?"border-primary bg-primary/5 ring-1 ring-primary":"border-border hover:border-primary/40 hover:bg-muted/30"}`,children:[e.jsx("div",{className:`shrink-0 h-9 w-9 rounded-lg bg-gradient-to-br ${y.cover_color} flex items-center justify-center text-lg`,children:y.icon}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:y.name}),y.is_active&&e.jsx($e,{variant:"outline",className:"text-[9px] bg-emerald-500/10 text-emerald-600 border-emerald-200 px-1 py-0",children:"Active"})]}),y.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-0.5",children:y.description})]}),d===y.id&&e.jsx(ca,{className:"h-4 w-4 text-primary shrink-0 mt-1"})]},y.id))})})]}),e.jsxs(Sr,{className:"gap-2 sm:gap-2",children:[f.length>0&&e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>m(!0),className:"mr-auto text-xs",children:[e.jsx(dn,{className:"h-3.5 w-3.5 mr-1"})," New campaign"]}),e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{onClick:x,disabled:!d||l.isPending,children:[l.isPending&&e.jsx(Ct,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),"Enroll ",n.length," contact",n.length!==1?"s":""]})]})]}),e.jsx(RQt,{open:h,onOpenChange:m})]})}function P9n({selectedIds:s,contacts:t,onClearSelection:n,onSendToLeadPond:r,showLeadPondAction:a,onTransfer:i,showTransferAction:l}){const o=Xn(),{data:c}=qw(),d=SHs(),u=Wt(),{isGmailConnected:h}=gy(),{isReady:m}=l6(),{data:f}=e9(),g=Zat(),x=DXt(),[y,v]=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),Y=s.size;if(Y===0)return null;const X=async _e=>{v(!0);try{const ue=Array.from(s).map(Ee=>({contact_id:Ee,relationship_type_id:_e})),{error:ve}=await q.from("innercircle_contact_tags").upsert(ue,{onConflict:"contact_id,relationship_type_id",ignoreDuplicates:!0});if(ve)throw ve;u.invalidateQueries({queryKey:["innercircle-contacts"]}),u.invalidateQueries({queryKey:["innercircle-contact-counts"]}),_a({title:`Assigned type to ${Y} contacts`}),n()}catch(he){_a({title:"Error assigning type",description:he.message,variant:"destructive"})}finally{v(!1)}},ae=async _e=>{v(!0);try{const he=Array.from(s);for(const ue of he)try{await x.mutateAsync({contactId:ue,tagId:_e})}catch{}u.invalidateQueries({queryKey:["all-contact-custom-tags"]}),_a({title:`Tagged ${Y} contacts`}),R(!1),O("")}catch(he){_a({title:"Error adding tags",description:he.message,variant:"destructive"})}finally{v(!1)}},le=async()=>{if(D.trim()){v(!0);try{const _e=await g.mutateAsync({name:D.trim()});await ae(_e.id)}catch(_e){_a({title:"Error creating tag",description:_e.message,variant:"destructive"}),v(!1)}}},ne=(f==null?void 0:f.filter(_e=>_e.name.toLowerCase().includes(D.toLowerCase())))||[],te=f==null?void 0:f.find(_e=>_e.name.toLowerCase()===D.trim().toLowerCase()),J=()=>{const _e=t.filter(Fe=>s.has(Fe.id)),he=["First Name","Last Name","Email","Phone","Street Address","City","State","ZIP","Full Address","Birthday","Home Anniversary","Notes","Relationship Types"],ue=_e.map(Fe=>{var qe;const ke=Fe,Be=ke.address||"",Ne=ke.city||"",Ae=ke.state||"",Ce=ke.zip||ke.zip_code||"",Ve=[Ne,[Ae,Ce].filter(Boolean).join(" ")].filter(Boolean).join(", "),ze=[Be,Ve].filter(Boolean).join(", ");return[Fe.first_name,Fe.last_name||"",Fe.email||"",Fe.phone||"",Be,Ne,Ae,Ce,ze,Fe.birthday||"",Fe.home_anniversary||"",Fe.notes||"",((qe=Fe.tags)==null?void 0:qe.map(dt=>{var Xe;return(Xe=dt.relationship_type)==null?void 0:Xe.name}).join("; "))||""]}),ve=[he.join(","),...ue.map(Fe=>Fe.map(ke=>`"${(ke||"").replace(/"/g,'""')}"`).join(","))].join(` `),Ee=new Blob([ve],{type:"text/csv"}),Se=URL.createObjectURL(Ee),Le=document.createElement("a");Le.href=Se,Le.download=`contacts-export-${new Date().toISOString().slice(0,10)}.csv`,Le.click(),URL.revokeObjectURL(Se),_a({title:`Exported ${Y} contacts`})},ce=async()=>{if(!await fo(`Are you sure you want to delete ${Y} contacts? This cannot be undone.`))return;const _e=Array.from(s);v(!0),G({done:0,total:_e.length});try{const he=await d.mutateAsync({ids:_e,onProgress:(ue,ve)=>G({done:ue,total:ve})});n(),_a({title:`Deleted ${he.toLocaleString()} contacts`})}catch(he){const ue=typeof(he==null?void 0:he.deleted)=="number"?he.deleted:0;_a({title:"Error deleting contacts",description:ue>0?`${ue.toLocaleString()} of ${_e.length.toLocaleString()} were deleted before this failed: ${he.message}`:he.message,variant:"destructive"})}finally{G(null),v(!1)}};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-primary/5 border border-primary/20 rounded-lg",children:[e.jsxs($e,{variant:"secondary",className:"font-semibold",children:[Y," selected"]}),V&&e.jsxs("span",{className:"text-sm text-muted-foreground",children:["Deleting ",V.done.toLocaleString()," of ",V.total.toLocaleString(),"…"]}),e.jsxs(ms,{onValueChange:X,disabled:y,children:[e.jsx(us,{className:"w-[180px] h-8",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Ap,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-sm",children:"Assign Type"})]})}),e.jsx(hs,{children:c==null?void 0:c.filter(_e=>_e.active).map(_e=>e.jsx(Ge,{value:_e.id,children:_e.name},_e.id))})]}),e.jsxs(Kd,{open:P,onOpenChange:R,children:[e.jsx(Yd,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",disabled:y,children:[e.jsx(dn,{className:"h-3.5 w-3.5 mr-1"}),"Add Tag"]})}),e.jsxs(Od,{className:"w-56 p-2",align:"start",children:[e.jsx(pe,{placeholder:"Search or create tag...",value:D,onChange:_e=>O(_e.target.value),onKeyDown:_e=>{_e.key==="Enter"&&D.trim()&&!te?(_e.preventDefault(),le()):_e.key==="Enter"&&te&&(_e.preventDefault(),ae(te.id))},className:"h-8 text-sm mb-2"}),e.jsxs("div",{className:"max-h-[200px] overflow-y-auto space-y-0.5",children:[ne.map(_e=>e.jsxs("button",{onClick:()=>ae(_e.id),className:"flex items-center gap-2 w-full px-2 py-1.5 rounded-md text-sm hover:bg-accent transition-colors",children:[e.jsx("div",{className:"h-3 w-3 rounded-full shrink-0",style:{backgroundColor:_e.color}}),e.jsx("span",{className:"flex-1 text-left truncate",children:_e.name})]},_e.id)),D.trim()&&!te&&e.jsxs("button",{onClick: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(dn,{className:"h-3.5 w-3.5"}),'Create "',D.trim(),'"']}),ne.length===0&&!D.trim()&&e.jsx("p",{className:"text-xs text-muted-foreground text-center py-2",children:"Type to create a tag"})]})]})]}),h&&e.jsxs($,{variant:"outline",size:"sm",onClick:()=>w(!0),disabled:y,children:[e.jsx(mn,{className:"h-3.5 w-3.5 mr-1"}),"Email"]}),m&&e.jsxs($,{variant:"outline",size:"sm",onClick:()=>{const _e=Array.from(s).join(",");o(`/admin/email-campaigns/new?contactIds=${_e}`)},disabled:y,children:[e.jsx(gm,{className:"h-3.5 w-3.5 mr-1"}),"Mass Email"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>A(!0),disabled:y,children:[e.jsx(ua,{className:"h-3.5 w-3.5 mr-1"}),"Send Video"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>I(!0),disabled:y,children:[e.jsx(Nn,{className:"h-3.5 w-3.5 mr-1"}),"Enroll in Campaign"]}),a&&r&&e.jsxs($,{variant:"outline",size:"sm",onClick:()=>r(Array.from(s)),disabled:y,children:[e.jsx(g1,{className:"h-3.5 w-3.5 mr-1"}),"Send to Lead Pond"]}),l&&i&&e.jsxs($,{variant:"outline",size:"sm",onClick:()=>i(Array.from(s)),disabled:y,children:[e.jsx(C4,{className:"h-3.5 w-3.5 mr-1"}),"Transfer"]}),Y>=2&&Y<=10&&e.jsxs($,{variant:"outline",size:"sm",onClick:()=>W(!0),disabled:y,children:[e.jsx(Wz,{className:"h-3.5 w-3.5 mr-1"}),"Merge"]}),e.jsx(pit,{disabled:y,label:"Mail",build:()=>({source:"contacts",contactIds:Array.from(s).slice(0,500)})}),e.jsxs($,{variant:"outline",size:"sm",onClick:J,disabled:y,children:[e.jsx(xi,{className:"h-3.5 w-3.5 mr-1"}),"Export"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:ce,disabled:y,className:"text-destructive hover:text-destructive",children:[e.jsx(Hn,{className:"h-3.5 w-3.5 mr-1"}),"Delete"]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:n,className:"ml-auto",children:[e.jsx(pr,{className:"h-3.5 w-3.5 mr-1"}),"Clear"]})]}),e.jsx(NQt,{open:U,onOpenChange:W,contactIds:Array.from(s),onMerged:n}),e.jsx(M9n,{open:E,onOpenChange:I,contactIds:Array.from(s),onSuccess:n}),e.jsx(kk,{open:b,onOpenChange:w,bulkContacts:Array.from(s).map(_e=>{const he=t.find(ue=>ue.id===_e);return he?{id:he.id,first_name:he.first_name,last_name:he.last_name,email:he.email||""}:null}).filter(_e=>_e!==null&&_e.email!==""),onSendComplete:()=>{w(!1),n()}}),e.jsx(i9n,{open:S,onOpenChange:A,contacts:Array.from(s).map(_e=>t.find(he=>he.id===_e)).filter(_e=>!!_e).map(_e=>({id:_e.id,first_name:_e.first_name,last_name:_e.last_name,email:_e.email})),isGmailConnected:!!h,isMassEmailReady:!!m,onSendComplete:()=>{A(!1),n()}})]})}function rCt({contact:s,onEdit:t,onDelete:n,onSnooze:r,onSendToLeadPond:a,showLeadPondAction:i,onTransfer:l,showTransferAction:o}){const c=Xn(),{isReady:d}=l6(),u=`${s.first_name} ${s.last_name||""}`.trim();return e.jsxs($u,{children:[e.jsx(Uu,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:h=>h.stopPropagation(),children:e.jsx(l_,{className:"h-4 w-4"})})}),e.jsxs(Au,{align:"end",onClick:h=>h.stopPropagation(),children:[e.jsxs(ja,{onClick:()=>c(`/mission-control/contacts/${s.id}?tab=activity&action=log`),children:[e.jsx(Da,{className:"h-4 w-4 mr-2"}),"Log Touch"]}),e.jsxs(ja,{onClick:()=>c(`/mission-control/video?contactId=${s.id}`),children:[e.jsx(ua,{className:"h-4 w-4 mr-2"}),"Send Video"]}),e.jsxs(ja,{onClick:()=>c(`/mission-control/popbys?contactId=${s.id}`),children:[e.jsx(ci,{className:"h-4 w-4 mr-2"}),"Schedule Pop-by"]}),d&&s.email&&e.jsxs(ja,{onClick:()=>c(`/admin/email-campaigns/new?contactIds=${s.id}`),children:[e.jsx(mn,{className:"h-4 w-4 mr-2"}),"Mass Email"]}),e.jsxs(ja,{onClick:()=>r(s.id,u),children:[e.jsx(Av,{className:"h-4 w-4 mr-2"}),"Snooze"]}),i&&a&&e.jsxs(ja,{onClick:()=>a(s.id),children:[e.jsx(g1,{className:"h-4 w-4 mr-2"}),"Send to Lead Pond"]}),o&&l&&e.jsxs(ja,{onClick:()=>l(s.id),children:[e.jsx(C4,{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(Hn,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})}function aCt({currentFilters:s,currentSortBy:t,onApplySmartList:n}){const{data:r}=Xat(),a=FXt(),i=OXt(),[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($u,{children:[e.jsx(Uu,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:"gap-1.5",children:[e.jsx(Cw,{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(Au,{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(Hn,{className:"h-3 w-3 text-destructive"})})]},m.id)),e.jsx(I0,{})]}):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(BI,{className:"h-4 w-4 mr-2"}),"Save Current Filter"]})]})]}),e.jsx(zs,{open:l,onOpenChange:o,children:e.jsxs(Os,{className:"max-w-sm",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Save Smart Filter"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(pe,{placeholder:"e.g. Buyers in 40205",value:c,onChange:m=>d(m.target.value),onKeyDown:m=>m.key==="Enter"&&h(),autoFocus:!0}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx($,{onClick:h,disabled:!c.trim()||a.isPending,children:"Save"})]})]})]})})]})}const QMe=[{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"}],DQt=[{value:"home_anniversary",label:"Home anniversary"},{value:"wedding_anniversary",label:"Wedding anniversary"}],I9n=[{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 L9n({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}=BB(),g=j.useMemo(()=>{const v=new Map;return(f||[]).forEach(b=>{v.set(b.name.trim().toLowerCase(),{value:`name:${b.name}`,label:b.name})}),(c||[]).forEach(b=>{const w=b.trim().toLowerCase();!w||v.has(w)||v.set(w,{value:`name:${b}`,label:b})}),Array.from(v.values()).sort((b,w)=>b.label.localeCompare(w.label))},[f,c]);j.useEffect(()=>{s&&u(r)},[s,r]);const x=v=>u(b=>({...b,...v})),y=Object.entries(d).filter(([,v])=>v!==void 0&&v!==!1&&v!=="").length;return e.jsx(Gy,{open:s,onOpenChange:t,children:e.jsxs(my,{side:"right",className:"w-full sm:max-w-lg overflow-y-auto",children:[e.jsxs(L0,{children:[e.jsxs(R0,{className:"flex items-center gap-2",children:[e.jsx(Nn,{className:"h-4 w-4 text-primary"}),"Advanced Filters"]}),e.jsx(DB,{children:"Slice your database by website activity, contact details, and engagement."})]}),e.jsxs(ha,{value:h,onValueChange:v=>m(v),className:"mt-4",children:[e.jsxs(ma,{className:"grid w-full grid-cols-3",children:[e.jsxs(Zt,{value:"contact",className:"gap-1.5",children:[e.jsx(Yn,{className:"h-3.5 w-3.5"})," Contact"]}),e.jsxs(Zt,{value:"behavior",disabled:!n,className:"gap-1.5",children:[e.jsx(rf,{className:"h-3.5 w-3.5"})," Behavior"]}),e.jsx(Zt,{value:"engagement",children:"Engagement"})]}),e.jsxs(Xt,{value:"contact",className:"space-y-6 mt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Contact Type"}),e.jsxs(ms,{value:i,onValueChange:l,children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"All types"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Types"}),o==null?void 0:o.map(v=>e.jsx(Ge,{value:v.id,children:v.name},v.id))]})]})]}),e.jsxs(nA,{title:"Contact Info Present",children:[e.jsx(Kb,{label:"Has email",checked:d.hasEmail===!0,onChange:v=>x({hasEmail:v||void 0})}),e.jsx(Kb,{label:"Has phone",checked:d.hasPhone===!0,onChange:v=>x({hasPhone:v||void 0})}),e.jsx(Kb,{label:"Has address",checked:d.hasAddress===!0,onChange:v=>x({hasAddress:v||void 0})}),e.jsx(Kb,{label:"Has birthday",checked:d.hasBirthday===!0,onChange:v=>x({hasBirthday:v||void 0})}),e.jsx(Kb,{label:"Has spouse",checked:d.hasSpouse===!0,onChange:v=>x({hasSpouse:v||void 0})}),e.jsx(Kb,{label:"Has company / job",checked:d.hasCompany===!0,onChange:v=>x({hasCompany:v||void 0})}),e.jsx(Kb,{label:"Has notes",checked:d.hasNotes===!0,onChange:v=>x({hasNotes:v||void 0})})]}),e.jsxs(nA,{title:"Location",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:[e.jsx(G9e,{label:"City",value:d.city||"",onChange:v=>x({city:v||void 0}),placeholder:"Any city"}),e.jsx(G9e,{label:"State",value:d.state||"",onChange:v=>x({state:v||void 0}),placeholder:"Any state"})]}),e.jsx(G9e,{label:"ZIP / Postal",value:d.zip||"",onChange:v=>x({zip:v||void 0}),placeholder:"Any ZIP"})]}),e.jsxs(nA,{title:"Important Dates",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Birthday month"}),e.jsxs(ms,{value:d.birthdayMonth?String(d.birthdayMonth):"all",onValueChange:v=>x({birthdayMonth:v==="all"?void 0:Number(v)}),children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Any month"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"Any month"}),QMe.map(v=>e.jsx(Ge,{value:String(v.value),children:v.label},v.value))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Anniversary month"}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:[e.jsxs(ms,{value:d.anniversaryField||"home_anniversary",onValueChange:v=>x({anniversaryField:v}),children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Field"})}),e.jsx(hs,{children:DQt.map(v=>e.jsx(Ge,{value:v.value,children:v.label},v.value))})]}),e.jsxs(ms,{value:d.anniversaryMonth?String(d.anniversaryMonth):"all",onValueChange:v=>x({anniversaryMonth:v==="all"?void 0:Number(v)}),children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Any month"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"Any month"}),QMe.map(v=>e.jsx(Ge,{value:String(v.value),children:v.label},v.value))]})]})]})]})]}),e.jsx(nA,{title:"Date Added",children:e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:[e.jsx(iCt,{label:"From",value:d.dateAddedFrom,onChange:v=>x({dateAddedFrom:v||void 0})}),e.jsx(iCt,{label:"To",value:d.dateAddedTo,onChange:v=>x({dateAddedTo:v||void 0})})]})}),e.jsx(nA,{title:"Lead Source",children:e.jsxs(ms,{value:d.leadSourceId||"all",onValueChange:v=>x({leadSourceId:v==="all"?void 0:v}),children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"All sources"})}),e.jsxs(hs,{className:"max-h-72",children:[e.jsx(Ge,{value:"all",children:"All sources"}),e.jsx(Ge,{value:"none",children:"No source"}),g.map(v=>e.jsx(Ge,{value:v.value,children:v.label},v.value))]})]})})]}),e.jsx(Xt,{value:"behavior",className:"space-y-6 mt-4",children:n?e.jsxs(e.Fragment,{children:[e.jsxs(nA,{title:"Last Active On Site",children:[e.jsx(vw,{value:d.lastActive||"",onValueChange:v=>x({lastActive:v||void 0}),className:"grid grid-cols-2 gap-2",children:I9n.map(v=>e.jsxs("label",{className:"flex items-center gap-2 rounded-md border px-3 py-2 cursor-pointer hover:bg-accent",children:[e.jsx(Km,{value:v.value}),e.jsx("span",{className:"text-sm",children:v.label})]},v.value))}),d.lastActive&&e.jsx($,{variant:"ghost",size:"sm",className:"mt-1 h-7 px-2 text-xs",onClick:()=>x({lastActive:void 0}),children:"Clear"})]}),e.jsxs(nA,{title:"Registration",children:[e.jsx(Kb,{label:"Registered on lead site",checked:d.registered==="yes",onChange:v=>x({registered:v?"yes":void 0})}),e.jsx(Kb,{label:"Anonymous visitors only",checked:d.registered==="no",onChange:v=>x({registered:v?"no":void 0})})]}),e.jsxs(nA,{title:"Property Activity",children:[e.jsx(Kb,{label:"Viewed any listing",checked:d.viewedListing==="any",onChange:v=>x({viewedListing:v?"any":void 0})}),e.jsx(Kb,{label:"Hot buyer — 3+ views in last 7 days",checked:d.viewedListing==="multiple7d",onChange:v=>x({viewedListing:v?"multiple7d":void 0})}),e.jsx(Kb,{label:"Saved a property",checked:!!d.savedProperty,onChange:v=>x({savedProperty:v||void 0})}),e.jsx(Kb,{label:"Has an active saved search / alert",checked:!!d.hasSavedSearch,onChange:v=>x({hasSavedSearch:v||void 0})})]}),e.jsxs(nA,{title:"Requests",children:[e.jsx(Kb,{label:"Requested a showing / asked a question",checked:!!d.requestedShowing,onChange:v=>x({requestedShowing:v||void 0})}),e.jsx(Kb,{label:"Requested a home valuation",checked:!!d.requestedValuation,onChange:v=>x({requestedValuation:v||void 0})})]})]}):e.jsx("div",{className:"rounded-md border border-dashed p-4 text-sm text-muted-foreground",children:"Connect a Lead Site with MLS to unlock website behavior filters."})}),e.jsxs(Xt,{value:"engagement",className:"space-y-4 mt-4",children:[e.jsx(Kb,{label:"Any website activity",checked:!!d.websiteActiveOnly,onChange:v=>x({websiteActiveOnly:v||void 0})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"More engagement filters (last emailed, awaiting response, past-due tasks) are in the pipeline."})]})]}),e.jsxs(DOt,{className:"mt-6 flex-row gap-2 sm:justify-between",children:[e.jsx($,{variant:"ghost",onClick:()=>u({}),disabled:y===0,children:"Clear behavior filters"}),e.jsx($,{onClick:()=>{a(d),t(!1)},children:"Apply"})]})]})})}function nA({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 Kb({label:s,checked:t,onChange:n}){return e.jsxs("div",{className:"flex items-center justify-between rounded-md border px-3 py-2",children:[e.jsx("span",{className:"text-sm",children:s}),e.jsx(Sn,{checked:t,onCheckedChange:n})]})}function G9e({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(pr,{className:"h-3 w-3"})})]})]})}function iCt({label:s,value:t,onChange:n}){const[r,a]=j.useState(!1),i=t?gv(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(Kd,{open:r,onOpenChange:a,children:[e.jsx(Yd,{asChild:!0,children:e.jsxs($,{variant:"outline",className:Pt("w-full justify-start text-left font-normal h-8",!i&&"text-muted-foreground"),children:[e.jsx(Ta,{className:"mr-2 h-3.5 w-3.5"}),i?en(i,"MMM d, yyyy"):e.jsx("span",{children:"Pick a date"})]})}),e.jsx(Od,{className:"w-auto p-0",align:"start",children:e.jsx(T2,{mode:"single",selected:i,onSelect:l=>{n(l?en(l,"yyyy-MM-dd"):void 0),a(!1)},initialFocus:!0})})]})]})}function R9n({behavior:s,onRemove:t,onClearAll:n}){const r=D9n(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 D9n(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=QMe.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=QMe.find(i=>i.value===s.anniversaryMonth),a=((n=DQt.find(i=>i.value===(s.anniversaryField||"home_anniversary")))==null?void 0:n.label)||"Anniversary";t.push({key:"anniversaryMonth",label:`${a} in ${(r==null?void 0:r.label)||s.anniversaryMonth}`})}return s.dateAddedFrom&&t.push({key:"dateAddedFrom",label:`Added on/after ${en(gv(s.dateAddedFrom),"MMM d, yyyy")}`}),s.dateAddedTo&&t.push({key:"dateAddedTo",label:`Added on/before ${en(gv(s.dateAddedTo),"MMM d, yyyy")}`}),s.leadSourceId&&t.push({key:"leadSourceId",label:s.leadSourceId==="none"?"No lead source":"Lead source"}),t}function F9n(){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 O9n(){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 RSr(){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 DSr(){const s=Sa(),t=Wt();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 FSr(){const s=Wt();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 z9n(){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 OSr(){const s=Sa(),t=Wt();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 zSr(){const s=Wt();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 BSr(){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 $Sr(){const s=Sa(),t=Wt();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 USr(){const s=Wt();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 qSr(){const s=Wt();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=Wt();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 HSr(){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 GSr(){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 KSr(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 FQt(s,t,n){const r=Wt(),{token:a}=F9n();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:y}=await q.from(s).update({latitude:x,longitude:g}).eq("id",d.id);y||l++}catch(h){console.error("Geocode error:",h)}}return l},onSuccess:i=>{r.invalidateQueries({queryKey:[t]}),_a({title:i?`${i} ${i===1?n.one:n.many} placed on the map`:"No locations found",description:i?void 0:"Check the street address, city and state."})},onError:i=>_a({title:"Could not look up addresses",description:i.message,variant:"destructive"})})}function YSr(){return FQt("listings","sphere-map-listings",{one:"listing",many:"listings"})}function ZSr(){return FQt("open_houses","sphere-map-open-houses",{one:"open house",many:"open houses"})}const XSr={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 B9n(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 QSr(s){return s===null?"never":s>=365?"red":s>=180?"orange":s>=90?"yellow":"green"}function $9n(s){return`${s.first_name??""} ${s.last_name??""}`.trim()||"Unnamed contact"}function U9n(s){return[s.address,[s.city,s.state].filter(Boolean).join(", "),s.zip].filter(Boolean).join(" · ")}function JSr(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=>B9n(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?$9n(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:U9n(r[0]),gapDays:i}})}const q9n=3958.8;function OQt(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*q9n*Math.asin(Math.sqrt(o))}function V9n(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 eCr(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 tCr(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 sCr(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=OQt(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)V9n(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 zQt(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 G9n({selected:s,onChange:t,className:n}){const{neighborhoods:r,unmappedCount:a,isLoading:i}=yit(),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(Kd,{children:[e.jsx(Yd,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:`gap-1.5 h-8 rounded-lg ${n??""}`,children:[e.jsx(ci,{className:"h-3.5 w-3.5"}),"Neighborhoods",s.length>0&&e.jsx($e,{variant:"secondary",className:"h-5 px-1.5 text-[10px]",children:s.length})]})}),e.jsxs(Od,{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(wr,{to:"/mission-control/sphere-map",children:"Open the contacts map"})})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"max-h-64 overflow-y-auto p-2 space-y-1",children:r.map(c=>e.jsxs("button",{type:"button",onClick:()=>o(c.id),className:"w-full flex items-center gap-2 px-2 py-1.5 rounded-md hover:bg-muted text-sm text-left",children:[e.jsx(ai,{checked:l.has(c.id),className:"pointer-events-none"}),e.jsx("span",{className:"h-2.5 w-2.5 rounded-full shrink-0",style:{backgroundColor:c.color}}),e.jsx("span",{className:"flex-1 truncate",children:c.name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:c.count})]},c.id))}),e.jsxs("div",{className:"p-2 border-t space-y-2",children:[a>0&&e.jsxs("p",{className:"text-[11px] text-muted-foreground px-1",children:[a.toLocaleString()," contacts don't have a mapped address yet, so they can't land in a neighborhood."," ",e.jsx(wr,{to:"/mission-control/sphere-map",className:"underline",children:"Map them"})]}),s.length>0&&e.jsx($,{variant:"ghost",size:"sm",className:"w-full text-xs",onClick:()=>t([]),children:"Clear neighborhoods"})]})]})]})]})}async function O$(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 rX(){return{lastActiveAt:null,registered:!1,propertyViewCount:0,propertyViewCount7d:0,savedListingCount:0,activeSavedSearchCount:0,showingRequests:0,valuationRequests:0,viewedCities:[],viewedZips:[]}}function W9n(){const{user:s}=bs(),{leadSite:t,hasLeadSite:n}=ng(),{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=(v,b)=>{const w=i.get(v)||rX();i.set(v,{...w,...b})},o=await O$((v,b)=>q.from("lead_site_visitors").select("id, contact_id, last_seen_at, email").eq("lead_site_id",t.id).not("contact_id","is",null).range(v,b)),c=new Map,d=new Map;o.forEach(v=>{if(!v.contact_id)return;c.set(v.id,v.contact_id),v.email&&d.set(v.email.toLowerCase(),v.contact_id);const b=i.get(v.contact_id);(!b||!b.lastActiveAt||v.last_seen_at>b.lastActiveAt)&&l(v.contact_id,{lastActiveAt:v.last_seen_at})});const u=await O$((v,b)=>q.from("lead_site_consumer_profiles").select("contact_id, user_id").eq("lead_site_id",t.id).not("contact_id","is",null).range(v,b)),h=new Map;u.forEach(v=>{v.contact_id&&(h.set(v.user_id,v.contact_id),l(v.contact_id,{registered:!0}))});const m=new Date(Date.now()-7*24*60*60*1e3).toISOString();return(await O$((v,b)=>q.from("lead_site_property_views").select("visitor_id, viewed_at, property_address").eq("lead_site_id",t.id).not("visitor_id","is",null).range(v,b))).forEach(v=>{const b=v.visitor_id?c.get(v.visitor_id):null;if(!b)return;const w=i.get(b)||rX();w.propertyViewCount+=1,v.viewed_at>=m&&(w.propertyViewCount7d+=1),i.set(b,w)}),(await O$((v,b)=>q.from("lead_site_saved_listings").select("user_id, mls_number").eq("lead_site_id",t.id).range(v,b))).forEach(v=>{const b=h.get(v.user_id);if(!b)return;const w=i.get(b)||rX();w.savedListingCount+=1,i.set(b,w)}),(await O$((v,b)=>q.from("lead_site_saved_searches").select("user_id").eq("lead_site_id",t.id).eq("is_active",!0).range(v,b))).forEach(v=>{const b=h.get(v.user_id);if(!b)return;const w=i.get(b)||rX();w.activeSavedSearchCount+=1,i.set(b,w)}),(await O$((v,b)=>q.from("lead_site_leads").select("email, lead_type").eq("lead_site_id",t.id).not("email","is",null).range(v,b))).forEach(v=>{if(!v.email)return;const b=d.get(v.email.toLowerCase());if(!b)return;const w=i.get(b)||rX(),S=(v.lead_type||"").toLowerCase();(S.includes("showing")||S.includes("question")||S==="contact")&&(w.showingRequests+=1),(S.includes("valuation")||S.includes("cma")||S.includes("home_value"))&&(w.valuationRequests+=1),i.set(b,w)}),i},enabled:!!s&&n,staleTime:5*60*1e3});return{behaviorMap:r??new Map,hasLeadSite:n,isLoading:a}}const BQt="innercircle_geocode_cache_v1";function K9n(){try{return JSON.parse(localStorage.getItem(BQt)||"{}")}catch{return{}}}function Y9n(s){try{localStorage.setItem(BQt,JSON.stringify(s))}catch{}}function Z9n(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 X9n({open:s,onOpenChange:t,contacts:n,onCitySelect:r}){const a=j.useRef(null),i=j.useRef(null),[l,o]=j.useState(""),[c,d]=j.useState(!0),[u,h]=j.useState([]),[m,f]=j.useState({done:0,total:0}),[g,x]=j.useState(!1),[y,v]=j.useState("heat");j.useEffect(()=>{if(!s)return;let w=!1;return(async()=>{d(!0);const{data:S}=await q.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();w||(o((S==null?void 0:S.value)||""),d(!1))})(),()=>{w=!0}},[s]),j.useEffect(()=>{if(!s||!l)return;let w=!1;return(async()=>{const A=K9n(),E=n.map(V=>({c:V,addr:Z9n(V)})).filter(V=>V.addr),I=[],P=[];for(const{c:V,addr:G}of E){const Y=A[G];Y!==null&&(Y?I.push({id:V.id,name:`${V.first_name||""} ${V.last_name||""}`.trim(),city:V.city||null,state:V.state||null,zip:V.zip||V.zip_code||null,lat:Y.lat,lng:Y.lng}):P.push({c:V,addr:G}))}if(w||h(I),f({done:I.length,total:E.length}),P.length===0)return;x(!0);const R=6;let D=0;const O={...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 wu.accessToken=l,i.current=new wu.Map({container:a.current,style:"mapbox://styles/mapbox/light-v11",center:[-98.5795,39.8283],zoom:3.5}),i.current.addControl(new wu.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 wu.Popup({offset:12}).setLngLat(D).setHTML(`
${R.properties.name||"Contact"}
`).addTo(w)}),w.on("mouseenter","contacts-points",()=>{w.getCanvas().style.cursor="pointer"}),w.on("mouseleave","contacts-points",()=>{w.getCanvas().style.cursor=""})),w.getLayer("contacts-heat")&&w.setLayoutProperty("contacts-heat","visibility",y==="heat"?"visible":"none"),w.getLayer("contacts-points")&&(w.setPaintProperty("contacts-points","circle-opacity",y==="points"?.9:0),w.setLayoutProperty("contacts-points","visibility","visible")),u.length>0&&!w._fitDone){const P=new wu.LngLatBounds;u.forEach(R=>P.extend([R.lng,R.lat]));try{w.fitBounds(P,{padding:60,maxZoom:11,duration:600}),w._fitDone=!0}catch{}}};w.isStyleLoaded()?S():w.once("load",S)},[u,y]),e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-6xl w-[95vw] h-[90vh] p-0 flex flex-col",children:[e.jsx(Us,{className:"p-4 pb-2 border-b",children:e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(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:y==="heat"?"default":"ghost",onClick:()=>v("heat"),className:"h-8",children:[e.jsx(sh,{className:"h-3.5 w-3.5 mr-1"})," Heat"]}),e.jsxs($,{size:"sm",variant:y==="points"?"default":"ghost",onClick:()=>v("points"),className:"h-8",children:[e.jsx(M4,{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(ll,{className:"h-10 w-10 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:"Map Not Configured"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Mapbox token is not set. Contact your administrator."})]})]})}),e.jsxs("div",{className:"w-full md:w-72 border-t md:border-t-0 md:border-l flex flex-col bg-muted/30 min-h-[200px]",children:[e.jsxs("div",{className:"p-3 border-b bg-background",children:[e.jsxs("h3",{className:"text-sm font-semibold flex items-center gap-1.5",children:[e.jsx(ci,{className:"h-4 w-4 text-primary"}),"Top Cities"]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Tap a city to filter your contacts"})]}),e.jsx(uo,{className:"flex-1",children:e.jsxs("div",{className:"p-2 space-y-1.5",children:[b.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground p-3 text-center",children:"No city data on your contacts yet. Add city/state to contacts to populate the map."}),b.slice(0,50).map((w,S)=>{var I;const 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(Ie,{className:"p-2.5 relative",children:[e.jsx("div",{className:"absolute inset-y-0 left-0 bg-primary/10",style:{width:`${E}%`}}),e.jsxs("div",{className:"relative flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"text-sm font-medium truncate",children:[w.city,w.state?`, ${w.state}`:""]}),e.jsx("div",{className:"text-[10px] text-muted-foreground",children:S===0?"🔥 Hottest market":`Rank #${S+1}`})]}),e.jsx($e,{variant:"secondary",className:"shrink-0",children:w.count})]})]})},`${w.city}-${w.state}-${S}`)})]})})]})]})]})})}function OO(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 oCt({birthday:s,homeAnniversary:t,weddingAnniversary:n,className:r,contactId:a,contactName:i,contactAddress:l}){const o=Xn(),c=W9e(s,"birthday",7),d=W9e(t,"anniversary",7),u=W9e(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(mn,{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(mn,{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(mn,{className:"h-2.5 w-2.5"}),"Send Card"]})]})]})}function lCt({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 cCt({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(JI,{className:"h-2.5 w-2.5"}),s===1?"In drip":`${s} drips`]})}function Q9n(){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 J9n(){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 e$n="#6366F1";function dCt(s,t){return`color-mix(in srgb, ${s} ${t}%, transparent)`}function t$n(s){return`color-mix(in oklab, ${s} 78%, hsl(var(--foreground)))`}function $Qt({label:s,color:t,className:n,onClick:r,title:a}){const i=t||e$n,l=r?"button":"span";return e.jsxs(l,{type:r?"button":void 0,onClick:r,title:a??s,style:{backgroundColor:dCt(i,14),color:t$n(i),boxShadow:`inset 0 0 0 1px ${dCt(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 s$n({tags:s,max:t=2,className:n}){const[r,a]=j.useState(!1);if(!s||s.length===0)return null;const i=r?s:s.slice(0,t),l=s.length-i.length;return e.jsxs("div",{className:Pt("flex flex-wrap items-center gap-1.5",n),children:[i.map(o=>{var c,d;return e.jsx($Qt,{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 uCt({contactId:s,compact:t=!1}){const{data:n}=e9(),{data:r}=EDn(s),a=Zat(),i=DXt(),l=PDn(),[o,c]=j.useState(!1),[d,u]=j.useState(""),h=j.useRef(null),m=new Set((r==null?void 0:r.map(v=>v.tag_id))||[]),f=(n==null?void 0:n.filter(v=>v.name.toLowerCase().includes(d.toLowerCase())))||[],g=n==null?void 0:n.find(v=>v.name.toLowerCase()===d.trim().toLowerCase()),x=async v=>{m.has(v.id)?await l.mutateAsync({contactId:s,tagId:v.id}):await i.mutateAsync({contactId:s,tagId:v.id})},y=async()=>{if(!(!d.trim()||g))try{const v=await a.mutateAsync({name:d.trim()});await i.mutateAsync({contactId:s,tagId:v.id}),u("")}catch{}};return e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[r==null?void 0:r.map(v=>{var b,w,S;return e.jsxs($e,{variant:"outline",className:"text-xs gap-1 pr-1",style:{borderColor:((b=v.tag)==null?void 0:b.color)||"#6366F1",color:((w=v.tag)==null?void 0:w.color)||"#6366F1"},children:[e.jsx(Ap,{className:"h-2.5 w-2.5"}),(S=v.tag)==null?void 0:S.name,e.jsx("button",{onClick:A=>{A.stopPropagation(),l.mutate({contactId:s,tagId:v.tag_id})},className:"ml-0.5 rounded-full hover:bg-accent p-0.5",children:e.jsx(pr,{className:"h-2.5 w-2.5"})})]},v.id)}),e.jsxs(Kd,{open:o,onOpenChange:c,children:[e.jsx(Yd,{asChild:!0,children:e.jsxs($,{variant:"ghost",size:"sm",className:t?"h-6 w-6 p-0":"h-6 px-2 text-xs",onClick:v=>v.stopPropagation(),children:[e.jsx(dn,{className:"h-3 w-3"}),!t&&e.jsx("span",{className:"ml-1",children:"Tag"})]})}),e.jsxs(Od,{className:"w-56 p-2",align:"start",onClick:v=>v.stopPropagation(),children:[e.jsx(pe,{ref:h,placeholder:"Search or create tag...",value:d,onChange:v=>u(v.target.value),onKeyDown:v=>{v.key==="Enter"&&d.trim()&&!g?(v.preventDefault(),y()):v.key==="Enter"&&g&&!m.has(g.id)&&(v.preventDefault(),x(g))},className:"h-8 text-sm mb-2"}),e.jsxs("div",{className:"max-h-[200px] overflow-y-auto space-y-0.5",children:[f.map(v=>e.jsxs("button",{onClick:()=>x(v),className:"flex items-center gap-2 w-full px-2 py-1.5 rounded-md text-sm hover:bg-accent transition-colors",children:[e.jsx("div",{className:"h-3 w-3 rounded-full shrink-0",style:{backgroundColor:v.color}}),e.jsx("span",{className:"flex-1 text-left truncate",children:v.name}),m.has(v.id)&&e.jsx(ca,{className:"h-3.5 w-3.5 text-primary shrink-0"})]},v.id)),d.trim()&&!g&&e.jsxs("button",{onClick:y,className:"flex items-center gap-2 w-full px-2 py-1.5 rounded-md text-sm hover:bg-accent transition-colors text-primary",children:[e.jsx(dn,{className:"h-3.5 w-3.5"}),'Create "',d.trim(),'"']}),f.length===0&&!d.trim()&&e.jsx("p",{className:"text-xs text-muted-foreground text-center py-2",children:"Type to create your first tag"})]})]})]})]})}function hCt({contactId:s,tags:t,max:n=2}){return!t||t.length===0?null:e.jsx(s$n,{tags:t,max:n})}const iue=["#6366F1","#8B5CF6","#EC4899","#EF4444","#F97316","#F59E0B","#10B981","#14B8A6","#06B6D4","#3B82F6","#6B7280","#1F2937"];function n$n({open:s,onOpenChange:t}){const{data:n,isLoading:r}=e9(),a=Zat(),i=MDn(),l=TDn(),[o,c]=j.useState(""),[d,u]=j.useState(iue[0]),[h,m]=j.useState(null),[f,g]=j.useState(""),[x,y]=j.useState(""),v=async()=>{if(o.trim())try{await a.mutateAsync({name:o.trim(),color:d}),c(""),u(iue[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 fo(`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),y(A.color)};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-md",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Manage Tags"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{placeholder:"New tag name...",value:o,onChange:A=>c(A.target.value),onKeyDown:A=>A.key==="Enter"&&v(),className:"flex-1 h-9"}),e.jsxs($,{size:"sm",onClick:v,disabled:!o.trim()||a.isPending,className:"h-9",children:[e.jsx(dn,{className:"h-4 w-4 mr-1"}),"Add"]})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:iue.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:iue.map(E=>e.jsx("button",{onClick:()=>y(E),className:`h-5 w-5 rounded-full border-2 ${x===E?"border-foreground":"border-transparent"}`,style:{backgroundColor:E}},E))}),e.jsx(pe,{value:f,onChange:E=>g(E.target.value),onKeyDown:E=>E.key==="Enter"&&b(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(ca,{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(pr,{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(Hn,{className:"h-3.5 w-3.5"})})]})},A.id))]})]})})}function r$n({open:s,onOpenChange:t}){const{data:n,isLoading:r}=BB(),a=ont(),i=TWs(),l=MWs(),[o,c]=j.useState(""),[d,u]=j.useState(null),[h,m]=j.useState(""),f=async()=>{if(o.trim())try{await a.mutateAsync(o.trim()),c("")}catch(v){re.error(v.message||"Failed to add lead source")}},g=async v=>{if(h.trim())try{await i.mutateAsync({id:v,name:h.trim()}),u(null)}catch(b){re.error(b.message||"Failed to update")}},x=async(v,b)=>{if(await fo(`Remove lead source "${b}"? Contacts using it will keep the label but it won't appear in new dropdowns.`))try{await l.mutateAsync(v)}catch(w){re.error(w.message||"Failed to remove")}},y=v=>{u(v.id),m(v.name)};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-md",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Manage Lead Sources"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{placeholder:"New lead source name...",value:o,onChange:v=>c(v.target.value),onKeyDown:v=>v.key==="Enter"&&f(),className:"flex-1 h-9"}),e.jsxs($,{size:"sm",onClick:f,disabled:!o.trim()||a.isPending,className:"h-9",children:[e.jsx(dn,{className:"h-4 w-4 mr-1"}),"Add"]})]}),e.jsxs("div",{className:"mt-2 space-y-1 max-h-[360px] overflow-y-auto",children:[r&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"Loading..."}),(n==null?void 0:n.length)===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No lead sources yet. Create one above!"}),n==null?void 0:n.map(v=>e.jsx("div",{className:"flex items-center gap-2 p-2 rounded-lg hover:bg-accent/50 group",children:d===v.id?e.jsxs(e.Fragment,{children:[e.jsx(pe,{value:h,onChange:b=>m(b.target.value),onKeyDown:b=>b.key==="Enter"&&g(v.id),className:"flex-1 h-8 text-sm",autoFocus:!0}),e.jsx($,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>g(v.id),children:e.jsx(ca,{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(pr,{className:"h-4 w-4"})})]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"flex-1 text-sm",children:v.name}),v.owner_user_id&&e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>y(v),children:e.jsx(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(v.id,v.name),children:e.jsx(Hn,{className:"h-3.5 w-3.5"})})]}),!v.owner_user_id&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Default"})]})},v.id))]})]})})}function UQt({value:s,onChange:t,label:n="Lead Source"}){const{data:r}=BB(),a=ont(),[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(pr,{className:"h-4 w-4"}):e.jsx(dn,{className:"h-4 w-4"})})]}),i&&e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{placeholder:"New lead source name...",value:o,onChange:u=>c(u.target.value),onKeyDown:u=>{u.key==="Enter"&&(u.preventDefault(),d())},className:"flex-1"}),e.jsx($,{type:"button",size:"sm",onClick:d,disabled:!o.trim()||a.isPending,children:"Add"})]})]})}function IYe({contactId:s,currentSpouseContactId:t,currentSpouseName:n,currentSpouseEmail:r,onLink:a,onUnlink:i,isEditing:l}){const o=Xn(),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:y}=await q.from("innercircle_contacts").select("id, first_name, last_name, email, phone, birthday").eq("id",t).maybeSingle();if(y)throw y;return x},enabled:!!t}),{data:g}=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:y,error:v}=await x;if(v)throw v;return y},enabled:d&&!!c});if(t&&f){const x=`${f.first_name} ${f.last_name||""}`.trim();return e.jsxs("div",{className:"space-y-1",children:[e.jsx(ee,{className:"text-sm font-medium",children:"Spouse / Partner"}),e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-border bg-muted/30 px-3 py-2",children:[e.jsx(sl,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("button",{onClick:()=>o(`/mission-control/contacts/${f.id}`),className:"text-sm font-medium text-primary hover:underline truncate block",children:x}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:[f.phone,f.email].filter(Boolean).join(" · ")||"No contact info"})]}),l&&e.jsxs($,{variant:"ghost",size:"sm",onClick:i,className:"shrink-0 h-7 px-2",children:[e.jsx(n7,{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(Kd,{open:d,onOpenChange:u,children:[e.jsx(Yd,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:"shrink-0 h-7 px-2",children:[e.jsx(Wd,{className:"h-3.5 w-3.5 mr-1"}),"Link Contact"]})}),e.jsx(Od,{className:"w-72 p-2",align:"end",children:e.jsx(mCt,{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(Kd,{open:d,onOpenChange:u,children:[e.jsx(Yd,{asChild:!0,children:e.jsxs($,{variant:"outline",className:"w-full justify-start text-muted-foreground font-normal h-10",children:[e.jsx(Wd,{className:"h-4 w-4 mr-2"}),"Link an existing contact as spouse..."]})}),e.jsx(Od,{className:"w-72 p-2",align:"start",children:e.jsx(mCt,{search:h,setSearch:m,results:g,onSelect:x=>{a(x),u(!1),m("")}})})]})]}):null}function mCt({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(Zr,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(pe,{value:s,onChange:a=>t(a.target.value),placeholder:"Search contacts...",className:"pl-7 h-8 text-sm",autoFocus:!0})]}),e.jsx(uo,{className:"max-h-48",children:n&&n.length>0?e.jsx("div",{className:"space-y-0.5",children:n.map(a=>e.jsxs("button",{onClick:()=>r(a.id),className:"w-full text-left px-2 py-1.5 rounded hover:bg-accent transition-colors",children:[e.jsxs("div",{className:"text-sm font-medium truncate",children:[a.first_name," ",a.last_name]}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:[a.phone,a.email].filter(Boolean).join(" · ")||"No contact info"})]},a.id))}):e.jsx("p",{className:"text-xs text-muted-foreground text-center py-3",children:s?"No contacts found":"Type to search contacts"})})]})}const a$n={warm:"stroke-emerald-500",cooling:"stroke-amber-500","at-risk":"stroke-red-500"},i$n={warm:"text-emerald-600 dark:text-emerald-400",cooling:"text-amber-600 dark:text-amber-400","at-risk":"text-red-600 dark:text-red-400"};function o$n({score:s,status:t,size:n=36,className:r}){const a=n>=56?5:3,i=(n-a)/2,l=2*Math.PI*i,o=Math.max(0,Math.min(100,s)),c=l-o/100*l;return e.jsxs("div",{className:Pt("relative shrink-0",r),style:{width:n,height:n},children:[e.jsxs("svg",{width:n,height:n,className:"-rotate-90",children:[e.jsx("circle",{cx:n/2,cy:n/2,r:i,fill:"none",strokeWidth:a,className:"stroke-muted"}),e.jsx("circle",{cx:n/2,cy:n/2,r:i,fill:"none",strokeWidth:a,strokeLinecap:"round",strokeDasharray:l,strokeDashoffset:c,className:a$n[t]})]}),e.jsx("span",{className:Pt("absolute inset-0 flex items-center justify-center font-semibold tabular-nums",i$n[t],n>=56?"text-lg":"text-[11px]"),children:o})]})}const oue=new Map;async function l$n(s){const t=new TextEncoder().encode(s),n=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(r=>r.toString(16).padStart(2,"0")).join("")}async function c$n(s,t=256){const n=s.trim().toLowerCase();if(!n||!n.includes("@"))return null;const r=`${n}|${t}`;if(oue.has(r))return oue.get(r)??null;try{const i=`https://gravatar.com/avatar/${await l$n(n)}?s=${t}&d=404`;return oue.set(r,i),i}catch{return oue.set(r,null),null}}function d$n(s,t=256){const[n,r]=j.useState(null);return j.useEffect(()=>{let a=!0;if(!s){r(null);return}return c$n(s,t).then(i=>{a&&r(i)}),()=>{a=!1}},[s,t]),n}function vit({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=d$n(n?null:r,Math.max(64,a*2)),[u,h]=j.useState(!1);j.useEffect(()=>h(!1),[d]);const m=n||(u?null:d);return e.jsx("div",{className:Pt("shrink-0 overflow-hidden bg-primary/10 text-primary flex items-center justify-center font-semibold select-none",c,i),style:{width:a,height:a,fontSize:Math.max(10,Math.round(a*.36))},children:m?e.jsx("img",{src:m,alt:`${s??""} ${t??""}`.trim()||"Contact photo",className:"h-full w-full object-cover",loading:"lazy",onError:()=>h(!0)}):e.jsx("span",{children:o})})}function u$n({spouseName:s,linked:t,onClick:n}){if(!s&&!t)return null;const r=s?`${t?"Linked spouse":"Spouse"}: ${s}`:"Spouse / partner linked";return e.jsxs(iy,{children:[e.jsx(oy,{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(jx,{children:r})]})}function h$n({totalLabel:s,stats:t,search:n,onSearchChange:r,onAddContact:a,onImportCsv:i,onImportPhone:l,onManageTags:o,onHeatMap:c,viewMode:d="my",onViewModeChange:u,showTeamTab:h,showLeadPondTab:m,extraActions:f}){const g=!!u&&(h||m);return e.jsx("section",{className:"hub-ink relative overflow-hidden rounded-2xl p-5 sm:p-6",children:e.jsxs("div",{className:"relative flex flex-col gap-5",children:[e.jsxs("div",{className:"flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-xs uppercase tracking-wider hub-ink-muted",children:"Agent OS"}),e.jsx("h1",{className:"mt-1 text-2xl font-bold sm:text-3xl",children:"Contacts"}),e.jsx("p",{className:"mt-1 text-sm hub-ink-muted",children:s})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("button",{onClick:a,className:"inline-flex items-center gap-2 rounded-full bg-background px-4 py-2 text-sm font-semibold text-foreground shadow-sm transition-transform hover:scale-[1.02]",children:[e.jsx(dn,{className:"h-4 w-4"}),"Add Contact"]}),e.jsxs("button",{onClick:c,className:"hub-glass inline-flex items-center gap-2 rounded-full px-4 py-2 text-sm font-medium transition-colors",children:[e.jsx(sh,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Heat Map"]}),e.jsxs($u,{children:[e.jsx(Uu,{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(Au,{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(x1,{className:"mr-2 h-4 w-4"})," Import from Phone"]}),e.jsxs(ja,{onClick:o,children:[e.jsx(Ap,{className:"mr-2 h-4 w-4"})," Manage Tags"]})]})]}),f]})]}),e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center",children:[e.jsxs("div",{className:"relative flex-1 min-w-0",children:[e.jsx(Zr,{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:g1,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 m$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 f$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 fCt({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 qQt(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 pCt(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:da,color:"text-amber-600 dark:text-amber-400",match:s=>{const t=s.relationshipScore.daysSinceTouch;return t!==null&&t>90}},{key:"cooling",title:"Cooling Off",icon:Xj,color:"text-cyan-600 dark:text-cyan-400",match:s=>s.relationshipScore.status==="cooling"},{key:"birthdays-soon",title:"Birthdays Soon",icon:Fg,color:"text-pink-600 dark:text-pink-400",match:(s,t)=>t.daysToBirthday!==null&&t.daysToBirthday<=30},{key:"anniversary-soon",title:"Home Anniversary",icon:va,color:"text-emerald-600 dark:text-emerald-400",match:(s,t)=>t.daysToAnniv!==null&&t.daysToAnniv<=30},{key:"has-deal",title:"Active Deal",icon:kx,color:"text-teal-700 dark:text-teal-400",match:(s,t)=>t.hasDeal},{key:"website-active",title:"Active on Site",icon:dl,color:"text-indigo-600 dark:text-indigo-400",match:()=>!1},{key:"vips",title:"VIPs",icon:Nn,color:"text-amber-600 dark:text-amber-300",match:s=>s.relationshipScore.score>=80},{key:"active-buyers",title:"Active Buyers",icon:Zr,color:"text-sky-600 dark:text-sky-400",match:(s,t)=>t.hasCriteria},{key:"missing-criteria",title:"No Home Search",icon:Jq,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=>qQt(s)}];function p$n({contacts:s,contactDealsMap:t,websiteActiveIds:n,criteriaContactIds:r,totalCount:a,activeKey:i,onSelectSegment:l,currentFilters:o,currentSortBy:c,activeViewId:d,onApplyView:u,onClearAll:h}){const{data:m}=Xat(),f=FXt(),g=OXt(),[x,y]=j.useState(!1),[v,b]=j.useState(""),w=j.useMemo(()=>{const I={"needs-attention":0,cooling:0,"never-contacted":0,"stale-90":0,"birthdays-soon":0,"anniversary-soon":0,"has-deal":0,"website-active":n.size,"missing-info":0,vips:0,"active-buyers":0,"missing-criteria":0};if(!s)return I;for(const P of s){const R={hasDeal:!!(t&&t[P.id]),daysToBirthday:pCt(P.birthday),daysToAnniv:pCt(P.home_anniversary),hasCriteria:!!(r!=null&&r.has(P.id))};for(const D of gCt)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()=>{v.trim()&&(await f.mutateAsync({name:v.trim(),filters:o,sort_by:c}),b(""),y(!1))},E="inline-flex items-center gap-1.5 h-8 shrink-0 rounded-full border px-3 text-xs font-medium transition-colors whitespace-nowrap";return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2 overflow-x-auto pb-1 -mx-1 px-1 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",children:[e.jsxs("button",{type:"button",onClick:h,className:Pt(E,!i&&!d?"bg-primary text-primary-foreground border-primary":"bg-card hover:bg-accent border-border"),children:[e.jsx(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(pr,{className:"h-3 w-3"})})]},I.id)}),e.jsx("div",{className:"h-5 w-px bg-border shrink-0"}),gCt.map(I=>{const P=I.icon,R=w[I.key],D=i===I.key;return e.jsxs("button",{type:"button",onClick:()=>l(D?null:I.key),"aria-pressed":D,className:Pt(E,D?"bg-primary text-primary-foreground border-primary":"bg-card hover:bg-accent border-border",!D&&R===0&&"opacity-55"),children:[e.jsx(P,{className:Pt("h-3.5 w-3.5",D?"":I.color)}),I.title,e.jsx("span",{className:"tabular-nums opacity-70",children:R.toLocaleString()})]},I.key)}),e.jsxs($,{variant:"ghost",size:"sm",className:"h-8 gap-1.5 text-xs shrink-0",disabled:!S,onClick:()=>y(!0),children:[e.jsx(BI,{className:"h-3.5 w-3.5"}),"Save view"]})]}),e.jsx(zs,{open:x,onOpenChange:y,children:e.jsxs(Os,{className:"sm:max-w-sm",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Save this view"}),e.jsx(Pr,{children:"Your current search, filters, and sorting are saved as a one-click chip."})]}),e.jsx(pe,{autoFocus:!0,placeholder:"e.g. Past clients cooling off",value:v,onChange:I=>b(I.target.value),onKeyDown:I=>I.key==="Enter"&&A()}),e.jsxs(Sr,{children:[e.jsx($,{variant:"outline",onClick:()=>y(!1),children:"Cancel"}),e.jsx($,{onClick:A,disabled:!v.trim()||f.isPending,children:"Save view"})]})]})})]})}const xCt=[{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"}],K9e={relationship:!0,buyerCriteria:!0,stage:!0,leadSource:!0,tags:!0,lastTouch:!0,nextAction:!0,dealValue:!0,email:!1,phone:!1,address:!1,birthday:!1},yCt="innercircle:contact-columns:v1";function g$n(){const[s,t]=j.useState(()=>{try{const a=localStorage.getItem(yCt);if(a)return{...K9e,...JSON.parse(a)}}catch{}return K9e});j.useEffect(()=>{try{localStorage.setItem(yCt,JSON.stringify(s))}catch{}},[s]);const n=j.useCallback(a=>{t(i=>({...i,[a]:!i[a]}))},[]),r=j.useCallback(()=>t(K9e),[]);return{columns:s,toggle:n,reset:r}}function x$n({columns:s,onToggle:t,onReset:n}){const r=xCt.filter(a=>s[a.key]).length;return e.jsxs(Kd,{children:[e.jsx(Yd,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:"h-8 gap-1.5 rounded-lg text-xs",children:[e.jsx(rP,{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(Od,{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(Ax,{className:"h-3 w-3"}),"Reset"]})]}),e.jsx("div",{className:"max-h-[320px] overflow-y-auto space-y-0.5",children:xCt.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 MV=1e3;function VQt(){const s=Sa();return st({queryKey:["contact-criteria-map",s],enabled:!!s,staleTime:60*1e3,queryFn:async()=>{const t=[];for(let r=0;;r+=MV){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+MV-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+=MV){const{data:c,error:d}=await q.from("contact_property_alerts").select("id, contact_id").eq("owner_user_id",t).range(o,o+MV-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 b$n(){const s=Wt();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 lq=s=>String(s??"").trim().toLowerCase();function _$n(s,t){const n=lq(s).replace(/[\s_-]+/g,""),r=lq(t).replace(/[\s_-]+/g,"");return!n||!r?!1:n===r||n.includes(r)||r.includes(n)}function w$n(s,t){var m,f,g;const n=[],r=[],a=t.price??null,i=t.bedrooms??null,l=t.bathrooms??null,o=t.sqft??null;if((((m=s.cities)==null?void 0:m.length)||0)>0||(((f=s.zip_codes)==null?void 0:f.length)||0)>0){const x=!!t.city&&(s.cities||[]).some(v=>lq(v)===lq(t.city)),y=!!t.zip&&(s.zip_codes||[]).some(v=>lq(v)===lq(t.zip));x?n.push(`Wants ${t.city}`):y?n.push(`Wants ${t.zip}`):(t.city||t.zip)&&r.push(`Looking in ${[...s.cities||[],...s.zip_codes||[]].slice(0,3).join(", ")}`)}a!==null&&(s.min_price&&as.max_price?r.push(`Over their $${Math.round(s.max_price/1e3)}k budget`):(s.min_price||s.max_price)&&n.push("In their price range")),s.min_beds&&(i!==null&&i0&&(s.min_sqft&&os.max_sqft?r.push("Over their max sqft"):(s.min_sqft||s.max_sqft)&&n.push("Size fits")),(((g=s.property_types)==null?void 0:g.length)||0)>0&&t.propertyType&&(s.property_types.some(y=>_$n(y,t.propertyType))?n.push(String(t.propertyType).replace(/_/g," ")):r.push(`Wants ${s.property_types.slice(0,2).join(" / ")}`));const d=r.length===0&&n.length>0,u=n.length+r.length,h=u===0?0:Math.round(n.length/u*100);return{matches:d,score:h,reasons:n,misses:r}}function j$n(s,t,n,r={}){const a=[];for(const i of s){const l=t[i.id];if(!l)continue;const o=w$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 lue=s=>s>=1e3?`$${Math.round(s/1e3)}k`:`$${s}`;function HQt(s){var t,n,r;return s?!!(s.min_price||s.max_price||s.min_beds||s.min_baths||s.min_sqft||s.max_sqft||(t=s.cities)!=null&&t.length||(n=s.zip_codes)!=null&&n.length||(r=s.property_types)!=null&&r.length):!1}function N$n(s){var r;if(!s)return"";const t=[];s.min_price&&s.max_price?t.push(`${lue(s.min_price)}–${lue(s.max_price)}`):s.max_price?t.push(`up to ${lue(s.max_price)}`):s.min_price&&t.push(`${lue(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 vCt({criteria:s,onEdit:t,showAlertState:n,matchCount:r,className:a,compact:i}){const l=N$n(s);return HQt(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(Uy,{className:"h-3.5 w-3.5 shrink-0 text-emerald-600 dark:text-emerald-400"}):e.jsx(YS,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):e.jsx(Zr,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),e.jsx("span",{className:Pt("truncate",i?"text-[11px]":"text-xs","text-foreground/80"),children:l}),!!r&&r>0&&e.jsxs("span",{className:"shrink-0 rounded-full bg-primary/10 px-1.5 text-[10px] font-semibold text-primary tabular-nums",children:[r," new"]})]}):t?e.jsxs("button",{type:"button",onClick:c=>{c.stopPropagation(),t()},className:Pt("inline-flex items-center gap-1 whitespace-nowrap rounded-full border border-dashed border-primary/40 px-2 py-0.5","text-[11px] text-muted-foreground hover:bg-primary/5 hover:text-primary transition-colors",a),children:[e.jsx(dn,{className:"h-3 w-3"}),"Add home search"]}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"—"})}const GQt=["Single Family","Condo","Townhouse","Multi-Family","Land","Commercial"];function k$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 bCt({value:s,onChange:t,onAdd:n,suggestions:r,placeholder:a,icon:i}){const[l,o]=j.useState(!1),c=j.useRef(null),d=j.useRef(null);j.useEffect(()=>{const h=m=>{d.current&&!d.current.contains(m.target)&&o(!1)};return document.addEventListener("mousedown",h),()=>document.removeEventListener("mousedown",h)},[]);const u=r.filter(h=>h.toLowerCase().includes(s.trim().toLowerCase()));return e.jsxs("div",{className:"relative",ref:d,children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx("div",{className:"flex-1",children:e.jsx(pe,{value:s,onChange:h=>{t(h.target.value),o(!0)},onFocus:()=>o(!0),onKeyDown:h=>{h.key==="Enter"&&(h.preventDefault(),n(s),o(!1))},placeholder:a})}),e.jsx($,{type:"button",variant:"outline",size:"sm",onClick:()=>n(s),children:e.jsx(dn,{className:"h-4 w-4"})})]}),l&&u.length>0&&e.jsx("div",{ref:c,className:"absolute z-50 mt-1 w-full max-h-60 overflow-y-auto rounded-md border bg-popover shadow-md",children:u.map(h=>e.jsxs("button",{type:"button",className:"w-full text-left px-3 py-2 text-sm hover:bg-accent hover:text-accent-foreground transition-colors flex items-center gap-2",onClick:()=>{n(h),o(!1)},children:[i||e.jsx(ci,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}),h]},h))})]})}function WQt({value:s,onChange:t,hasIdx:n=!0,idxNote:r}){const[a,i]=j.useState(""),[l,o]=j.useState(""),{data:c}=k$n(),d=((c==null?void 0:c.cities)||[]).filter(g=>{var x;return!((x=s.cities)!=null&&x.includes(g))}),u=((c==null?void 0:c.zipCodes)||[]).filter(g=>{var x;return!((x=s.zip_codes)!=null&&x.includes(g))}),h=g=>{var y;const x=g.trim();x&&!((y=s.cities)!=null&&y.includes(x))&&t(v=>({...v,cities:[...v.cities||[],x]})),i("")},m=g=>{var y;const x=g.trim();x&&!((y=s.zip_codes)!=null&&y.includes(x))&&t(v=>({...v,zip_codes:[...v.zip_codes||[],x]})),o("")},f=g=>{t(x=>{const y=x.property_types||[];return{...x,property_types:y.includes(g)?y.filter(v=>v!==g):[...y,g]}})};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsxs(ee,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(nu,{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(A4,{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(A0,{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(P4,{className:"h-3.5 w-3.5"})," Square Feet"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(pe,{type:"number",placeholder:"Min sqft",value:s.min_sqft??"",onChange:g=>t(x=>({...x,min_sqft:g.target.value?Number(g.target.value):null}))}),e.jsx(pe,{type:"number",placeholder:"Max sqft",value:s.max_sqft??"",onChange:g=>t(x=>({...x,max_sqft:g.target.value?Number(g.target.value):null}))})]})]}),e.jsxs("div",{children:[e.jsxs(ee,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(ci,{className:"h-3.5 w-3.5"})," Cities"]}),e.jsx(bCt,{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 y;return{...x,cities:(y=x.cities)==null?void 0:y.filter(v=>v!==g)}}),children:e.jsx(pr,{className:"h-3 w-3"})})]},g))})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"mb-1.5",children:"Zip Codes"}),e.jsx(bCt,{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 y;return{...x,zip_codes:(y=x.zip_codes)==null?void 0:y.filter(v=>v!==g)}}),children:e.jsx(pr,{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:GQt.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(Sn,{checked:s.is_active??!0,onCheckedChange:g=>t(x=>({...x,is_active:g}))})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"mb-1.5",children:"Frequency"}),e.jsxs(ms,{value:s.frequency||"daily",onValueChange:g=>t(x=>({...x,frequency:g})),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"daily",children:"Daily"}),e.jsx(Ge,{value:"weekly",children:"Weekly"})]})]})]})]}):e.jsxs("div",{className:"rounded-lg border border-dashed bg-muted/40 p-3 space-y-1.5",children:[e.jsxs("p",{className:"text-xs text-muted-foreground flex items-start gap-2",children:[e.jsx(QS,{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 S$n({open:s,onOpenChange:t,contactId:n,contactName:r,existing:a}){const{hasIdx:i}=ng(),l=v$n(),o=b$n(),[c,d]=j.useState({});j.useEffect(()=>{s&&d({is_active:(a==null?void 0:a.is_active)??!0,min_price:(a==null?void 0:a.min_price)??null,max_price:(a==null?void 0:a.max_price)??null,min_beds:(a==null?void 0:a.min_beds)??null,min_baths:(a==null?void 0:a.min_baths)??null,min_sqft:(a==null?void 0:a.min_sqft)??null,max_sqft:(a==null?void 0:a.max_sqft)??null,cities:(a==null?void 0:a.cities)??[],zip_codes:(a==null?void 0:a.zip_codes)??[],property_types:(a==null?void 0:a.property_types)??[],frequency:(a==null?void 0:a.frequency)??"daily"})},[s,a]);const u=async()=>{try{await l.mutateAsync({contactId:n,existingId:(a==null?void 0:a.id)??null,values:c}),re.success(`Home search saved for ${r}`),t(!1)}catch(m){re.error((m==null?void 0:m.message)||"Could not save home search")}},h=async()=>{if(a!=null&&a.id)try{await o.mutateAsync({id:a.id,contactId:n}),re.success("Home search removed"),t(!1)}catch(m){re.error((m==null?void 0:m.message)||"Could not remove home search")}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{children:["Home search for ",r]}),e.jsx(Pr,{children:"What are they looking for? This shows on your contacts dashboard so you can match new listings to them."})]}),e.jsx(WQt,{value:c,onChange:d,hasIdx:i,idxNote:e.jsx($,{asChild:!0,variant:"link",size:"sm",className:"h-auto p-0 text-xs",children:e.jsx(wr,{to:"/mission-control/website",children:"Explore IDX websites"})})}),e.jsxs(Sr,{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(Hn,{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 Rp=s=>s.replace(/&/g,"&").replace(//g,">").replace(/"/g,"""),C$n=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s);function A$n(s,t){const n=s.address||[s.city,s.state].filter(Boolean).join(", ")||"a home";return t?`${t}, this one looks like your kind of home — ${n}`:`Thought of you: ${n}`}function E$n(s){const t=[];return s.bedrooms&&t.push(`${s.bedrooms} bedrooms`),s.bathrooms&&t.push(`${s.bathrooms} baths`),s.city&&t.push(`in ${s.city}`),`Hi {{first_name}}, This just came across my desk and it lines up with what you told me you're looking for${t.length?` — ${t.join(", ")}`:""}. I wanted you to see it before it gets busy. Want me to set up a private showing?`}function T$n(s,t,n){const r=(s.photos||[]).filter(Boolean),a=r[0]||"",i=r[1]||"",l=r[2]||"",o=s.publicUrl||"",c=[s.city,s.state].filter(Boolean).join(", ")+(s.zip?` ${s.zip}`:""),d=s.address||c||"A home worth seeing",u=s.price?C$n(Number(s.price)):"",h=(n==null?void 0:n.name)||"",m=(n==null?void 0:n.title)||"Real Estate Agent",f=(n==null?void 0:n.phone)||"",g=(n==null?void 0:n.email)||"",x=(n==null?void 0:n.avatar_url)||"",y=(n==null?void 0:n.brokerage_name)||"",v=h?h.split(" ").map(S=>S[0]).slice(0,2).join("").toUpperCase():"A",b=(S,A,E=!1)=>`
${Rp(S)}
${Rp(A)}
`,w=[];return s.bedrooms&&w.push(b(String(s.bedrooms),"Beds")),s.bathrooms&&w.push(b(String(s.bathrooms),"Baths")),s.sqft&&w.push(b(Number(s.sqft).toLocaleString(),"Sq Ft")),s.propertyType&&w.push(b(s.propertyType,"Type")),` ${Rp(d)}
${Rp([u,d].filter(Boolean).join(" · "))}
${a?` `:""} ${w.length?` `:""} ${t?` `:""} ${o?` `:""} ${i||l?` `:""} ${h?` `:""}
 
${o?``:""} ${Rp(d)} ${o?"":""}
${u?``:""}
A home matched to your search${Rp(u)}

${Rp(d)}

${s.address&&c?`

${Rp(c)}

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

${Rp(t)}

View this home  →

See all the photos and details

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

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

`}function M$n({open:s,onOpenChange:t,property:n,recipient:r}){const{user:a}=bs(),i=Sa(),{isGmailConnected:l,gmailEmail:o}=gy(),{isReady:c,settings:d}=l6(),[u,h]=j.useState(""),[m,f]=j.useState(""),[g,x]=j.useState(!1),[y,v]=j.useState(!1),{data:b}=st({queryKey:["match-email-agent",i],enabled:!!i&&s,queryFn:async()=>{const{data:R}=await q.from("profiles").select("name, title, email, phone, avatar_url, brokerage_name").eq("id",i).maybeSingle();return R??null}});j.useEffect(()=>{!s||!r||(h(A$n(n,r.first_name)),f(E$n(n)),x(!1))},[s,r==null?void 0:r.id]);const w=j.useMemo(()=>m.replace(/\{\{first_name\}\}/gi,(r==null?void 0:r.first_name)||"there"),[m,r==null?void 0:r.first_name]),S=j.useMemo(()=>T$n(n,w,b??null),[n,w,b]),A=l||c,E=!!(r!=null&&r.email&&u.trim()&&A&&!y),I=async()=>{if(!(!E||!(r!=null&&r.email))){v(!0);try{if(l){const{data:R,error:D}=await q.functions.invoke("gmail-send",{body:{to:r.email,subject:u.trim(),body:S,contactId:r.id}});if(D)throw D;if(!(R!=null&&R.success))throw new Error((R==null?void 0:R.error)||"Failed to send")}else{const R=(d==null?void 0:d.display_name)||"ReLevelUp",D=`${R.toLowerCase().replace(/[^a-z]/g,".")}@send.relevelup.com`,{data:O,error:U}=await q.functions.invoke("ses-send-campaign",{body:{action:"test_send",to:r.email,from_email:`${R} <${D}>`,subject:u.trim(),body_html:S,reply_to:(d==null?void 0:d.reply_to_email)||(b==null?void 0:b.email)||void 0,contact_id:r.id}});if(U)throw U;if(!(O!=null&&O.success))throw new Error((O==null?void 0:O.error)||"Failed to send")}if(a)try{await q.from("bulk_email_sends").insert({user_id:a.id,contact_id:r.id,contact_email:r.email,subject:u.trim(),source:"listing_match"})}catch{}re.success(`Sent to ${r.first_name}`),t(!1)}catch(R){re.error((R==null?void 0:R.message)||"Could not send the email")}finally{v(!1)}}},P=r?`${r.first_name} ${r.last_name||""}`.trim():"";return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"w-[95vw] max-w-[95vw] sm:max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(mn,{className:"h-4 w-4 text-primary"}),"Email this home to ",P||"your buyer"]}),e.jsx(Pr,{children:A?e.jsxs(e.Fragment,{children:["Sending from ",l?`your Gmail (${o})`:"your mass email sender","."]}):"Connect Gmail or set up mass email first."})]}),!A&&e.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-amber-500/40 bg-amber-500/10 p-3 text-sm",children:[e.jsx(ll,{className:"h-4 w-4 mt-0.5 text-amber-600 shrink-0"}),e.jsx("span",{children:"You don't have an email sender connected yet. Connect Gmail in Settings, or finish mass email setup, and this will send straight from you."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"To"}),e.jsxs("div",{className:"flex items-center gap-2 rounded-md border px-3 py-2 text-sm",children:[e.jsx("span",{className:"font-medium",children:P}),e.jsx($e,{variant:"secondary",className:"font-normal",children:r==null?void 0:r.email})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"match-subject",className:"text-xs",children:"Subject"}),e.jsx(pe,{id:"match-subject",value:u,onChange:R=>h(R.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"match-message",className:"text-xs",children:"Your note"}),e.jsx(Ls,{id:"match-message",rows:6,value:m,onChange:R=>f(R.target.value)}),e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Use ","{{first_name}}"," anywhere and we'll swap in their name."]})]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>x(R=>!R),children:[g?e.jsx($g,{className:"h-4 w-4 mr-2"}):e.jsx(Ca,{className:"h-4 w-4 mr-2"}),g?"Hide preview":"Preview email"]}),g&&e.jsx(uo,{className:"h-[380px] rounded-lg border",children:e.jsx("iframe",{title:"Email preview",srcDoc:S,className:"w-full h-[1200px] border-0"})})]}),e.jsxs(Sr,{children:[e.jsx($,{variant:"ghost",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{onClick:I,disabled:!E,children:[y?e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Kr,{className:"h-4 w-4 mr-2"}),"Send email"]})]})]})})}const P$n={city:"",state:"",zip:"",price:null,bedrooms:null,bathrooms:null,sqft:null,propertyType:"",address:""};function I$n({open:s,onOpenChange:t,contacts:n}){const r=Xn(),{data:a}=VQt(),{data:i}=Hst(),[l,o]=j.useState(P$n),[c,d]=j.useState(!0),[u,h]=j.useState(""),[m,f]=j.useState(null),g=S=>o(A=>({...A,...S})),x=S=>{h(S);const A=(i||[]).find(E=>E.id===S);A&&g({address:A.property_address||"",city:A.city||"",state:A.state||"",zip:"",price:A.price??null,bedrooms:A.bedrooms??null,bathrooms:A.bathrooms??null,sqft:A.square_footage??null,propertyType:A.property_type||""})},y=!!(l.city||l.zip||l.price),v=j.useMemo(()=>{const S=i==null?void 0:i.find(I=>I.id===u),A=Array.isArray(S==null?void 0:S.photos)?S.photos.slice().sort((I,P)=>!!P.is_primary!=!!I.is_primary?P.is_primary?1:-1:(I.sort_order??0)-(P.sort_order??0)).map(I=>I.photo_url).filter(Boolean):[],E=S&&S.is_public&&S.is_approved?`${window.location.origin}/public/listing/${S.slug||S.id}`:null;return{address:l.address||void 0,city:l.city||void 0,state:l.state||void 0,zip:l.zip||void 0,price:l.price,bedrooms:l.bedrooms,bathrooms:l.bathrooms,sqft:l.sqft,propertyType:l.propertyType||void 0,photos:A,publicUrl:E}},[i,u,l]),b=j.useMemo(()=>!a||!y?[]:j$n(n,a,l,{includeNearMatches:c}),[n,a,l,c,y]),w=j.useMemo(()=>Object.keys(a||{}).length,[a]);return e.jsxs(Gy,{open:s,onOpenChange:t,children:[e.jsxs(my,{side:"right",className:"w-full sm:max-w-xl overflow-y-auto",children:[e.jsxs(L0,{children:[e.jsxs(R0,{className:"flex items-center gap-2",children:[e.jsx(Yn,{className:"h-4 w-4 text-primary"}),"Who wants this house?"]}),e.jsx(DB,{children:"Enter a property — or pick one of your listings — and we'll show the contacts whose saved home search fits. No IDX needed."})]}),e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsxs(ha,{defaultValue:i!=null&&i.length?"listing":"manual",children:[e.jsxs(ma,{className:"grid w-full grid-cols-2",children:[e.jsx(Zt,{value:"listing",children:"My listings"}),e.jsx(Zt,{value:"manual",children:"Enter a property"})]}),e.jsx(Xt,{value:"listing",className:"pt-3",children:i!=null&&i.length?e.jsxs(ms,{value:u,onValueChange:x,children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Choose a listing…"})}),e.jsx(hs,{children:i.map(S=>e.jsxs(Ge,{value:S.id,children:[[S.property_address,S.city].filter(Boolean).join(", "),S.price?` — ${Xm(Number(S.price))}`:""]},S.id))})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:`You don't have any Listing Exchange listings yet. Use "Enter a property" instead.`})}),e.jsx(Xt,{value:"manual",className:"pt-3",children:e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"Saw something in your MLS? Type the basics here."})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"col-span-2",children:[e.jsx(ee,{className:"mb-1.5 text-xs",children:"Address (optional)"}),e.jsx(pe,{value:l.address||"",onChange:S=>g({address:S.target.value}),placeholder:"123 Main St"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"mb-1.5 text-xs",children:"City"}),e.jsx(pe,{value:l.city||"",onChange:S=>g({city:S.target.value}),placeholder:"Cypress"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"mb-1.5 text-xs",children:"Zip"}),e.jsx(pe,{value:l.zip||"",onChange:S=>g({zip:S.target.value}),placeholder:"90630"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"mb-1.5 text-xs",children:"Price"}),e.jsx(pe,{type:"number",value:l.price??"",onChange:S=>g({price:S.target.value?Number(S.target.value):null}),placeholder:"750000"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"mb-1.5 text-xs",children:"Sqft"}),e.jsx(pe,{type:"number",value:l.sqft??"",onChange:S=>g({sqft:S.target.value?Number(S.target.value):null}),placeholder:"1800"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"mb-1.5 text-xs",children:"Beds"}),e.jsx(pe,{type:"number",value:l.bedrooms??"",onChange:S=>g({bedrooms:S.target.value?Number(S.target.value):null}),placeholder:"3"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"mb-1.5 text-xs",children:"Baths"}),e.jsx(pe,{type:"number",step:"0.5",value:l.bathrooms??"",onChange:S=>g({bathrooms:S.target.value?Number(S.target.value):null}),placeholder:"2"})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx(ee,{className:"mb-1.5 text-xs",children:"Property type"}),e.jsxs(ms,{value:l.propertyType||"any",onValueChange:S=>g({propertyType:S==="any"?"":S}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"any",children:"Any"}),GQt.map(S=>e.jsx(Ge,{value:S,children:S},S))]})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between border-t pt-3",children:[e.jsxs("div",{className:"text-xs text-muted-foreground",children:[w," ",w===1?"contact has":"contacts have"," a saved home search"]}),e.jsx($,{variant:c?"secondary":"outline",size:"sm",className:"h-7 text-xs",onClick:()=>d(S=>!S),children:c?"Including close matches":"Exact matches only"})]}),y?b.length===0?e.jsxs("div",{className:"rounded-lg border border-dashed p-6 text-center text-sm text-muted-foreground",children:[e.jsx(va,{className:"h-5 w-5 mx-auto mb-2 opacity-60"}),"No contacts match this property yet. Add home searches to your buyers so matches show up here."]}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:[b.length," ",b.length===1?"match":"matches"]}),b.map(({contact:S,result:A})=>{const E=`${S.first_name} ${S.last_name||""}`.trim();return e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border p-3",children:[e.jsx(vit,{firstName:S.first_name,lastName:S.last_name||void 0,avatarUrl:S.avatar_url||void 0,email:S.email||void 0,size:36}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("button",{type:"button",className:"font-medium text-sm hover:underline",onClick:()=>r(`/mission-control/contacts/${S.id}`),children:E}),e.jsxs("div",{className:"mt-1 flex flex-wrap gap-1",children:[A.reasons.slice(0,4).map(I=>e.jsx($e,{variant:"secondary",className:"text-[10px]",children:I},I)),A.misses.map(I=>e.jsx($e,{variant:"outline",className:"text-[10px] text-muted-foreground",children:I},I))]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[S.email&&e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",title:`Email ${E}`,onClick:()=>f(S),children:e.jsx(mn,{className:"h-4 w-4"})}),S.phone&&e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",title:`Text ${E}`,asChild:!0,children:e.jsx("a",{href:`sms:${S.phone}`,children:e.jsx(eo,{className:"h-4 w-4"})})})]})]},S.id)})]}):e.jsxs("div",{className:"rounded-lg border border-dashed p-6 text-center text-sm text-muted-foreground",children:[e.jsx(Zr,{className:"h-5 w-5 mx-auto mb-2 opacity-60"}),"Add a city, zip, or price to see matches."]})]})]}),e.jsx(M$n,{open:!!m,onOpenChange:S=>!S&&f(null),property:v,recipient:m})]})}function L$n(){var Yc;const s=Xn(),[t,n]=gc(),{user:r}=bs(),a=FK(),i=Wt(),{columns:l,toggle:o,reset:c}=g$n(),d=t.get("type"),u=t.get("filter")??t.get("status"),h=t.get("new")==="true",{contactsWithScores:m,isLoading:f}=rie(),{activeContactIds:g,hasLeadSite:x}=GBn(),{data:y}=Q9n(),{data:v}=qw(),{data:b}=J9n(),{data:w}=e9(),{data:S}=Tie(),{hasIdx:A}=ng(),{data:E}=VQt(),{data:I}=y$n(!!A),P=j.useMemo(()=>new Set(Object.entries(E||{}).filter(([,_s])=>HQt(_s)).map(([_s])=>_s)),[E]),[R,D]=j.useState(null),[O,U]=j.useState(!1),[W,V]=j.useState(new Set),[G,Y]=j.useState("any"),X=v6e(),ae=Jst(),le=MUt(),ne=TUt(),[te,J]=j.useState(""),[ce,_e]=j.useState(!1),[he,ue]=j.useState(d||"all"),[ve,Ee]=j.useState(u||"all"),[Se,Le]=j.useState("date-added"),[Fe,ke]=j.useState("all"),[Be,Ne]=j.useState({}),Ae=j.useMemo(()=>Object.values(Be).filter(_s=>_s!==void 0&&_s!==!1&&_s!=="").length,[Be]),[Ce,Ve]=j.useState(!1),[ze,qe]=j.useState([]),{neighborhoods:dt}=yit(),Xe=j.useMemo(()=>zQt(dt,ze),[dt,ze]),{behaviorMap:at,hasLeadSite:rt}=W9n(),[Ke,Je]=j.useState(h),[pt,gt]=j.useState(null),[ss,Yt]=j.useState(!1),[ts,ys]=j.useState(!1),[Bt,Ft]=j.useState(null),[as,kt]=j.useState(""),[Ks,wt]=j.useState(new Set),[gs,ks]=j.useState(!1),[Is,Xs]=j.useState(!1),ds=Math.max(1,parseInt(t.get("page")||"1",10)||1),[Ss,yn]=j.useState(ds),Js=j.useCallback(_s=>{yn(Xa=>{const No=typeof _s=="function"?_s(Xa):_s;return n(Ba=>{const io=new URLSearchParams(Ba);return No<=1?io.delete("page"):io.set("page",String(No)),io},{replace:!0}),No})},[]),[Ut,hn]=j.useState(50),[hr,Rs]=j.useState("my"),[jr,kr]=j.useState(!1),[$n,kn]=j.useState(!1),{data:Fn}=zw(),{addToLeadPond:bn}=PWt(Fn==null?void 0:Fn.teamId),{ponds:xs}=Drt(Fn==null?void 0:Fn.teamId),Lr=xs.filter(_s=>_s.has_access),[Or,la]=j.useState(null),[Qn,Cr]=j.useState(""),Un=!!((Yc=Fn==null?void 0:Fn.team)!=null&&Yc.lead_pond_enabled&&(Fn!=null&&Fn.teamId)),dr=!!(Fn!=null&&Fn.teamId),[Pa,ii]=j.useState([]),[$i,Rn]=j.useState(!1),xa=_s=>{ii([_s]),Rn(!0)},Ya=_s=>{ii(_s),Rn(!0)},ho=(_s,Xa)=>{Fn!=null&&Fn.teamId&&_s.forEach(No=>{bn.mutate({contact_id:No,team_id:Fn.teamId,pond_id:Xa||null})})},Tc=_s=>{var Xa;if(Fn!=null&&Fn.teamId){if(Lr.length>1){Cr(Lr[0].id),la(_s);return}ho(_s,((Xa=Lr[0])==null?void 0:Xa.id)||null)}},zd=_s=>Tc([_s]),Nl=_s=>Tc(_s),Ho=j.useCallback(_s=>{Xs(!1),wt(Xa=>{const No=new Set(Xa);return No.has(_s)?No.delete(_s):No.add(_s),No})},[]);j.useEffect(()=>{if(!(r!=null&&r.id))return;const _s=q.channel(`innercircle_contacts_inserts_${r.id}`).on("postgres_changes",{event:"INSERT",schema:"public",table:"innercircle_contacts",filter:`owner_user_id=eq.${r.id}`},()=>{i.invalidateQueries({queryKey:["innercircle-contacts"]}),i.invalidateQueries({queryKey:["innercircle-contact-counts"]})}).subscribe();return()=>{q.removeChannel(_s)}},[i,r==null?void 0:r.id]),j.useEffect(()=>{u&&Ee(u)},[u]);const[ti,Xr]=j.useState({first_name:"",last_name:"",email:"",phone:"",address:"",city:"",state:"",zip_code:"",address2_label:"",address2:"",address2_city:"",address2_state:"",address2_zip:"",mail_to_secondary:!1,birthday:"",home_anniversary:"",spouse_name:"",spouse_email:"",lead_source_id:"",notes:"",tagIds:[]}),[Eo,Th]=j.useState(!1);j.useEffect(()=>{h&&Je(!0)},[h]),j.useEffect(()=>{var _s;pt&&Xr({first_name:pt.first_name||"",last_name:pt.last_name||"",email:pt.email||"",phone:pt.phone||"",address:pt.address||"",city:pt.city||"",state:pt.state||"",zip_code:pt.zip_code||"",address2_label:pt.address2_label||"",address2:pt.address2||"",address2_city:pt.address2_city||"",address2_state:pt.address2_state||"",address2_zip:pt.address2_zip||"",mail_to_secondary:!!pt.mail_to_secondary,birthday:pt.birthday||"",home_anniversary:pt.home_anniversary||"",spouse_name:pt.spouse_name||"",spouse_email:pt.spouse_email||"",lead_source_id:pt.lead_source_id||"",notes:pt.notes||"",tagIds:((_s=pt.tags)==null?void 0:_s.map(Xa=>Xa.relationship_type_id))||[]})},[pt]);const ah=j.useMemo(()=>{const _s=new Set;return w==null||w.forEach(Xa=>{(Xa.name==="Recruits"||Xa.name==="Brokerage Agents")&&_s.add(Xa.id)}),_s},[w]),ao=j.useMemo(()=>Array.from(W).some(_s=>ah.has(_s)),[W,ah]),ta=j.useMemo(()=>{const _s={};return(m||[]).forEach(Xa=>{_s[Xa.id]=`${Xa.first_name||""} ${Xa.last_name||""}`.trim()}),_s},[m]),xc=j.useMemo(()=>{const _s=new Set;return(m||[]).forEach(Xa=>{var Ba;const No=(((Ba=Xa.lead_source_ref)==null?void 0:Ba.name)||Xa.lead_source||"").trim();No&&_s.add(No)}),Array.from(_s).sort((Xa,No)=>Xa.localeCompare(No))},[m]),fl=j.useMemo(()=>{if(!m)return[];let _s=m.filter(Ba=>{var Zd,Vh,cf,Ky,ih,gh,xt,We,ct,jt,Rt;const io=Ba.synced_source;if(!ao&&(io==="recruit"||io==="brokerage_agent")||Xe&&!Xe.has(Ba.id))return!1;const qi=te===""||`${Ba.first_name} ${Ba.last_name}`.toLowerCase().includes(te.toLowerCase())||((Zd=Ba.email)==null?void 0:Zd.toLowerCase().includes(te.toLowerCase()))||((Vh=Ba.phone)==null?void 0:Vh.includes(te))||((cf=Ba.city)==null?void 0:cf.toLowerCase().includes(te.toLowerCase()))||((Ky=Ba.state)==null?void 0:Ky.toLowerCase().includes(te.toLowerCase()))||((ih=Ba.address)==null?void 0:ih.toLowerCase().includes(te.toLowerCase()))||((gh=Ba.zip_code)==null?void 0:gh.toLowerCase().includes(te.toLowerCase())),cm=he==="all"||((xt=Ba.tags)==null?void 0:xt.some(zt=>zt.relationship_type_id===he)),Zo=W.size===0||(()=>{const zt=(S==null?void 0:S.filter(Ht=>Ht.contact_id===Ba.id).map(Ht=>Ht.tag_id))||[];return G==="any"?zt.some(Ht=>W.has(Ht)):Array.from(W).every(Ht=>zt.includes(Ht))})(),vo=!!((We=Ba.address)!=null&&We.trim()||(ct=Ba.city)!=null&&ct.trim()||(jt=Ba.state)!=null&&jt.trim()||(Rt=Ba.zip_code)!=null&&Rt.trim()),Zg=Fe==="all"||Fe==="has-address"&&vo||Fe==="no-address"&&!vo,Fl=Ba,Ol=Be,xy=(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 ws;const zt=Ol.leadSourceId;if(!zt)return!0;const Ht=(((ws=Fl.lead_source_ref)==null?void 0:ws.name)||Fl.lead_source||"").trim();return zt==="none"?!Ht&&!Fl.lead_source_id:zt.startsWith("name:")?Ht.toLowerCase()===zt.slice(5).toLowerCase():Fl.lead_source_id===zt})();return qi&&cm&&Zo&&Zg&&xy});ve==="not-touched-90"?_s=_s.filter(Ba=>{const io=Ba.relationshipScore.daysSinceTouch;return io===null||io>90}):ve==="at-risk"?_s=_s.filter(Ba=>Ba.relationshipScore.status==="at-risk"):ve==="cooling"?_s=_s.filter(Ba=>Ba.relationshipScore.status==="cooling"):ve==="warm"?_s=_s.filter(Ba=>Ba.relationshipScore.status==="warm"):ve==="has-deal"?_s=_s.filter(Ba=>b&&b[Ba.id]):ve==="no-deal"?_s=_s.filter(Ba=>!b||!b[Ba.id]):ve==="open-house"?_s=_s.filter(Ba=>{var ko;return(((ko=Ba.lead_source_ref)==null?void 0:ko.name)||Ba.lead_source)==="Open House"}):ve==="website-active"?_s=_s.filter(Ba=>g.has(Ba.id)):ve==="never-contacted"?_s=_s.filter(Ba=>Ba.relationshipScore.daysSinceTouch===null):ve==="vips"?_s=_s.filter(Ba=>Ba.relationshipScore.score>=80):ve==="missing-info"?_s=_s.filter(Ba=>qQt(Ba)):ve==="birthdays-soon"?_s=_s.filter(Ba=>{const io=OO(Ba.birthday);return io!==null&&io<=30}):ve==="anniversary-soon"?_s=_s.filter(Ba=>{const io=OO(Ba.home_anniversary);return io!==null&&io<=30}):ve==="in-drip"?_s=_s.filter(Ba=>((y==null?void 0:y[Ba.id])??0)>0):ve==="not-in-drip"?_s=_s.filter(Ba=>((y==null?void 0:y[Ba.id])??0)===0):ve==="active-buyers"?_s=_s.filter(Ba=>P.has(Ba.id)):ve==="missing-criteria"&&(_s=_s.filter(Ba=>!P.has(Ba.id)));const Xa=Be;if(Xa.lastActive||Xa.registered||Xa.viewedListing||Xa.savedProperty||Xa.hasSavedSearch||Xa.requestedShowing||Xa.requestedValuation||Xa.websiteActiveOnly){const Ba=Date.now(),io={today:24*60*60*1e3,"7d":7*24*60*60*1e3,"30d":30*24*60*60*1e3,"90d":90*24*60*60*1e3};_s=_s.filter(ko=>{const qi=at.get(ko.id);if(Xa.lastActive==="never"){if(qi!=null&&qi.lastActiveAt)return!1}else if(Xa.lastActive){const cm=Ba-io[Xa.lastActive];if(!(qi!=null&&qi.lastActiveAt)||new Date(qi.lastActiveAt).getTime()0)||Xa.viewedListing==="multiple7d"&&!(qi&&qi.propertyViewCount7d>=3)||Xa.savedProperty&&!(qi&&qi.savedListingCount>0)||Xa.hasSavedSearch&&!(qi&&qi.activeSavedSearchCount>0)||Xa.requestedShowing&&!(qi&&qi.showingRequests>0)||Xa.requestedValuation&&!(qi&&qi.valuationRequests>0)||Xa.websiteActiveOnly&&!g.has(ko.id))})}return _s=[..._s].sort((Ba,io)=>{switch(Se){case"important-dates":{const ko=OO(Ba.birthday),qi=OO(io.birthday),cm=OO(Ba.home_anniversary),Zo=OO(io.home_anniversary),vo=[ko,cm].filter(Fl=>Fl!==null).sort((Fl,Ol)=>(Fl??1/0)-(Ol??1/0))[0]??1/0,Zg=[qi,Zo].filter(Fl=>Fl!==null).sort((Fl,Ol)=>(Fl??1/0)-(Ol??1/0))[0]??1/0;return vo-Zg}case"last-touched":{const ko=Ba.relationshipScore.lastTouchDate,qi=io.relationshipScore.lastTouchDate;return!ko&&!qi?0:ko?qi?new Date(ko).getTime()-new Date(qi).getTime():1:-1}case"next-touch":{const ko=Ba.relationshipScore.daysSinceTouch,qi=io.relationshipScore.daysSinceTouch;return ko===null&&qi===null?0:ko===null?-1:qi===null?1:qi-ko}case"score":return Ba.relationshipScore.score-io.relationshipScore.score;case"date-added":{const ko=Ba.created_at,qi=io.created_at;return!ko&&!qi?0:ko?qi?new Date(qi).getTime()-new Date(ko).getTime():-1:1}case"last-name":{const ko=(Ba.last_name||"").toLowerCase(),qi=(io.last_name||"").toLowerCase();if(ko!==qi)return ko.localeCompare(qi);const cm=(Ba.first_name||"").toLowerCase(),Zo=(io.first_name||"").toLowerCase();return cm.localeCompare(Zo)}case"name":default:{const ko=`${Ba.first_name||""} ${Ba.last_name||""}`.toLowerCase(),qi=`${io.first_name||""} ${io.last_name||""}`.toLowerCase();return ko.localeCompare(qi)}}}),_s},[m,te,he,W,G,ve,Se,b,S,g,y,Fe,Be,at,ao,P,Xe]),Co=fl.length,fu=Math.max(1,Math.ceil(Co/Ut)),cc=Math.min(Ss,fu),nd=j.useMemo(()=>{const _s=(cc-1)*Ut;return fl.slice(_s,_s+Ut)},[fl,cc,Ut]),zr=j.useMemo(()=>{const _s=(m||[]).length;return{total:_s,label:_s===0?"Build your database — add or import your first contacts.":`${_s.toLocaleString()} ${_s===1?"person":"people"} in your database`}},[m]),Hi=j.useMemo(()=>{const _s=m||[],Xa=_s.filter(ko=>{var qi;return((qi=ko.relationshipScore)==null?void 0:qi.status)==="at-risk"}).length,No=_s.filter(ko=>{var cm;const qi=(cm=ko.relationshipScore)==null?void 0:cm.daysSinceTouch;return typeof qi=="number"&&qi<=7}).length,Ba=new Date().getMonth()+1,io=_s.filter(ko=>ko.birthday?String(ko.birthday).split(/[-/T]/).map(Number)[1]===Ba:!1).length;return[{label:"Total contacts",value:zr.total.toLocaleString(),onClick:()=>{Ee("all"),Js(1)},active:ve==="all"},{label:"Needs attention",value:Xa,onClick:()=>{Ee("at-risk"),Js(1)},active:ve==="at-risk"},{label:"Touched this week",value:No,onClick:()=>{Ee("warm"),Js(1)},active:ve==="warm"},{label:"Birthdays this month",value:io,onClick:()=>{Ee("birthdays-soon"),Js(1)},active:ve==="birthdays-soon"}]},[m,zr.total,ve,Js]),zc=j.useCallback(_s=>{const Xa=new URLSearchParams;te&&Xa.set("search",te),he!=="all"&&Xa.set("type",he),ve!=="all"&&Xa.set("filter",ve),W.size>0&&(Xa.set("tags",Array.from(W).join(",")),Xa.set("tagMode",G));const No=Xa.toString();s(`/mission-control/contacts/${_s}${No?`?${No}`:""}`)},[s,te,he,ve,W,G]),Bc=j.useRef(!1);j.useEffect(()=>{if(!Bc.current){Bc.current=!0;return}Js(1)},[te,he,W,G,ve,Se,Fe,Be]);const yc=j.useCallback(()=>{Xs(!1),wt(_s=>_s.size>0?new Set:new Set(nd.map(Xa=>Xa.id)))},[nd]),$l=j.useCallback(()=>{Xs(!0),wt(new Set(fl.map(_s=>_s.id)))},[fl]),[rg,Ix]=j.useState(null),Yo=j.useCallback((_s,Xa)=>{J(_s.search||""),ue(_s.type||"all"),Ee(_s.status||"all"),Ne(_s.behavior||{}),Le(Xa||"name")},[]),Mc=()=>{Xr({first_name:"",last_name:"",email:"",phone:"",address:"",city:"",state:"",zip_code:"",address2_label:"",address2:"",address2_city:"",address2_state:"",address2_zip:"",mail_to_secondary:!1,birthday:"",home_anniversary:"",spouse_name:"",spouse_email:"",lead_source_id:"",notes:"",tagIds:[]})},Mh=async _s=>{_s.preventDefault();const Xa={...ti,lead_source_id:ti.lead_source_id||null};pt?(await ae.mutateAsync({id:pt.id,...Xa}),gt(null)):(await X.mutateAsync(Xa),Je(!1)),Mc()},lm=async _s=>{await fo("Are you sure you want to delete this contact?")&&await le.mutateAsync(_s)};return e.jsx(Vs,{title:"Contacts",description:"Manage your InnerCircle contacts",children:e.jsxs("div",{className:"space-y-6 overflow-x-hidden",children:[e.jsx(h$n,{totalLabel:zr.label,stats:Hi,search:te,onSearchChange:J,onAddContact:()=>Je(!0),onImportCsv:()=>Yt(!0),onImportPhone:()=>ys(!0),onManageTags:()=>kr(!0),onHeatMap:()=>_e(!0),viewMode:hr,onViewModeChange:_s=>Rs(_s),showTeamTab:!!Fn&&(Fn.team.contact_visibility==="full_team"||Fn.team.contact_visibility==="leader_only"&&Fn.role==="team_leader"),showLeadPondTab:!!(Fn!=null&&Fn.team.lead_pond_enabled),extraActions:e.jsxs(e.Fragment,{children:[e.jsxs($,{variant:"secondary",size:"sm",className:"h-9 gap-1.5",onClick:()=>s("/mission-control/sphere-map"),children:[e.jsx(LJ,{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(Zr,{className:"h-4 w-4"}),"Match a listing"]}),e.jsxs($,{variant:"secondary",size:"sm",className:"h-9 gap-1.5",onClick:()=>ks(!0),children:[e.jsx(Wz,{className:"h-4 w-4"}),"Find duplicates"]}),e.jsx(TBn,{})]})}),e.jsx(FBn,{open:gs,onOpenChange:ks}),e.jsx(I$n,{open:O,onOpenChange:U,contacts:m||[]}),R&&e.jsx(S$n,{open:!!R,onOpenChange:_s=>{_s||D(null)},contactId:R.id,contactName:R.name,existing:(E==null?void 0:E[R.id])??null}),hr==="team"?e.jsx(aRe,{}):hr==="lead-pond"&&Fn?e.jsx(iRe,{teamId:Fn.teamId}):e.jsxs(e.Fragment,{children:[e.jsx(p$n,{contacts:m,contactDealsMap:b,websiteActiveIds:g,criteriaContactIds:P,totalCount:(m||[]).length,activeViewId:rg,currentFilters:{search:te,type:he,status:ve,behavior:Be},currentSortBy:Se,onApplyView:(_s,Xa,No)=>{Ix(_s),Yo(Xa,No),Js(1)},onClearAll:()=>{Ix(null),Yo({search:"",type:"all",status:"all",behavior:{}},"name"),Js(1)},activeKey:{"at-risk":"needs-attention",cooling:"cooling","not-touched-90":"stale-90","never-contacted":"never-contacted","birthdays-soon":"birthdays-soon","anniversary-soon":"anniversary-soon","has-deal":"has-deal","website-active":"website-active",vips:"vips","missing-info":"missing-info","active-buyers":"active-buyers","missing-criteria":"missing-criteria"}[ve]??null,onSelectSegment:_s=>{const No=_s?{"needs-attention":"at-risk",cooling:"cooling","stale-90":"not-touched-90","never-contacted":"never-contacted","birthdays-soon":"birthdays-soon","anniversary-soon":"anniversary-soon","has-deal":"has-deal","website-active":"website-active",vips:"vips","missing-info":"missing-info","active-buyers":"active-buyers","missing-criteria":"missing-criteria"}[_s]:"all";Ee(No),Js(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(Gy,{children:[e.jsx(Pae,{asChild:!0,children:e.jsxs($,{variant:"outline",className:"h-10 flex-1 rounded-xl relative gap-2","aria-label":"Filters",children:[e.jsx(XI,{className:"h-4 w-4"}),"Filters & Views",(()=>{const _s=(he!=="all"?1:0)+(ve!=="all"?1:0)+(Fe!=="all"?1:0)+W.size+Ae;return _s>0?e.jsx("span",{className:"absolute -top-1 -right-1 h-4 min-w-[16px] px-1 rounded-full bg-primary text-primary-foreground text-[10px] font-bold flex items-center justify-center",children:_s}):null})()]})}),e.jsxs(my,{side:"bottom",className:"h-[85vh] rounded-t-2xl overflow-y-auto",children:[e.jsx(L0,{className:"text-left",children:e.jsx(R0,{children:"Filters & Views"})}),e.jsxs("div",{className:"space-y-5 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Type"}),e.jsxs(ms,{value:he,onValueChange:ue,children:[e.jsx(us,{className:"h-11 rounded-xl bg-muted/40",children:e.jsx(fs,{placeholder:"All Types"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Types"}),v==null?void 0:v.filter(_s=>_s.active).map(_s=>e.jsx(Ge,{value:_s.id,children:_s.name},_s.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Status"}),e.jsxs(ms,{value:ve,onValueChange:Ee,children:[e.jsx(us,{className:"h-11 rounded-xl bg-muted/40",children:e.jsx(fs,{placeholder:"All Status"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Status"}),e.jsx(Ge,{value:"warm",children:"🟢 Warm"}),e.jsx(Ge,{value:"cooling",children:"🟡 Cooling Off"}),e.jsx(Ge,{value:"at-risk",children:"🔴 At Risk"}),e.jsx(Ge,{value:"has-deal",children:"📋 Has Deal"}),e.jsx(Ge,{value:"no-deal",children:"📭 No Deal"}),e.jsx(Ge,{value:"open-house",children:"🏠 Open House"}),x&&e.jsx(Ge,{value:"website-active",children:"🌐 Website Active"}),e.jsx(Ge,{value:"in-drip",children:"🌱 In Drip Campaign"}),e.jsx(Ge,{value:"not-in-drip",children:"🚫 Not In Drip"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Address"}),e.jsxs(ms,{value:Fe,onValueChange:_s=>ke(_s),children:[e.jsx(us,{className:"h-11 rounded-xl bg-muted/40",children:e.jsx(fs,{placeholder:"All Addresses"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Addresses"}),e.jsx(Ge,{value:"has-address",children:"Has Address"}),e.jsx(Ge,{value:"no-address",children:"No Address"})]})]})]}),w&&w.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Tags"}),e.jsxs("div",{className:"flex items-center gap-1 bg-muted rounded-md p-0.5",children:[e.jsx("button",{onClick:()=>Y("any"),className:`px-2 py-0.5 rounded text-xs font-medium ${G==="any"?"bg-background shadow-sm":"text-muted-foreground"}`,children:"Any"}),e.jsx("button",{onClick:()=>Y("all"),className:`px-2 py-0.5 rounded text-xs font-medium ${G==="all"?"bg-background shadow-sm":"text-muted-foreground"}`,children:"All"})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:w.map(_s=>{const Xa=W.has(_s.id);return e.jsxs("button",{onClick:()=>{V(No=>{const Ba=new Set(No);return Ba.has(_s.id)?Ba.delete(_s.id):Ba.add(_s.id),Ba})},className:`inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs border transition-colors ${Xa?"bg-primary text-primary-foreground border-primary":"bg-background border-border"}`,children:[e.jsx("span",{className:"h-2 w-2 rounded-full",style:{backgroundColor:_s.color}}),_s.name]},_s.id)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Sort by"}),e.jsxs(ms,{value:Se,onValueChange:Le,children:[e.jsx(us,{className:"h-11 rounded-xl bg-muted/40",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"name",children:"Name (A-Z)"}),e.jsx(Ge,{value:"last-name",children:"Last Name (A-Z)"}),e.jsx(Ge,{value:"important-dates",children:"Important Dates"}),e.jsx(Ge,{value:"last-touched",children:"Last Touched"}),e.jsx(Ge,{value:"next-touch",children:"Next Touch Due"}),e.jsx(Ge,{value:"score",children:"Relationship Score"}),e.jsx(Ge,{value:"date-added",children:"Date Added"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 pt-2",children:[e.jsxs($,{variant:"outline",className:"h-11 rounded-xl gap-1.5",onClick:()=>Ve(!0),children:[e.jsx(Nn,{className:"h-4 w-4"})," Advanced"]}),e.jsxs($,{variant:"outline",className:"h-11 rounded-xl gap-1.5",onClick:()=>kr(!0),children:[e.jsx(Ap,{className:"h-4 w-4"})," Manage Tags"]})]}),e.jsx("div",{children:e.jsx(aCt,{currentFilters:{search:te,type:he,status:ve,behavior:Be},currentSortBy:Se,onApplySmartList:Yo})}),e.jsx($,{variant:"ghost",className:"w-full h-11 rounded-xl text-muted-foreground",onClick:()=>{ue("all"),Ee("all"),ke("all"),V(new Set),Ne({})},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(Kd,{children:[e.jsx(Yd,{asChild:!0,children:e.jsx($,{variant:"outline",size:"icon",className:"h-10 w-10 rounded-xl",title:"Sort contacts",children:e.jsx(u2,{className:"h-4 w-4"})})}),e.jsxs(Od,{align:"end",className:"w-56 p-2",children:[e.jsx("div",{className:"text-xs font-semibold text-muted-foreground px-2 py-1.5",children:"Sort by"}),[{v:"name",l:"Name (A-Z)"},{v:"last-name",l:"Last Name (A-Z)"},{v:"important-dates",l:"Important Dates"},{v:"last-touched",l:"Last Touched"},{v:"next-touch",l:"Next Touch Due"},{v:"score",l:"Relationship Score"},{v:"date-added",l:"Date Added"}].map(_s=>e.jsx("button",{onClick:()=>Le(_s.v),className:`w-full text-left px-2 py-1.5 rounded-md text-sm hover:bg-accent transition-colors ${Se===_s.v?"bg-accent font-medium text-primary":""}`,children:_s.l},_s.v))]})]})]})]}),e.jsxs("div",{className:"hidden sm:flex px-3 sm:px-4 py-3 bg-muted/40 border-t flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs(ms,{value:he,onValueChange:ue,children:[e.jsx(us,{className:"h-8 text-xs rounded-lg bg-background w-auto min-w-[130px] gap-2",children:e.jsx(fs,{placeholder:"All Types"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Types"}),v==null?void 0:v.filter(_s=>_s.active).map(_s=>e.jsx(Ge,{value:_s.id,children:_s.name},_s.id))]})]}),e.jsxs(ms,{value:ve,onValueChange:Ee,children:[e.jsx(us,{className:"h-8 text-xs rounded-lg bg-background w-auto min-w-[130px] gap-2",children:e.jsx(fs,{placeholder:"All Status"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Status"}),e.jsx(Ge,{value:"warm",children:"🟢 Warm"}),e.jsx(Ge,{value:"cooling",children:"🟡 Cooling Off"}),e.jsx(Ge,{value:"at-risk",children:"🔴 At Risk"}),e.jsx(Ge,{value:"has-deal",children:"📋 Has Deal"}),e.jsx(Ge,{value:"no-deal",children:"📭 No Deal"}),e.jsx(Ge,{value:"open-house",children:"🏠 Open House"}),x&&e.jsx(Ge,{value:"website-active",children:"🌐 Website Active"}),e.jsx(Ge,{value:"in-drip",children:"🌱 In Drip Campaign"}),e.jsx(Ge,{value:"not-in-drip",children:"🚫 Not In Drip"})]})]}),e.jsxs(ms,{value:Fe,onValueChange:_s=>ke(_s),children:[e.jsx(us,{className:"h-8 text-xs rounded-lg bg-background w-auto min-w-[130px] gap-2",children:e.jsx(fs,{placeholder:"All Addresses"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Addresses"}),e.jsx(Ge,{value:"has-address",children:"Has Address"}),e.jsx(Ge,{value:"no-address",children:"No Address"})]})]}),w&&w.length>0&&e.jsxs("div",{className:"inline-flex items-center bg-background border rounded-lg overflow-hidden h-8",children:[e.jsxs(Kd,{children:[e.jsx(Yd,{asChild:!0,children:e.jsxs("button",{className:"pl-2.5 pr-2 h-full text-xs font-medium text-muted-foreground hover:text-foreground inline-flex items-center gap-1.5",children:[e.jsx(Ap,{className:"h-3.5 w-3.5"}),W.size===0?"Filter by Tags":`${W.size} tag${W.size>1?"s":""}`]})}),e.jsx(Od,{className:"w-60 p-3",align:"start",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-medium",children:"Tags"}),e.jsxs("div",{className:"flex items-center gap-1 bg-muted rounded-md p-0.5",children:[e.jsx("button",{onClick:()=>Y("any"),className:`px-2 py-0.5 rounded text-xs font-medium transition-colors ${G==="any"?"bg-background text-foreground shadow-sm":"text-muted-foreground"}`,children:"Any"}),e.jsx("button",{onClick:()=>Y("all"),className:`px-2 py-0.5 rounded text-xs font-medium transition-colors ${G==="all"?"bg-background text-foreground shadow-sm":"text-muted-foreground"}`,children:"All"})]})]}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto space-y-0.5",children:w.map(_s=>{const Xa=W.has(_s.id);return e.jsxs("button",{onClick:()=>{V(No=>{const Ba=new Set(No);return Ba.has(_s.id)?Ba.delete(_s.id):Ba.add(_s.id),Ba})},className:"flex items-center gap-2 w-full px-2 py-1.5 rounded-md text-sm hover:bg-accent transition-colors",children:[e.jsx(ai,{checked:Xa,className:"pointer-events-none"}),e.jsx("div",{className:"h-2.5 w-2.5 rounded-full shrink-0",style:{backgroundColor:_s.color}}),e.jsx("span",{className:"flex-1 text-left truncate",children:_s.name})]},_s.id)})}),W.size>0&&e.jsx($,{variant:"ghost",size:"sm",className:"w-full text-xs",onClick:()=>V(new Set),children:"Clear tags"})]})})]}),e.jsx("div",{className:"w-px h-4 bg-border"}),e.jsxs($u,{children:[e.jsx(Uu,{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(Au,{align:"end",children:[e.jsxs(ja,{onClick:()=>kr(!0),children:[e.jsx(Ap,{className:"h-4 w-4 mr-2"}),"Manage Tags"]}),e.jsxs(ja,{onClick:()=>kn(!0),children:[e.jsx(g1,{className:"h-4 w-4 mr-2"}),"Manage Lead Sources"]})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(aCt,{currentFilters:{search:te,type:he,status:ve,behavior:Be},currentSortBy:Se,onApplySmartList:Yo}),e.jsx("div",{className:"h-5 w-px bg-border"}),e.jsx(G9n,{selected:ze,onChange:qe}),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:()=>Ve(!0),children:[e.jsx(Nn,{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(x$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(R9n,{behavior:Be,onRemove:_s=>Ne(Xa=>{const No={...Xa};return delete No[_s],No}),onClearAll:()=>Ne({})})})]}),e.jsx(L9n,{open:Ce,onOpenChange:Ve,hasLeadSite:rt||x,behavior:Be,onApply:Ne,selectedType:he,onSelectedTypeChange:ue,relationshipTypes:v,contactLeadSources:xc}),e.jsx(P9n,{selectedIds:Ks,contacts:fl,onClearSelection:()=>{wt(new Set),Xs(!1)},showLeadPondAction:Un,onSendToLeadPond:Nl,showTransferAction:dr,onTransfer:Ya}),Ks.size>0&&Ks.size===nd.length&&!Is&&Co>Ut&&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"]})]}),Is&&e.jsxs("div",{className:"flex items-center justify-center gap-2 p-2 bg-primary/10 border border-primary/30 rounded-lg text-sm font-medium",children:["All ",Co.toLocaleString()," matching contacts are selected.",e.jsx($,{variant:"link",size:"sm",className:"h-auto p-0",onClick:()=>{wt(new Set),Xs(!1)},children:"Clear selection"})]}),Co>Ut&&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)*Ut+1,"–",Math.min(cc*Ut,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:()=>Js(1),children:"First"}),e.jsx($,{variant:"outline",size:"sm",disabled:cc<=1,onClick:()=>Js(_s=>_s-1),children:e.jsx(kd,{className:"h-4 w-4"})}),e.jsxs("span",{className:"px-3 text-sm font-medium",children:["Page ",cc," of ",fu]}),e.jsx($,{variant:"outline",size:"sm",disabled:cc>=fu,onClick:()=>Js(_s=>_s+1),children:e.jsx(Di,{className:"h-4 w-4"})}),e.jsx($,{variant:"outline",size:"sm",disabled:cc>=fu,onClick:()=>Js(fu),children:"Last"})]})]}),a?e.jsx("div",{className:"space-y-3",children:f?e.jsx(f$n,{}):fl.length===0?e.jsx(je,{children:e.jsx(fCt,{filtered:!!te||he!=="all"||ve!=="all"||Fe!=="all"||W.size>0,onAdd:()=>Je(!0),onImport:()=>Yt(!0),onClearFilters:()=>{J(""),ue("all"),Ee("all"),ke("all"),V(new Set),Ne({})}})}):nd.map(_s=>{var No,Ba,io;const{relationshipScore:Xa}=_s;return e.jsx(je,{className:"cursor-pointer hover:bg-accent/50 transition-colors",onClick:()=>zc(_s.id),children:e.jsx(Ie,{className:"p-4",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2 flex-wrap",children:[e.jsxs("h3",{className:"font-semibold text-base truncate",children:[_s.first_name," ",_s.last_name]}),e.jsx(cCt,{count:(y==null?void 0:y[_s.id])??0}),e.jsx(Di,{className:"h-4 w-4 text-muted-foreground shrink-0 ml-auto"})]}),e.jsxs("div",{className:"space-y-1 text-sm mb-3",children:[_s.email&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(mn,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:_s.email})]}),_s.phone&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Da,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{children:_s.phone})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1 mb-2",children:[e.jsx(MYe,{score:Xa,size:"sm"}),e.jsx(sCt,{contact:_s}),(((No=_s.lead_source_ref)==null?void 0:No.name)||_s.lead_source)&&e.jsx($e,{variant:"outline",className:"text-xs gap-1 border-primary/30 text-primary",children:((Ba=_s.lead_source_ref)==null?void 0:Ba.name)||_s.lead_source}),(io=_s.tags)==null?void 0:io.map(ko=>{var qi;return e.jsx($e,{variant:"secondary",className:"text-xs",children:(qi=ko.relationship_type)==null?void 0:qi.name},ko.id)}),e.jsx(hCt,{contactId:_s.id,tags:S==null?void 0:S.filter(ko=>ko.contact_id===_s.id)}),e.jsx(lCt,{deal:b==null?void 0:b[_s.id]})]}),e.jsx("div",{className:"mb-2",children:e.jsx(vCt,{criteria:E==null?void 0:E[_s.id],onEdit:()=>D({id:_s.id,name:`${_s.first_name}${_s.last_name?" "+_s.last_name:""}`}),showAlertState:!!A,matchCount:I==null?void 0:I[_s.id],compact:!0})}),e.jsx(oCt,{birthday:_s.birthday,homeAnniversary:_s.home_anniversary,weddingAnniversary:_s.wedding_anniversary,className:"mb-2",contactId:_s.id,contactName:`${_s.first_name}${_s.last_name?" "+_s.last_name:""}`,contactAddress:[_s.address,_s.city,_s.state].filter(Boolean).join(", ")}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-xs text-muted-foreground",children:[Xa.lastTouchDate?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(da,{className:"h-3 w-3"}),en(new Date(Xa.lastTouchDate),"MMM d")]}):e.jsx("span",{className:"italic",children:"Never contacted"}),_s.birthday&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Ta,{className:"h-3 w-3"}),en(kh(_s.birthday),"MMM d")]}),_s.home_anniversary&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(va,{className:"h-3 w-3"}),en(kh(_s.home_anniversary),"MMM d")]}),_s.created_at&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(dn,{className:"h-3 w-3"}),"Added ",en(new Date(_s.created_at),"MMM d, yyyy")]})]})]}),e.jsx("div",{className:"ml-2",onClick:ko=>ko.stopPropagation(),children:e.jsx(rCt,{contact:_s,onEdit:gt,onDelete:lm,onSnooze:(ko,qi)=>{Ft(ko),kt(qi)},showLeadPondAction:Un,onSendToLeadPond:zd,showTransferAction:dr,onTransfer:xa})})]})})},_s.id)})}):e.jsx(je,{children:e.jsx(Ie,{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(En,{className:"hover:bg-transparent",children:[e.jsx(Dt,{className:"w-[40px]",children:e.jsx(ai,{checked:nd.length>0&&nd.every(_s=>Ks.has(_s.id)),onCheckedChange:()=>yc()})}),e.jsx(Dt,{children:e.jsxs("button",{onClick:()=>Le(_s=>_s==="last-name"?"name":"last-name"),className:"group inline-flex items-center gap-1 font-medium text-muted-foreground hover:text-foreground transition-colors",children:["Contact",Se==="name"&&e.jsx(Di,{className:"h-3 w-3 rotate-90 text-primary"}),Se==="last-name"&&e.jsx(Di,{className:"h-3 w-3 -rotate-90 text-primary"})]})}),l.relationship&&e.jsx(Dt,{children:"Relationship"}),l.buyerCriteria&&e.jsx(Dt,{className:"min-w-[170px] whitespace-nowrap",children:"Looking For"}),l.stage&&e.jsx(Dt,{children:"Stage"}),l.leadSource&&e.jsx(Dt,{children:"Lead Source"}),l.tags&&e.jsx(Dt,{children:"Tags"}),l.lastTouch&&e.jsx(Dt,{children:"Last Touch"}),l.nextAction&&e.jsx(Dt,{children:"Next Action"}),l.dealValue&&e.jsx(Dt,{title:"Total value of deals linked to this contact in your pipeline",children:"Pipeline Value"}),l.email&&e.jsx(Dt,{children:"Email"}),l.phone&&e.jsx(Dt,{children:"Phone"}),l.address&&e.jsx(Dt,{children:"Address"}),l.birthday&&e.jsx(Dt,{children:"Birthday"}),e.jsx(Dt,{className:"w-[50px]"})]})}),e.jsx(fi,{children:f?e.jsx(m$n,{columns:2+Object.values(l).filter(Boolean).length}):fl.length===0?e.jsx(En,{className:"hover:bg-transparent",children:e.jsx(_t,{colSpan:3+Object.values(l).filter(Boolean).length,className:"p-0",children:e.jsx(fCt,{filtered:!!te||he!=="all"||ve!=="all"||Fe!=="all"||W.size>0,onAdd:()=>Je(!0),onImport:()=>Yt(!0),onClearFilters:()=>{J(""),ue("all"),Ee("all"),ke("all"),V(new Set),Ne({})}})})}):nd.map(_s=>{var Ba;const{relationshipScore:Xa}=_s,No=b==null?void 0:b[_s.id];return e.jsxs(En,{className:`group cursor-pointer border-border/60 transition-colors hover:bg-accent/40 [&>td]:py-3.5 ${Ks.has(_s.id)?"bg-accent/30":""}`,onClick:()=>zc(_s.id),children:[e.jsx(_t,{onClick:io=>io.stopPropagation(),children:e.jsx(ai,{checked:Ks.has(_s.id),onCheckedChange:()=>Ho(_s.id)})}),e.jsx(_t,{className:"min-w-[220px]",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(vit,{firstName:_s.first_name,lastName:_s.last_name,avatarUrl:_s.avatar_url,email:_s.email,size:36}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsxs("span",{className:"font-medium truncate",children:[_s.first_name," ",_s.last_name]}),e.jsx(u$n,{linked:!!_s.spouse_contact_id||!!_s.spouse_name,spouseName:_s.spouse_contact_id&&ta[_s.spouse_contact_id]||_s.spouse_name||null}),e.jsx(cCt,{count:(y==null?void 0:y[_s.id])??0})]}),_s.email&&!l.email&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:_s.email}),_s.phone&&!l.phone&&e.jsx("p",{className:"text-xs text-muted-foreground",children:_s.phone})]})]})}),l.relationship&&e.jsx(_t,{children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx(o$n,{score:Xa.score,status:Xa.status}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium leading-tight",children:Xa.status==="warm"?"Strong":Xa.status==="cooling"?"Cooling":"At Risk"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Xa.daysSinceTouch===null?"Never contacted":Xa.daysSinceTouch===0?"Touched today":`${Xa.daysSinceTouch}d since touch`})]})]})}),l.buyerCriteria&&e.jsx(_t,{className:"min-w-[170px] max-w-[240px]",children:e.jsx(vCt,{criteria:E==null?void 0:E[_s.id],onEdit:()=>D({id:_s.id,name:`${_s.first_name}${_s.last_name?" "+_s.last_name:""}`}),showAlertState:!!A,matchCount:I==null?void 0:I[_s.id]})}),l.stage&&e.jsx(_t,{children:e.jsx(lCt,{deal:No})}),l.leadSource&&e.jsx(_t,{className:"text-sm text-muted-foreground max-w-[160px] truncate",children:((Ba=_s.lead_source_ref)==null?void 0:Ba.name)||_s.lead_source||"—"}),l.tags&&e.jsx(_t,{children:e.jsx("div",{className:"flex flex-wrap items-center gap-1 max-w-[220px]",children:e.jsx(hCt,{contactId:_s.id,tags:S==null?void 0:S.filter(io=>io.contact_id===_s.id)})})}),l.lastTouch&&e.jsx(_t,{children:Xa.lastTouchDate?e.jsxs("div",{className:"flex items-center gap-1.5 text-sm text-muted-foreground",children:[e.jsx(da,{className:"h-3.5 w-3.5"}),en(new Date(Xa.lastTouchDate),"MMM d, yyyy")]}):e.jsx("span",{className:"text-xs italic text-muted-foreground",children:"No activity"})}),l.nextAction&&e.jsx(_t,{children:e.jsxs("div",{className:"flex flex-col items-start gap-1",children:[e.jsx(sCt,{contact:_s}),e.jsx(oCt,{birthday:_s.birthday,homeAnniversary:_s.home_anniversary,weddingAnniversary:_s.wedding_anniversary,contactId:_s.id,contactName:`${_s.first_name}${_s.last_name?" "+_s.last_name:""}`,contactAddress:[_s.address,_s.city,_s.state].filter(Boolean).join(", ")})]})}),l.dealValue&&e.jsx(_t,{children:(()=>{const io=(No==null?void 0:No.sale_price)??(No==null?void 0:No.expected_price);return io?e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold",children:Xm(Number(io))}),(No==null?void 0:No.deal_type)&&e.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:String(No.deal_type).replace(/_/g," ")})]}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"—"})})()}),l.email&&e.jsx(_t,{className:"text-sm text-muted-foreground max-w-[220px] truncate",children:_s.email||"—"}),l.phone&&e.jsx(_t,{className:"text-sm text-muted-foreground whitespace-nowrap",children:_s.phone||"—"}),l.address&&e.jsx(_t,{className:"text-sm text-muted-foreground max-w-[220px] truncate",children:[_s.address,_s.city,_s.state].filter(Boolean).join(", ")||"—"}),l.birthday&&e.jsx(_t,{className:"text-sm text-muted-foreground whitespace-nowrap",children:_s.birthday?(()=>{const[io,ko,qi]=String(_s.birthday).split(/[-/T]/).map(Number);return ko&&qi?`${ko}/${qi}${io&&io>1900?`/${io}`:""}`:"—"})():"—"}),e.jsx(_t,{onClick:io=>io.stopPropagation(),children:e.jsx(rCt,{contact:_s,onEdit:gt,onDelete:lm,onSnooze:(io,ko)=>{Ft(io),kt(ko)},showLeadPondAction:Un,onSendToLeadPond:zd,showTransferAction:dr,onTransfer:xa})})]},_s.id)})})]})})}),Co>0&&e.jsxs("div",{className:"flex flex-col sm:flex-row items-center justify-between gap-4 py-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsxs("span",{children:["Showing ",(cc-1)*Ut+1,"–",Math.min(cc*Ut,Co)," of ",Co.toLocaleString()," contacts"]}),e.jsxs(ms,{value:String(Ut),onValueChange:_s=>{hn(Number(_s)),Js(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:()=>Js(1),children:"First"}),e.jsx($,{variant:"outline",size:"sm",disabled:cc<=1,onClick:()=>Js(_s=>_s-1),children:e.jsx(kd,{className:"h-4 w-4"})}),e.jsxs("span",{className:"px-3 text-sm font-medium",children:["Page ",cc," of ",fu]}),e.jsx($,{variant:"outline",size:"sm",disabled:cc>=fu,onClick:()=>Js(_s=>_s+1),children:e.jsx(Di,{className:"h-4 w-4"})}),e.jsx($,{variant:"outline",size:"sm",disabled:cc>=fu,onClick:()=>Js(fu),children:"Last"})]})]}),e.jsx(zs,{open:Ke||!!pt,onOpenChange:_s=>{_s||(Je(!1),gt(null),Mc())},children:e.jsxs(Os,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(Bs,{children:pt?"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:_s=>Xr({...ti,first_name:_s.target.value}),required:!0})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"last_name",children:"Last Name"}),e.jsx(pe,{id:"last_name",value:ti.last_name,onChange:_s=>Xr({...ti,last_name:_s.target.value})})]})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"email",children:"Email"}),e.jsx(pe,{id:"email",type:"email",value:ti.email,onChange:_s=>Xr({...ti,email:_s.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"phone",children:"Phone"}),e.jsx(pe,{id:"phone",value:ti.phone,onChange:_s=>Xr({...ti,phone:_s.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"address",children:"Address"}),e.jsx(pe,{id:"address",value:ti.address,onChange:_s=>Xr({...ti,address:_s.target.value}),placeholder:"Street address"})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"city",children:"City"}),e.jsx(pe,{id:"city",value:ti.city,onChange:_s=>Xr({...ti,city:_s.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"state",children:"State"}),e.jsx(pe,{id:"state",value:ti.state,onChange:_s=>Xr({...ti,state:_s.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"zip_code",children:"Zip"}),e.jsx(pe,{id:"zip_code",value:ti.zip_code,onChange:_s=>Xr({...ti,zip_code:_s.target.value})})]})]}),Eo?e.jsxs("div",{className:"space-y-4 rounded-lg border p-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"address2_label",children:"Label"}),e.jsx(pe,{id:"address2_label",list:"contact-address-labels-new",value:ti.address2_label,onChange:_s=>Xr({...ti,address2_label:_s.target.value}),placeholder:"Vacation home"}),e.jsx("datalist",{id:"contact-address-labels-new",children:wQt.map(_s=>e.jsx("option",{value:_s},_s))})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"address2",children:"Street Address"}),e.jsx(pe,{id:"address2",value:ti.address2,onChange:_s=>Xr({...ti,address2:_s.target.value})})]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"address2_city",children:"City"}),e.jsx(pe,{id:"address2_city",value:ti.address2_city,onChange:_s=>Xr({...ti,address2_city:_s.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"address2_state",children:"State"}),e.jsx(pe,{id:"address2_state",value:ti.address2_state,onChange:_s=>Xr({...ti,address2_state:_s.target.value}),maxLength:2})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"address2_zip",children:"Zip"}),e.jsx(pe,{id:"address2_zip",value:ti.address2_zip,onChange:_s=>Xr({...ti,address2_zip:_s.target.value})})]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx(ee,{htmlFor:"mail_to_secondary",className:"text-sm font-normal",children:"Send mail here instead of the main address"}),e.jsx(Sn,{id:"mail_to_secondary",checked:ti.mail_to_secondary,onCheckedChange:_s=>Xr({...ti,mail_to_secondary:_s})})]})]}):e.jsx($,{type:"button",variant:"ghost",size:"sm",className:"justify-start px-0 text-primary",onClick:()=>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:_s=>Xr({...ti,birthday:_s.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"home_anniversary",children:"Home Anniversary"}),e.jsx(pe,{id:"home_anniversary",type:"date",value:ti.home_anniversary,onChange:_s=>Xr({...ti,home_anniversary:_s.target.value})})]})]}),pt&&e.jsx(IYe,{contactId:pt.id,currentSpouseContactId:(pt==null?void 0:pt.spouse_contact_id)||null,currentSpouseName:(pt==null?void 0:pt.spouse_name)||null,currentSpouseEmail:(pt==null?void 0:pt.spouse_email)||null,onLink:_s=>ne.mutate({contactId:pt.id,spouseContactId:_s}),onUnlink:()=>ne.mutate({contactId:pt.id,spouseContactId:null}),isEditing:!0}),e.jsx(UQt,{value:ti.lead_source_id,onChange:_s=>Xr({...ti,lead_source_id:_s})}),e.jsxs("div",{children:[e.jsx(ee,{children:"Relationship Types"}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:v==null?void 0:v.filter(_s=>_s.active).map(_s=>e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx(ai,{checked:ti.tagIds.includes(_s.id),onCheckedChange:Xa=>{Xr(Xa?{...ti,tagIds:[...ti.tagIds,_s.id]}:{...ti,tagIds:ti.tagIds.filter(No=>No!==_s.id)})}}),e.jsx("span",{className:"text-sm",children:_s.name})]},_s.id))})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"notes",children:"Notes"}),e.jsx(Ls,{id:"notes",value:ti.notes,onChange:_s=>Xr({...ti,notes:_s.target.value}),rows:3})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>{Je(!1),gt(null),Mc()},children:"Cancel"}),e.jsxs($,{type:"submit",disabled:X.isPending||ae.isPending,children:[pt?"Update":"Create"," Contact"]})]})]})]})}),e.jsx(ZBn,{open:ss,onOpenChange:Yt,relationshipTypes:(v==null?void 0:v.filter(_s=>_s.active))||[],onSuccess:()=>{Yt(!1)}}),e.jsx(JBn,{open:ts,onOpenChange:ys,onComplete:()=>ys(!1)}),e.jsx(nDe,{open:!!Bt,onOpenChange:_s=>{_s||Ft(null)},contactId:Bt||"",contactName:as}),e.jsx(n$n,{open:jr,onOpenChange:kr}),e.jsx(r$n,{open:$n,onOpenChange:kn}),e.jsx(X9n,{open:ce,onOpenChange:_e,contacts:m||[],onCitySelect:_s=>{J(_s),Js(1)}}),e.jsx(IWt,{open:$i,onOpenChange:Rn,contactIds:Pa,contactNames:Pa.map(_s=>{const Xa=fl.find(No=>No.id===_s);return Xa?`${Xa.first_name} ${Xa.last_name||""}`.trim():""}),onComplete:()=>{ii([]),wt(new Set),Xs(!1)}}),e.jsx(zs,{open:!!Or,onOpenChange:_s=>!_s&&la(null),children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Choose a Lead Pond"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Sharing ",(Or==null?void 0:Or.length)||0," contact",((Or==null?void 0:Or.length)||0)===1?"":"s"," with your team."]}),e.jsxs(ms,{value:Qn,onValueChange:Cr,children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Select a pond"})}),e.jsx(hs,{children:Lr.map(_s=>e.jsx(Ge,{value:_s.id,children:_s.name},_s.id))})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>la(null),children:"Cancel"}),e.jsx($,{onClick:()=>{Or&&ho(Or,Qn),la(null)},disabled:!Qn,children:"Share to Pond"})]})]})]})})]})]})})}const R$n=5*1024*1024;function D$n({contactId:s,firstName:t,lastName:n,avatarUrl:r,email:a,size:i=88}){const l=j.useRef(null),o=Wt(),[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>R$n){_a({title:"Image too large",description:"Please use an image under 5MB.",variant:"destructive"});return}d(!0);try{const{data:y}=await q.auth.getUser(),v=(x=y.user)==null?void 0:x.id,b=(g.name.split(".").pop()||"jpg").toLowerCase(),w=`contacts/${v}/${s}-${Date.now()}.${b}`,{error:S}=await q.storage.from("avatars").upload(w,g,{upsert:!0,contentType:g.type});if(S)throw S;const{data:A}=q.storage.from("avatars").getPublicUrl(w);await h(A.publicUrl),_a({title:"Photo updated"})}catch(y){_a({title:"Upload failed",description:y.message,variant:"destructive"})}finally{d(!1),l.current&&(l.current.value="")}},f=async()=>{d(!0);try{await h(null),_a({title:"Photo removed"})}catch(g){_a({title:"Could not remove photo",description:g.message,variant:"destructive"})}finally{d(!1)}};return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{type:"button",onClick:()=>{var g;return(g=l.current)==null?void 0:g.click()},disabled:c,className:"relative group rounded-full focus:outline-none focus-visible:ring-2 focus-visible:ring-ring","aria-label":r?"Change contact photo":"Upload contact photo",children:[e.jsx(vit,{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(Sx,{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(Hn,{className:"h-3.5 w-3.5"}),"Remove"]}),e.jsx("input",{ref:l,type:"file",accept:"image/*",className:"hidden",onChange:g=>{var y;const x=(y=g.target.files)==null?void 0:y[0];x&&m(x)}})]})}const F$n={job_title:"Job title",company_name:"Company",city:"City",state:"State",avatar_url:"Profile photo",email:"Email",phone:"Phone"},O$n=4e3,z$n=5*60*1e3;function B$n({open:s,onOpenChange:t,contactId:n,contactName:r,hasEmail:a}){var W;const{toast:i}=Bi(),l=Wt(),[o,c]=j.useState(""),[d,u]=j.useState(!1),[h,m]=j.useState(!1),[f,g]=j.useState(null),[x,y]=j.useState(!1),[v,b]=j.useState(null),[w,S]=j.useState(null),[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,Y=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)):(y(!0),S(null))}catch(ae){i({title:"Enrichment status check failed",description:(ae==null?void 0:ae.message)??"Please try again.",variant:"destructive"}),S(null)}};return X(),G=setInterval(X,O$n),Y=setTimeout(()=>{V||(S(null),i({title:"Enrichment is taking longer than expected",description:"The provider has not finished processing yet. You can close this dialog and try again later.",variant:"default"}))},z$n),()=>{V=!0,G&&clearInterval(G),Y&&clearTimeout(Y)}},[w,s,n,i]);const D=async()=>{u(!0),y(!1),g(null),S(null);try{const{data:V,error:G}=await q.functions.invoke("enrich-contact",{body:{contact_id:n,linkedin_url:o.trim()||void 0}});if(G)throw G;if((V==null?void 0:V.status)==="pending"&&(V!=null&&V.batch_id)){S(V.batch_id);return}if(!(V!=null&&V.found)){y(!0);return}g(V.profile),b(V.matched_on??null)}catch(V){i({title:"Enrichment failed",description:(V==null?void 0:V.message)??"Please try again.",variant:"destructive"})}finally{u(!1)}},O=()=>{var G,Y;if(!f)return[];const V=[];if(f.job_title&&V.push({key:"job_title",value:f.job_title}),f.company_name&&V.push({key:"company_name",value:f.company_name}),f.city&&V.push({key:"city",value:f.city}),f.state&&V.push({key:"state",value:f.state}),f.photo_url&&V.push({key:"avatar_url",value:f.photo_url}),(G=f.emails)!=null&&G.length&&V.push({key:"email",value:f.emails[0]}),(Y=f.phones)!=null&&Y.length&&V.push({key:"phone",value:f.phones[0]}),!f.city&&!f.state&&f.location){const[X,ae]=f.location.split(",").map(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(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-lg",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(Nn,{className:"h-4 w-4 text-primary"}),"Find person details — ",r]}),e.jsx(Pr,{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(uo,{className:"max-h-[45vh] pr-3",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border p-3",children:[f.photo_url&&e.jsx("img",{src:f.photo_url,alt:f.full_name??"Profile photo",className:"h-14 w-14 rounded-full object-cover"}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-semibold truncate",children:f.full_name||r}),v&&e.jsxs($e,{variant:"secondary",className:"text-[10px]",children:["matched via ",v]})]}),f.headline&&e.jsx("p",{className:"text-sm text-muted-foreground",children:f.headline}),e.jsxs("div",{className:"mt-1 flex flex-wrap gap-3 text-xs text-muted-foreground",children:[f.company_name&&e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(ji,{className:"h-3 w-3"}),f.company_name]}),f.location&&e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(ci,{className:"h-3 w-3"}),f.location]}),f.industry&&e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(kx,{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(dy,{className:"h-3 w-3"})," LinkedIn ",e.jsx(Fr,{className:"h-3 w-3"})]})]})]}),f.summary&&e.jsx("p",{className:"text-sm text-muted-foreground whitespace-pre-line",children:f.summary}),!!((W=f.experience)!=null&&W.length)&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-semibold uppercase text-muted-foreground",children:"Experience"}),f.experience.map((V,G)=>e.jsxs("p",{className:"text-sm",children:[V.title," ",V.company?`· ${V.company}`:"",V.starts_at?e.jsxs("span",{className:"text-muted-foreground text-xs",children:[" (",V.starts_at,V.ends_at?` – ${V.ends_at}`:" – present",")"]}):null]},G))]}),O().length===0&&e.jsx("div",{className:"rounded-lg border border-dashed p-3 text-sm text-muted-foreground",children:"We found this person, but the public profile didn’t include any details we can save to the contact (job title, company, city, state, photo, email or phone). Try adding their LinkedIn address and searching again."}),O().length>0&&e.jsxs("div",{className:"space-y-2 rounded-lg border p-3",children:[e.jsx("p",{className:"text-xs font-semibold uppercase text-muted-foreground",children:"Save to contact"}),O().map(V=>e.jsxs("label",{className:"flex items-start gap-2 text-sm",children:[e.jsx(ai,{checked:P[V.key],onCheckedChange:G=>R(Y=>({...Y,[V.key]:G===!0}))}),e.jsxs("span",{className:"min-w-0",children:[e.jsxs("span",{className:"font-medium",children:[F$n[V.key],": "]}),e.jsx("span",{className:"text-muted-foreground break-all",children:V.value})]})]},V.key))]})]})})]}),e.jsxs(Sr,{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(Nn,{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 $$n=["jeremy@relevelup.com"];function U$n(){const{user:s}=bs(),t=((s==null?void 0:s.email)||"").toLowerCase();return $$n.includes(t)}const _Ct="America/New_York";function q$n(s){const t=new Date(s),n=new Intl.DateTimeFormat("en-US",{timeZone:_Ct,month:"short",day:"numeric",year:"numeric"}).format(t),r=new Intl.DateTimeFormat("en-US",{timeZone:_Ct,hour:"numeric",minute:"2-digit"}).format(t);return`${n} · ${r}`}function V$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 H$n({contactId:s,ownerUserId:t,legacyNote:n}){const r=Wt(),[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,y,v;const{data:h}=await q.auth.getUser(),m=h.user,f=((x=m==null?void 0:m.user_metadata)==null?void 0:x.full_name)||[(y=m==null?void 0:m.user_metadata)==null?void 0:y.first_name,(v=m==null?void 0:m.user_metadata)==null?void 0:v.last_name].filter(Boolean).join(" ")||(m==null?void 0:m.email)||null,{error:g}=await q.from("innercircle_contact_notes").insert({contact_id:s,owner_user_id:t||(m==null?void 0:m.id),author_user_id:m==null?void 0:m.id,author_name:f,source:"agent",body:u});if(g)throw g},onSuccess:()=>{i(""),r.invalidateQueries({queryKey:["contact-notes",s]}),_a({title:"Note added"})},onError:u=>_a({title:"Could not add note",description:u.message,variant:"destructive"})}),d=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(eo,{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(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ls,{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(da,{className:"h-3 w-3"}),q$n(u.created_at)]}),e.jsxs("span",{children:["· ",V$n(u.created_at)]}),u.source!=="agent"?e.jsxs($e,{variant:"outline",className:"gap-1 text-[10px]",children:[e.jsx(Nn,{className:"h-2.5 w-2.5"})," System"]}):u.author_name?e.jsxs("span",{children:["· ",u.author_name]}):null,e.jsx("button",{type:"button",onClick:()=>d.mutate(u.id),className:"ml-auto opacity-0 transition-opacity hover:text-destructive group-hover:opacity-100","aria-label":"Delete note",children:e.jsx(Hn,{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 G$n="9a88a47c-cb2a-4401-a2b5-111a76b19f9d";function W$n({open:s,onOpenChange:t,contact:n}){var W;const{user:r}=bs(),a=Xn(),i=Wt(),{intakePage:l,isLoading:o}=j6e(),{isGmailConnected:c,gmailEmail:d}=gy(),u=b6e(),{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]),[y,v]=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),v(c?"gmail":"system"))},[s,x,n.first_name,c]);const P=j.useMemo(()=>S.split(/\n\n+/).map(V=>`

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

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

A note from ${m}

${P}

Update Your Info

Takes about a minute — promise

Share My Info →

${V}

Sent with care by ${m}

Powered by ReLevelUp

`,O=async()=>{if(!l){re.error("Set up your Connect Page first",{action:{label:"Set Up",onClick:()=>a("/mission-control/connect-page")}});return}if(!b.trim()||!S.trim()){re.error("Subject and message are required");return}I(!0);const V=await R(),G=D(V),Y=async()=>{const{data:X,error:ae}=await q.functions.invoke("send-connect-invite",{body:{contactEmail:n.email,subject:b,htmlBody:G,replyToEmail:(h==null?void 0:h.email)||(r==null?void 0:r.email),agentName:m}});if(ae)throw ae;if(!(X!=null&&X.success))throw new Error((X==null?void 0:X.error)||"Failed to send")};try{if(y==="gmail"&&c){const{data:X,error:ae}=await q.functions.invoke("gmail-send",{body:{to:n.email,subject:b,body:G,contactId:n.id}});let le=X&&X.error?X:null;if(ae){le={error:"send_failed",message:ae.message};const ne=ae.context;if(ne&&typeof ne.json=="function")try{le=await ne.clone().json()}catch{}}if(le)if(le.error==="insufficient_scope")await Y(),re.warning("Sent using system email — your Gmail connection is missing send permission. Reconnect Gmail in Integrations to send from your own inbox.",{duration:8e3});else throw new Error(le.message||le.error||"Failed to send");else if(!(X!=null&&X.success))throw new Error("Failed to send")}else await Y();try{await u.mutateAsync({contactId:n.id,actionTypeId:G$n,notes:`Sent Connect Page invite — Subject: "${b}"`})}catch(X){console.warn("Failed to log activity:",X)}i.invalidateQueries({queryKey:["contact-touch-logs"]}),re.success("Connect Page invite sent!"),t(!1)}catch(X){console.error("Send error:",X),re.error(X instanceof Error?X.message:"Failed to send invite")}finally{I(!1)}},U=S.split(/\n\n+/).filter(Boolean);return e.jsx(zs,{open:s,onOpenChange:V=>!E&&t(V),children:e.jsxs(Os,{className:"sm:max-w-[720px] max-h-[92vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(Nn,{className:"h-5 w-5 text-primary"}),"Send Connect Page Invite"]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Ask ",e.jsxs("span",{className:"font-medium",children:[n.first_name," ",n.last_name||""]})," to share their latest contact info — takes them about a minute."]})]}),o?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(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(ha,{value:y,onValueChange:V=>v(V),className:"mt-1.5",children:e.jsxs(ma,{className:"grid w-full grid-cols-2",children:[e.jsxs(Zt,{value:"gmail",disabled:!c,children:[e.jsx(mn,{className:"h-3.5 w-3.5 mr-1.5"}),c?`Gmail (${d})`:"Gmail (not connected)"]}),e.jsxs(Zt,{value:"system",children:[e.jsx(Nn,{className:"h-3.5 w-3.5 mr-1.5"}),"System Email"]})]})}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-1.5",children:y==="gmail"?"Replies go directly to your Gmail inbox.":`Sent from notifications@dashboard.relevelup.com — replies go to ${(h==null?void 0:h.email)||(r==null?void 0:r.email)||"your account email"}.`})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"invite-subject",children:"Subject"}),e.jsx(pe,{id:"invite-subject",value:b,onChange:V=>w(V.target.value),className:"mt-1.5"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"invite-message",children:"Personal Message"}),e.jsx(Ls,{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(Fr,{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(Kr,{className:"h-4 w-4 mr-1.5"})," Send Invite"]})})]})]}):e.jsxs("div",{className:"space-y-4 py-6 text-center",children:[e.jsx(ll,{className:"h-10 w-10 text-amber-500 mx-auto"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"You haven't set up a Connect Page yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Create yours in one click — it only takes a moment."})]}),e.jsxs($,{onClick:()=>a("/mission-control/connect-page"),children:[e.jsx(Wd,{className:"h-4 w-4 mr-1"})," Set Up Connect Page"]})]})]})})}function K$n(){const{user:s}=bs();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 Y$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 Z$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 KQt(){const s=Wt(),{user:t}=bs(),{leadSite:n}=ng();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 X$n(){const s=Wt();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 Q$n(){const s=Wt();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 J$n(){const{leadSite:s}=ng();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 eUn(){const{leadSite:s}=ng();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 tUn(){const s=Wt();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 wCt(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 sUn(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 nUn(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 bit(){const s=Sa(),t=Wt();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 OK(){const s=Wt();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 YQt(){const s=Wt();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 ZQt(){const s=Wt();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 XQt(){const s=Wt();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 rUn(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=Wt();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 aUn(){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 iUn(){const s=Sa(),t=Wt();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 oUn(){const s=Wt();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 lUn(){const s=Wt();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 lC(s){const t=window.location.hostname;return t==="localhost"||t.includes("lovable.app")?`${window.location.origin}/portal/${s}`:`https://clients.relevelup.com/${s}`}function cUn({contactId:s}){const t=Xn(),n=Wt(),[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=OK(),y=QQt(),{data:v,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=(v==null?void 0:v.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(lC(P)),a(P),re.success("Portal link copied!"),setTimeout(()=>a(null),2e3)},E=async(P,R)=>{if(!d.trim())return;const D=d.trim(),O=h.trim();await y.mutateAsync({portal_id:P,title:D,content:O||void 0}),c(!1),u(""),m(""),n.invalidateQueries({queryKey:["contact-portal-updates"]});try{const{data:U,error:W}=await q.functions.invoke("send-portal-notification",{body:{portal_id:P,update_title:D,update_content:O||null,portal_url:R?lC(R):void 0,force:!0}});if(W)throw W;U!=null&&U.emailSent?re.success("Update posted & client emailed"):re.success(`Update posted (${(U==null?void 0:U.reason)||"no email sent"})`)}catch(U){console.error("Portal notification failed:",U),re.success("Update posted (notification failed to send)")}},I=async()=>{f&&(await x.mutateAsync({id:f.id,welcome_message:f.welcome_message,next_step_text:f.next_step_text,is_enabled:f.is_enabled,show_post_close_tips:f.show_post_close_tips,review_url:f.review_url}),l(!1),g(null),n.invalidateQueries({queryKey:["contact-portals",s]}),re.success("Portal settings updated!"))};return b||!v||v.length===0?null:e.jsxs(je,{children:[e.jsx(St,{className:"pb-2",children:e.jsxs(Et,{className:"text-base flex items-center gap-2",children:[e.jsx(dl,{className:"h-4 w-4"}),"Client Portal"]})}),e.jsx(Ie,{className:"space-y-3",children:v.map(P=>{var U,W,V;const R=((U=P.stage_mapping)==null?void 0:U.length)>0?P.stage_mapping:JLe(((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:en(new Date(O.created_at),"MMM d, yyyy")})]}),e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[e.jsxs($,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>A(P.slug),children:[r===P.slug?e.jsx(ca,{className:"h-3 w-3 mr-1"}):e.jsx(Ha,{className:"h-3 w-3 mr-1"}),"Copy Link"]}),e.jsxs($,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>window.open(lC(P.slug),"_blank"),children:[e.jsx(Fr,{className:"h-3 w-3 mr-1"}),"View"]}),e.jsxs(zs,{open:o,onOpenChange:c,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>c(!0),children:[e.jsx(eo,{className:"h-3 w-3 mr-1"}),"Post Update"]})}),e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Post Portal Update"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Title"}),e.jsx(pe,{value:d,onChange:G=>u(G.target.value),placeholder:"e.g. Inspection completed!"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Details (optional)"}),e.jsx(Ls,{value:h,onChange:G=>m(G.target.value),placeholder:"Add more details...",rows:3})]}),e.jsxs($,{onClick:()=>E(P.id,P.slug),disabled:!d.trim()||y.isPending,className:"w-full",children:[e.jsx(Kr,{className:"h-4 w-4 mr-1"}),"Post Update"]})]})]})]}),e.jsxs(zs,{open:i,onOpenChange:l,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>{g({...P}),l(!0)},children:[e.jsx(Nd,{className:"h-3 w-3 mr-1"}),"Settings"]})}),e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Portal Settings"})}),f&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{children:"Portal Enabled"}),e.jsx(Sn,{checked:f.is_enabled,onCheckedChange:G=>g({...f,is_enabled:G})})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Welcome Message"}),e.jsx(Ls,{value:f.welcome_message||"",onChange:G=>g({...f,welcome_message:G.target.value}),placeholder:"Welcome to your home journey!",rows:2})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Next Step"}),e.jsx(pe,{value:f.next_step_text||"",onChange:G=>g({...f,next_step_text:G.target.value}),placeholder:"What your client should do next..."})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Review URL"}),e.jsx(pe,{value:f.review_url||"",onChange:G=>g({...f,review_url:G.target.value}),placeholder:"https://..."})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{children:"Show Post-Close Tips"}),e.jsx(Sn,{checked:f.show_post_close_tips,onCheckedChange:G=>g({...f,show_post_close_tips:G})})]}),e.jsx(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"]})]})]})]})]})]}),v.length>1&&e.jsx(Vc,{})]},P.id)})})]})}function dUn({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(Ca,{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(Ie,{className:"pt-0",children:e.jsx("div",{className:"space-y-1",children:r.map(l=>{const o=i(l),c=l.property_address||`MLS# ${l.mls_number}`;return e.jsxs("a",{href:o||"#",target:"_blank",rel:"noopener noreferrer",onClick:d=>{o||d.preventDefault()},className:"group flex items-center gap-3 p-2.5 rounded-lg hover:bg-muted/60 transition-colors",children:[l.photo_url?e.jsx("div",{className:"h-10 w-10 rounded-lg overflow-hidden flex-shrink-0 bg-muted",children:e.jsx("img",{src:l.photo_url,alt:c,className:"w-full h-full object-cover"})}):e.jsx("div",{className:"h-9 w-9 rounded-lg bg-gradient-to-br from-primary/15 to-primary/5 flex items-center justify-center flex-shrink-0",children:e.jsx(va,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"flex items-center gap-1.5",children:e.jsx("span",{className:"font-medium text-sm truncate",children:c})}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(da,{className:"h-3 w-3"}),e.jsx("span",{title:en(new Date(l.viewed_at),"PPp"),children:hu(new Date(l.viewed_at),{addSuffix:!0})})]})]}),o&&e.jsx(Fr,{className:"h-3.5 w-3.5 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity"})]},l.mls_number)})})})]})}function uUn({contactId:s,contactName:t}){var O,U,W;const{user:n}=bs(),r=Sa(),{hasIdx:a}=ng(),i=Wt(),[l,o]=j.useState(!1),[c,d]=j.useState(!1),[u,h]=j.useState(""),[m,f]=j.useState(null),[g,x]=j.useState(!1),[y,v]=j.useState(!1),{data:b,isLoading:w}=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),re.success("Home search saved!")},onError:V=>{re.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),re.success("Home search removed")}}),R=async()=>{if(b!=null&&b.id){x(!0),d(!0),h(""),f(null);try{const{data:V,error:G}=await q.functions.invoke("process-property-alerts",{body:{alert_id:b.id,mode:"preview"}});if(G)throw G;V!=null&&V.html?(h(V.html),f({count:V.listings_count||0,recipient:V.recipient,subject:V.subject})):f({count:0,message:(V==null?void 0:V.message)||"No matching listings found right now."})}catch(V){re.error(V.message||"Failed to generate preview"),d(!1)}finally{x(!1)}}},D=async()=>{if(b!=null&&b.id&&await fo(`Send property alert email to ${t} now?`)){v(!0);try{const{data:V,error:G}=await q.functions.invoke("process-property-alerts",{body:{alert_id:b.id,mode:"send"}});if(G)throw G;V!=null&&V.sent_count?(re.success(`Sent ${V.sent_count} ${V.sent_count===1?"listing":"listings"} to ${V.recipient}`),i.invalidateQueries({queryKey:["contact-property-alert",s]})):re.info((V==null?void 0:V.message)||"No new matching listings to send right now.")}catch(V){re.error(V.message||"Failed to send alert")}finally{v(!1)}}};return w?null:b&&!l?e.jsxs(e.Fragment,{children:[e.jsxs(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(Uy,{className:"h-4 w-4 text-green-600"}):e.jsx(YS,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Zr,{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(Ie,{className:"pt-0 space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap gap-1.5 text-xs",children:[b.min_price||b.max_price?e.jsxs($e,{variant:"outline",className:"gap-1",children:[e.jsx(nu,{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(A4,{className:"h-3 w-3"}),b.min_beds,"+ beds"]}):null,b.min_baths?e.jsxs($e,{variant:"outline",className:"gap-1",children:[e.jsx(A0,{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(ci,{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(wr,{to:"/mission-control/website",className:"text-primary hover:underline",children:"explore IDX websites"}),"."]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[a&&e.jsxs(e.Fragment,{children:[e.jsxs($,{variant:"outline",size:"sm",onClick:R,disabled:g,children:[g?e.jsx(Ct,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Ca,{className:"h-4 w-4 mr-1"}),"Preview Email"]}),e.jsxs($,{size:"sm",onClick:D,disabled:y||!b.is_active,title:b.is_active?"Send this alert email now":"Activate alert to send",children:[y?e.jsx(Ct,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Kr,{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(pr,{className:"h-4 w-4 mr-1"}),"Remove"]})]})]})]}),e.jsx(zs,{open:c,onOpenChange:d,children:e.jsxs(Os,{className:"max-w-3xl max-h-[90vh] flex flex-col",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Property Alert Email Preview"}),(m==null?void 0:m.subject)&&e.jsxs("div",{className:"text-xs text-muted-foreground space-y-0.5 pt-1",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"To:"})," ",m.recipient]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Subject:"})," ",m.subject]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Listings:"})," ",m.count]})]})]}),e.jsx("div",{className:"flex-1 overflow-hidden border rounded-md bg-muted/30",children:g?e.jsxs("div",{className:"flex items-center justify-center h-96 text-muted-foreground",children:[e.jsx(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(Sr,{children:[e.jsx($,{variant:"outline",onClick:()=>d(!1),children:"Close"}),u&&e.jsxs($,{onClick:()=>{d(!1),D()},disabled:y||!b.is_active,children:[e.jsx(Kr,{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(Uy,{className:"h-4 w-4 text-primary"}):e.jsx(Zr,{className:"h-4 w-4 text-primary"}),b?"Edit":"Set up"," home search for ",t]})}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsx(WQt,{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(wr,{to:"/mission-control/website",children:"Explore IDX websites"})})}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs($,{onClick:()=>I.mutate(),disabled:I.isPending,className:"flex-1",children:[I.isPending?e.jsx(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(pr,{className:"h-4 w-4"})})]})]})]}):e.jsx(je,{className:"overflow-hidden",children:e.jsx(Ie,{className:"p-4",children:e.jsxs("button",{onClick:E,className:"w-full flex items-center gap-3 p-3 rounded-lg border border-dashed border-primary/30 hover:bg-primary/5 transition-colors",children:[e.jsx("div",{className:"h-9 w-9 rounded-lg bg-primary/10 flex items-center justify-center flex-shrink-0",children:a?e.jsx(Uy,{className:"h-4 w-4 text-primary"}):e.jsx(Zr,{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 hUn({contactId:s,contactName:t}){var Y;const{user:n}=bs(),r=Sa(),{hasLeadSite:a}=ng(),i=Wt(),[l,o]=j.useState(!1),[c,d]=j.useState(""),[u,h]=j.useState([]),[m,f]=j.useState(!1),[g,x]=j.useState(!1),[y,v]=j.useState(!1),[b,w]=j.useState(""),S=j.useRef(null),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||{},ne=Array.isArray(le.searchCities)?le.searchCities:[];return X.mls_market_area&&!ne.includes(X.mls_market_area)&&ne.unshift(X.mls_market_area),ne},enabled:!!r}),{data:I,isLoading:P}=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),v(!0)},onError:X=>{re.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:()=>{re.success(`Market report sent to ${t}!`)},onError:X=>{re.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),re.success(m?"Monthly market report enabled!":"Market report disabled")},onError:X=>{re.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([]),re.success("Market report removed")},onError:X=>{re.error(X.message||"Failed to remove market report")}});return!a||P?null:I!=null&&I.market_report_enabled&&!l?e.jsxs(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(Ie,{className:"pt-0 space-y-2",children:[e.jsx("div",{className:"flex flex-wrap gap-1.5 text-xs",children:((Y=I.market_report_cities)==null?void 0:Y.length)>0?I.market_report_cities.map(X=>e.jsxs($e,{variant:"outline",className:"gap-1",children:[e.jsx(ci,{className:"h-3 w-3"}),X]},X)):e.jsx("span",{className:"text-muted-foreground",children:"Using default market area"})}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[t," receives a branded market report on the 1st of each month."]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{variant:"outline",size:"sm",onClick:()=>U.mutate(),disabled:U.isPending,className:"flex-1",children:[U.isPending?e.jsx(Ct,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Ca,{className:"h-4 w-4 mr-1"}),"Preview"]}),e.jsxs($,{variant:"default",size:"sm",onClick:()=>W.mutate(),disabled:W.isPending,className:"flex-1",children:[W.isPending?e.jsx(Ct,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Kr,{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(pr,{className:"h-4 w-4 mr-1"}),"Remove"]})]}),e.jsx(zs,{open:y,onOpenChange:v,children:e.jsxs(Os,{className:"max-w-3xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsx(Us,{children:e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(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:()=>{v(!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(Kr,{className:"h-4 w-4 mr-1"}),"Send to ",t]}),e.jsx($,{variant:"outline",onClick:()=>v(!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(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{children:"Send Monthly Report"}),e.jsx(Sn,{checked:m,onCheckedChange:f})]}),m&&e.jsxs("div",{children:[e.jsxs(ee,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(ci,{className:"h-3.5 w-3.5"})," Report Cities"]}),e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Select cities from your website's configured areas."}),e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(pe,{ref:S,value:c,onChange:X=>{d(X.target.value),x(!0)},onFocus:()=>x(!0),placeholder:"Type to search cities...",onKeyDown:X=>{X.key==="Enter"&&(X.preventDefault(),O.length>0?D(O[0]):D())}}),e.jsx(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(dn,{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(ci,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}),X]},X))})]}),u.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-2",children:u.map(X=>e.jsxs($e,{variant:"secondary",className:"gap-1",children:[X,e.jsx("button",{onClick:()=>h(u.filter(ae=>ae!==X)),children:e.jsx(pr,{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(Ie,{className:"p-4",children:e.jsxs("button",{onClick:R,className:"w-full flex items-center gap-3 p-3 rounded-lg border border-dashed border-primary/30 hover:bg-primary/5 transition-colors",children:[e.jsx("div",{className:"h-9 w-9 rounded-lg bg-primary/10 flex items-center justify-center flex-shrink-0",children:e.jsx(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 mUn({contactId:s,contactName:t}){const n=Wt(),[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"]}),re.success(d?`${t} will no longer receive newsletters or marketing emails`:`${t} is opted back in to marketing emails`)},onError:d=>re.error(d.message)}),c=!!(i!=null&&i.email_opt_out);return e.jsxs(je,{children:[e.jsx(St,{className:"pb-3",children:e.jsxs(Et,{className:"flex items-center gap-2 text-base",children:[e.jsx(YI,{className:"h-4 w-4"}),"Email Preferences",c&&e.jsx($e,{variant:"destructive",className:"ml-1",children:"Opted out"})]})}),e.jsx(Ie,{className:"space-y-4",children:l?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(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(Sn,{id:"opt-out-toggle",checked:c,disabled:o.isPending,onCheckedChange:d=>o.mutate({optOut:d,reasonText:r})})]}),c&&e.jsxs("div",{className:"space-y-2 rounded-lg border bg-muted/40 p-3",children:[e.jsx(ee,{htmlFor:"opt-out-reason",className:"text-xs",children:"Reason (optional)"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{id:"opt-out-reason",value:r,placeholder:"e.g. Asked to stop monthly newsletter",onChange:d=>a(d.target.value)}),e.jsx($,{variant:"outline",size:"sm",disabled:o.isPending||r===((i==null?void 0:i.email_opt_out_reason)||""),onClick:()=>o.mutate({optOut:!0,reasonText:r}),children:"Save"})]}),(i==null?void 0:i.email_opt_out_at)&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Opted out ",en(new Date(i.email_opt_out_at),"MMM d, yyyy")]})]})]})})]})}function fUn(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 pUn(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 jCt(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(Av,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(da,{className:"h-4 w-4 text-muted-foreground"})}function gUn({contactId:s}){const t=Xn(),{data:n,isLoading:r}=fUn(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(JI,{className:"h-5 w-5 text-emerald-500"}),"Drip Campaign Activity"]})}),e.jsxs(Ie,{className:"space-y-4",children:[l.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Enrollments"}),l.map(c=>{var d;return e.jsxs("button",{onClick:()=>t("/mission-control/smart-drips"),className:"w-full text-left flex items-start gap-3 p-3 rounded-lg border hover:bg-muted/50 transition-colors",children:[e.jsx("div",{className:"h-8 w-8 rounded-full bg-emerald-500/10 flex items-center justify-center text-emerald-600 flex-shrink-0",children:e.jsx(JI,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:((d=c.campaign)==null?void 0:d.name)||"Untitled campaign"}),pUn(c.status)]}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:["Step ",c.current_step+1,c.next_send_at&&c.status==="active"&&e.jsxs(e.Fragment,{children:[" · Next: ",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(zs,{open:(a==null?void 0:a.id)===c.id,onOpenChange:h=>!h&&i(null),children:[e.jsx(jl,{asChild:!0,children:e.jsxs("button",{onClick:()=>i(c),className:"w-full text-left flex items-start gap-3 p-2.5 rounded-lg border hover:bg-muted/50 transition-colors",children:[e.jsx("div",{className:"mt-0.5 flex-shrink-0",children:jCt(c.status)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[c.channel==="sms"?e.jsx(eo,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}):e.jsx(mn,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}),e.jsx("p",{className:"text-sm truncate",children:c.subject||`${c.channel.toUpperCase()} step ${c.step_order+1}`})]}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5 truncate",children:[((d=c.campaign)==null?void 0:d.name)||"Campaign"," · ",en(new Date(c.sent_at),"MMM d, h:mm a")]}),c.status==="failed"&&c.error_message&&e.jsx("p",{className:"text-xs text-destructive mt-0.5 truncate",children:c.error_message})]})]})}),e.jsxs(Os,{className:"max-w-lg",children:[e.jsx(Us,{children:e.jsxs(Bs,{className:"flex items-center gap-2",children:[jCt(c.status),c.subject||"Drip step"]})}),e.jsxs("div",{className:"space-y-2 text-sm",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Campaign"}),e.jsx("span",{className:"font-medium",children:((u=c.campaign)==null?void 0:u.name)||"—"})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Channel"}),e.jsx("span",{className:"font-medium uppercase",children:c.channel})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Step"}),e.jsxs("span",{className:"font-medium",children:["#",c.step_order+1]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Recipient"}),e.jsx("span",{className:"font-medium",children:c.recipient_email||"—"})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Status"}),e.jsx("span",{className:"font-medium capitalize",children:c.status})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Sent"}),e.jsx("span",{className:"font-medium",children:en(new Date(c.sent_at),"MMM d, yyyy h:mm a")})]}),c.error_message&&e.jsx("div",{className:"rounded-md border border-destructive/30 bg-destructive/5 p-2 text-destructive text-xs",children:c.error_message})]})]})]},c.id)}),o.length>8&&e.jsx($,{variant:"ghost",size:"sm",className:"w-full text-xs",onClick:()=>t("/mission-control/smart-drips"),children:"View all in Smart Drips"})]})]})]})]})}const Y9e=1e3,xUn=5e4;async function cue(s){const t=[];for(let n=0;n{const n=t.id,r=await cue(()=>{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 cue(()=>{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 cue(()=>q.from("email_campaigns").select("id, subject").eq("user_id",n).order("id")),l=i.map(f=>f.id),o=new Map(i.map(f=>[f.id,f.subject]));let c=[];if(l.length>0)for(let g=0;g{let v=q.from("email_campaign_recipients").select("id, contact_id, email, sent_at, campaign_id, opened_at, clicked_at").in("campaign_id",x).eq("status","sent").not("sent_at","is",null).order("sent_at",{ascending:!1});return s&&(v=v.eq("contact_id",s)),v});c.push(...y)}const d=r.map(f=>({id:`g-${f.id}`,channel:f.source==="portal_invite"?"Client Portal Invite":String(f.source||"").startsWith("card_studio")?"Card Studio":"Gmail",subject:f.subject,to_email:f.to_email,contact_id:f.contact_id,sent_at:f.sent_at,source:f.source})),u=a.map(f=>({id:`b-${f.id}`,channel:"Mass Email",subject:f.subject,to_email:f.contact_email,contact_id:f.contact_id,sent_at:f.sent_at,source:f.source,opened_at:f.opened_at,clicked_at:f.clicked_at})),h=c.map(f=>({id:`c-${f.id}`,channel:"Campaign",subject:o.get(f.campaign_id)||"(campaign)",to_email:f.email,contact_id:f.contact_id,sent_at:f.sent_at,source:null,campaign_id:f.campaign_id,opened_at:f.opened_at,clicked_at:f.clicked_at})),m=[...d,...u,...h];return m.sort((f,g)=>f.sent_at0&&e.jsx($e,{variant:"secondary",className:"ml-1",children:t.length})]})}),e.jsx(Ie,{children:n?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading..."}):t.length===0?e.jsxs("div",{className:"text-center py-6 text-sm text-muted-foreground",children:[e.jsx(mn,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),"No emails sent to this contact yet."]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-2",children:i.map(l=>e.jsx("div",{className:"flex items-start justify-between gap-3 p-3 rounded-lg border hover:bg-muted/30",children:e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx($e,{variant:"outline",className:`text-xs ${yUn[l.channel]}`,children:l.channel}),e.jsx("span",{className:"text-xs text-muted-foreground",children:en(new Date(l.sent_at),"MMM d, yyyy h:mm a")})]}),e.jsx("p",{className:"text-sm font-medium truncate",children:l.subject}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:["to ",l.to_email]})]})},l.id))}),t.length>5&&e.jsx($,{variant:"ghost",size:"sm",className:"w-full mt-3",onClick:()=>a(!r),children:r?"Show less":`Show all ${t.length}`}),e.jsx("div",{className:"mt-3 pt-3 border-t",children:e.jsx(wr,{to:"/mission-control/sent-emails",className:"text-xs text-primary hover:underline",children:"View all sent emails →"})})]})})]})}const bUn={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"},_Un={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 wUn(s){if(!s)return null;const t=s.trim();if(/^[A-Za-z]{2}$/.test(t))return t.toUpperCase();const n=t.toLowerCase();return bUn[n]||null}function jUn(s){return!s||!s.trim().match(/^\d{5}(-?\d{4})?$/)?null:s.trim().split("-")[0]}function NUn(s){let t=s.toLowerCase();for(const[n,r]of Object.entries(_Un))t=t.replace(new RegExp(`\\b${n}\\b`,"g"),r);return t}function kUn(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 eJt(s,t,n,r){const a=[s,t,n,r].filter(Boolean).join(", ").trim(),i=wUn(n),l=jUn(r);let o=null,c=null;if(s){const g=kUn(s.trim());o=g.street,c=g.unit}const d=(t==null?void 0:t.trim())||null,u=[];o&&u.push(NUn(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 _it(){const{data:{user:s},error:t}=await q.auth.getUser();if(t||!s)throw new Error("Not authenticated");return s.id}async function SUn(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 _it(),{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 AUn(s,t,n={}){const a={owner_user_id:await _it(),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 EUn(s){const{error:t}=await q.from("contact_properties").delete().eq("id",s);if(t)throw new Error(t.message)}async function NCt(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 rA(s){return s==null||Number.isNaN(s)?"—":new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s)}function aA(s,t=""){return s==null||Number.isNaN(s)?"—":`${new Intl.NumberFormat("en-US").format(s)}${t}`}function kCt(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 aCr(){const{data:{user:s}}=await q.auth.getUser();if(!s)throw new Error("Not authenticated");const t=s.id,n=new Date;n.setDate(n.getDate()-90);const r=n.toISOString(),[{count:a,error:i},{count:l,error:o},{count:c,error:d},{count:u,error:h},{count:m,error:f},{count:g,error:x},{count:y,error:v},{count:b,error:w},{count:S,error: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,v,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:y??0,possibleNonOwnerOccupied:b??0,propertiesMissingValuation:S??0}}async function iCr(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 TUn(s){switch(s){case"verified":return"default";case"high":return"default";case"medium":return"secondary";case"low":return"outline";default:return"outline"}}async function oCr(s,t={}){const n=await _it();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:eJt(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 tJt=[{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"}],sJt=[{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:()=>NCt(r.id,{relationship_type:d,ownership_status:h,is_primary_residence:f}),onSuccess:()=>{re.success("Property relationship updated"),c(!1),t()},onError:A=>re.error(A instanceof Error?A.message:"Update failed")}),y=mt({mutationFn:()=>EUn(r.id),onSuccess:()=>{re.success("Property unlinked"),t()},onError:A=>re.error(A instanceof Error?A.message:"Unlink failed")}),v=a[0],b=n.primary_data_source||(v==null?void 0:v.source_name)||"Manual",w=n.last_enriched_at||(v==null?void 0:v.retrieved_at)||n.updated_at,S=[{id:"overview",title:"Property Overview",icon:$I,rows:[{label:"Property type",value:n.property_type||"—"},{label:"Bedrooms",value:aA(n.bedrooms)},{label:"Bathrooms",value:aA(n.bathrooms,"+")},{label:"Living area",value:aA(n.living_area_square_feet," sq ft")},{label:"Lot size",value:n.lot_size?`${aA(n.lot_size)} ${n.lot_size_units||""}`:"—"},{label:"Year built",value:aA(n.year_built)},{label:"Parcel ID",value:n.parcel_id||"—"},{label:"County",value:n.county||"—"}]},{id:"value",title:"Value & Valuation",icon:nu,rows:[{label:"Estimated value",value:rA(n.estimated_value)},{label:"Value range",value:n.estimated_value_low&&n.estimated_value_high?`${rA(n.estimated_value_low)} – ${rA(n.estimated_value_high)}`:"—"},{label:"Rent estimate",value:rA(n.rent_estimate)},{label:"Data confidence",value:n.data_confidence}]},{id:"tax",title:"Tax Information",icon:Tf,rows:[{label:"Tax-assessed value",value:rA(n.tax_assessed_value)},{label:"Assessed year",value:aA(n.tax_assessed_year)},{label:"Annual property tax",value:rA(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:Aw,rows:[{label:"Last sale price",value:rA(n.last_sale_price)},{label:"Last sale date",value:n.last_sale_date||"—"}]},{id:"sources",title:"Data Sources",icon:Aq,rows:[{label:"Primary source",value:b},{label:"Source URL",value:n.source_property_url?"View source":"—"},{label:"Last updated",value:w?new Date(w).toLocaleDateString():"—"}]},{id:"history",title:"Enrichment History",icon:Ta,rows:a.length?a.slice(0,5).map(A=>({label:new Date(A.created_at).toLocaleDateString(),value:`${A.source_name} — ${kCt(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(ci,{className:"h-3.5 w-3.5"}),[n.city,n.state,n.postal_code].filter(Boolean).join(", ")]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[r.is_primary_residence&&e.jsxs($e,{variant:"default",className:"gap-1",children:[e.jsx(ei,{className:"h-3 w-3"})," Primary"]}),e.jsx($e,{variant:TUn(n.data_confidence),children:n.data_confidence}),e.jsx($e,{variant:"outline",children:kCt(n.enrichment_status)})]})]})}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsx(due,{label:"Estimated value",value:rA(n.estimated_value)}),e.jsx(due,{label:"Tax assessed",value:rA(n.tax_assessed_value)}),e.jsx(due,{label:"Bed / Bath",value:`${aA(n.bedrooms)} / ${aA(n.bathrooms)}`}),e.jsx(due,{label:"Sq ft",value:aA(n.living_area_square_feet)})]}),e.jsxs(v1,{open:i,onOpenChange:l,children:[e.jsx(b1,{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(_1,{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(zs,{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(Os,{className:"sm:max-w-md",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Edit property relationship"})}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Relationship type"}),e.jsxs(ms,{value:d,onValueChange:A=>u(A),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:tJt.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:sJt.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(Sr,{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:()=>NCt(r.id,{is_primary_residence:!r.is_primary_residence}).then(()=>{re.success(r.is_primary_residence?"Removed primary residence":"Marked as primary residence"),t()}).catch(A=>re.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:()=>y.mutate(),disabled:y.isPending,children:[e.jsx(jv,{className:"mr-1 h-3.5 w-3.5"})," Unlink property"]})]})]})]})}function due({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 PUn({contactId:s,defaultAddress:t,defaultCity:n,defaultState:r,defaultZip:a,onAdded:i}){const[l,o]=j.useState(!1),[c,d]=j.useState(t||""),[u,h]=j.useState(n||""),[m,f]=j.useState(r||""),[g,x]=j.useState(a||""),[y,v]=j.useState("owner"),[b,w]=j.useState("current"),[S,A]=j.useState(!1),E=mt({mutationFn:async()=>{const I=[c,u,m,g].filter(Boolean).join(", "),P=eJt(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 AUn(s,R.id,{relationship_type:y,ownership_status:b,is_primary_residence:S})},onSuccess:()=>{re.success("Property added"),o(!1),d(t||""),h(n||""),f(r||""),x(a||""),i()},onError:I=>re.error(I instanceof Error?I.message:"Failed to add property")});return e.jsxs(zs,{open:l,onOpenChange:o,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{size:"sm",children:[e.jsx(dn,{className:"mr-1 h-4 w-4"})," Add property"]})}),e.jsxs(Os,{className:"sm:max-w-lg",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Add property to contact"})}),e.jsxs("div",{className:"grid gap-4 py-2",children:[e.jsxs("div",{className:"grid gap-2",children:[e.jsx(ee,{htmlFor:"pi-street",children:"Street address"}),e.jsx(pe,{id:"pi-street",value:c,onChange:I=>d(I.target.value),placeholder:"123 Main St"})]}),e.jsxs("div",{className:"grid gap-2 sm:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"pi-city",children:"City"}),e.jsx(pe,{id:"pi-city",value:u,onChange:I=>h(I.target.value),placeholder:"City"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"pi-state",children:"State"}),e.jsx(pe,{id:"pi-state",value:m,onChange:I=>f(I.target.value),placeholder:"State"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"pi-zip",children:"ZIP"}),e.jsx(pe,{id:"pi-zip",value:g,onChange:I=>x(I.target.value),placeholder:"ZIP"})]})]}),e.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Relationship type"}),e.jsxs(ms,{value:y,onValueChange:I=>v(I),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:tJt.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:sJt.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(Sr,{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 IUn({contactId:s,contactAddress:t,contactCity:n,contactState:r,contactZip:a}){const i=Wt(),{data:l,isLoading:o,error:c}=st({queryKey:["contact-properties",s],queryFn:()=>SUn(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(Ie,{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(PUn,{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(Ie,{className:"flex flex-col items-center justify-center py-10 text-center",children:[e.jsx(va,{className:"mb-3 h-10 w-10 text-muted-foreground/60"}),e.jsx("h4",{className:"text-base font-medium",children:"No properties linked yet"}),e.jsx("p",{className:"max-w-md text-sm text-muted-foreground",children:"Add the contact's property above, or run a ChatGPT enrichment to match addresses with public property data."}),t&&e.jsxs("p",{className:"mt-2 text-xs text-muted-foreground",children:["Contact address on file: ",t,n?`, ${n}`:"",r?`, ${r}`:"",a?` ${a}`:""]})]})}):e.jsx("div",{className:"space-y-4",children:u.map(h=>e.jsx(MUn,{detail:h,onMutate:d},h.relationship.id))})]})}function LUn({videoId:s}){var l;const{data:t,isLoading:n,error:r}=N9n(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 RUn({contactId:s}){const t=Xn(),[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(ca,{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(dn,{className:"h-3.5 w-3.5"})})]})]})}),e.jsx(Ie,{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:en(new Date(h.due_date),"MMM d")})]},h.id)),u.length>0&&e.jsx("div",{className:"pt-1 border-t mt-1",children:e.jsxs("p",{className:"text-[10px] text-muted-foreground px-2 py-1",children:[u.length," completed"]})})]})}),n&&e.jsx(DUn,{contactId:s,open:n,onOpenChange:h=>{r(h),h||o()}})]})}function DUn({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?en(o,"yyyy-MM-dd"):null}]);if(h){console.error("Task create error:",h);return}n(!1)};return e.jsx(zs,{open:t,onOpenChange:n,children:e.jsxs(Os,{className:"sm:max-w-[400px]",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Add Task"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Title"}),e.jsx(pe,{value:r,onChange:h=>a(h.target.value),placeholder:"Task title...",onKeyDown:h=>h.key==="Enter"&&u()})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Priority"}),e.jsxs("select",{value:i,onChange:h=>l(h.target.value),className:"w-full h-10 rounded-md border border-input bg-background px-3 text-sm",children:[e.jsx("option",{value:"low",children:"🟢 Low"}),e.jsx("option",{value:"medium",children:"🟡 Medium"}),e.jsx("option",{value:"high",children:"🟠 High"}),e.jsx("option",{value:"urgent",children:"🔴 Urgent"})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Due Date"}),e.jsx(pe,{type:"date",value:o?en(o,"yyyy-MM-dd"):"",onChange:h=>c(h.target.value?new Date(h.target.value+"T00:00:00"):void 0)})]})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx($,{onClick:u,disabled:!r.trim(),children:"Create Task"})]})]})]})})}function FUn({contactId:s}){const t=Xn(),{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(kx,{className:"h-4 w-4"}),"Linked Deals"]})}),e.jsx(Ie,{className:"space-y-2",children:n.map(a=>{const i=a.stage;return e.jsx("button",{onClick:()=>t(`/mission-control/pipeline?deal=${a.id}`),className:"w-full text-left p-3 rounded-lg border hover:bg-accent transition-colors group",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:a.deal_name}),a.property_address&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:a.property_address}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx($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 OUn(){var Js,Ut,hn,hr;const{contactId:s}=Wi(),{isAdmin:t}=bs(),{hasIdx:n}=ng(),r=Xn(),[a]=gc(),i=a.get("search")||"",l=a.get("type")||"all",o=a.get("status")||a.get("filter")||"all",c=a.get("tags")||"",d=a.get("tagMode")==="all"?"all":"any",u=j.useMemo(()=>new Set(c.split(",").map(Rs=>Rs.trim()).filter(Boolean)),[c]),{data:h,isLoading:m}=kHs(s||""),{data:f}=qw(),{data:g}=tie(),{data:x}=uK(3650),{data:y}=rDe(365),{data:v}=sUn(s),{contactsWithScores:b}=rie(),{data:w}=Tie(),{score:S}=UWs(s||""),A=Jst(),E=MUt(),I=b6e(),P=TUt(),[R,D]=j.useState(!1),[O,U]=j.useState("overview"),[W,V]=j.useState(!1),G=U$n(),[Y,X]=j.useState({}),[ae,le]=j.useState(!1),[ne,te]=j.useState(!1),[J,ce]=j.useState(null),[_e,he]=j.useState(""),[ue,ve]=j.useState(void 0),[Ee,Se]=j.useState(""),[Le,Fe]=j.useState(null),[ke,Be]=j.useState(!1),[Ne,Ae]=j.useState(null),[Ce,Ve]=j.useState(!1),{isGmailConnected:ze,gmailEmail:qe}=gy(),{isReady:dt}=l6(),Xe=dt||ze,at=KQt(),[rt,Ke]=j.useState(!1),{data:Je}=st({queryKey:["cma-eligible"],queryFn:async()=>{const{data:{user:Rs}}=await q.auth.getUser();if(!Rs)return!1;const{data:jr}=await q.from("lead_sites").select("id, mls_provider_id, no_mls_mode, is_active").eq("agent_id",Rs.id);return(jr||[]).some(kr=>kr.is_active&&kr.mls_provider_id&&!kr.no_mls_mode)}}),pt=async()=>{var kn,Fn,bn,xs;if(!h)return;const Rs=(kn=h.address)==null?void 0:kn.trim(),jr=(Fn=h.city)==null?void 0:Fn.trim(),kr=(bn=h.state)==null?void 0:bn.trim().toUpperCase(),$n=((xs=h.zip_code)==null?void 0:xs.trim())||"";if(!Rs||!jr||!kr){re.error("Add a full address (street, city, state) before creating a CMA.");return}try{Ke(!0);const Lr=await at.mutateAsync({subject:{address:Rs,city:jr,state:kr,zip:$n},contactId:h.id,title:`${h.first_name||""} ${h.last_name||""}`.trim()+" — "+Rs});r(`/mission-control/cma/${Lr.id}`)}catch(Lr){re.error("Could not create CMA: "+((Lr==null?void 0:Lr.message)||"unknown error"))}finally{Ke(!1)}},{data:gt}=st({queryKey:["gmail-sent-emails",s],queryFn:async()=>{const{data:Rs,error:jr}=await q.from("gmail_sent_emails").select("*").eq("contact_id",s).order("sent_at",{ascending:!1});if(jr)throw jr;return Rs},enabled:!!s}),ss=Rs=>{if(!Rs)return null;const jr=Rs.match(/Video ID:\s*([a-f0-9-]+)/i);return jr?jr[1]:null},Yt=j.useMemo(()=>{if(!b)return[];const Rs=new Map;if(u.size>0&&w)for(const kr of w)Rs.has(kr.contact_id)||Rs.set(kr.contact_id,new Set),Rs.get(kr.contact_id).add(kr.tag_id);let jr=b.filter(kr=>{var bn,xs,Lr;const $n=i===""||`${kr.first_name} ${kr.last_name}`.toLowerCase().includes(i.toLowerCase())||((bn=kr.email)==null?void 0:bn.toLowerCase().includes(i.toLowerCase()))||((xs=kr.phone)==null?void 0:xs.includes(i)),kn=l==="all"||((Lr=kr.tags)==null?void 0:Lr.some(Or=>Or.relationship_type_id===l));let Fn=!0;if(u.size>0){const Or=Rs.get(kr.id)||new Set;d==="all"?Fn=Array.from(u).every(la=>Or.has(la)):Fn=Array.from(u).some(la=>Or.has(la))}return $n&&kn&&Fn});return o==="not-touched-90"?jr=jr.filter(kr=>{const $n=kr.relationshipScore.daysSinceTouch;return $n===null||$n>90}):o==="at-risk"?jr=jr.filter(kr=>kr.relationshipScore.status==="at-risk"):o==="cooling"?jr=jr.filter(kr=>kr.relationshipScore.status==="cooling"):o==="warm"&&(jr=jr.filter(kr=>kr.relationshipScore.status==="warm")),jr.map(kr=>kr.id)},[b,i,l,o,u,d,w]),ts=Yt.indexOf(s||""),ys=ts>0?Yt[ts-1]:null,Bt=ts1&&ts!==-1,as=Rs=>{const jr=new URLSearchParams;i&&jr.set("search",i),l!=="all"&&jr.set("type",l),o!=="all"&&jr.set("status",o),u.size>0&&(jr.set("tags",Array.from(u).join(",")),jr.set("tagMode",d));const kr=jr.toString();return`/mission-control/contacts/${Rs}${kr?`?${kr}`:""}`},kt=j.useMemo(()=>{const Rs=((x==null?void 0:x.filter(kr=>kr.contact_id===s))||[]).map(kr=>{var bn,xs,Lr;const $n=ss(kr.notes);let kn=((bn=kr.action_type)==null?void 0:bn.name)||"Touch",Fn=kr.notes;if(kn==="Other"&&((xs=kr.notes)!=null&&xs.startsWith("["))){const Or=kr.notes.indexOf("]");Or>0&&(kn=kr.notes.substring(1,Or),Fn=kr.notes.substring(Or+1).replace(/^\s*—\s*/,"").trim()||null)}return{id:kr.id,type:"touch",completed_at:kr.completed_at,name:kn,color:((Lr=kr.action_type)==null?void 0:Lr.color)||"#3B82F6",notes:Fn,videoId:$n}}),jr=((y==null?void 0:y.filter(kr=>kr.contact_id===s))||[]).map(kr=>({id:kr.id,type:"popby",completed_at:kr.completed_at,name:"Pop-by",color:"#F97316",notes:kr.notes,videoId:null}));return[...Rs,...jr].sort((kr,$n)=>new Date($n.completed_at).getTime()-new Date(kr.completed_at).getTime())},[x,y,s]),Ks=Rs=>{var jr;return{first_name:Rs.first_name||"",last_name:Rs.last_name||"",email:Rs.email||"",phone:Rs.phone||"",address:Rs.address||"",city:Rs.city||"",state:Rs.state||"",zip_code:Rs.zip_code||"",address2_label:Rs.address2_label||"",address2:Rs.address2||"",address2_city:Rs.address2_city||"",address2_state:Rs.address2_state||"",address2_zip:Rs.address2_zip||"",mail_to_secondary:!!Rs.mail_to_secondary,birthday:Rs.birthday||"",home_anniversary:Rs.home_anniversary||"",wedding_anniversary:Rs.wedding_anniversary||"",spouse_birthday:Rs.spouse_birthday||"",spouse_name:Rs.spouse_name||"",spouse_email:Rs.spouse_email||"",company_name:Rs.company_name||"",job_title:Rs.job_title||"",lead_source_id:Rs.lead_source_id||"",notes:Rs.notes||"",tagIds:((jr=Rs.tags)==null?void 0:jr.map(kr=>kr.relationship_type_id))||[]}};j.useEffect(()=>{D(!1),X({})},[s]);const wt=j.useRef(null);j.useEffect(()=>{h!=null&&h.id&&wt.current!==h.id&&(wt.current=h.id,X(Ks(h)))},[h==null?void 0:h.id,h]);const gs=()=>{h&&(X(Ks(h)),le(eCt(h)),D(!0))},ks=async()=>{await A.mutateAsync({id:s,...Y,lead_source_id:Y.lead_source_id||null}),D(!1)},Is=async()=>{await fo("Are you sure you want to delete this contact?")&&(await E.mutateAsync(s),r("/mission-control/contacts"))},ds=((Js=g==null?void 0:g.find(Rs=>Rs.id===J))==null?void 0:Js.name)==="Other",Ss=async()=>{if(!J||ds&&!Ee.trim())return;const Rs=ue?new Date(ue.getFullYear(),ue.getMonth(),ue.getDate(),12,0,0).toISOString():void 0,jr=ds?`[${Ee.trim()}]${_e?" — "+_e:""}`:_e;await I.mutateAsync({contactId:s,actionTypeId:J,notes:jr,completedAt:Rs}),te(!1),ce(null),he(""),ve(void 0),Se("")},yn=(Rs,jr)=>{Xe&&h?(Ae({email:Rs,name:jr||`${h.first_name} ${h.last_name||""}`.trim()}),Be(!0)):window.location.href=`mailto:${Rs}`};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:()=>ys&&r(as(ys)),disabled:!ys,children:e.jsx(kd,{className:"h-4 w-4"})}),e.jsxs("span",{className:"px-1 text-xs text-muted-foreground whitespace-nowrap",children:[ts+1," of ",Yt.length]}),e.jsx($,{variant:"outline",size:"sm",className:"h-8 px-2",onClick:()=>Bt&&r(as(Bt)),disabled:!Bt,children:e.jsx(Di,{className:"h-4 w-4"})})]})]}),e.jsx("section",{className:"hub-ink relative overflow-hidden rounded-2xl p-4 sm:p-6",children:e.jsxs("div",{className:"relative flex flex-col gap-5",children:[e.jsxs("div",{className:"flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between",children:[e.jsxs("div",{className:"flex min-w-0 items-start gap-4",children:[e.jsx("div",{className:"shrink-0 rounded-full bg-background p-1 shadow-lg ring-2 ring-white/20",children:e.jsx(D$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(YI,{className:"h-3 w-3"}),"Emails opted out"]}),(((Ut=h.lead_source_ref)==null?void 0:Ut.name)||h.lead_source)&&e.jsx("span",{className:"hub-glass rounded-full px-2.5 py-1 text-[11px] font-medium",children:((hn=h.lead_source_ref)==null?void 0:hn.name)||h.lead_source}),(hr=h.tags)==null?void 0:hr.map(Rs=>{const jr=f==null?void 0:f.find(kr=>kr.id===Rs.relationship_type_id);return jr?e.jsx("span",{className:"hub-glass rounded-full px-2.5 py-1 text-[11px] font-medium",children:jr.name},Rs.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:()=>yn(h.email),className:"inline-flex min-w-0 items-center gap-1.5 hub-ink-muted transition-opacity hover:opacity-100",children:[e.jsx(mn,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:h.email})]}),h.phone&&e.jsxs("a",{href:`tel:${h.phone}`,className:"inline-flex items-center gap-1.5 hub-ink-muted",children:[e.jsx(Da,{className:"h-3.5 w-3.5"}),h.phone]}),(h.address||h.city)&&e.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5 hub-ink-muted",children:[e.jsx(ci,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:[h.address,h.city,h.state].filter(Boolean).join(", ")})]})]})]})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[G&&e.jsxs("button",{onClick:()=>V(!0),className:"hub-glass inline-flex items-center gap-2 rounded-full px-4 py-2 text-sm font-semibold transition-transform hover:scale-[1.02]",title:"Find public professional details (job, company, social profiles) for this person. Property data is on the Property tab.",children:[e.jsx(Nn,{className:"h-4 w-4"}),"Find person details"]}),e.jsxs("button",{onClick:()=>{gs(),U("details")},className:"inline-flex items-center gap-2 rounded-full bg-background px-4 py-2 text-sm font-semibold text-foreground shadow-sm transition-transform hover:scale-[1.02]",children:[e.jsx(_p,{className:"h-4 w-4"}),"Edit"]}),e.jsx("button",{onClick:Is,className:"hub-glass inline-flex h-9 w-9 items-center justify-center rounded-full",title:"Delete contact",children:e.jsx(Hn,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 sm:flex sm:flex-wrap",children:[h.phone&&e.jsxs("a",{href:`tel:${h.phone}`,className:"hub-glass inline-flex items-center justify-center gap-2 rounded-xl px-4 py-2.5 text-sm font-medium",children:[e.jsx(Da,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Call"]}),h.phone&&e.jsxs("button",{onClick:()=>window.location.href=`sms:${h.phone}`,className:"hub-glass inline-flex items-center justify-center gap-2 rounded-xl px-4 py-2.5 text-sm font-medium",children:[e.jsx(eo,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Text"]}),h.email&&e.jsxs("button",{onClick:()=>yn(h.email,`${h.first_name} ${h.last_name||""}`.trim()),className:"hub-glass inline-flex items-center justify-center gap-2 rounded-xl px-4 py-2.5 text-sm font-medium",children:[e.jsx(mn,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Email"]}),e.jsxs("button",{onClick:()=>r(`/mission-control/video/record?contact_id=${s}`),className:"hub-glass inline-flex items-center justify-center gap-2 rounded-xl px-4 py-2.5 text-sm font-medium",children:[e.jsx(ua,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Video"]}),e.jsxs("button",{onClick:()=>te(!0),className:"hub-glass inline-flex items-center justify-center gap-2 rounded-xl px-4 py-2.5 text-sm font-medium",children:[e.jsx(dn,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Log Action"]}),h.email&&e.jsxs("button",{onClick:()=>Ve(!0),className:"hub-glass inline-flex items-center justify-center gap-2 rounded-xl px-4 py-2.5 text-sm font-medium",children:[e.jsx(Nn,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Connect Page"]})]})]})}),e.jsxs(ha,{value:O,onValueChange:Rs=>{Rs==="details"&&!R&&gs(),U(Rs)},children:[e.jsx("div",{className:"-mx-1 overflow-x-auto px-1",children:e.jsxs(ma,{className:"inline-flex h-10 w-auto",children:[e.jsx(Zt,{value:"overview",children:"Overview"}),e.jsx(Zt,{value:"details",children:"Details"}),e.jsx(Zt,{value:"activity",children:"Activity"}),e.jsx(Zt,{value:"marketing",children:"Marketing"}),t&&e.jsx(Zt,{value:"property-intel",children:"Property Intelligence"})]})}),e.jsx(Xt,{value:"overview",className:"mt-4 space-y-5",children:e.jsxs("div",{className:"grid gap-5 lg:grid-cols-3",children:[e.jsxs("div",{className:"space-y-5 lg:col-span-2",children:[e.jsx(HBn,{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(Ta,{className:"h-4 w-4 text-primary"}),"Key Dates"]})}),e.jsxs(Ie,{children:[e.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:[{icon:ul,label:"Birthday",value:h.birthday},{icon:va,label:"Home Anniversary",value:h.home_anniversary},{icon:Jo,label:"Wedding Anniversary",value:h.wedding_anniversary},{icon:Jo,label:"Spouse Birthday",value:h.spouse_birthday}].map(({icon:Rs,label:jr,value:kr})=>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(Rs,{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:jr}),e.jsx("p",{className:"truncate text-sm font-medium",children:kr?en(kh(kr),kh(kr).getFullYear()===1900?"MMMM d":"MMMM d, yyyy"):"—"})]})]},jr))}),kt.length>0&&e.jsxs("p",{className:"mt-3 text-xs text-muted-foreground",children:["Last contacted ",en(new Date(kt[0].completed_at),"MMM d, yyyy")," (",kt[0].name,")",h.created_at&&` · Added ${en(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(Ie,{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(ci,{className:"mt-0.5 h-4 w-4 text-muted-foreground"}),e.jsxs("div",{className:"text-sm",children:[h.address&&e.jsx("div",{children:h.address}),e.jsxs("div",{className:"text-muted-foreground",children:[[h.city,h.state].filter(Boolean).join(", "),h.zip_code?` ${h.zip_code}`:""]})]})]}),Je&&h.address&&h.city&&h.state&&e.jsxs($,{size:"sm",variant:"outline",onClick:pt,disabled:rt,children:[rt?e.jsx(Ct,{className:"mr-1 h-4 w-4 animate-spin"}):e.jsx(a2,{className:"mr-1 h-4 w-4"}),"Create CMA"]})]}),eCt(h)&&e.jsx(Ie,{className:"pt-0",children:e.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-dashed p-3",children:[e.jsx(ci,{className:"mt-0.5 h-4 w-4 text-muted-foreground"}),e.jsxs("div",{className:"text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:TYe(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:ABn(TYe(h))})]})]})})]}),e.jsx(H$n,{contactId:h.id,ownerUserId:h.owner_user_id,legacyNote:h.notes}),e.jsx(RUn,{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(Ie,{children:e.jsx(uCt,{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(Ie,{className:"space-y-3",children:[e.jsx(IYe,{contactId:s,currentSpouseContactId:(h==null?void 0:h.spouse_contact_id)||null,currentSpouseName:h.spouse_name||null,currentSpouseEmail:h.spouse_email||null,onLink:Rs=>P.mutate({contactId:s,spouseContactId:Rs}),onUnlink:()=>P.mutate({contactId:s,spouseContactId:null}),isEditing:!1}),e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(ji,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:Pt(!h.company_name&&!h.job_title&&"text-muted-foreground"),children:h.job_title&&h.company_name?`${h.job_title} at ${h.company_name}`:h.job_title||h.company_name||"No company on file"})]})]})]}),e.jsx(FUn,{contactId:s}),e.jsx(cUn,{contactId:s})]})]})}),e.jsx(Xt,{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(Ie,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Basics"}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"first_name",children:"First Name"}),e.jsx(pe,{id:"first_name",value:Y.first_name||"",onChange:Rs=>X({...Y,first_name:Rs.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"last_name",children:"Last Name"}),e.jsx(pe,{id:"last_name",value:Y.last_name||"",onChange:Rs=>X({...Y,last_name:Rs.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"email",children:"Email"}),e.jsx(pe,{id:"email",type:"email",value:Y.email||"",onChange:Rs=>X({...Y,email:Rs.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"phone",children:"Phone"}),e.jsx(pe,{id:"phone",value:Y.phone||"",onChange:Rs=>X({...Y,phone:Rs.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:Y.address||"",onChange:Rs=>X({...Y,address:Rs.target.value}),placeholder:"123 Main St"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 sm:grid-cols-4",children:[e.jsxs("div",{className:"col-span-2",children:[e.jsx(ee,{htmlFor:"city",children:"City"}),e.jsx(pe,{id:"city",value:Y.city||"",onChange:Rs=>X({...Y,city:Rs.target.value}),placeholder:"City"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"state",children:"State"}),e.jsx(pe,{id:"state",value:Y.state||"",onChange:Rs=>X({...Y,state:Rs.target.value}),placeholder:"TX",maxLength:2})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"zip_code",children:"Zip Code"}),e.jsx(pe,{id:"zip_code",value:Y.zip_code||"",onChange:Rs=>X({...Y,zip_code:Rs.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:Y.address2_label||"",onChange:Rs=>X({...Y,address2_label:Rs.target.value}),placeholder:"Vacation home"}),e.jsx("datalist",{id:"contact-address-labels",children:wQt.map(Rs=>e.jsx("option",{value:Rs},Rs))})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"address2",children:"Street Address"}),e.jsx(pe,{id:"address2",value:Y.address2||"",onChange:Rs=>X({...Y,address2:Rs.target.value}),placeholder:"456 Lake Rd"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 sm:grid-cols-4",children:[e.jsxs("div",{className:"col-span-2",children:[e.jsx(ee,{htmlFor:"address2_city",children:"City"}),e.jsx(pe,{id:"address2_city",value:Y.address2_city||"",onChange:Rs=>X({...Y,address2_city:Rs.target.value}),placeholder:"City"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"address2_state",children:"State"}),e.jsx(pe,{id:"address2_state",value:Y.address2_state||"",onChange:Rs=>X({...Y,address2_state:Rs.target.value}),placeholder:"TX",maxLength:2})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"address2_zip",children:"Zip Code"}),e.jsx(pe,{id:"address2_zip",value:Y.address2_zip||"",onChange:Rs=>X({...Y,address2_zip:Rs.target.value}),placeholder:"12345"})]})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"mail_to_secondary",className:"text-sm",children:"Send mail here instead"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Pop-bys and mailers will use this address."})]}),e.jsx(Sn,{id:"mail_to_secondary",checked:!!Y.mail_to_secondary,onCheckedChange:Rs=>X({...Y,mail_to_secondary:Rs})})]}),e.jsx($,{type:"button",variant:"ghost",size:"sm",className:"text-destructive",onClick:()=>{X({...Y,address2_label:"",address2:"",address2_city:"",address2_state:"",address2_zip:"",mail_to_secondary:!1}),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:Y.birthday||"",onChange:Rs=>X({...Y,birthday:Rs.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"home_anniversary",children:"Home Anniversary"}),e.jsx(pe,{id:"home_anniversary",type:"date",value:Y.home_anniversary||"",onChange:Rs=>X({...Y,home_anniversary:Rs.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"wedding_anniversary",children:"Wedding Anniversary"}),e.jsx(pe,{id:"wedding_anniversary",type:"date",value:Y.wedding_anniversary||"",onChange:Rs=>X({...Y,wedding_anniversary:Rs.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"spouse_birthday",children:"Spouse Birthday"}),e.jsx(pe,{id:"spouse_birthday",type:"date",value:Y.spouse_birthday||"",onChange:Rs=>X({...Y,spouse_birthday:Rs.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(IYe,{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:Rs=>P.mutate({contactId:s,spouseContactId:Rs}),onUnlink:()=>P.mutate({contactId:s,spouseContactId:null}),isEditing:!0}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"company_name",children:"Company"}),e.jsx(pe,{id:"company_name",value:Y.company_name||"",onChange:Rs=>X({...Y,company_name:Rs.target.value}),placeholder:"Enter company name"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"job_title",children:"Job Title"}),e.jsx(pe,{id:"job_title",value:Y.job_title||"",onChange:Rs=>X({...Y,job_title:Rs.target.value}),placeholder:"Enter job title"})]})]}),e.jsx(UQt,{value:Y.lead_source_id||"",onChange:Rs=>X({...Y,lead_source_id:Rs})})]}),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(Rs=>Rs.active).map(Rs=>{var kr;const jr=!!((kr=Y.tagIds)!=null&&kr.includes(Rs.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",jr?"border-primary bg-primary/10 text-primary":"border-border hover:bg-accent"),children:[e.jsx(ai,{checked:jr,onCheckedChange:$n=>{var kn;X($n?{...Y,tagIds:[...Y.tagIds||[],Rs.id]}:{...Y,tagIds:(kn=Y.tagIds)==null?void 0:kn.filter(Fn=>Fn!==Rs.id)})}}),Rs.name]},Rs.id)})}),e.jsxs("div",{children:[e.jsx(ee,{children:"Tags"}),e.jsx("div",{className:"mt-2",children:e.jsx(uCt,{contactId:s})})]})]}),e.jsx(Vc,{}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"notes",children:"Notes"}),e.jsx(Ls,{id:"notes",value:Y.notes||"",onChange:Rs=>X({...Y,notes:Rs.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:ks,disabled:A.isPending,children:[A.isPending?e.jsx(Ct,{className:"mr-1 h-4 w-4 animate-spin"}):e.jsx(ca,{className:"mr-1 h-4 w-4"}),"Save Changes"]})]})]})]})}),e.jsx(Xt,{value:"activity",className:"mt-4",children:e.jsxs("div",{className:"grid gap-5 lg:grid-cols-3",children:[e.jsx("div",{className:"lg:col-span-2",children:e.jsxs(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(dn,{className:"mr-1 h-3.5 w-3.5"})," Log Action"]})]}),e.jsx(Ie,{children:kt.length>0?e.jsx("div",{className:"space-y-4",children:kt.map(Rs=>{var jr;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:Rs.color},children:Rs.type==="popby"?e.jsx(ul,{className:"h-4 w-4"}):(jr=Rs.name)==null?void 0:jr.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:Rs.name}),Rs.videoId&&e.jsxs($,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:()=>Fe(Rs.videoId),children:[e.jsx(zu,{className:"mr-1 h-3 w-3"}),"Preview"]})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:en(new Date(Rs.completed_at),"MMM d, yyyy h:mm a")}),Rs.notes&&!Rs.videoId&&e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:Rs.notes})]})]},Rs.id)})}):e.jsx("p",{className:"py-6 text-center text-sm text-muted-foreground",children:"No activity logged yet"})})]})}),e.jsxs("div",{className:"space-y-5",children:[v&&v.length>0&&e.jsxs(je,{children:[e.jsx(St,{className:"pb-3",children:e.jsxs(Et,{className:"flex items-center gap-2 text-base",children:[e.jsx(eo,{className:"h-4 w-4 text-primary"}),"Video Replies"]})}),e.jsx(Ie,{children:e.jsx("div",{className:"space-y-4",children:v.map(Rs=>{var jr,kr;return e.jsxs("div",{className:"flex items-start gap-3 border-b pb-3 last:border-0",children:[(jr=Rs.video)!=null&&jr.thumbnail_url?e.jsx("img",{src:Rs.video.thumbnail_url,alt:Rs.video.title||"Video",className:"h-12 w-16 cursor-pointer rounded object-cover transition-opacity hover:opacity-80",onClick:()=>Fe(Rs.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(Rs.video_id),children:e.jsx(ua,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("span",{className:"block truncate text-sm font-medium",children:["Replied to: ",((kr=Rs.video)==null?void 0:kr.title)||"Untitled Video"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:en(new Date(Rs.created_at),"MMM d, yyyy h:mm a")}),Rs.message&&e.jsxs("p",{className:"mt-1 line-clamp-2 text-sm text-muted-foreground",children:['"',Rs.message,'"']})]})]},Rs.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(Kr,{className:"h-4 w-4 text-sky-500"}),"Sent Emails"]})}),e.jsx(Ie,{children:e.jsx("div",{className:"space-y-3",children:gt.map(Rs=>e.jsxs(zs,{children:[e.jsx(jl,{asChild:!0,children:e.jsxs("button",{className:"flex w-full cursor-pointer items-start gap-3 rounded-lg border p-3 text-left transition-colors hover:bg-muted/50",children:[e.jsx("div",{className:"flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full bg-sky-500/10 text-sky-600",children:e.jsx(mn,{className:"h-4 w-4"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:Rs.subject}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["To: ",Rs.to_email," · ",en(new Date(Rs.sent_at),"MMM d, yyyy h:mm a")]})]}),e.jsx(Di,{className:"mt-1 h-4 w-4 flex-shrink-0 text-muted-foreground"})]})}),e.jsxs(Os,{className:"flex max-h-[85vh] max-w-2xl flex-col",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(mn,{className:"h-5 w-5 text-sky-500"}),Rs.subject]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["To: ",Rs.to_email," · ",en(new Date(Rs.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:Rs.body,className:"h-[400px] w-full border-0",sandbox:"",title:`Email: ${Rs.subject}`})})]})]},Rs.id))})})]}),e.jsx(vUn,{contactId:s})]})]})}),e.jsx(Xt,{value:"marketing",className:"mt-4",children:e.jsxs("div",{className:"grid gap-5 lg:grid-cols-2",children:[e.jsx(mUn,{contactId:s,contactName:h.first_name}),e.jsx(dUn,{contactId:s}),n&&e.jsxs(e.Fragment,{children:[e.jsx(uUn,{contactId:s,contactName:h.first_name}),e.jsx(hUn,{contactId:s,contactName:h.first_name})]}),e.jsx(gUn,{contactId:s})]})}),t&&e.jsx(Xt,{value:"property-intel",className:"mt-4",children:e.jsx(IUn,{contactId:s,contactAddress:h.address,contactCity:h.city,contactState:h.state,contactZip:h.zip_code})})]}),e.jsxs("div",{className:"fixed inset-x-0 bottom-0 z-40 flex items-center gap-2 border-t bg-background/95 px-3 py-2 pb-[calc(env(safe-area-inset-bottom)+0.5rem)] backdrop-blur lg:hidden",children:[h.phone&&e.jsx("a",{href:`tel:${h.phone}`,className:"flex-1",children:e.jsxs($,{variant:"outline",className:"w-full",children:[e.jsx(Da,{className:"mr-1 h-4 w-4"})," Call"]})}),h.phone&&e.jsxs($,{variant:"outline",className:"flex-1",onClick:()=>window.location.href=`sms:${h.phone}`,children:[e.jsx(eo,{className:"mr-1 h-4 w-4"})," Text"]}),e.jsxs($,{className:"flex-1",onClick:()=>te(!0),children:[e.jsx(dn,{className:"mr-1 h-4 w-4"})," Log"]})]}),e.jsx(zs,{open:ne,onOpenChange:te,children:e.jsxs(Os,{className:"max-h-[85vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Log an Action"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Action Type"}),e.jsx("div",{className:"mt-2 grid grid-cols-2 gap-2",children:g==null?void 0:g.filter(Rs=>Rs.active).map(Rs=>e.jsxs("button",{onClick:()=>ce(Rs.id),className:Pt("rounded-lg border p-3 text-left transition-all",J===Rs.id?"border-primary bg-primary/10":"hover:bg-accent"),children:[e.jsx("div",{className:"font-medium",children:Rs.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Rs.description})]},Rs.id))}),ds&&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:Rs=>Se(Rs.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(Kd,{children:[e.jsx(Yd,{asChild:!0,children:e.jsxs($,{variant:"outline",className:Pt("mt-2 w-full justify-start text-left font-normal",!ue&&"text-muted-foreground"),children:[e.jsx(Ta,{className:"mr-2 h-4 w-4"}),ue?en(ue,"PPP"):"Today (default)"]})}),e.jsx(Od,{className:"w-auto p-0",align:"start",children:e.jsx(T2,{mode:"single",selected:ue,onSelect:ve,disabled:Rs=>Rs>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(Ls,{id:"action-notes",value:_e,onChange:Rs=>he(Rs.target.value),placeholder:"Add any notes about this interaction...",rows:3})]}),e.jsxs($,{onClick:Ss,disabled:!J||ds&&!Ee.trim()||I.isPending,className:"w-full",children:[e.jsx(ca,{className:"mr-1 h-4 w-4"}),"Complete Action"]})]})]})}),e.jsx(zs,{open:!!Le,onOpenChange:Rs=>!Rs&&Fe(null),children:e.jsxs(Os,{className:"max-w-2xl",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Video Preview"})}),Le&&e.jsx(LUn,{videoId:Le})]})})]})}),G&&h&&e.jsx(B$n,{open:W,onOpenChange:V,contactId:h.id,contactName:`${h.first_name} ${h.last_name||""}`.trim(),hasEmail:!!h.email}),Xe&&h&&Ne&&e.jsx(kk,{open:ke,onOpenChange:Be,contact:{id:h.id,first_name:h.first_name,last_name:h.last_name,email:Ne.email},gmailEmail:qe}),h&&h.email&&e.jsx(W$n,{open:Ce,onOpenChange:Ve,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 zUn({rangeDays:s}){const{user:t}=bs(),n=Wt(),[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 y=new Date(Date.now()-s*864e5).toISOString();f=f.gte("created_at",y)}const{data:g,error:x}=await f;if(x)throw x;return g||[]}}),{data:h}=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){re.info("All recipients opened — nothing to resend!"),l(null),c(!1);return}const{data:x}=await q.from("email_campaigns").select("subject, body_html, from_email, reply_to_email").eq("id",i.id).single();if(!x)throw new Error("Original campaign not found");const{data:y,error:v}=await q.from("email_campaigns").insert({user_id:t.id,name:`${i.name} (Resend to non-openers)`,subject:x.subject,body_html:x.body_html,from_email:x.from_email,reply_to_email:x.reply_to_email,total_recipients:f.length,status:"draft"}).select("id").single();if(v)throw v;const b=f.map(S=>({campaign_id:y.id,contact_id:S.contact_id,email:S.email,name:S.name,status:"pending"}));for(let S=0;S{const g=f.sent_count||0,x=g>0?f.open_count/g*100:0,y=g>0?f.click_count/g*100:0,v=f.sent_at?dk(new Date,new Date(f.sent_at)):0,b=f.status==="sent"&&v>=3&&g>0&&f.open_counta(f.id),children:[e.jsx(Ca,{className:"h-3.5 w-3.5 mr-1"})," Details"]}),b&&e.jsxs($,{variant:"outline",size:"sm",onClick:()=>l(f),children:[e.jsx(Zz,{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(uue,{icon:e.jsx(Kr,{className:"h-3.5 w-3.5"}),label:"Sent",value:g,sub:`of ${f.total_recipients}`}),e.jsx(uue,{icon:e.jsx(Ca,{className:"h-3.5 w-3.5 text-blue-600"}),label:"Opens",value:f.open_count,sub:`${x.toFixed(1)}%`,children:e.jsx(Yi,{value:x,className:"h-1 mt-1"})}),e.jsx(uue,{icon:e.jsx(Pm,{className:"h-3.5 w-3.5 text-purple-600"}),label:"Clicks",value:f.click_count,sub:`${y.toFixed(1)}%`,children:e.jsx(Yi,{value:y,className:"h-1 mt-1"})}),e.jsx(uue,{icon:e.jsx(YI,{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(Gy,{open:!!r,onOpenChange:f=>!f&&a(null),children:e.jsxs(my,{className:"w-full sm:max-w-2xl overflow-y-auto",children:[e.jsx(L0,{children:e.jsx(R0,{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:en(new Date(f.opened_at),"MMM d")}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx("td",{className:"py-2 text-xs",children:f.clicked_at?e.jsx($e,{variant:"default",className:"text-xs bg-purple-600",children:en(new Date(f.clicked_at),"MMM d")}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsxs("td",{className:"py-2 text-xs",children:[f.status==="sent"&&e.jsx($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(Zz,{className:"h-4 w-4 mr-1"}),"Resend"]})})]})]})})]})}function uue({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 une(){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 BUn(){const{user:s}=bs(),t=Xn(),n=Wt(),{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 une(),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:()=>{re.success("Schedule cancelled — saved as draft"),n.invalidateQueries({queryKey:["scheduled-email-campaigns"]})},onError:d=>re.error(d.message)}),o=mt({mutationFn:d=>i("delete",d),onSuccess:()=>{re.success("Scheduled email deleted"),n.invalidateQueries({queryKey:["scheduled-email-campaigns"]})},onError:d=>re.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:()=>{re.success("Send time updated"),n.invalidateQueries({queryKey:["scheduled-email-campaigns"]})},onError:d=>re.error(d.message)});return a?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading scheduled emails..."}):r.length===0?e.jsx(je,{children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(da,{className:"h-12 w-12 text-muted-foreground mb-3"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No scheduled emails."}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Emails you schedule for the future will appear here."})]})}):e.jsx("div",{className:"space-y-3",children:r.map(d=>e.jsx($Un,{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 $Un({campaign:s,onEdit:t,onCancel:n,onDelete:r,onReschedule:a,isBusy:i}){const l=s.scheduled_at?new Date(s.scheduled_at):null,[o,c]=j.useState(!1),[d,u]=j.useState(l||void 0),[h,m]=j.useState(l?`${String(l.getHours()).padStart(2,"0")}:${String(l.getMinutes()).padStart(2,"0")}`:"09:00"),f=()=>{if(!d)return re.error("Pick a date");const g=new Date(`${en(d,"yyyy-MM-dd")}T${h}:00`).toISOString();if(new Date(g).getTime()gm(g.target.value)})]})]}),e.jsxs(Sr,{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(Tg,{asChild:!0,children:e.jsxs($,{size:"sm",variant:"outline",disabled:i,children:[e.jsx(Nu,{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(Tg,{asChild:!0,children:e.jsxs($,{size:"sm",variant:"ghost",className:"text-destructive hover:text-destructive",disabled:i,children:[e.jsx(Hn,{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 UUn({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 hue({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 qUn({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(UUn,{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(hue,{icon:e.jsx(Vr,{className:"h-3.5 w-3.5"}),label:"Delivered",value:s.toLocaleString(),hint:"All sends completed"}),e.jsx(hue,{icon:e.jsx(Ca,{className:"h-3.5 w-3.5"}),label:"Opened",value:t.toLocaleString(),hint:r>0?`${Math.round(c)}% of tracked`:"No tracked emails"}),e.jsx(hue,{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(hue,{icon:e.jsx(da,{className:"h-3.5 w-3.5"}),label:"Scheduled",value:a.toLocaleString(),hint:a>0?"Editable before send":"Nothing queued",tone:a>0?"alert":"default",onClick:o})]})]})})}const SCt=["Gmail","Mass Email","Campaign","Client Portal Invite","Card Studio"],VUn={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 HUn(){const{user:s}=bs(),[t,n]=gc(),{data:r=[],isLoading:a}=JQt(),[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:y=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 v=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,v.length],enabled:v.length>0,queryFn:async()=>{const{data:I}=await q.from("innercircle_contacts").select("id, first_name, last_name").in("id",v),P=new Map;return(I||[]).forEach(R=>{P.set(R.id,[R.first_name,R.last_name].filter(Boolean).join(" ")||"Contact")}),P}}),w=j.useMemo(()=>{const I=d==="all"?null:Date.now()-parseInt(d)*864e5,P=i.trim().toLowerCase();return r.filter(R=>{if(o!=="all"&&R.channel!==o||I&&new Date(R.sent_at).getTime(){const I={};let P=0,R=0,D=0;return w.forEach(O=>{I[O.channel]=(I[O.channel]||0)+1,(O.channel==="Campaign"||O.channel==="Mass Email")&&(D++,O.opened_at&&P++,O.clicked_at&&R++)}),{byChannel:I,opened:P,clicked:R,trackable:D}},[w]),A=d==="all"?"All time":`Last ${d} days`,E=SCt.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(Kr,{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(Kr,{className:"h-3.5 w-3.5"})," Sent"]}),e.jsxs("button",{onClick:()=>g("scheduled"),className:`inline-flex items-center gap-1.5 rounded-full px-3 py-1.5 text-sm transition-colors ${f==="scheduled"?"bg-background shadow-sm font-medium":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(da,{className:"h-3.5 w-3.5"})," Scheduled",y>0&&e.jsx($e,{variant:"secondary",className:"ml-0.5 h-5 min-w-5 px-1.5 text-xs",children:y})]})]}),e.jsxs($,{onClick:()=>m(!0),className:"rounded-full",children:[e.jsx(mn,{className:"h-4 w-4 mr-2"})," Send Email"]})]})]}),e.jsxs(ha,{value:f,onValueChange:I=>g(I),className:"space-y-5",children:[e.jsxs(Xt,{value:"sent",className:"space-y-5 mt-0",children:[e.jsx(qUn,{total:w.length,opened:S.opened,clicked:S.clicked,trackable:S.trackable,scheduled:y,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(Zr,{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"}),SCt.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(QS,{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(zUn,{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(Ie,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(mn,{className:"h-12 w-12 text-muted-foreground mb-3"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No sent emails match your filters."})]})}):e.jsx(je,{className:"rounded-2xl overflow-hidden",children:e.jsx(Ie,{className:"p-0",children:e.jsxs("div",{className:"overflow-x-auto",children:[e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-muted/50 text-xs uppercase text-muted-foreground",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left py-3 px-4 font-medium",children:"Sent"}),e.jsx("th",{className:"text-left py-3 px-4 font-medium",children:"Channel"}),e.jsx("th",{className:"text-left py-3 px-4 font-medium",children:"Subject"}),e.jsx("th",{className:"text-left py-3 px-4 font-medium",children:"Recipient"}),e.jsx("th",{className:"text-left py-3 px-4 font-medium",children:"Contact"}),e.jsx("th",{className:"text-left py-3 px-4 font-medium",children:e.jsx(bk,{children:e.jsxs(iy,{children:[e.jsxs(oy,{className:"inline-flex items-center gap-1",children:["Engagement ",e.jsx(QS,{className:"h-3 w-3"})]}),e.jsx(jx,{className:"max-w-xs",children:"Open & click tracking works for Mass Emails and Campaigns. Emails sent through your connected Gmail inbox aren't tracked."})]})})})]})}),e.jsx("tbody",{children:w.slice(0,500).map(I=>{const P=I.contact_id?b==null?void 0:b.get(I.contact_id):null,R=I.channel==="Campaign"||I.channel==="Mass Email";return e.jsxs("tr",{className:"border-t hover:bg-muted/30",children:[e.jsx("td",{className:"py-3 px-4 whitespace-nowrap text-muted-foreground",children:en(new Date(I.sent_at),"MMM d, yyyy h:mm a")}),e.jsx("td",{className:"py-3 px-4",children:e.jsx($e,{variant:"outline",className:VUn[I.channel],children:I.channel})}),e.jsx("td",{className:"py-3 px-4 max-w-xs truncate font-medium",children:I.subject}),e.jsx("td",{className:"py-3 px-4 text-muted-foreground",children:I.to_email}),e.jsx("td",{className:"py-3 px-4",children:I.contact_id&&P?e.jsx(wr,{to:`/mission-control/contacts/${I.contact_id}`,className:"text-primary hover:underline",children:P}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx("td",{className:"py-3 px-4",children:R?e.jsxs("div",{className:"flex flex-wrap gap-1",children:[e.jsxs($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(Ca,{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(Xt,{value:"scheduled",className:"mt-0",children:e.jsx(BUn,{})})]}),e.jsx(kk,{open:h,onOpenChange:m,gmailEmail:x})]})})}const CCt={Crown:Bg,FileText:Jr,Users:Yn,Globe:dl,Star:ei,Phone:Da,MessageSquare:eo,PenTool:IE,Video:ua,Gift:ul},mue=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function GUn(){var gt,ss;const s=Xn(),{user:t}=bs(),{data:n}=qw(),{data:r}=AHs(),{data:a}=RHs(),{data:i}=EUt(),{data:l}=tie(),{data:o}=CHs(),c=DHs(),d=EHs(),u=MHs(),h=PHs(),m=IHs(),f=LHs(),g=THs(),[x,y]=j.useState(null),[v,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,Y]=j.useState(null),[X,ae]=j.useState(!1),[le,ne]=j.useState(""),[te,J]=j.useState(""),[ce,_e]=j.useState(""),[he,ue]=j.useState(""),ve=(Yt,ts)=>a==null?void 0:a.some(ys=>ys.plan_id===Yt&&ys.relationship_type_id===ts&&ys.active),Ee=Yt=>a==null?void 0:a.find(ts=>ts.relationship_type_id===Yt&&ts.active),Se=async(Yt,ts)=>{const ys=ve(Yt,ts);await c.mutateAsync({planId:Yt,relationshipTypeId:ts,active:!ys})},Le=(r==null?void 0:r.filter(Yt=>Yt.active&&!Yt.owner_user_id))||[],Fe=(r==null?void 0:r.filter(Yt=>Yt.owner_user_id===(t==null?void 0:t.id)))||[],ke=n==null?void 0:n.find(Yt=>Yt.id===x),Be=x?Ee(x):null,Ne=r==null?void 0:r.find(Yt=>Yt.id===(Be==null?void 0:Be.plan_id)),Ae=async()=>{if(!A.trim())return;const Yt=await d.mutateAsync({name:A,description:I});Yt&&R.length>0&&await m.mutateAsync({planId:Yt.id,items:R}),qe()},Ce=async()=>{!A.trim()||!w||(await u.mutateAsync({id:w,name:A,description:I}),await m.mutateAsync({planId:w,items:R}),qe())},Ve=Yt=>{var ts;S(Yt.id),E(Yt.name),P(Yt.description||""),D(((ts=Yt.items)==null?void 0:ts.map(ys=>({month_number:ys.month_number,action_type_id:ys.action_type_id,default_script_id:ys.default_script_id||void 0,notes:ys.notes||void 0})))||[]),b(!0)},ze=async(Yt,ts)=>{if(Yt.owner_user_id===(t==null?void 0:t.id)){Ve(Yt);return}try{const ys=await g.mutateAsync({sourcePlanId:Yt.id,newName:`${Yt.name} (My Copy)`});if(!ys)return;await c.mutateAsync({planId:Yt.id,relationshipTypeId:ts,active:!1}),await c.mutateAsync({planId:ys.id,relationshipTypeId:ts,active:!0}),S(ys.id),E(ys.name),P(ys.description||""),D((Yt.items||[]).map(Bt=>({month_number:Bt.month_number,action_type_id:Bt.action_type_id,default_script_id:Bt.default_script_id||void 0,notes:Bt.notes||void 0}))),b(!0)}catch{}},qe=()=>{b(!1),S(null),E(""),P(""),D([])},dt=(Yt,ts)=>{V(ts)},Xe=(Yt,ts,ys)=>{D(Bt=>[...Bt.filter(as=>as.month_number!==Yt),{month_number:Yt,action_type_id:ts,default_script_id:ys}]),U(null),V(null)},at=Yt=>{D(ts=>ts.filter(ys=>ys.month_number!==Yt))},rt=async()=>{if(!le.trim()||!te.trim()||!W)return;const Yt=await f.mutateAsync({actionTypeId:W,title:le,scriptBody:te,emailSubject:ce||void 0,tone:he||void 0});Yt&&O!==null&&Xe(O,W,Yt.id),ae(!1),ne(""),J(""),_e(""),ue("")},Ke=W?o==null?void 0:o.filter(Yt=>Yt.action_type_id===W&&Yt.active):[],Je=Yt=>CCt[Yt||"Phone"]||Da,pt=Yt=>CCt[Yt||"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(dn,{className:"h-4 w-4 mr-2"}),"Create Custom Plan"]})]}),e.jsxs("div",{className:"grid lg:grid-cols-3 gap-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx("h3",{className:"font-semibold text-lg",children:"Your Contact Groups"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Select a group to assign a touchpoint plan"}),n==null?void 0:n.filter(Yt=>Yt.active).map(Yt=>{const ts=pt(Yt.icon),ys=(i==null?void 0:i[Yt.id])||0,Bt=Ee(Yt.id),Ft=r==null?void 0:r.find(kt=>kt.id===(Bt==null?void 0:Bt.plan_id)),as=x===Yt.id;return e.jsxs("button",{onClick:()=>y(Yt.id),className:` w-full flex items-center gap-3 p-4 rounded-lg border text-left transition-all ${as?"border-primary bg-primary/5 ring-2 ring-primary":"hover:bg-accent"} `,children:[e.jsx(ts,{className:"h-5 w-5 text-muted-foreground"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium",children:Yt.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[ys," 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"})]},Yt.id)})]}),e.jsx("div",{className:"lg:col-span-2",children:x&&ke?e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsxs(Et,{className:"flex items-center gap-2",children:[(()=>{const Yt=pt(ke.icon);return e.jsx(Yt,{className:"h-5 w-5"})})(),ke.name," Touchpoint Plan"]}),e.jsxs(Gn,{children:["Choose a plan for your ",ke.name," contacts"]})]}),e.jsxs(Ie,{className:"space-y-6",children:[Ne&&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: ",Ne.name]}),Ne.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:Ne.description})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{variant:"outline",size:"sm",disabled:g.isPending||c.isPending,onClick:()=>ze(Ne,x),children:[e.jsx(AN,{className:"h-4 w-4 mr-1"}),"Edit Steps"]}),e.jsx($,{variant:"outline",size:"sm",onClick:()=>Se(Ne.id,x),children:"Disable"})]})]}),Ne.items&&Ne.items.length>0&&e.jsxs("div",{className:"mt-4",children:[e.jsxs("div",{className:"text-sm font-medium mb-2 flex items-center gap-2",children:[e.jsx(Ta,{className:"h-4 w-4"}),"12-Month Schedule"]}),e.jsx("div",{className:"grid grid-cols-4 sm:grid-cols-6 gap-2",children:mue.map((Yt,ts)=>{var as,kt;const ys=((as=Ne.items)==null?void 0:as.filter(Ks=>Ks.month_number===ts+1))||[],Bt=(kt=ys[0])==null?void 0:kt.action_type,Ft=Bt?Je(Bt.icon):null;return e.jsxs("div",{className:` p-2 rounded border text-center ${ys.length>0?"bg-primary/10 border-primary":"bg-muted"} `,children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:Yt}),Ft&&e.jsx(Ft,{className:"h-4 w-4 mx-auto mt-1",style:{color:(Bt==null?void 0:Bt.color)||"#3B82F6"}})]},ts)})})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-3",children:Ne?"Switch to a Different Plan":"Choose a Plan"}),Le.length>0&&e.jsxs("div",{className:"space-y-2 mb-4",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:"Pre-built Templates"}),Le.map(Yt=>{var ys;const ts=(Ne==null?void 0:Ne.id)===Yt.id;return e.jsxs("div",{className:` flex items-center justify-between p-3 rounded-lg border ${ts?"opacity-50":"hover:bg-accent"} `,children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Yt.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[((ys=Yt.items)==null?void 0:ys.length)||0," touchpoints/year"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{size:"sm",variant:"ghost",title:"View plan details",onClick:()=>Y(Yt.id),children:e.jsx(Ca,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:"ghost",title:"Duplicate as my own plan",disabled:g.isPending,onClick:()=>{const Bt=`${Yt.name} (Copy)`;g.mutate({sourcePlanId:Yt.id,newName:Bt})},children:e.jsx(Ha,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:ts?"outline":"default",disabled:ts||c.isPending,onClick:()=>Se(Yt.id,x),children:ts?"Active":"Use This"})]})]},Yt.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(Yt=>{var ys;const ts=(Ne==null?void 0:Ne.id)===Yt.id;return e.jsxs("div",{className:` flex items-center justify-between p-3 rounded-lg border ${ts?"opacity-50":"hover:bg-accent"} `,children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Yt.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[((ys=Yt.items)==null?void 0:ys.length)||0," touchpoints/year"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{size:"sm",variant:"ghost",title:"View plan details",onClick:()=>Y(Yt.id),children:e.jsx(Ca,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:"ghost",title:"Edit plan",onClick:()=>Ve(Yt),children:e.jsx(AN,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:"ghost",title:"Delete plan",onClick:()=>h.mutate(Yt.id),children:e.jsx(Hn,{className:"h-4 w-4 text-destructive"})}),e.jsx($,{size:"sm",variant:ts?"outline":"default",disabled:ts||c.isPending,onClick:()=>Se(Yt.id,x),children:ts?"Active":"Use This"})]})]},Yt.id)})]}),Le.length===0&&Fe.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No plans available. Create a custom plan to get started."})]})]})]}):e.jsx(je,{children:e.jsxs(Ie,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(Ta,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"Select a contact group to view and assign plans"})]})})})]}),e.jsx(je,{className:"bg-muted/50",children:e.jsx(Ie,{className:"py-4",children:e.jsxs("p",{className:"text-sm text-muted-foreground",children:[e.jsx("strong",{children:"How it works:"})," When you assign a plan to a contact group, those contacts will appear in your daily suggested actions based on the plan's schedule."]})})})]}),e.jsx(zs,{open:v,onOpenChange:Yt=>{Yt?b(!0):qe()},children:e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(Bs,{children:w?"Edit Touchpoint Plan":"Create Custom Touchpoint Plan"})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"plan-name",children:"Plan Name"}),e.jsx(pe,{id:"plan-name",value:A,onChange:Yt=>E(Yt.target.value),placeholder:"e.g., My VIP Plan"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"plan-description",children:"Description (optional)"}),e.jsx(Ls,{id:"plan-description",value:I,onChange:Yt=>P(Yt.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:mue.map((Yt,ts)=>{const ys=ts+1,Bt=R.find(kt=>kt.month_number===ys),Ft=Bt?l==null?void 0:l.find(kt=>kt.id===Bt.action_type_id):null,as=Ft?Je(Ft.icon):null;return e.jsxs("div",{className:"relative",children:[e.jsxs("button",{type:"button",onClick:()=>U(O===ys?null:ys),className:` w-full p-3 rounded-lg border text-center transition-all ${Bt?"bg-primary/10 border-primary":"bg-muted hover:bg-accent"} ${O===ys?"ring-2 ring-primary":""} `,children:[e.jsx("div",{className:"text-xs text-muted-foreground font-medium",children:Yt}),as?e.jsx(as,{className:"h-5 w-5 mx-auto mt-1",style:{color:(Ft==null?void 0:Ft.color)||"#3B82F6"}}):e.jsx(dn,{className:"h-5 w-5 mx-auto mt-1 text-muted-foreground/50"})]}),Bt&&e.jsx("button",{type:"button",onClick:kt=>{kt.stopPropagation(),at(ys)},className:"absolute -top-1 -right-1 p-1 bg-destructive text-destructive-foreground rounded-full",children:e.jsx(pr,{className:"h-3 w-3"})})]},ts)})}),O!==null&&!W&&e.jsxs("div",{className:"mt-4 p-3 bg-muted rounded-lg",children:[e.jsxs("div",{className:"text-sm font-medium mb-2",children:["Step 1: Select action for ",mue[O-1],":"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:l==null?void 0:l.filter(Yt=>Yt.active).map(Yt=>{const ts=Je(Yt.icon);return e.jsxs("button",{type:"button",onClick:()=>dt(O,Yt.id),className:"flex items-center gap-2 px-3 py-2 rounded-lg border bg-background hover:bg-accent transition-colors",children:[e.jsx(ts,{className:"h-4 w-4",style:{color:Yt.color||"#3B82F6"}}),e.jsx("span",{className:"text-sm",children:Yt.name})]},Yt.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:()=>Xe(O,W),className:"w-full flex items-center gap-3 p-3 rounded-lg border bg-background hover:bg-accent transition-colors text-left",children:e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-medium text-sm",children:"No Script"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Use without a predefined script"})]})}),Ke==null?void 0:Ke.map(Yt=>e.jsx("button",{type:"button",onClick:()=>Xe(O,W,Yt.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:Yt.title}),Yt.tone&&e.jsx($e,{variant:"secondary",className:"text-xs mt-1",children:Yt.tone}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-1 line-clamp-2",children:[Yt.script_body.substring(0,100),"..."]})]})},Yt.id)),e.jsxs("button",{type:"button",onClick:()=>ae(!0),className:"w-full flex items-center gap-3 p-3 rounded-lg border border-dashed bg-background hover:bg-accent transition-colors text-left",children:[e.jsx(dn,{className:"h-5 w-5 text-muted-foreground"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-medium text-sm",children:"Create Custom Script"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Write your own script for this action"})]})]})]})]})]}),R.length>0&&e.jsxs("div",{className:"text-sm text-muted-foreground",children:[R.length," touchpoint",R.length!==1?"s":""," per year"]})]}),e.jsxs(Sr,{children:[e.jsx($,{variant:"outline",onClick:qe,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(zs,{open:X,onOpenChange:ae,children:e.jsxs(Os,{className:"max-w-lg",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Create Custom Script"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"script-title",children:"Script Title"}),e.jsx(pe,{id:"script-title",value:le,onChange:Yt=>ne(Yt.target.value),placeholder:"e.g., Friendly Check-in Call"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"script-tone",children:"Tone (optional)"}),e.jsxs(ms,{value:he,onValueChange:ue,children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Select tone..."})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"friendly",children:"Friendly"}),e.jsx(Ge,{value:"professional",children:"Professional"}),e.jsx(Ge,{value:"casual",children:"Casual"}),e.jsx(Ge,{value:"formal",children:"Formal"})]})]})]}),((ss=(gt=l==null?void 0:l.find(Yt=>Yt.id===W))==null?void 0:gt.name)==null?void 0:ss.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:Yt=>_e(Yt.target.value),placeholder:"e.g., Quick Hello!"})]}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"script-body",children:"Script Content"}),e.jsx(Ls,{id:"script-body",value:te,onChange:Yt=>J(Yt.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(Sr,{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(zs,{open:!!G,onOpenChange:Yt=>{Yt||Y(null)},children:e.jsx(Os,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:(()=>{const Yt=r==null?void 0:r.find(Bt=>Bt.id===G);if(!Yt)return null;const ts=Yt.owner_user_id===(t==null?void 0:t.id),ys=[...Yt.items||[]].sort((Bt,Ft)=>Bt.month_number-Ft.month_number);return e.jsxs(e.Fragment,{children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[Yt.name,!ts&&e.jsx($e,{variant:"secondary",children:"Template"})]}),Yt.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:Yt.description})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:[ys.length," touchpoint",ys.length!==1?"s":""," per year"]}),e.jsx("div",{className:"space-y-2",children:Array.from({length:12},(Bt,Ft)=>Ft+1).map(Bt=>{const Ft=ys.find(wt=>wt.month_number===Bt),as=Ft?l==null?void 0:l.find(wt=>wt.id===Ft.action_type_id):null,kt=Ft!=null&&Ft.default_script_id?o==null?void 0:o.find(wt=>wt.id===Ft.default_script_id):null,Ks=as?Je(as.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:mue[Bt-1]}),Ft&&as?e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[Ks&&e.jsx(Ks,{className:"h-4 w-4",style:{color:as.color||"#3B82F6"}}),e.jsx("span",{className:"font-medium text-sm",children:as.name}),kt&&e.jsx($e,{variant:"outline",className:"text-xs",children:kt.title})]}),kt&&e.jsx("div",{className:"mt-2 text-sm text-muted-foreground whitespace-pre-wrap bg-background p-2 rounded border",children:kt.script_body}),Ft.notes&&e.jsx("div",{className:"mt-1 text-xs text-muted-foreground italic",children:Ft.notes})]}):e.jsx("div",{className:"flex-1 text-sm text-muted-foreground",children:"No touchpoint scheduled"})]},Bt)})})]}),e.jsxs(Sr,{children:[e.jsx($,{variant:"outline",onClick:()=>Y(null),children:"Close"}),ts?e.jsxs($,{onClick:()=>{const Bt=r==null?void 0:r.find(Ft=>Ft.id===G);Bt&&(Y(null),Ve(Bt))},children:[e.jsx(AN,{className:"h-4 w-4 mr-2"}),"Edit Plan"]}):e.jsxs($,{disabled:g.isPending,onClick:()=>{g.mutate({sourcePlanId:Yt.id,newName:`${Yt.name} (Copy)`}),Y(null)},children:[e.jsx(Ha,{className:"h-4 w-4 mr-2"}),"Duplicate to Edit"]})]})]})})()})})]})}const Z9e="https://cma.relevelup.com";function nJt({open:s,onOpenChange:t,cma:n}){var Y;const{user:r}=bs(),{toast:a}=Bi(),[i,l]=j.useState([]),[o,c]=j.useState(null),[d,u]=j.useState(!1),[h,m]=j.useState(""),[f,g]=j.useState(""),[x,y]=j.useState(""),[v,b]=j.useState(!1),[w,S]=j.useState(null),[A,E]=j.useState(!1),[I,P]=j.useState(!1),[R,D]=j.useState(null);j.useEffect(()=>{!s||!r||(async()=>{var _e;const[X,ae,le,ne,te]=await Promise.all([q.from("innercircle_contacts").select("id, first_name, last_name, email").eq("owner_user_id",r.id).not("email","is",null).order("first_name"),q.from("profiles").select("name, email, phone, brokerage_name, avatar_url, email_signature").eq("id",r.id).maybeSingle(),q.from("gmail_integrations").select("id, is_active").eq("user_id",r.id).maybeSingle(),q.from("ses_verified_emails").select("email, status").eq("user_id",r.id).eq("status","Success").limit(1),q.from("mass_email_settings").select("*").eq("user_id",r.id).maybeSingle()]),J=(X.data||[]).filter(he=>he.email&&he.email.includes("@"));l(J),S(ae.data||null),E(!!((_e=le.data)!=null&&_e.is_active)),P(!!(ne.data&&ne.data.length>0)),D(te.data||null);const ce=n.contact_id?J.find(he=>he.id===n.contact_id):null;ce&&(c(ce),m(ce.email))})()},[s,r,n.contact_id]),j.useEffect(()=>{var ne;if(!s)return;const X=((ne=n.subject)==null?void 0:ne.address)||"your home",ae=((w==null?void 0:w.name)||"").split(" ")[0]||"your agent",le=(o==null?void 0:o.first_name)||"there";g(`Your home value report for ${X}`),y(`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,(Y=n.subject)==null?void 0:Y.address]);const O=j.useMemo(()=>A?"Gmail (your inbox)":I?"Amazon SES":null,[A,I]),U=!!(h.trim()&&f.trim()&&x.trim()&&O&&!v),W=X=>{c(X),m(X.email||""),u(!1)},V=X=>{const ae=`${Z9e}/${n.share_token}?e=${X}`,te=x.replace(/&/g,"&").replace(//g,">").replace(/\{\{cma_link\}\}/g,`View Your Home Value Report`).split(/\n{2,}/).map(_e=>`

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

`).join(""),J=w!=null&&w.use_email_signature&&(w!=null&&w.email_signature)?`
${w.email_signature}
`:`
${w!=null&&w.name?`
${w.name}
`:""} ${w!=null&&w.brokerage_name?`
${w.brokerage_name}
`:""} ${w!=null&&w.phone?`
${w.phone}
`:""} ${w!=null&&w.email?``:""}
`,ce=``;return`
${te} ${J}
Prepared with LevelUp · ReLevelUp Real Estate
${ce}
`},G=async()=>{if(!(!r||!U)){b(!0);try{const{data:X,error:ae}=await q.from("cma_email_sends").insert({cma_id:n.id,agent_id:r.id,contact_id:(o==null?void 0:o.id)??null,recipient_email:h.trim(),subject:f.trim(),sent_via:A?"gmail":"ses"}).select("id").single();if(ae)throw ae;const le=V(X.id);if(A){const{data:ne,error:te}=await q.functions.invoke("gmail-send",{body:{to:h.trim(),subject:f.trim(),body:le}});if(te)throw te;if(!(ne!=null&&ne.success))throw new Error((ne==null?void 0:ne.error)||"Gmail send failed")}else if(I){const ne=(R==null?void 0:R.display_name)||(w==null?void 0:w.name)||"ReLevelUp",te=`${ne.toLowerCase().replace(/[^a-z]/g,".").replace(/^\.+|\.+$/g,"")||"noreply"}@send.relevelup.com`,{data:J,error:ce}=await q.functions.invoke("ses-send-campaign",{body:{action:"test_send",to:h.trim(),from_email:`${ne} <${te}>`,subject:f.trim(),body_html: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(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(mn,{className:"w-5 h-5"}),"Send CMA to contact"]})}),O?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Sending via ",e.jsx("span",{className:"font-semibold text-foreground",children:O})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Contact"}),e.jsxs(Kd,{open:d,onOpenChange:u,children:[e.jsx(Yd,{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(Sw,{className:"w-4 h-4 opacity-50"})]})}),e.jsx(Od,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(S2,{children:[e.jsx(C2,{placeholder:"Search contacts…"}),e.jsxs(A2,{children:[e.jsx(E2,{children:"No contacts with email found."}),e.jsx(Dw,{children:i.map(X=>e.jsxs(m1,{value:`${X.first_name} ${X.last_name||""} ${X.email}`,onSelect:()=>W(X),children:[e.jsx(ca,{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(Ls,{rows:10,value:x,onChange:X=>y(X.target.value)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[e.jsx("code",{children:"{{cma_link}}"})," will be replaced with a styled button linking to ",e.jsxs("code",{children:["cma.relevelup.com/",n.share_token]}),". Email opens are tracked and shown on the contact's Signals."]})]}),e.jsxs("div",{className:"rounded border bg-muted/40 p-3 text-sm flex items-center gap-2",children:[e.jsx(Fr,{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:`${Z9e}/${n.share_token}`,target:"_blank",rel:"noreferrer",children:`${Z9e}/${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(Sr,{children:[e.jsx($,{variant:"ghost",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{onClick:G,disabled:!U,children:[v?e.jsx(Ct,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(Kr,{className:"w-4 h-4 mr-2"}),"Send CMA"]})]})]})})}function WUn(s){const{user:t}=bs(),n=Wt(),{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]}),re.success("Request sent — we'll reach out about upgrading your site.")},onError:l=>re.error((l==null?void 0:l.message)||"Could not send your request")});return{requestUpgrade:a,hasRequested:l=>!!(r!=null&&r.some(o=>o.feature_key===l&&o.status!=="declined")),isSending:a.isPending}}const KUn="free_luxury",YUn="free_beta";function rJt(s){const t=s==null?void 0:s.planTier;return t===KUn||t===YUn}const ZUn={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 XUn({featureKey:s,siteId:t,bullets:n}){const r=ZUn[s],{requestUpgrade:a,hasRequested:i,isSending:l}=WUn(t),o=i(s);return e.jsx("section",{className:"rounded-xl border border-amber-500/30 bg-gradient-to-br from-amber-500/10 via-card to-card p-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"h-10 w-10 shrink-0 rounded-full bg-amber-500/15 flex items-center justify-center",children:e.jsx(pc,{className:"h-5 w-5 text-amber-500"})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h2",{className:"text-lg font-semibold text-foreground",children:r.title}),e.jsx("span",{className:"text-[10px] font-bold uppercase tracking-wide px-2 py-0.5 rounded-full bg-amber-100 text-amber-700",children:"Upgrade"})]}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:r.description}),n!=null&&n.length?e.jsx("ul",{className:"mt-4 space-y-2",children:n.map(c=>e.jsxs("li",{className:"flex items-start gap-2 text-sm text-muted-foreground",children:[e.jsx(Nn,{className:"h-4 w-4 mt-0.5 text-amber-500 shrink-0"}),c]},c))}):null,e.jsx($,{className:"mt-5",disabled:o||l,onClick:()=>a.mutate({featureKey:s}),children:o?e.jsxs(e.Fragment,{children:[e.jsx(ca,{className:"h-4 w-4 mr-2"})," Upgrade requested"]}):"Request this upgrade"})]})]})})}function QUn({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=J$n(),m=KQt(),{toast:f}=Bi(),[g,x]=j.useState([]),y=async()=>{var w;x([]);try{const S=await h.mutateAsync({address:r,city:i,state:o,zip:d});x(S.matches||[]),(w=S.matches)!=null&&w.length||f({title:"No MLS match",description:'Use "Create from manual entry" below.'})}catch(S){f({title:"Search failed",description:S.message,variant:"destructive"})}},v=async w=>{const S=await m.mutateAsync({subject:w});n(!1),s(S.id)},b=async()=>{if(!r||!i||!o){f({title:"Address, city, state required"});return}const w=await m.mutateAsync({subject:{address:r,city:i,state:o,zip:d}});n(!1),s(w.id)};return e.jsxs(zs,{open:t,onOpenChange:n,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{children:[e.jsx(dn,{className:"w-4 h-4 mr-2"}),"New CMA"]})}),e.jsxs(Os,{className:"max-w-2xl",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Start a CMA"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-2",children:[e.jsx(pe,{className:"md:col-span-2",placeholder:"Street address",value:r,onChange:w=>a(w.target.value)}),e.jsx(pe,{placeholder:"City",value:i,onChange:w=>l(w.target.value)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{placeholder:"ST",maxLength:2,value:o,onChange:w=>c(w.target.value.toUpperCase())}),e.jsx(pe,{placeholder:"ZIP",value:d,onChange:w=>u(w.target.value)})]})]}),e.jsxs($,{onClick:y,disabled:!r||h.isPending,className:"w-full",children:[h.isPending?e.jsx(Ct,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(Zr,{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:()=>v(w),className:"w-full text-left p-3 border rounded hover:bg-accent transition",children:[e.jsx("div",{className:"font-medium",children:w.address}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[w.city,", ",w.state," ",w.zip," · ",w.bedrooms??"?"," bd / ",w.bathrooms??"?"," ba · ",((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 JUn(){const{data:s,isLoading:t}=K$n(),n=Q$n(),r=Xn(),{toast:a}=Bi(),[i,l]=j.useState(null),{isFreePlan:o,leadSite:c}=ng();return o?e.jsx(Vs,{children:e.jsxs("div",{className:"container mx-auto p-4 md:p-6 max-w-3xl space-y-6",children:[e.jsxs("h1",{className:"text-2xl md:text-3xl font-bold flex items-center gap-2",children:[e.jsx(Jr,{className:"w-7 h-7"})," CMAs"]}),e.jsx(XUn,{featureKey:"cma_reports",siteId:c==null?void 0:c.id,bullets:["Pull live MLS comparables for any subject property","Interactive, shareable CMA presentations for sellers","Track when your seller opens and interacts with the report"]})]})}):e.jsx(Vs,{children:e.jsxs("div",{className:"container mx-auto p-4 md:p-6 max-w-6xl",children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl md:text-3xl font-bold flex items-center gap-2",children:[e.jsx(Jr,{className:"w-7 h-7"})," CMAs"]}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Comparative Market Analyses — interactive, shareable, no static PDFs."})]}),e.jsx(QUn,{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(Ie,{className:"p-4 flex flex-wrap items-center gap-3 justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-[200px]",children:[e.jsx("div",{className:"font-semibold",children:d.title||((u=d.subject)==null?void 0:u.address)||"Untitled CMA"}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[(h=d.subject)==null?void 0:h.city,", ",(m=d.subject)==null?void 0:m.state," · ",d.buyer_mode?"Buyer":"Seller"," ·"," ",e.jsx($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(Fr,{className:"w-4 h-4"})}),e.jsxs($,{variant:"secondary",size:"sm",onClick:()=>l(d),children:[e.jsx(mn,{className:"w-4 h-4 mr-1"}),"Send"]})]}),e.jsx($,{variant:"ghost",size:"sm",onClick:async()=>{await fo("Delete this CMA?")&&n.mutate(d.id)},children:e.jsx(Hn,{className:"w-4 h-4"})})]})]})},d.id)})}):e.jsx(je,{children:e.jsx(Ie,{className:"py-12 text-center text-muted-foreground",children:"No CMAs yet. Start one above."})}),i&&e.jsx(nJt,{open:!!i,onOpenChange:d=>!d&&l(null),cma:i})]})})}function eqn(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 ACt(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 tqn({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;wu.accessToken=o;const u=new wu.Map({container:a.current,style:"mapbox://styles/mapbox/light-v11",center:[d.lng,d.lat],zoom:12});return u.addControl(new wu.NavigationControl({showCompass:!1}),"top-right"),u.on("load",()=>{u.addSource("radius",{type:"geojson",data:ACt(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(ACt(d.lat,d.lng,n))};u.isStyleLoaded()?h():u.once("load",h)},[n,d]),j.useEffect(()=>{const u=i.current;if(!u||!d)return;l.current.forEach(y=>y.remove()),l.current=[];const h=document.createElement("div");h.style.cssText=` width: 28px; height: 28px; border-radius: 50%; background: hsl(222 47% 11%); border: 3px solid white; box-shadow: 0 4px 12px rgba(0,0,0,0.3); display: flex; align-items: center; justify-content: center; color: white; font-size: 12px; font-weight: 700; `,h.textContent="★";const m=new wu.Marker({element:h}).setLngLat([d.lng,d.lat]).setPopup(new wu.Popup({offset:18}).setHTML(`Subject
${s.address??""}`)).addTo(u);l.current.push(m);const f=new wu.LngLatBounds;f.extend([d.lng,d.lat]),t.forEach((y,v)=>{const b=Number(y.latitude),w=Number(y.longitude);if(!Number.isFinite(b)||!Number.isFinite(w))return;const S=eqn(y.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: ${y.selected===!1?.4:1}; transition: transform 0.15s; transform-origin: center; `,E.onmouseenter=()=>{E.style.transform="scale(1.25)"},E.onmouseleave=()=>{E.style.transform="scale(1)"},r&&(E.onclick=()=>r(v)),A.appendChild(E);const I=y.soldPrice||y.price,P=new wu.Popup({offset:14}).setHTML(`
${y.address??""}
${y.status??""}`+(I?` · $${I.toLocaleString()}`:"")+"
"),R=new wu.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 J_=null;function aJt(){if(J_)return J_;try{const s=document.createElement("canvas"),t=s.getContext("webgl2")||s.getContext("webgl");if(!t)return J_={canRunVirtualBg:!1,reason:"WebGL is not supported on this device"},J_;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 J_={canRunVirtualBg:!1,reason:"Your device uses a software renderer which may cause lag",renderer:r},J_;const o=performance;return o.memory&&o.memory.jsHeapSizeLimit<256*1024*1024?(J_={canRunVirtualBg:!1,reason:"Limited device memory detected",renderer:r},J_):navigator.hardwareConcurrency&&navigator.hardwareConcurrency<2?(J_={canRunVirtualBg:!1,reason:"Single-core device detected — virtual backgrounds may cause lag",renderer:r},J_):(J_={canRunVirtualBg:!0,renderer:r},J_)}catch{return J_={canRunVirtualBg:!0},J_}}const sqn=[{type:"none",label:"Off"},{type:"blur",label:"Blur"}];function nqn({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(()=>aJt()),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=[...sqn,...g],y=w=>w.type!==s.type?!1:w.type==="image"?w.imageUrl===s.imageUrl:!0,v=async w=>{if(!(!w.id||!w.imageUrl)&&window.confirm(`Delete the background "${w.label}"? This can't be undone.`)){d(w.id);try{const{error:S}=await q.from("video_backgrounds").delete().eq("id",w.id);if(S)throw S;const 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(),re.success("Background deleted")}catch(S){console.error("Delete background error:",S),re.error((S==null?void 0:S.message)||"Failed to delete background")}finally{d(null)}}},b=async w=>{var A;const S=(A=w.target.files)==null?void 0:A[0];if(S){if(!S.type.startsWith("image/")){re.error("Please select an image file");return}if(S.size>5*1024*1024){re.error("Image must be under 5MB");return}o(!0);try{const{data:{user:E}}=await q.auth.getUser();if(!E)throw new Error("Not authenticated");const I=S.name.split(".").pop()||"jpg",P=`${E.id}/${crypto.randomUUID()}.${I}`,{error:R}=await q.storage.from("video-backgrounds").upload(P,S,{contentType:S.type});if(R)throw R;const{data:D}=q.storage.from("video-backgrounds").getPublicUrl(P),O=D.publicUrl,{error:U}=await q.from("video_backgrounds").insert({name:S.name.replace(/\.[^.]+$/,""),image_url:O,thumbnail_url:O,category:"custom",is_stock:!1,user_id:E.id});if(U)throw U;await f(),t({type:"image",imageUrl:O,blurRadius:15}),re.success("Background uploaded!")}catch(E){console.error("Upload error:",E),re.error("Failed to upload background")}finally{o(!1),i.current&&(i.current.value="")}}};return e.jsxs("div",{className:Pt("flex flex-col gap-1",a),children:[h&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-amber-600 bg-amber-50 dark:bg-amber-950/30 dark:text-amber-400 rounded px-2 py-1",children:[e.jsx(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=y(w);return e.jsxs("div",{className:"relative flex-shrink-0 group",children:[e.jsxs("button",{type:"button",disabled:r,onClick:()=>t({type:w.type,imageUrl:w.imageUrl,blurRadius:15,mirror:s.mirror}),className:Pt("flex-shrink-0 flex flex-col items-center gap-0.5 rounded-lg border-2 p-1 transition-all","hover:border-primary/50 focus:outline-none focus:ring-2 focus:ring-primary/30",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(Rz,{className:"h-4 w-4 text-muted-foreground"}),w.type==="blur"&&e.jsx("div",{className:"w-full h-full bg-gradient-to-br from-primary/20 to-primary/40 flex items-center justify-center",children:e.jsx("span",{className:"text-[10px] font-medium text-primary",children:"Blur"})}),w.type==="image"&&w.thumbnail&&e.jsx("img",{src:w.thumbnail,alt:w.label,className:"w-full h-full object-cover"})]}),e.jsx("span",{className:"text-[10px] text-muted-foreground truncate max-w-14",children:w.label})]}),w.deletable&&e.jsx("button",{type:"button","aria-label":`Delete background ${w.label}`,disabled:r||c===w.id,onClick:E=>{E.stopPropagation(),v(w)},className:Pt("absolute -top-1 -right-1 h-5 w-5 rounded-full bg-background border shadow-sm","flex items-center justify-center text-muted-foreground hover:text-destructive hover:border-destructive","opacity-100 sm:opacity-0 sm:group-hover:opacity-100 focus:opacity-100 transition-opacity"),children:c===w.id?e.jsx(Ct,{className:"h-3 w-3 animate-spin"}):e.jsx(pr,{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(dn,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:l?"Uploading":"Custom"})]}),e.jsx("input",{ref:i,type:"file",accept:"image/*",className:"hidden",onChange:b}),e.jsxs("button",{type:"button",disabled:r,onClick:()=>t({...s,mirror:!s.mirror}),className:Pt("flex-shrink-0 flex flex-col items-center gap-0.5 rounded-lg border-2 p-1 transition-all ml-1","hover:border-primary/50 focus:outline-none focus:ring-2 focus:ring-primary/30",s.mirror?"border-primary bg-primary/10":"border-transparent bg-muted/50",r&&"opacity-50 cursor-not-allowed"),children:[e.jsx("div",{className:"w-12 h-8 rounded flex items-center justify-center",children:e.jsx(jJ,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:"Mirror"})]})]})]})}var uW=typeof self<"u"?self:{};function iJt(s,t){e:{for(var n=["CLOSURE_FLAGS"],r=uW,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 lJt(s){uW.setTimeout(()=>{throw s},0)}var LYe,oqn=iJt(610401301,!1),TCt=iJt(748402147,!0);function MCt(){var s=uW.navigator;return s&&(s=s.userAgent)?s:""}const PCt=uW.navigator;function oDe(s){return oDe[" "](s),s}LYe=PCt&&PCt.userAgentData||null,oDe[" "]=function(){};const cJt={};let _Q=null;function lqn(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 dJt(){if(!_Q){_Q={};var s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split(""),t=["+/=","+/","-_=","-_.","-_"];for(let n=0;n<5;n++){const r=s.concat(t[n].split(""));cJt[n]=r;for(let a=0;a0)&&(MCt().indexOf("Trident")!=-1||MCt().indexOf("MSIE")!=-1))&&typeof btoa=="function";const ICt=/[-_.]/g,dqn={"-":"+",_:"/",".":"="};function uqn(s){return dqn[s]||""}function hJt(s){if(!uJt)return lqn(s);s=ICt.test(s)?s.replace(ICt,uqn):s,s=atob(s);const t=new Uint8Array(s.length);for(let n=0;n=t||(n[s]=r+1,fJt(s=Error(),"incident"),lJt(s))}}function zK(){return typeof BigInt=="function"}var BK=typeof Symbol=="function"&&typeof Symbol()=="symbol";function g3(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 fqn=g3("jas",void 0,!0),LCt=g3(void 0,"0di"),aX=g3(void 0,"1oa"),b2=g3(void 0,Symbol()),pqn=g3(void 0,"0ub"),gqn=g3(void 0,"0ubs"),DYe=g3(void 0,"0ubsb"),xqn=g3(void 0,"0actk"),fW=g3("m_m","Pa",!0),RCt=g3();const pJt={Ga:{value:0,configurable:!0,writable:!0,enumerable:!1}},gJt=Object.defineProperties,hl=BK?fqn:"Ga";var n9;const DCt=[];function Lie(s,t){BK||hl in s||gJt(s,pJt),s[hl]|=t}function D0(s,t){BK||hl in s||gJt(s,pJt),s[hl]=t}function Rie(s){return Lie(s,34),s}function hne(s){return Lie(s,8192),s}D0(DCt,7),n9=Object.freeze(DCt);var pW={};function M2(s,t){return t===void 0?s.h!==cB&&!!(2&(0|s.v[hl])):!!(2&t)&&s.h!==cB}const cB={};function Nit(s,t){if(s!=null){if(typeof s=="string")s=s?new U4(s,hW):lB();else if(s.constructor!==U4)if(wit(s))s=s.length?new U4(new Uint8Array(s),hW):lB();else{if(!t)throw Error();s=void 0}}return s}let FCt=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 yqn=Object.freeze({});function xJt(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"),OCt=lDe(s=>typeof s=="string"),bqn=lDe(s=>typeof s=="boolean"),cDe=typeof uW.BigInt=="function"&&typeof uW.BigInt(0)=="bigint";function _2(s){var t=s;if(OCt(t)){if(!/^\s*(?:-?[1-9]\d*|0)?\s*$/.test(t))throw Error(String(t))}else if(vqn(t)&&!Number.isSafeInteger(t))throw Error(String(t));return cDe?BigInt(s):s=bqn(s)?s?"1":"0":OCt(s)?s.trim()||"0":String(s)}var FYe=lDe(s=>cDe?s>=wqn&&s<=Nqn:s[0]==="-"?zCt(s,_qn):zCt(s,jqn));const _qn=Number.MIN_SAFE_INTEGER.toString(),wqn=cDe?BigInt(Number.MIN_SAFE_INTEGER):void 0,jqn=Number.MAX_SAFE_INTEGER.toString(),Nqn=cDe?BigInt(Number.MAX_SAFE_INTEGER):void 0;function zCt(s,t){if(s.length>t.length)return!1;if(s.lengtha)return!1;if(r>>0;Ng=t,Dy=(s-t)/4294967296>>>0}function gW(s){if(s<0){BCt(-s);const[t,n]=Cit(Ng,Dy);Ng=t>>>0,Dy=n>>>0}else BCt(s)}function kit(s){const t=Sqn||(Sqn=new DataView(new ArrayBuffer(8)));t.setFloat32(0,+s,!0),Dy=0,Ng=t.getUint32(0,!0)}function vJt(s,t){const n=4294967296*t+(s>>>0);return Number.isSafeInteger(n)?n:mne(s,t)}function Cqn(s,t){return _2(zK()?BigInt.asUintN(64,(BigInt(t>>>0)<>>0)):mne(s,t))}function bJt(s,t){return zK()?_2(BigInt.asIntN(64,(BigInt.asUintN(32,BigInt(t))<>>=0,(t>>>=0)<=2097151)var n=""+(4294967296*t+s);else zK()?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+$Ct(n)+$Ct(s));return n}function $Ct(s){return s=String(s),"0000000".slice(s.length)+s}function Sit(s,t){if(2147483648&t)if(zK())s=""+(BigInt(0|t)<>>0));else{const[n,r]=Cit(s,t);s="-"+mne(n,r)}else s=mne(s,t);return s}function dDe(s){if(s.length<16)gW(Number(s));else if(zK())s=BigInt(s),Ng=Number(s&BigInt(4294967295))>>>0,Dy=Number(s>>BigInt(32)&BigInt(4294967295));else{const t=+(s[0]==="-");Dy=Ng=0;const n=s.length;for(let r=t,a=(n-t)%6+t;a<=n;r=a,a+=6){const i=Number(s.slice(r,a));Dy*=1e6,Ng=1e6*Ng+i,Ng>=4294967296&&(Dy+=Math.trunc(Ng/4294967296),Dy>>>=0,Ng>>>=0)}if(t){const[r,a]=Cit(Ng,Dy);Ng=r,Dy=a}}}function Cit(s,t){return t=~t,s?s=1+~s:t+=1,[s,t]}function cC(s){return Array.prototype.slice.call(s)}const Die=typeof BigInt=="function"?BigInt.asIntN:void 0,Aqn=typeof BigInt=="function"?BigInt.asUintN:void 0,dB=Number.isSafeInteger,uDe=Number.isFinite,xW=Math.trunc,Eqn=_2(0);function wQ(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 v4(s){return s==null||typeof s=="number"?s:s==="NaN"||s==="Infinity"||s==="-Infinity"?Number(s):void 0}function fne(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 _Jt(s){return s==null||typeof s=="boolean"?s:typeof s=="number"?!!s:void 0}const Tqn=/^-?([1-9][0-9]*|0)(\.[0-9]+)?$/;function Fie(s){switch(typeof s){case"bigint":return!0;case"number":return uDe(s);case"string":return Tqn.test(s);default:return!1}}function UK(s){if(s==null)return s;if(typeof s=="string"&&s)s=+s;else if(typeof s!="number")return;return uDe(s)?0|s:void 0}function wJt(s){if(s==null)return s;if(typeof s=="string"&&s)s=+s;else if(typeof s!="number")return;return uDe(s)?s>>>0:void 0}function jJt(s){const t=s.length;return(s[0]==="-"?t<20||t===20&&s<="-9223372036854775808":t<19||t===19&&s<="9223372036854775807")?s:(dDe(s),Sit(Ng,Dy))}function Ait(s){if(s=xW(s),!dB(s)){gW(s);var t=Ng,n=Dy;(s=2147483648&n)&&(n=~n>>>0,(t=1+~t>>>0)==0&&(n=n+1>>>0)),s=typeof(t=vJt(t,n))=="number"?s?-t:t:s?"-"+t:t}return s}function NJt(s){var t=xW(Number(s));return dB(t)?String(t):((t=s.indexOf("."))!==-1&&(s=s.substring(0,t)),jJt(s))}function kJt(s){var t=xW(Number(s));return dB(t)?_2(t):((t=s.indexOf("."))!==-1&&(s=s.substring(0,t)),zK()?_2(Die(64,BigInt(s))):_2(jJt(s)))}function SJt(s){return dB(s)?s=_2(Ait(s)):(s=xW(s),dB(s)?s=String(s):(gW(s),s=Sit(Ng,Dy)),s=_2(s)),s}function JMe(s){const t=typeof s;return s==null?s:t==="bigint"?_2(Die(64,s)):Fie(s)?t==="string"?kJt(s):SJt(s):void 0}function CJt(s){if(typeof s!="string")throw Error();return s}function Oie(s){if(s!=null&&typeof s!="string")throw Error();return s}function wb(s){return s==null||typeof s=="string"?s:void 0}function Eit(s,t,n,r){return s!=null&&s[fW]===pW?s:Array.isArray(s)?((r=(n=0|s[hl])|32&r|2&r)!==n&&D0(s,r),new t(s)):(n?2&r?((s=t[LCt])||(Rie((s=new t).v),s=t[LCt]=s),t=s):t=new t:t=void 0,t)}function Mqn(s,t,n){if(t)e:{if(!Fie(t=s))throw RYe("int64");switch(typeof t){case"string":t=kJt(t);break e;case"bigint":t=_2(Die(64,t));break e;default:t=SJt(t)}}else t=JMe(s);return(s=t)==null?n?Eqn:void 0:s}const Pqn={};let Iqn=function(){try{return oDe(new class extends Map{constructor(){super()}}),!1}catch{return!0}}(),Q9e=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 Lqn=Iqn?(Object.setPrototypeOf(Q9e.prototype,Map.prototype),Object.defineProperties(Q9e.prototype,{size:{value:0,configurable:!0,enumerable:!0,writable:!0}}),Q9e):class extends Map{constructor(){super()}};function UCt(s){return s}function J9e(s){if(2&s.J)throw Error("Cannot mutate an immutable Map")}var xT=class extends Lqn{constructor(s,t,n=UCt,r=UCt){super(),this.J=0|s[hl],this.K=t,this.S=n,this.fa=this.K?Rqn:r;for(let a=0;a{s.call(t,a.get(r),r,a)}):super.forEach(s,t)}set(s,t){return J9e(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 Rqn(s,t,n,r,a,i){return s=Eit(s,r,n,i),a&&(s=Mit(s)),s}function Dqn(s){return[s,this.get(s)]}let Fqn;function qCt(){return Fqn||(Fqn=new xT(Rie([]),void 0,void 0,void 0,Pqn))}function hDe(s){return b2?s[b2]:void 0}function ePe(s,t){for(const n in s)!isNaN(n)&&t(s,+n,s[n])}xT.prototype.toJSON=void 0;var OYe=class{};const Oqn={Ka:!0};function zqn(s,t){t<100||mW(gqn,1)}function mDe(s,t,n,r){const a=r!==void 0;r=!!r;var i,l=b2;!a&&BK&&l&&(i=s[l])&&ePe(i,zqn),l=[];var o=s.length;let c;i=4294967295;let d=!1;const u=!!(64&t),h=u?128&t?0:-1:void 0;1&t||(c=o&&s[o-1],c!=null&&typeof c=="object"&&c.constructor===Object?i=--o:c=void 0,!u||128&t||a||(d=!0,i=i-h+h)),t=void 0;for(var m=0;m=i){const g=m-h;(t??(t={}))[g]=f}else l[m]=f}if(c)for(let f in c){if((o=c[f])==null||(o=n(o,r))==null)continue;let g;m=+f,u&&!Number.isNaN(m)&&(g=m+h){g[y]=cC(v)}),g.da=f.da,g}(s)),l}function Bqn(s){return s[0]=pne(s[0]),s[1]=pne(s[1]),s}function pne(s){switch(typeof s){case"number":return Number.isFinite(s)?s:""+s;case"bigint":return FYe(s)?Number(s):""+s;case"boolean":return s?1:0;case"object":if(Array.isArray(s)){var t=0|s[hl];return s.length===0&&1&t?void 0:mDe(s,t,pne)}if(s!=null&&s[fW]===pW)return AJt(s);if(s instanceof U4){if((t=s.g)==null)s="";else if(typeof t=="string")s=t;else{if(uJt){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 xT?s=s.size!==0?s.V(Bqn):void 0:void 0}return s}let $qn,Uqn;function AJt(s){return mDe(s=s.v,0|s[hl],pne)}function w7(s,t){return EJt(s,t[0],t[1])}function EJt(s,t,n,r=0){if(s==null){var a=32;n?(s=[n],a|=128):s=[],t&&(a=-16760833&a|(1023&t)<<14)}else{if(!Array.isArray(s))throw Error("narr");if(a=0|s[hl],TCt&&1&a)throw Error("rfarr");if(2048&a&&!(2&a)&&function(){if(TCt)throw Error("carr");mW(xqn,5)}(),256&a)throw Error("farr");if(64&a)return(a|r)!==a&&D0(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 D0(s,64|a|r),s}function qqn(s,t){if(typeof s!="object")return s;if(Array.isArray(s)){var n=0|s[hl];return s.length===0&&1&n?void 0:VCt(s,n,t)}if(s!=null&&s[fW]===pW)return HCt(s);if(s instanceof xT){if(2&(t=s.J))return s;if(!s.size)return;if(n=Rie(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){HK(s),M0(s=s.v,0|s[hl],t,n,r)}function M0(s,t,n,r,a){const i=n+(a?0:-1);var l=s.length-1;if(l>=1+(a?0:-1)&&i>=l){const o=s[l];if(o!=null&&typeof o=="object"&&o.constructor===Object)return o[n]=r,t}return i<=l?(s[i]=r,t):(r!==void 0&&(n>=(l=(t??(t=0|s[hl]))>>14&1023||536870912)?r!=null&&(s[l+(a?0:-1)]={[n]:r}):s[i]=r),t)}function b8(){return yqn===void 0?2:4}function _8(s,t,n,r,a){let i=s.v,l=0|i[hl];r=M2(s,l)?1:r,a=!!a||r===3,r===2&&VK(s)&&(i=s.v,l=0|i[hl]);let o=(s=Iit(i,t))===n9?7:0|s[hl],c=Lit(o,l);var d=!(4&c);if(d){4&c&&(s=cC(s),o=0,c=N7(c,l),l=M0(i,l,t,s));let u=0,h=0;for(;u{const o=Eit(l,n,!1,t);return i=o!==l&&o!=null,o}))!=null)return i&&!M2(r)&&r9(s,t),r}function $h(s,t,n,r){let a=s.v,i=0|a[hl];if((t=RJt(a,i,t,n,r))==null)return t;if(i=0|a[hl],!M2(s,i)){const l=Mit(t);l!==t&&(VK(s)&&(a=s.v,i=0|a[hl]),i=M0(a,i,n,t=l,r),r9(a,i))}return t}function DJt(s,t,n,r,a,i,l,o){var c=M2(s,n);i=c?1:i,l=!!l||i===3,c=o&&!c,(i===2||c)&&VK(s)&&(n=0|(t=s.v)[hl]);var d=(s=Iit(t,a))===n9?7:0|s[hl],u=Lit(d,n);if(o=!(4&u)){var h=s,m=n;const f=!!(2&u);f&&(m|=2);let g=!f,x=!0,y=0,v=0;for(;y32)for(a|=(127&n)>>4,i=3;i<32&&128&n;i+=7)n=l[o++],a|=(127&n)<>>0,a>>>0);throw Error()}function $it(s){let t=0,n=s.g;const r=n+10,a=s.h;for(;n>>0}function sPe(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],k7(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 Vqn(s){return FL(s)}function k7(s,t){if(s.g=t,t>s.l)throw Error()}function OJt(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 zJt(s,t){if(t==0)return lB();var n=OJt(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):kqn?s.slice(n,t):new Uint8Array(s.subarray(n,t))),n.length==0?lB():new U4(n,hW)}var GCt=[];function BJt(s,t,n,r){if(nPe.length){const a=nPe.pop();return a.o(r),a.g.init(s,t,n,r),a}return new Hqn(s,t,n,r)}function $Jt(s){s.g.clear(),s.l=-1,s.h=-1,nPe.length<100&&nPe.push(s)}function UJt(s){var t=s.g;if(t.g==t.l)return!1;s.m=s.g.g;var n=J4(s.g);if(t=n>>>3,!((n&=7)>=0&&n<=5)||t<1)throw Error();return s.l=t,s.h=n,!0}function S3e(s){switch(s.h){case 0:s.h!=0?S3e(s):$it(s.g);break;case 1:k7(s=s.g,s.g+8);break;case 2:if(s.h!=2)S3e(s);else{var t=J4(s.g);k7(s=s.g,s.g+t)}break;case 5:k7(s=s.g,s.g+4);break;case 3:for(t=s.l;;){if(!UJt(s))throw Error();if(s.h==4){if(s.l!=t)throw Error();break}S3e(s)}break;default:throw Error()}}function zie(s,t,n){const r=s.g.l;var a=J4(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 Uit(s){var t=J4(s.g),n=OJt(s=s.g,t);if(s=s.h,rqn){var r,a=s;(r=X9e)||(r=X9e=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(fue===void 0){try{r.decode(new Uint8Array([128]))}catch{}try{r.decode(new Uint8Array([97])),fue=!0}catch{fue=!1}}throw!fue&&(X9e=void 0),o}}else{t=(i=n)+t,n=[];let o,c=null;for(;i=t?bR():(o=s[i++],l<194||(192&o)!=128?(i--,bR()):n.push((31&l)<<6|63&o)):l<240?i>=t-1?bR():(o=s[i++],(192&o)!=128||l===224&&o<160||l===237&&o>=160||(192&(r=s[i++]))!=128?(i--,bR()):n.push((15&l)<<12|(63&o)<<6|63&r)):l<=244?i>=t-2?bR():(o=s[i++],(192&o)!=128||o-144+(l<<28)>>30||(192&(r=s[i++]))!=128||(192&(a=s[i++]))!=128?(i--,bR()):(l=(7&l)<<18|(63&o)<<12|(63&r)<<6|63&a,l-=65536,n.push(55296+(l>>10&1023),56320+(1023&l)))):bR(),n.length>=8192&&(c=ECt(c,n),n.length=0)}i=ECt(c,n)}return i}function qJt(s){const t=J4(s.g);return zJt(s.g,t)}function pDe(s,t,n){var r=J4(s.g);for(r=s.g.g+r;s.g.g>>0,this.g=t>>>0}};let Gqn;function KCt(s){return s?/^-?\d+$/.test(s)?(dDe(s),new BYe(Ng,Dy)):null:Wqn||(Wqn=new BYe(0,0))}var BYe=class{constructor(s,t){this.h=s>>>0,this.g=t>>>0}};let Wqn;function PV(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 WK(s,t){for(;t>127;)s.g.push(127&t|128),t>>>=7;s.g.push(t)}function gDe(s,t){if(t>=0)WK(s,t);else{for(let n=0;n<9;n++)s.g.push(127&t|128),t>>=7;s.g.push(1)}}function qit(s){var t=Ng;s.g.push(t>>>0&255),s.g.push(t>>>8&255),s.g.push(t>>>16&255),s.g.push(t>>>24&255)}function yW(s,t){t.length!==0&&(s.l.push(t),s.h+=t.length)}function Ek(s,t,n){WK(s.g,8*t+n)}function Vit(s,t){return Ek(s,t,2),t=s.g.end(),yW(s,t),t.push(s.h),t}function Hit(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 xDe(s,t,n){Ek(s,t,2),WK(s.g,n.length),yW(s,s.g.end()),yW(s,n)}function rPe(s,t,n,r){n!=null&&(t=Vit(s,t),r(n,s),Hit(s,t))}function x3(){const s=class{constructor(){throw Error()}};return Object.setPrototypeOf(s,s.prototype),s}var Git=x3(),VJt=x3(),Wit=x3(),Kit=x3(),Yit=x3(),HJt=x3(),Kqn=x3(),yDe=x3(),GJt=x3(),WJt=x3();function y3(s,t,n){var r=s.v;b2&&b2 in r&&(r=r[b2])&&delete r[t.g],t.h?t.j(s,t.h,t.g,n,t.l):t.j(s,t.g,n,t.l)}var ml=class{constructor(s,t){this.v=EJt(s,t,void 0,2048)}toJSON(){return AJt(this)}j(){var a;var s=EVn,t=this.v,n=s.g,r=b2;if(BK&&r&&((a=t[r])==null?void 0:a[n])!=null&&mW(pqn,3),t=s.g,RCt&&b2&&RCt===void 0&&(r=(n=this.v)[b2])&&(r=r.da))try{r(n,t,Oqn)}catch(i){lJt(i)}return s.h?s.m(this,s.h,s.g,s.l):s.m(this,s.g,s.defaultValue,s.l)}clone(){const s=this.v,t=0|s[hl];return Pit(this,s,t)?Tit(this,s,!0):new this.constructor(qK(s,t,!1))}};ml.prototype[fW]=pW,ml.prototype.toString=function(){return this.v.toString()};var KK=class{constructor(s,t,n){this.g=s,this.h=t,s=Git,this.l=!!s&&n===s||!1}};function vDe(s,t){return new KK(s,t,Git)}function KJt(s,t,n,r,a){rPe(s,n,QJt(t,r),a)}const Yqn=vDe(function(s,t,n,r,a){return s.h===2&&(zie(s,Fit(t,r,n),a),!0)},KJt),Zqn=vDe(function(s,t,n,r,a){return s.h===2&&(zie(s,Fit(t,r,n),a),!0)},KJt);var bDe=Symbol(),_De=Symbol(),$Ye=Symbol(),YCt=Symbol(),ZCt=Symbol();let YJt,ZJt;function a9(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 $qn||($qn=[0,void 0,!0]);case"number":return h>0?void 0:h===0?Uqn||(Uqn=[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,YJt??(YJt=i),ZJt??(ZJt=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 Xit(s,t,n,r,a){const i=n.g;let l,o;s[t]=(c,d,u)=>i(c,d,u,o||(o=a9(_De,Zit,Xit,r).T),l||(l=Qit(r)),a)}function Qit(s){let t=s[$Ye];if(t!=null)return t;const n=a9(_De,Zit,Xit,s);return t=n.ma?(r,a)=>YJt(r,a,n):(r,a)=>{for(;UJt(a)&&a.h!=4;){var i=a.l,l=n[i];if(l==null){var o=n.ba;o&&(o=o[i])&&(o=Qqn(o))!=null&&(l=n[i]=o)}if(l==null||!l(a,r,i)){if(l=(o=a).m,S3e(o),o.ha)var c=void 0;else c=o.g.g-l,o.g.g=l,c=zJt(o.g,c);l=void 0,o=r,c&&((l=o[b2]??(o[b2]=new OYe))[i]??(l[i]=[])).push(c)}}return(r=hDe(r))&&(r.da=n.qa[ZCt]),!0},s[$Ye]=t,s[ZCt]=Xqn.bind(s),t}function Xqn(s,t,n,r){var a=this[_De];const i=this[$Ye],l=w7(void 0,a.T),o=hDe(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=BJt(f);try{c=!0,i(l,u)}finally{$Jt(u)}}else r==null||r(s,h,m)},t==null)ePe(o,a);else if(o!=null){const u=o[t];u&&a(o,t,u)}if(c){let u=0|s[hl];if(2&u&&2048&u&&!(n!=null&&n.Ka))throw Error();const h=$K(u),m=(f,g)=>{if(yT(s,f,h)!=null){if((n==null?void 0:n.Qa)===1)return;throw Error()}g!=null&&(u=M0(s,u,f,g,h)),delete o[f]};t==null?xJt(l,0|l[hl],(f,g)=>{m(f,g)}):m(t,yT(l,t,h))}}}}function Qqn(s){const t=(s=XJt(s))[0].g;if(s=s[1]){const n=Qit(s),r=a9(_De,Zit,Xit,s).T;return(a,i,l)=>t(a,i,l,r,n)}return t}function wDe(s,t,n){s[t]=n.h}function jDe(s,t,n,r){let a,i;const l=n.h;s[t]=(o,c,d)=>l(o,c,d,i||(i=a9(bDe,wDe,jDe,r).T),a||(a=JJt(r)))}function JJt(s){let t=s[YCt];if(!t){const n=a9(bDe,wDe,jDe,s);t=(r,a)=>ees(r,a,n),s[YCt]=t}return t}function ees(s,t,n){xJt(s,0|s[hl],(r,a)=>{if(a!=null){var i=function(l,o){var c=l[o];if(c)return c;if((c=l.ba)&&(c=c[o])){var d=(c=XJt(c))[0].h;if(c=c[1]){const u=JJt(c),h=a9(bDe,wDe,jDe,c).T;c=l.ma?ZJt(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||mW(DYe,3)}}),(s=hDe(s))&&ePe(s,(r,a,i)=>{for(yW(t,t.g.end()),r=0;r{rPe(s,n,w7([l,i],r),a)});else if(Array.isArray(t)){for(let i=0;i>BigInt(32))),PV(s.g,n.h,n.g);break;default:n=KCt(t),PV(s.g,n.h,n.g)}}function nes(s,t,n){(t=UK(t))!=null&&t!=null&&(Ek(s,n,0),gDe(s.g,t))}function res(s,t,n){(t=_Jt(t))!=null&&(Ek(s,n,0),s.g.g.push(t?1:0))}function aes(s,t,n){(t=wb(t))!=null&&xDe(s,n,oJt(t))}function ies(s,t,n,r,a){rPe(s,n,QJt(t,r),a)}function oes(s,t,n){(t=t==null||typeof t=="string"||t instanceof U4?t:void 0)!=null&&xDe(s,n,zit(t,!0).buffer)}function les(s,t,n){(t=wJt(t))!=null&&t!=null&&(Ek(s,n,0),WK(s.g,t))}function ces(s,t,n){return(s.h===5||s.h===2)&&(t=GK(t,0|t[hl],n),s.h==2?pDe(s,sPe,t):t.push(sPe(s.g)),!0)}var $y=M1(function(s,t,n){return s.h===5&&(P1(t,n,sPe(s.g)),!0)},tes,yDe),tVn=ZK(ces,function(s,t,n){if((t=YK(v4,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"))||(dDe(r),r=mne(Ng,Dy))),r;if(a==="number")return(r=xW(r))>=0&&dB(r)||(gW(r),r=vJt(Ng,Dy)),r}}(t),t!=null&&(typeof t=="string"&&WCt(t),t!=null))switch(Ek(s,n,0),typeof t){case"number":s=s.g,gW(t),PV(s,Ng,Dy);break;case"bigint":n=BigInt.asUintN(64,t),n=new zYe(Number(n&BigInt(4294967295)),Number(n>>BigInt(32))),PV(s.g,n.h,n.g);break;default:n=WCt(t),PV(s.g,n.h,n.g)}},Kqn),S0=M1(function(s,t,n){return s.h===0&&(P1(t,n,FL(s.g)),!0)},nes,Kit),Bie=ZK(function(s,t,n){return(s.h===0||s.h===2)&&(t=GK(t,0|t[hl],n),s.h==2?pDe(s,FL,t):t.push(FL(s.g)),!0)},function(s,t,n){if((t=YK(UK,t))!=null&&t.length){n=Vit(s,n);for(let r=0;r{{const i={ea:!0};r&&Object.assign(i,r),n=BJt(n,void 0,void 0,i);try{const l=new s,o=l.v;Qit(t)(o,n);var a=l}finally{$Jt(n)}}return a}}function NDe(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}}}};ees(this.v,t,a9(bDe,wDe,jDe,s)),yW(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=JCt.createPolicy("goog#html",{createHTML:r,createScript:r,createScriptURL:r})}catch{}return n}()),s=(t=s$e)?t.createScriptURL(s):s,new class{constructor(n){this.g=n}toString(){return this.g+""}}(s)}function pue(s,...t){if(t.length===0)return e5t(s[0]);let n=s[0];for(let r=0;r({index:VN(r,1)??0??-1,score:Xx(r,2)??0,categoryName:wb(Pg(r,3))??""??"",displayName:wb(Pg(r,4))??""??""})),headIndex:t,headName:n}}function IVn(s){const t={classifications:vT(s,fVn,1).map(n=>{var r;return oot(((r=$h(n,yes,4))==null?void 0:r.g())??[],VN(n,2)??0,wb(Pg(n,3))??"")})};return function(n){return n==null?n:typeof n=="bigint"?(FYe(n)?n=Number(n):(n=Die(64,n),n=FYe(n)?Number(n):String(n)),n):Fie(n)?typeof n=="number"?Ait(n):NJt(n):void 0}(Pg(s,2,void 0,void 0,JMe))!=null&&(t.timestampMs=Hes(Pg(s,2,void 0,void 0,JMe)??TJt)),t}function Ges(s){var l,o;var t=_8(s,3,v4,b8()),n=_8(s,2,UK,b8()),r=_8(s,1,wb,b8()),a=_8(s,9,wb,b8());const i={categories:[],keypoints:[]};for(let c=0;ct>127?t-256:t)}function h5t(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 m5t(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 Yes(s){return s.videoWidth!==void 0?[s.videoWidth,s.videoHeight]:s.naturalWidth!==void 0?[s.naturalWidth,s.naturalHeight]:s.displayWidth!==void 0?[s.displayWidth,s.displayHeight]:[s.width,s.height]}function yl(s,t,n){s.m||console.error("No wasm multistream support detected: ensure dependency inclusion of :gl_graph_runner_internal_multi_input target"),n(t=s.i.stringToNewUTF8(t)),s.i._free(t)}function f5t(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]=Yes(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 p5t(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 n5(s,t,n){s.i.simpleListeners=s.i.simpleListeners||{},s.i.simpleListeners[t]=n}function SM(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)}}bU.forVisionTasks=function(s,t=!1){return xue("vision",s??pue``,t)},bU.forTextTasks=function(s,t=!1){return xue("text",s??pue``,t)},bU.forGenAiTasks=function(s,t=!1){return xue("genai",s??pue``,t)},bU.forAudioTasks=function(s,t=!1){return xue("audio",s??pue``,t)},bU.isSimdSupported=function(s=!1){return Wes(s)};async function RVn(s,t,n,r){return s=await(async(a,i,l,o,c)=>{if(i&&await m5t(i),!self.ModuleFactory||l&&(await m5t(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 a$e(s,t){const n=$h(s.baseOptions,aPe,1)||new aPe;typeof t=="string"?(tf(n,2,Oie(t)),tf(n,1)):t instanceof Uint8Array&&(tf(n,1,Nit(t,!1)),tf(n,2)),ec(s.baseOptions,0,1,n)}function g5t(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 ADe(s,t){s.B=new Gw,P2(s.B,2,"PassThroughCalculator"),tg(s.B,"free_memory"),ph(s.B,"free_memory_unused_out"),Hg(t,"free_memory"),Tk(t,s.B)}function vW(s,t){tg(s.B,t),ph(s.B,t+"_unused_out")}function EDe(s){s.g.addBoolToStream(!0,"free_memory",s.C)}var GYe=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,aPe,1))!=null&&a.g()||(i=$h(this.baseOptions,aPe,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,o5t,3);if(!h){var m=h=new o5t,f=new t5t;Zee(m,4,C3e,f)}"delegate"in u&&(u.delegate==="GPU"?(u=h,m=new oVn,Zee(u,2,C3e,m)):(u=h,m=new t5t,Zee(u,4,C3e,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),a$e(this,"/model.dat"),this.m(),this.L()});if(c.modelAssetBuffer instanceof Uint8Array)a$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=>{a$e(this,d),this.m(),this.L()})}return this.m(),this.L(),Promise.resolve()}L(){}ca(){let s;if(this.g.ca(t=>{s=lVn(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,g5t(this)}finishProcessing(){this.g.finishProcessing(),g5t(this)}close(){this.B=void 0,this.g.closeGraph()}};function mL(s,t){if(!s)throw Error(`Unable to obtain required WebGL resource: ${t}`);return s}GYe.prototype.close=GYe.prototype.close;class DVn{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 x5t(s,t,n){const r=s.g;if(n=mL(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 y5t(s,t){const n=s.g,r=mL(n.createVertexArray(),"Failed to create vertex array");n.bindVertexArray(r);const a=mL(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=mL(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 DVn(n,r,a,i)}function lot(s,t){if(s.g){if(t!==s.g)throw Error("Cannot change GL context once initialized")}else s.g=t}function FVn(s,t,n,r){return lot(s,t),s.h||(s.m(),s.D()),n?(s.u||(s.u=y5t(s,!0)),n=s.u):(s.A||(s.A=y5t(s,!1)),n=s.A),t.useProgram(s.h),n.bind(),s.l(),s=r(),n.g.bindVertexArray(null),s}function Zes(s,t,n){return lot(s,t),s=mL(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 Xes(s,t,n){lot(s,t),s.B||(s.B=mL(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 OVn(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=mL(s.createProgram(),"Failed to create WebGL program"),this.X=x5t(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=x5t(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 hE(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 WYe(s){var t=hE(s,1);if(!t){if(t=hE(s,0))t=new Float32Array(t).map(r=>r/255);else{t=new Float32Array(s.width*s.height);const r=bW(s);var n=cot(s);if(Xes(n,r,Jes(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 WYe(this)}N(){return Jes(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=bW(this),a=cot(this);r.activeTexture(r.TEXTURE1),n=Zes(a,r,this.m?r.LINEAR:r.NEAREST),r.bindTexture(r.TEXTURE_2D,n);const i=ets(this);r.texImage2D(r.TEXTURE_2D,0,i,this.width,this.height,0,r.RED,r.FLOAT,null),r.bindTexture(r.TEXTURE_2D,null),Xes(a,r,n),FVn(a,r,!1,()=>{tts(this),r.clearColor(0,0,0,0),r.clear(r.COLOR_BUFFER_BIT),r.drawArrays(r.TRIANGLE_FAN,0,4),KYe(this)}),OVn(a),KYe(this)}}s.push(n)}return new ev(s,this.m,this.R(),this.canvas,this.l,this.width,this.height)}close(){this.j&&bW(this).deleteTexture(hE(this,2)),v5t=-1}};ev.prototype.close=ev.prototype.close,ev.prototype.clone=ev.prototype.clone,ev.prototype.getAsWebGLTexture=ev.prototype.N,ev.prototype.getAsFloat32Array=ev.prototype.ia,ev.prototype.getAsUint8Array=ev.prototype.ja,ev.prototype.hasWebGLTexture=ev.prototype.R,ev.prototype.hasFloat32Array=ev.prototype.ka,ev.prototype.hasUint8Array=ev.prototype.Fa;var v5t=250;function SC(...s){return s.map(([t,n])=>({start:t,end:n}))}const zVn=function(s){return class extends s{Ja(){this.i._registerModelResourcesGraphService()}}}((b5t=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:Kes()?this.i.canvas=new OffscreenCanvas(1,1):(console.warn("OffscreenCanvas not supported and GraphRunner constructor glCanvas parameter is undefined. Creating backup canvas."),this.i.canvas=document.createElement("canvas"))}async initializeGraph(s){const t=await(await fetch(s)).arrayBuffer();s=!(s.endsWith(".pbtxt")||s.endsWith(".textproto")),this.setGraph(new Uint8Array(t),s)}setGraphFromString(s){this.setGraph(new TextEncoder().encode(s),!1)}setGraph(s,t){const n=s.length,r=this.i._malloc(n);this.i.HEAPU8.set(s,r),t?this.i._changeBinaryGraph(n,r):this.i._changeTextGraph(n,r),this.i._free(r)}configureAudio(s,t,n,r,a){this.i._configureAudio||console.warn('Attempting to use configureAudio without support for input audio. Is build dep ":gl_graph_runner_audio" missing?'),yl(this,r||"input_audio",i=>{yl(this,a=a||"audio_header",l=>{this.i._configureAudio(i,l,s,t??0,n)})})}setAutoResizeCanvas(s){this.l=s}setAutoRenderToScreen(s){this.i._setAutoRenderToScreen(s)}setGpuBufferVerticalFlip(s){this.i.gpuOriginForWebTexturesIsBottomLeft=s}ca(s){n5(this,"__graph_config__",t=>{s(t)}),yl(this,"__graph_config__",t=>{this.i._getGraphConfig(t,void 0)}),delete this.i.simpleListeners.__graph_config__}attachErrorListener(s){this.i.errorListener=s}attachEmptyPacketListener(s,t){this.i.emptyPacketListeners=this.i.emptyPacketListeners||{},this.i.emptyPacketListeners[s]=t}addAudioToStream(s,t,n){this.addAudioToStreamWithShape(s,0,0,t,n)}addAudioToStreamWithShape(s,t,n,r,a){const i=4*s.length;this.h!==i&&(this.g&&this.i._free(this.g),this.g=this.i._malloc(i),this.h=i),this.i.HEAPF32.set(s,this.g/4),yl(this,r,l=>{this.i._addAudioToInputStream(this.g,t,n,l,a)})}addGpuBufferToStream(s,t,n){yl(this,t,r=>{const[a,i]=f5t(this,s,r);this.i._addBoundTextureToStream(r,a,i,n)})}addBoolToStream(s,t,n){yl(this,t,r=>{this.i._addBoolToInputStream(s,r,n)})}addDoubleToStream(s,t,n){yl(this,t,r=>{this.i._addDoubleToInputStream(s,r,n)})}addFloatToStream(s,t,n){yl(this,t,r=>{this.i._addFloatToInputStream(s,r,n)})}addIntToStream(s,t,n){yl(this,t,r=>{this.i._addIntToInputStream(s,r,n)})}addUintToStream(s,t,n){yl(this,t,r=>{this.i._addUintToInputStream(s,r,n)})}addStringToStream(s,t,n){yl(this,t,r=>{yl(this,s,a=>{this.i._addStringToInputStream(a,r,n)})})}addStringRecordToStream(s,t,n){yl(this,t,r=>{p5t(this,Object.keys(s),a=>{p5t(this,Object.values(s),i=>{this.i._addFlatHashMapToInputStream(a,i,Object.keys(s).length,r,n)})})})}addProtoToStream(s,t,n,r){yl(this,n,a=>{yl(this,t,i=>{const l=this.i._malloc(s.length);this.i.HEAPU8.set(s,l),this.i._addProtoToInputStream(l,s.length,i,a,r),this.i._free(l)})})}addEmptyPacketToStream(s,t){yl(this,s,n=>{this.i._addEmptyPacketToInputStream(n,t)})}addBoolVectorToStream(s,t,n){yl(this,t,r=>{const a=this.i._allocateBoolVector(s.length);if(!a)throw Error("Unable to allocate new bool vector on heap.");for(const i of s)this.i._addBoolVectorEntry(a,i);this.i._addBoolVectorToInputStream(a,r,n)})}addDoubleVectorToStream(s,t,n){yl(this,t,r=>{const a=this.i._allocateDoubleVector(s.length);if(!a)throw Error("Unable to allocate new double vector on heap.");for(const i of s)this.i._addDoubleVectorEntry(a,i);this.i._addDoubleVectorToInputStream(a,r,n)})}addFloatVectorToStream(s,t,n){yl(this,t,r=>{const a=this.i._allocateFloatVector(s.length);if(!a)throw Error("Unable to allocate new float vector on heap.");for(const i of s)this.i._addFloatVectorEntry(a,i);this.i._addFloatVectorToInputStream(a,r,n)})}addIntVectorToStream(s,t,n){yl(this,t,r=>{const a=this.i._allocateIntVector(s.length);if(!a)throw Error("Unable to allocate new int vector on heap.");for(const i of s)this.i._addIntVectorEntry(a,i);this.i._addIntVectorToInputStream(a,r,n)})}addUintVectorToStream(s,t,n){yl(this,t,r=>{const a=this.i._allocateUintVector(s.length);if(!a)throw Error("Unable to allocate new unsigned int vector on heap.");for(const i of s)this.i._addUintVectorEntry(a,i);this.i._addUintVectorToInputStream(a,r,n)})}addStringVectorToStream(s,t,n){yl(this,t,r=>{const a=this.i._allocateStringVector(s.length);if(!a)throw Error("Unable to allocate new string vector on heap.");for(const i of s)yl(this,i,l=>{this.i._addStringVectorEntry(a,l)});this.i._addStringVectorToInputStream(a,r,n)})}addBoolToInputSidePacket(s,t){yl(this,t,n=>{this.i._addBoolToInputSidePacket(s,n)})}addDoubleToInputSidePacket(s,t){yl(this,t,n=>{this.i._addDoubleToInputSidePacket(s,n)})}addFloatToInputSidePacket(s,t){yl(this,t,n=>{this.i._addFloatToInputSidePacket(s,n)})}addIntToInputSidePacket(s,t){yl(this,t,n=>{this.i._addIntToInputSidePacket(s,n)})}addUintToInputSidePacket(s,t){yl(this,t,n=>{this.i._addUintToInputSidePacket(s,n)})}addStringToInputSidePacket(s,t){yl(this,t,n=>{yl(this,s,r=>{this.i._addStringToInputSidePacket(r,n)})})}addProtoToInputSidePacket(s,t,n){yl(this,n,r=>{yl(this,t,a=>{const i=this.i._malloc(s.length);this.i.HEAPU8.set(s,i),this.i._addProtoToInputSidePacket(i,s.length,a,r),this.i._free(i)})})}addBoolVectorToInputSidePacket(s,t){yl(this,t,n=>{const r=this.i._allocateBoolVector(s.length);if(!r)throw Error("Unable to allocate new bool vector on heap.");for(const a of s)this.i._addBoolVectorEntry(r,a);this.i._addBoolVectorToInputSidePacket(r,n)})}addDoubleVectorToInputSidePacket(s,t){yl(this,t,n=>{const r=this.i._allocateDoubleVector(s.length);if(!r)throw Error("Unable to allocate new double vector on heap.");for(const a of s)this.i._addDoubleVectorEntry(r,a);this.i._addDoubleVectorToInputSidePacket(r,n)})}addFloatVectorToInputSidePacket(s,t){yl(this,t,n=>{const r=this.i._allocateFloatVector(s.length);if(!r)throw Error("Unable to allocate new float vector on heap.");for(const a of s)this.i._addFloatVectorEntry(r,a);this.i._addFloatVectorToInputSidePacket(r,n)})}addIntVectorToInputSidePacket(s,t){yl(this,t,n=>{const r=this.i._allocateIntVector(s.length);if(!r)throw Error("Unable to allocate new int vector on heap.");for(const a of s)this.i._addIntVectorEntry(r,a);this.i._addIntVectorToInputSidePacket(r,n)})}addUintVectorToInputSidePacket(s,t){yl(this,t,n=>{const r=this.i._allocateUintVector(s.length);if(!r)throw Error("Unable to allocate new unsigned int vector on heap.");for(const a of s)this.i._addUintVectorEntry(r,a);this.i._addUintVectorToInputSidePacket(r,n)})}addStringVectorToInputSidePacket(s,t){yl(this,t,n=>{const r=this.i._allocateStringVector(s.length);if(!r)throw Error("Unable to allocate new string vector on heap.");for(const a of s)yl(this,a,i=>{this.i._addStringVectorEntry(r,i)});this.i._addStringVectorToInputSidePacket(r,n)})}attachBoolListener(s,t){n5(this,s,t),yl(this,s,n=>{this.i._attachBoolListener(n)})}attachBoolVectorListener(s,t){SM(this,s,t),yl(this,s,n=>{this.i._attachBoolVectorListener(n)})}attachIntListener(s,t){n5(this,s,t),yl(this,s,n=>{this.i._attachIntListener(n)})}attachIntVectorListener(s,t){SM(this,s,t),yl(this,s,n=>{this.i._attachIntVectorListener(n)})}attachUintListener(s,t){n5(this,s,t),yl(this,s,n=>{this.i._attachUintListener(n)})}attachUintVectorListener(s,t){SM(this,s,t),yl(this,s,n=>{this.i._attachUintVectorListener(n)})}attachDoubleListener(s,t){n5(this,s,t),yl(this,s,n=>{this.i._attachDoubleListener(n)})}attachDoubleVectorListener(s,t){SM(this,s,t),yl(this,s,n=>{this.i._attachDoubleVectorListener(n)})}attachFloatListener(s,t){n5(this,s,t),yl(this,s,n=>{this.i._attachFloatListener(n)})}attachFloatVectorListener(s,t){SM(this,s,t),yl(this,s,n=>{this.i._attachFloatVectorListener(n)})}attachStringListener(s,t){n5(this,s,t),yl(this,s,n=>{this.i._attachStringListener(n)})}attachStringVectorListener(s,t){SM(this,s,t),yl(this,s,n=>{this.i._attachStringVectorListener(n)})}attachProtoListener(s,t,n){n5(this,s,t),yl(this,s,r=>{this.i._attachProtoListener(r,n||!1)})}attachProtoVectorListener(s,t,n){SM(this,s,t),yl(this,s,r=>{this.i._attachProtoVectorListener(r,n||!1)})}attachAudioListener(s,t,n){this.i._attachAudioListener||console.warn('Attempting to use attachAudioListener without support for output audio. Is build dep ":gl_graph_runner_audio_out" missing?'),n5(this,s,(r,a)=>{r=new Float32Array(r.buffer,r.byteOffset,r.length/4),t(r,a)}),yl(this,s,r=>{this.i._attachAudioListener(r,n||!1)})}finishProcessing(){this.i._waitUntilIdle()}closeGraph(){this.i._closeGraph(),this.i.simpleListeners=void 0,this.i.emptyPacketListeners=void 0}},class extends b5t{get ga(){return this.i}pa(s,t,n){yl(this,t,r=>{const[a,i]=f5t(this,s,r);this.ga._addBoundTextureAsImageToStream(r,a,i,n)})}Z(s,t){n5(this,s,t),yl(this,s,n=>{this.ga._attachImageListener(n)})}aa(s,t){SM(this,s,t),yl(this,s,n=>{this.ga._attachImageVectorListener(n)})}}));var b5t,CC=class extends zVn{};async function Eh(s,t,n){return async function(r,a,i,l){return RVn(r,a,i,l)}(s,n.canvas??(Kes()?void 0:document.createElement("canvas")),t,n)}function sts(s,t,n,r){if(s.U){const i=new jes;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]=Yes(t);n=Xx(i,3)*o/l,a=Xx(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 AC(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'.");sts(s,t,n,s.C+1)}function b3(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'.");sts(s,t,n,r)}function _W(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 ev([a],n,!1,s.g.i.canvas,s.P,i,t),r?s.clone():s}var I2=class extends GYe{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,fne(!!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()}};I2.prototype.close=I2.prototype.close;var aN=class extends I2{constructor(s,t){super(new CC(s,t),"image_in","norm_rect_in",!1),this.j={detections:[]},ec(s=this.h=new SDe,0,1,t=new Tx),Cl(this.h,2,.5),Cl(this.h,3,.3)}get baseOptions(){return $h(this.h,Tx,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:[]},AC(this,s,t),this.j}G(s,t,n){return this.j={detections:[]},b3(this,s,n,t),this.j}m(){var s=new $2;Hg(s,"image_in"),Hg(s,"norm_rect_in"),tm(s,"detections");const t=new B2;y3(t,bVn,this.h);const n=new Gw;P2(n,2,"mediapipe.tasks.vision.face_detector.FaceDetectorGraph"),tg(n,"IMAGE:image_in"),tg(n,"NORM_RECT:norm_rect_in"),ph(n,"DETECTIONS:detections"),n.o(t),Tk(s,n),this.g.attachProtoVectorListener("detections",(r,a)=>{for(const i of r)r=bes(i),this.j.detections.push(Ges(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 dot=SC([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]),uot=SC([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]),hot=SC([276,283],[283,282],[282,295],[295,285],[300,293],[293,334],[334,296],[296,336]),nts=SC([474,475],[475,476],[476,477],[477,474]),mot=SC([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]),fot=SC([46,53],[53,52],[52,65],[65,55],[70,63],[63,105],[105,66],[66,107]),rts=SC([469,470],[470,471],[471,472],[472,469]),pot=SC([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]),ats=[...dot,...uot,...hot,...mot,...fot,...pot],its=SC([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 _5t(s){s.j={faceLandmarks:[],faceBlendshapes:[],facialTransformationMatrixes:[]}}var cx=class extends I2{constructor(s,t){super(new CC(s,t),"image_in","norm_rect",!1),this.j={faceLandmarks:[],faceBlendshapes:[],facialTransformationMatrixes:[]},this.outputFacialTransformationMatrixes=this.outputFaceBlendshapes=!1,ec(s=this.h=new Aes,0,1,t=new Tx),this.A=new Ces,ec(this.h,0,3,this.A),this.u=new SDe,ec(this.h,0,2,this.u),bT(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,Tx,1)}set baseOptions(s){ec(this.h,0,1,s)}o(s){return"numFaces"in s&&bT(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 _5t(this),AC(this,s,t),this.j}G(s,t,n){return _5t(this),b3(this,s,n,t),this.j}m(){var s=new $2;Hg(s,"image_in"),Hg(s,"norm_rect"),tm(s,"face_landmarks");const t=new B2;y3(t,wVn,this.h);const n=new Gw;P2(n,2,"mediapipe.tasks.vision.face_landmarker.FaceLandmarkerGraph"),tg(n,"IMAGE:image_in"),tg(n,"NORM_RECT:norm_rect"),ph(n,"NORM_LANDMARKS:face_landmarks"),n.o(t),Tk(s,n),this.g.attachProtoVectorListener("face_landmarks",(r,a)=>{for(const i of r)r=$ie(i),this.j.faceLandmarks.push(CDe(r));qo(this,a)}),this.g.attachEmptyPacketListener("face_landmarks",r=>{qo(this,r)}),this.outputFaceBlendshapes&&(tm(s,"blendshapes"),ph(n,"BLENDSHAPES:blendshapes"),this.g.attachProtoVectorListener("blendshapes",(r,a)=>{if(this.outputFaceBlendshapes)for(const i of r)r=kDe(i),this.j.faceBlendshapes.push(oot(r.g()??[]));qo(this,a)}),this.g.attachEmptyPacketListener("blendshapes",r=>{qo(this,r)})),this.outputFacialTransformationMatrixes&&(tm(s,"face_geometry"),ph(n,"FACE_GEOMETRY:face_geometry"),this.g.attachProtoVectorListener("face_geometry",(r,a)=>{if(this.outputFacialTransformationMatrixes)for(const i of r)(r=$h(r=_Vn(i),hVn,2))&&this.j.facialTransformationMatrixes.push({rows:VN(r,1)??0??0,columns:VN(r,2)??0??0,data:_8(r,3,v4,b8()).slice()??[]});qo(this,a)}),this.g.attachEmptyPacketListener("face_geometry",r=>{qo(this,r)})),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};cx.prototype.detectForVideo=cx.prototype.G,cx.prototype.detect=cx.prototype.F,cx.prototype.setOptions=cx.prototype.o,cx.createFromModelPath=function(s,t){return Eh(cx,s,{baseOptions:{modelAssetPath:t}})},cx.createFromModelBuffer=function(s,t){return Eh(cx,s,{baseOptions:{modelAssetBuffer:t}})},cx.createFromOptions=function(s,t){return Eh(cx,s,t)},cx.FACE_LANDMARKS_LIPS=dot,cx.FACE_LANDMARKS_LEFT_EYE=uot,cx.FACE_LANDMARKS_LEFT_EYEBROW=hot,cx.FACE_LANDMARKS_LEFT_IRIS=nts,cx.FACE_LANDMARKS_RIGHT_EYE=mot,cx.FACE_LANDMARKS_RIGHT_EYEBROW=fot,cx.FACE_LANDMARKS_RIGHT_IRIS=rts,cx.FACE_LANDMARKS_FACE_OVAL=pot,cx.FACE_LANDMARKS_CONTOURS=ats,cx.FACE_LANDMARKS_TESSELATION=its;var got=SC([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 w5t(s){s.gestures=[],s.landmarks=[],s.worldLandmarks=[],s.handedness=[]}function j5t(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 N5t(s,t=!0){const n=[];for(const a of s){var r=kDe(a);s=[];for(const i of r.g())r=t&&VN(i,1)!=null?VN(i,1)??0:-1,s.push({score:Xx(i,2)??0,index:r,categoryName:wb(Pg(i,3))??""??"",displayName:wb(Pg(i,4))??""??""});n.push(s)}return n}var fj=class extends I2{constructor(s,t){super(new CC(s,t),"image_in","norm_rect",!1),this.gestures=[],this.landmarks=[],this.worldLandmarks=[],this.handedness=[],ec(s=this.j=new Mes,0,1,t=new Tx),this.u=new not,ec(this.j,0,2,this.u),this.D=new sot,ec(this.u,0,3,this.D),this.A=new Tes,ec(this.u,0,2,this.A),this.h=new jVn,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,Tx,1)}set baseOptions(s){ec(this.j,0,1,s)}o(s){var a,i,l,o;if(bT(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 B$,n=t,r=HYe(s.cannedGesturesClassifierOptions,(a=$h(this.h,B$,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,B$,3))==null||i.g());return s.customGesturesClassifierOptions?(ec(n=t=new B$,0,2,r=HYe(s.customGesturesClassifierOptions,(l=$h(this.h,B$,4))==null?void 0:l.l())),ec(this.h,0,4,t)):s.customGesturesClassifierOptions===void 0&&((o=$h(this.h,B$,4))==null||o.g()),this.l(s)}Ha(s,t){return w5t(this),AC(this,s,t),j5t(this)}Ia(s,t,n){return w5t(this),b3(this,s,n,t),j5t(this)}m(){var s=new $2;Hg(s,"image_in"),Hg(s,"norm_rect"),tm(s,"hand_gestures"),tm(s,"hand_landmarks"),tm(s,"world_hand_landmarks"),tm(s,"handedness");const t=new B2;y3(t,NVn,this.j);const n=new Gw;P2(n,2,"mediapipe.tasks.vision.gesture_recognizer.GestureRecognizerGraph"),tg(n,"IMAGE:image_in"),tg(n,"NORM_RECT:norm_rect"),ph(n,"HAND_GESTURES:hand_gestures"),ph(n,"LANDMARKS:hand_landmarks"),ph(n,"WORLD_LANDMARKS:world_hand_landmarks"),ph(n,"HANDEDNESS:handedness"),n.o(t),Tk(s,n),this.g.attachProtoVectorListener("hand_landmarks",(r,a)=>{for(const i of r){r=$ie(i);const l=[];for(const o of vT(r,wes,1))l.push({x:Xx(o,1)??0,y:Xx(o,2)??0,z:Xx(o,3)??0,visibility:Xx(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=IV(i);const l=[];for(const o of vT(r,_es,1))l.push({x:Xx(o,1)??0,y:Xx(o,2)??0,z:Xx(o,3)??0,visibility:Xx(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(...N5t(r,!1)),qo(this,a)}),this.g.attachEmptyPacketListener("hand_gestures",r=>{qo(this,r)}),this.g.attachProtoVectorListener("handedness",(r,a)=>{this.handedness.push(...N5t(r)),qo(this,a)}),this.g.attachEmptyPacketListener("handedness",r=>{qo(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};function k5t(s){return{landmarks:s.landmarks,worldLandmarks:s.worldLandmarks,handednesses:s.handedness,handedness:s.handedness}}fj.prototype.recognizeForVideo=fj.prototype.Ia,fj.prototype.recognize=fj.prototype.Ha,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=got;var pj=class extends I2{constructor(s,t){super(new CC(s,t),"image_in","norm_rect",!1),this.landmarks=[],this.worldLandmarks=[],this.handedness=[],ec(s=this.h=new not,0,1,t=new Tx),this.u=new sot,ec(this.h,0,3,this.u),this.j=new Tes,ec(this.h,0,2,this.j),bT(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,Tx,1)}set baseOptions(s){ec(this.h,0,1,s)}o(s){return"numHands"in s&&bT(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=[],AC(this,s,t),k5t(this)}G(s,t,n){return this.landmarks=[],this.worldLandmarks=[],this.handedness=[],b3(this,s,n,t),k5t(this)}m(){var s=new $2;Hg(s,"image_in"),Hg(s,"norm_rect"),tm(s,"hand_landmarks"),tm(s,"world_hand_landmarks"),tm(s,"handedness");const t=new B2;y3(t,kVn,this.h);const n=new Gw;P2(n,2,"mediapipe.tasks.vision.hand_landmarker.HandLandmarkerGraph"),tg(n,"IMAGE:image_in"),tg(n,"NORM_RECT:norm_rect"),ph(n,"LANDMARKS:hand_landmarks"),ph(n,"WORLD_LANDMARKS:world_hand_landmarks"),ph(n,"HANDEDNESS:handedness"),n.o(t),Tk(s,n),this.g.attachProtoVectorListener("hand_landmarks",(r,a)=>{for(const i of r)r=$ie(i),this.landmarks.push(CDe(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=IV(i),this.worldLandmarks.push(Qee(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=kDe(c);const d=[];for(const u of r.g())d.push({score:Xx(u,2)??0,index:VN(u,1)??0??-1,categoryName:wb(Pg(u,3))??""??"",displayName:wb(Pg(u,4))??""??""});o.push(d)}l.call(i,...o),qo(this,a)}),this.g.attachEmptyPacketListener("handedness",r=>{qo(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};pj.prototype.detectForVideo=pj.prototype.G,pj.prototype.detect=pj.prototype.F,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)},pj.HAND_CONNECTIONS=got;var ots=SC([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 S5t(s){s.h={faceLandmarks:[],faceBlendshapes:[],poseLandmarks:[],poseWorldLandmarks:[],poseSegmentationMasks:[],leftHandLandmarks:[],leftHandWorldLandmarks:[],rightHandLandmarks:[],rightHandWorldLandmarks:[]}}function C5t(s){try{if(!s.D)return s.h;s.D(s.h)}finally{EDe(s)}}function vue(s,t){s=$ie(s),t.push(CDe(s))}var Dp=class extends I2{constructor(s,t){super(new CC(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 Des,0,1,t=new Tx),this.I=new sot,ec(this.j,0,2,this.I),this.W=new SVn,ec(this.j,0,3,this.W),this.u=new SDe,ec(this.j,0,4,this.u),this.O=new Ces,ec(this.j,0,5,this.O),this.A=new Les,ec(this.j,0,6,this.A),this.M=new Res,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,Tx,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,S5t(this),AC(this,s,r),C5t(this)}G(s,t,n,r){const a=typeof n!="function"?n:{};return this.D=typeof n=="function"?n:r,S5t(this),b3(this,s,a,t),C5t(this)}m(){var s=new $2;Hg(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 B2,n=new XCt;P2(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,mDe(i,0,pne));else{if(!(typeof i=="string"||i instanceof U4||wit(i)))throw Error("invalid value in Any.value field: "+i+" expected a ByteString, a base64 encoded string, a Uint8Array or a jspb array");xP(a,2,Nit(i,!1),lB())}}(n,this.j.g());const r=new Gw;P2(r,2,"mediapipe.tasks.vision.holistic_landmarker.HolisticLandmarkerGraph"),Oit(r,8,XCt,n),tg(r,"IMAGE:input_frames_image"),ph(r,"POSE_LANDMARKS:pose_landmarks"),ph(r,"POSE_WORLD_LANDMARKS:pose_world_landmarks"),ph(r,"FACE_LANDMARKS:face_landmarks"),ph(r,"LEFT_HAND_LANDMARKS:left_hand_landmarks"),ph(r,"LEFT_HAND_WORLD_LANDMARKS:left_hand_world_landmarks"),ph(r,"RIGHT_HAND_LANDMARKS:right_hand_landmarks"),ph(r,"RIGHT_HAND_WORLD_LANDMARKS:right_hand_world_landmarks"),r.o(t),Tk(s,r),ADe(this,s),this.g.attachProtoListener("pose_landmarks",(a,i)=>{vue(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=IV(a),l.push(Qee(a)),qo(this,i)}),this.g.attachEmptyPacketListener("pose_world_landmarks",a=>{qo(this,a)}),this.outputPoseSegmentationMasks&&(ph(r,"POSE_SEGMENTATION_MASK:pose_segmentation_mask"),vW(this,"pose_segmentation_mask"),this.g.Z("pose_segmentation_mask",(a,i)=>{this.h.poseSegmentationMasks=[_W(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)=>{vue(a,this.h.faceLandmarks),qo(this,i)}),this.g.attachEmptyPacketListener("face_landmarks",a=>{qo(this,a)}),this.outputFaceBlendshapes&&(tm(s,"extra_blendshapes"),ph(r,"FACE_BLENDSHAPES:extra_blendshapes"),this.g.attachProtoListener("extra_blendshapes",(a,i)=>{var l=this.h.faceBlendshapes;this.outputFaceBlendshapes&&(a=kDe(a),l.push(oot(a.g()??[]))),qo(this,i)}),this.g.attachEmptyPacketListener("extra_blendshapes",a=>{qo(this,a)})),this.g.attachProtoListener("left_hand_landmarks",(a,i)=>{vue(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=IV(a),l.push(Qee(a)),qo(this,i)}),this.g.attachEmptyPacketListener("left_hand_world_landmarks",a=>{qo(this,a)}),this.g.attachProtoListener("right_hand_landmarks",(a,i)=>{vue(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=IV(a),l.push(Qee(a)),qo(this,i)}),this.g.attachEmptyPacketListener("right_hand_world_landmarks",a=>{qo(this,a)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};Dp.prototype.detectForVideo=Dp.prototype.G,Dp.prototype.detect=Dp.prototype.F,Dp.prototype.setOptions=Dp.prototype.o,Dp.createFromModelPath=function(s,t){return Eh(Dp,s,{baseOptions:{modelAssetPath:t}})},Dp.createFromModelBuffer=function(s,t){return Eh(Dp,s,{baseOptions:{modelAssetBuffer:t}})},Dp.createFromOptions=function(s,t){return Eh(Dp,s,t)},Dp.HAND_CONNECTIONS=got,Dp.POSE_CONNECTIONS=ots,Dp.FACE_LANDMARKS_LIPS=dot,Dp.FACE_LANDMARKS_LEFT_EYE=uot,Dp.FACE_LANDMARKS_LEFT_EYEBROW=hot,Dp.FACE_LANDMARKS_LEFT_IRIS=nts,Dp.FACE_LANDMARKS_RIGHT_EYE=mot,Dp.FACE_LANDMARKS_RIGHT_EYEBROW=fot,Dp.FACE_LANDMARKS_RIGHT_IRIS=rts,Dp.FACE_LANDMARKS_FACE_OVAL=pot,Dp.FACE_LANDMARKS_CONTOURS=ats,Dp.FACE_LANDMARKS_TESSELATION=its;var iN=class extends I2{constructor(s,t){super(new CC(s,t),"input_image","norm_rect",!0),this.j={classifications:[]},ec(s=this.h=new Fes,0,1,t=new Tx)}get baseOptions(){return $h(this.h,Tx,1)}set baseOptions(s){ec(this.h,0,1,s)}o(s){return ec(this.h,0,2,HYe(s,$h(this.h,eot,2))),this.l(s)}sa(s,t){return this.j={classifications:[]},AC(this,s,t),this.j}ta(s,t,n){return this.j={classifications:[]},b3(this,s,n,t),this.j}m(){var s=new $2;Hg(s,"input_image"),Hg(s,"norm_rect"),tm(s,"classifications");const t=new B2;y3(t,CVn,this.h);const n=new Gw;P2(n,2,"mediapipe.tasks.vision.image_classifier.ImageClassifierGraph"),tg(n,"IMAGE:input_image"),tg(n,"NORM_RECT:norm_rect"),ph(n,"CLASSIFICATIONS:classifications"),n.o(t),Tk(s,n),this.g.attachProtoListener("classifications",(r,a)=>{this.j=IVn(pVn(r)),qo(this,a)}),this.g.attachEmptyPacketListener("classifications",r=>{qo(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};iN.prototype.classifyForVideo=iN.prototype.ta,iN.prototype.classify=iN.prototype.sa,iN.prototype.setOptions=iN.prototype.o,iN.createFromModelPath=function(s,t){return Eh(iN,s,{baseOptions:{modelAssetPath:t}})},iN.createFromModelBuffer=function(s,t){return Eh(iN,s,{baseOptions:{modelAssetBuffer:t}})},iN.createFromOptions=function(s,t){return Eh(iN,s,t)};var gj=class extends I2{constructor(s,t){super(new CC(s,t),"image_in","norm_rect",!0),this.h=new Oes,this.embeddings={embeddings:[]},ec(s=this.h,0,1,t=new Tx)}get baseOptions(){return $h(this.h,Tx,1)}set baseOptions(s){ec(this.h,0,1,s)}o(s){var t=this.h,n=$h(this.h,i5t,2);return n=n?n.clone():new i5t,s.l2Normalize!==void 0?tf(n,1,fne(s.l2Normalize)):"l2Normalize"in s&&tf(n,1),s.quantize!==void 0?tf(n,2,fne(s.quantize)):"quantize"in s&&tf(n,2),ec(t,0,2,n),this.l(s)}za(s,t){return AC(this,s,t),this.embeddings}Aa(s,t,n){return b3(this,s,n,t),this.embeddings}m(){var s=new $2;Hg(s,"image_in"),Hg(s,"norm_rect"),tm(s,"embeddings_out");const t=new B2;y3(t,AVn,this.h);const n=new Gw;P2(n,2,"mediapipe.tasks.vision.image_embedder.ImageEmbedderGraph"),tg(n,"IMAGE:image_in"),tg(n,"NORM_RECT:norm_rect"),ph(n,"EMBEDDINGS:embeddings_out"),n.o(t),Tk(s,n),this.g.attachProtoListener("embeddings_out",(r,a)=>{r=yVn(r),this.embeddings=function(i){return{embeddings:vT(i,xVn,1).map(l=>{var d,u;const o={headIndex:VN(l,3)??0??-1,headName:wb(Pg(l,4))??""??""};var c=l.v;return RJt(c,0|c[hl],a5t,e$e(l,1))!==void 0?(l=_8(l=$h(l,a5t,e$e(l,1),void 0),1,v4,b8()),o.floatEmbedding=l.slice()):(c=new Uint8Array(0),o.quantizedEmbedding=((u=(d=$h(l,gVn,e$e(l,2),void 0))==null?void 0:d.na())==null?void 0:u.h())??c),o}),timestampMs:Hes(Pg(i,2,void 0,void 0,JMe)??TJt)}}(r),qo(this,a)}),this.g.attachEmptyPacketListener("embeddings_out",r=>{qo(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};gj.cosineSimilarity=function(s,t){if(s.floatEmbedding&&t.floatEmbedding)s=h5t(s.floatEmbedding,t.floatEmbedding);else{if(!s.quantizedEmbedding||!t.quantizedEmbedding)throw Error("Cannot compute cosine similarity between quantized and float embeddings.");s=h5t(u5t(s.quantizedEmbedding),u5t(t.quantizedEmbedding))}return s},gj.prototype.embedForVideo=gj.prototype.Aa,gj.prototype.embed=gj.prototype.za,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)};var YYe=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 BVn(s){var n,r;const t=function(a){return vT(a,Gw,1)}(s.ca()).filter(a=>(wb(Pg(a,1))??"").includes("mediapipe.tasks.TensorsToSegmentationCalculator"));if(s.u=[],t.length>1)throw Error("The graph has more than one mediapipe.tasks.TensorsToSegmentationCalculator.");t.length===1&&(((r=(n=$h(t[0],B2,7))==null?void 0:n.j())==null?void 0:r.g())??new Map).forEach((a,i)=>{s.u[Number(i)]=wb(Pg(a,1))??""})}function A5t(s){s.categoryMask=void 0,s.confidenceMasks=void 0,s.qualityScores=void 0}function E5t(s){try{const t=new YYe(s.confidenceMasks,s.categoryMask,s.qualityScores);if(!s.j)return t;s.j(t)}finally{EDe(s)}}YYe.prototype.close=YYe.prototype.close;var J1=class extends I2{constructor(s,t){super(new CC(s,t),"image_in","norm_rect",!1),this.u=[],this.outputCategoryMask=!1,this.outputConfidenceMasks=!0,this.h=new iot,this.A=new zes,ec(this.h,0,3,this.A),ec(s=this.h,0,1,t=new Tx)}get baseOptions(){return $h(this.h,Tx,1)}set baseOptions(s){ec(this.h,0,1,s)}o(s){return s.displayNamesLocale!==void 0?tf(this.h,2,Oie(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(){BVn(this)}segment(s,t,n){const r=typeof t!="function"?t:{};return this.j=typeof t=="function"?t:n,A5t(this),AC(this,s,r),E5t(this)}La(s,t,n,r){const a=typeof n!="function"?n:{};return this.j=typeof n=="function"?n:r,A5t(this),b3(this,s,a,t),E5t(this)}Da(){return this.u}m(){var s=new $2;Hg(s,"image_in"),Hg(s,"norm_rect");const t=new B2;y3(t,$es,this.h);const n=new Gw;P2(n,2,"mediapipe.tasks.vision.image_segmenter.ImageSegmenterGraph"),tg(n,"IMAGE:image_in"),tg(n,"NORM_RECT:norm_rect"),n.o(t),Tk(s,n),ADe(this,s),this.outputConfidenceMasks&&(tm(s,"confidence_masks"),ph(n,"CONFIDENCE_MASKS:confidence_masks"),vW(this,"confidence_masks"),this.g.aa("confidence_masks",(r,a)=>{this.confidenceMasks=r.map(i=>_W(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"),ph(n,"CATEGORY_MASK:category_mask"),vW(this,"category_mask"),this.g.Z("category_mask",(r,a)=>{this.categoryMask=_W(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"),ph(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)}};J1.prototype.getLabels=J1.prototype.Da,J1.prototype.segmentForVideo=J1.prototype.La,J1.prototype.segment=J1.prototype.segment,J1.prototype.setOptions=J1.prototype.o,J1.createFromModelPath=function(s,t){return Eh(J1,s,{baseOptions:{modelAssetPath:t}})},J1.createFromModelBuffer=function(s,t){return Eh(J1,s,{baseOptions:{modelAssetBuffer:t}})},J1.createFromOptions=function(s,t){return Eh(J1,s,t)};var ZYe=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()}};ZYe.prototype.close=ZYe.prototype.close;var r5=class extends I2{constructor(s,t){super(new CC(s,t),"image_in","norm_rect_in",!1),this.outputCategoryMask=!1,this.outputConfidenceMasks=!0,this.h=new iot,this.u=new zes,ec(this.h,0,3,this.u),ec(s=this.h,0,1,t=new Tx)}get baseOptions(){return $h(this.h,Tx,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 Ues,t.keypoint&&t.scribble)throw Error("Cannot provide both keypoint and scribble.");if(t.keypoint){var i=new r$e;xP(i,3,fne(!0),!1),xP(i,1,wQ(t.keypoint.x),0),xP(i,2,wQ(t.keypoint.y),0),Zee(r,1,VYe,i)}else{if(!t.scribble)throw Error("Must provide either a keypoint or a scribble.");{const o=new TVn;for(i of t.scribble)xP(t=new r$e,3,fne(!0),!1),xP(t,1,wQ(i.x),0),xP(t,2,wQ(i.y),0),Oit(o,1,r$e,t);Zee(r,2,VYe,o)}}this.g.addProtoToStream(r.g(),"mediapipe.tasks.vision.interactive_segmenter.proto.RegionOfInterest","roi_in",n),AC(this,s,a);e:{try{const o=new ZYe(this.confidenceMasks,this.categoryMask,this.qualityScores);if(!this.j){var l=o;break e}this.j(o)}finally{EDe(this)}l=void 0}return l}m(){var s=new $2;Hg(s,"image_in"),Hg(s,"roi_in"),Hg(s,"norm_rect_in");const t=new B2;y3(t,$es,this.h);const n=new Gw;P2(n,2,"mediapipe.tasks.vision.interactive_segmenter.InteractiveSegmenterGraphV2"),tg(n,"IMAGE:image_in"),tg(n,"ROI:roi_in"),tg(n,"NORM_RECT:norm_rect_in"),n.o(t),Tk(s,n),ADe(this,s),this.outputConfidenceMasks&&(tm(s,"confidence_masks"),ph(n,"CONFIDENCE_MASKS:confidence_masks"),vW(this,"confidence_masks"),this.g.aa("confidence_masks",(r,a)=>{this.confidenceMasks=r.map(i=>_W(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"),ph(n,"CATEGORY_MASK:category_mask"),vW(this,"category_mask"),this.g.Z("category_mask",(r,a)=>{this.categoryMask=_W(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"),ph(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)}};r5.prototype.segment=r5.prototype.segment,r5.prototype.setOptions=r5.prototype.o,r5.createFromModelPath=function(s,t){return Eh(r5,s,{baseOptions:{modelAssetPath:t}})},r5.createFromModelBuffer=function(s,t){return Eh(r5,s,{baseOptions:{modelAssetBuffer:t}})},r5.createFromOptions=function(s,t){return Eh(r5,s,t)};var oN=class extends I2{constructor(s,t){super(new CC(s,t),"input_frame_gpu","norm_rect",!1),this.j={detections:[]},ec(s=this.h=new qes,0,1,t=new Tx)}get baseOptions(){return $h(this.h,Tx,1)}set baseOptions(s){ec(this.h,0,1,s)}o(s){return s.displayNamesLocale!==void 0?tf(this.h,2,Oie(s.displayNamesLocale)):"displayNamesLocale"in s&&tf(this.h,2),s.maxResults!==void 0?bT(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?tPe(this.h,5,s.categoryAllowlist):"categoryAllowlist"in s&&tf(this.h,5),s.categoryDenylist!==void 0?tPe(this.h,6,s.categoryDenylist):"categoryDenylist"in s&&tf(this.h,6),this.l(s)}F(s,t){return this.j={detections:[]},AC(this,s,t),this.j}G(s,t,n){return this.j={detections:[]},b3(this,s,n,t),this.j}m(){var s=new $2;Hg(s,"input_frame_gpu"),Hg(s,"norm_rect"),tm(s,"detections");const t=new B2;y3(t,MVn,this.h);const n=new Gw;P2(n,2,"mediapipe.tasks.vision.ObjectDetectorGraph"),tg(n,"IMAGE:input_frame_gpu"),tg(n,"NORM_RECT:norm_rect"),ph(n,"DETECTIONS:detections"),n.o(t),Tk(s,n),this.g.attachProtoVectorListener("detections",(r,a)=>{for(const i of r)r=bes(i),this.j.detections.push(Ges(r));qo(this,a)}),this.g.attachEmptyPacketListener("detections",r=>{qo(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};oN.prototype.detectForVideo=oN.prototype.G,oN.prototype.detect=oN.prototype.F,oN.prototype.setOptions=oN.prototype.o,oN.createFromModelPath=async function(s,t){return Eh(oN,s,{baseOptions:{modelAssetPath:t}})},oN.createFromModelBuffer=function(s,t){return Eh(oN,s,{baseOptions:{modelAssetBuffer:t}})},oN.createFromOptions=function(s,t){return Eh(oN,s,t)};var XYe=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 T5t(s){s.landmarks=[],s.worldLandmarks=[],s.segmentationMasks=void 0}function M5t(s){try{const t=new XYe(s.landmarks,s.worldLandmarks,s.segmentationMasks);if(!s.u)return t;s.u(t)}finally{EDe(s)}}XYe.prototype.close=XYe.prototype.close;var xj=class extends I2{constructor(s,t){super(new CC(s,t),"image_in","norm_rect",!1),this.landmarks=[],this.worldLandmarks=[],this.outputSegmentationMasks=!1,ec(s=this.h=new Ves,0,1,t=new Tx),this.A=new Res,ec(this.h,0,3,this.A),this.j=new Les,ec(this.h,0,2,this.j),bT(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,Tx,1)}set baseOptions(s){ec(this.h,0,1,s)}o(s){return"numPoses"in s&&bT(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,T5t(this),AC(this,s,r),M5t(this)}G(s,t,n,r){const a=typeof n!="function"?n:{};return this.u=typeof n=="function"?n:r,T5t(this),b3(this,s,a,t),M5t(this)}m(){var s=new $2;Hg(s,"image_in"),Hg(s,"norm_rect"),tm(s,"normalized_landmarks"),tm(s,"world_landmarks"),tm(s,"segmentation_masks");const t=new B2;y3(t,PVn,this.h);const n=new Gw;P2(n,2,"mediapipe.tasks.vision.pose_landmarker.PoseLandmarkerGraph"),tg(n,"IMAGE:image_in"),tg(n,"NORM_RECT:norm_rect"),ph(n,"NORM_LANDMARKS:normalized_landmarks"),ph(n,"WORLD_LANDMARKS:world_landmarks"),n.o(t),Tk(s,n),ADe(this,s),this.g.attachProtoVectorListener("normalized_landmarks",(r,a)=>{this.landmarks=[];for(const i of r)r=$ie(i),this.landmarks.push(CDe(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=IV(i),this.worldLandmarks.push(Qee(r));qo(this,a)}),this.g.attachEmptyPacketListener("world_landmarks",r=>{this.worldLandmarks=[],qo(this,r)}),this.outputSegmentationMasks&&(ph(n,"SEGMENTATION_MASK:segmentation_masks"),vW(this,"segmentation_masks"),this.g.aa("segmentation_masks",(r,a)=>{this.segmentationMasks=r.map(i=>_W(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)}};xj.prototype.detectForVideo=xj.prototype.G,xj.prototype.detect=xj.prototype.F,xj.prototype.setOptions=xj.prototype.o,xj.createFromModelPath=function(s,t){return Eh(xj,s,{baseOptions:{modelAssetPath:t}})},xj.createFromModelBuffer=function(s,t){return Eh(xj,s,{baseOptions:{modelAssetBuffer:t}})},xj.createFromOptions=function(s,t){return Eh(xj,s,t)},xj.POSE_CONNECTIONS=ots;let w8=null,jQ=null;async function $Vn(){return w8||jQ||(jQ=(async()=>{const s=await bU.forVisionTasks("https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@latest/wasm");return w8=await J1.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}),w8})(),jQ)}function UVn(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 qVn(){w8&&(w8.close(),w8=null,jQ=null)}const VVn=1280,HVn=720;function GVn(s,t){const n=j.useRef(null),r=j.useRef(null),a=j.useRef(null),i=j.useRef(0),l=j.useRef(t),[o,c]=j.useState(null),[d,u]=j.useState(!1),[h,m]=j.useState(null);l.current=t;const f=t.type!=="none"&&s!==null;return j.useEffect(()=>{if(t.type==="image"&&t.imageUrl){const g=new Image;g.crossOrigin="anonymous",g.src=t.imageUrl,g.onload=()=>{a.current=g},g.onerror=()=>{a.current=null}}else t.type!=="image"&&(a.current=null)},[t.type,t.imageUrl]),j.useEffect(()=>{if(!f||!s){r.current&&(r.current.srcObject=null,r.current=null);return}const g=document.createElement("video");return g.srcObject=s,g.muted=!0,g.playsInline=!0,g.autoplay=!0,g.play().catch(()=>{}),r.current=g,()=>{g.srcObject=null,r.current=null}},[f,s]),j.useEffect(()=>{if(!f){c(null),m(null);return}let g=!1,x=null,y=null;const v=async()=>{u(!0),m(null);try{const w=await $Vn();if(g)return;u(!1);const S=r.current;if(!S||(await new Promise(ts=>{if(S.videoWidth>0)return ts();S.onloadedmetadata=()=>ts(),setTimeout(ts,2e3)}),g))return;const A=S.videoWidth||640,E=S.videoHeight||480,I=Math.max(A,E),P=Math.min(A,E),R=Math.min(1,VVn/I,HVn/P),D=Math.max(2,Math.round(A*R/2)*2),O=Math.max(2,Math.round(E*R/2)*2),W=!aJt().canRunVirtualBg,G=(W?192:256)/Math.max(D,O),Y=Math.max(2,Math.round(D*G)),X=Math.max(2,Math.round(O*G)),ae=W?90:55,le=W?24:30,ne=n.current;if(!ne)return;ne.width=D,ne.height=O;const te=ne.getContext("2d",{alpha:!1}),J=document.createElement("canvas");J.width=D,J.height=O;const ce=J.getContext("2d"),_e=document.createElement("canvas");_e.width=Math.max(2,Math.round(D/2)),_e.height=Math.max(2,Math.round(O/2));const he=_e.getContext("2d",{alpha:!1}),ue=document.createElement("canvas");ue.width=Y,ue.height=X;const ve=ue.getContext("2d",{alpha:!1}),Ee=document.createElement("canvas");Ee.width=Y,Ee.height=X;const Se=Ee.getContext("2d"),Le=Se.createImageData(Y,X),Fe=Le.data;for(let ts=0;tske.addTrack(ts)),g||c(ke);const Ne=new Float32Array(Y*X),Ae=new Float32Array(Y*X),Ce=new Float32Array(Y*X);let Ve=!1,ze=!1;const qe=2,dt=.4;let Xe=0;const at=(ts,ys)=>{ve.drawImage(ts,0,0,Y,X);const Ft=w.segmentForVideo(ue,ys).confidenceMasks;if(!(!Ft||Ft.length===0)){Ae.fill(0);for(let as=1;as1?1:gs}}for(const as of Ft)as.close();if(UVn(Ae,Ne,Y,X,qe),Ve)for(let as=0;as=1?255:Ks*255|0}Se.putImageData(Le,0,0),ze=!0}},rt=ts=>{const ys=l.current;if(ys.type==="blur"){const Bt=Math.max(2,Math.round((ys.blurRadius??15)/2));he.filter=`blur(${Bt}px)`,he.drawImage(ts,0,0,_e.width,_e.height),he.filter="none",te.drawImage(_e,0,0,D,O)}else if(ys.type==="image"&&a.current){const Bt=a.current,Ft=Bt.width/Bt.height,as=D/O;let kt=0,Ks=0,wt=Bt.width,gs=Bt.height;Ft>as?(wt=Bt.height*as,kt=(Bt.width-wt)/2):(gs=Bt.width/as,Ks=(Bt.height-gs)/2),te.drawImage(Bt,kt,Ks,wt,gs,0,0,D,O)}else te.fillStyle="#000",te.fillRect(0,0,D,O)},Ke=()=>{if(g||!r.current)return;const ts=r.current;if(ts.readyState<2){Yt(ts);return}try{const ys=performance.now();ys-Xe>=ae&&(Xe=ys,at(ts,ys)),ze?(rt(ts),ce.globalCompositeOperation="source-over",ce.clearRect(0,0,D,O),ce.drawImage(ts,0,0,D,O),ce.globalCompositeOperation="destination-in",ce.drawImage(Ee,0,0,D,O),ce.globalCompositeOperation="source-over",l.current.mirror?(te.save(),te.translate(D,0),te.scale(-1,1),te.drawImage(J,0,0),te.restore()):te.drawImage(J,0,0)):te.drawImage(ts,0,0,D,O)}catch{try{te.drawImage(ts,0,0,D,O)}catch{}}Yt(ts)},Je=typeof S.requestVideoFrameCallback=="function",pt="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([pt],{type:"application/javascript"});y=URL.createObjectURL(gt),x=new Worker(y),x.onmessage=()=>{g||!document.hidden||Ke()};const ss=()=>{x&&(document.hidden?x.postMessage({type:"start",fps:le}):(x.postMessage({type:"stop"}),Yt(r.current)))};document.addEventListener("visibilitychange",ss);const Yt=ts=>{g||document.hidden||(Je?ts.requestVideoFrameCallback(()=>Ke()):i.current=requestAnimationFrame(Ke))};Yt(S),b=()=>{document.removeEventListener("visibilitychange",ss)}}catch(w){console.error("[useVirtualBackground] init error:",w),g||(u(!1),m(w.message||"Failed to initialize virtual background"))}};let b=null;return v(),()=>{g=!0,i.current&&cancelAnimationFrame(i.current),b==null||b(),x&&(x.postMessage({type:"stop"}),x.terminate(),x=null),y&&URL.revokeObjectURL(y),c(null)}},[f,s]),j.useEffect(()=>()=>{qVn()},[]),{canvasRef:n,compositedStream:o,isLoading:d,isActive:f,error:h}}function FT({maxDurationSeconds:s=600,onRecordingComplete:t,onError:n,onRecordingStateChange:r,showBackgroundPicker:a=!0,className:i,teleprompterContent:l}){const o=j.useRef(null),c=j.useRef(null),d=j.useRef(null),[u,h]=j.useState(null),m=j.useRef([]),f=j.useRef(null),g=j.useRef(null),x=j.useRef(null),y=j.useRef(null),v=FK(),[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),[Y,X]=j.useState(!1),[ae,le]=j.useState(!1),[ne,te]=j.useState(null),[J,ce]=j.useState(null),[_e,he]=j.useState(0),[ue,ve]=j.useState("user"),[Ee,Se]=j.useState(0),[Le,Fe]=j.useState(!1),[ke,Be]=j.useState(!0),[Ne,Ae]=j.useState(null),[Ce,Ve]=j.useState(!1),[ze,qe]=j.useState(null),dt=j.useRef(null),[Xe,at]=j.useState(()=>{try{const kn=localStorage.getItem("video-bg-config");if(kn)return JSON.parse(kn)}catch{}return{type:"none"}});j.useEffect(()=>{try{localStorage.setItem("video-bg-config",JSON.stringify(Xe))}catch{}},[Xe]);const[rt,Ke]=j.useState([]),[Je,pt]=j.useState([]),[gt,ss]=j.useState(()=>{try{return localStorage.getItem("video-mic-id")||""}catch{return""}}),[Yt,ts]=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",Yt)}catch{}},[Yt]),j.useEffect(()=>{var Fn,bn,xs;if(!((Fn=navigator.mediaDevices)!=null&&Fn.enumerateDevices))return;const kn=async()=>{try{const Lr=await navigator.mediaDevices.enumerateDevices();Ke(Lr.filter(Or=>Or.kind==="audioinput")),pt(Lr.filter(Or=>Or.kind==="videoinput"))}catch(Lr){console.warn("[VideoRecorder] enumerateDevices failed",Lr)}};return kn(),(xs=(bn=navigator.mediaDevices).addEventListener)==null||xs.call(bn,"devicechange",kn),()=>{var Lr,Or;return(Or=(Lr=navigator.mediaDevices).removeEventListener)==null?void 0:Or.call(Lr,"devicechange",kn)}},[V]);const{canvasRef:ys,compositedStream:Bt,isLoading:Ft,isActive:as}=GVn(u,Xe),kt=j.useRef(n);kt.current=n;const Ks=j.useCallback(kn=>{O(kn)},[]),wt=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(kn=>kn.stop()),S.current=null),P.current&&(P.current.getTracks().forEach(kn=>kn.stop()),P.current=null),R.current&&(R.current.srcObject=null,R.current=null)},[]),ks=j.useCallback(async()=>{var kn;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:Yt?{deviceId:{exact:Yt},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 Lr=Fn.getVideoTracks()[0],Or=Lr.getSettings(),la=Or.width||1920,Qn=Or.height||1080,Cr=document.createElement("canvas");Cr.width=la,Cr.height=Qn,A.current=Cr;const Un=Cr.getContext("2d");let dr=null;bn&&(dr=document.createElement("video"),dr.srcObject=bn,dr.muted=!0,dr.playsInline=!0,dr.autoplay=!0,await dr.play(),R.current=dr);const Pa=document.createElement("video");Pa.srcObject=Fn,Pa.muted=!0,Pa.playsInline=!0,Pa.autoplay=!0,await Pa.play();const ii=()=>{if(Un.drawImage(Pa,0,0,la,Qn),dr&&dr.readyState>=2){const Nl=Math.round(la*.2),Ho=Math.round(Nl*(dr.videoHeight/dr.videoWidth||.75)),ti=la-Nl-20,Xr=Qn-Ho-20,Eo=12;Un.save(),Un.beginPath(),Un.moveTo(ti+Eo,Xr),Un.lineTo(ti+Nl-Eo,Xr),Un.quadraticCurveTo(ti+Nl,Xr,ti+Nl,Xr+Eo),Un.lineTo(ti+Nl,Xr+Ho-Eo),Un.quadraticCurveTo(ti+Nl,Xr+Ho,ti+Nl-Eo,Xr+Ho),Un.lineTo(ti+Eo,Xr+Ho),Un.quadraticCurveTo(ti,Xr+Ho,ti,Xr+Ho-Eo),Un.lineTo(ti,Xr+Eo),Un.quadraticCurveTo(ti,Xr,ti+Eo,Xr),Un.closePath(),Un.clip(),Un.translate(ti+Nl,Xr),Un.scale(-1,1),Un.drawImage(dr,0,0,Nl,Ho),Un.restore(),Un.strokeStyle="rgba(255,255,255,0.6)",Un.lineWidth=2,Un.beginPath(),Un.moveTo(ti+Eo,Xr),Un.lineTo(ti+Nl-Eo,Xr),Un.quadraticCurveTo(ti+Nl,Xr,ti+Nl,Xr+Eo),Un.lineTo(ti+Nl,Xr+Ho-Eo),Un.quadraticCurveTo(ti+Nl,Xr+Ho,ti+Nl-Eo,Xr+Ho),Un.lineTo(ti+Eo,Xr+Ho),Un.quadraticCurveTo(ti,Xr+Ho,ti,Xr+Ho-Eo),Un.lineTo(ti,Xr+Eo),Un.quadraticCurveTo(ti,Xr,ti+Eo,Xr),Un.closePath(),Un.stroke()}},$i="let id=null;onmessage=(e)=>{if(e.data&&e.data.type==='start'){clearInterval(id);id=setInterval(()=>postMessage('tick'),Math.round(1000/(e.data.fps||30)))}else if(e.data==='stop'){clearInterval(id);id=null}}",Rn=new Blob([$i],{type:"application/javascript"}),xa=new Worker(URL.createObjectURL(Rn));I.current=xa,xa.onmessage=()=>ii(),xa.postMessage({type:"start",fps:30}),ii();const Ya=Cr.captureStream(30),ho=[],Tc=Fn.getAudioTracks();Tc.length&&ho.push(...Tc),xs&&ho.push(...xs.getAudioTracks());const zd=new MediaStream([...Ya.getVideoTracks(),...ho]);return P.current=zd,Lr.onended=()=>{c.current&&c.current.state!=="inactive"&&c.current.stop(),gs()},zd}catch(Fn){return console.error("[VideoRecorder] Screen capture error:",Fn),Fn.name!=="NotAllowedError"&&((kn=kt.current)==null||kn.call(kt,"Failed to start screen capture: "+(Fn.message||"Unknown error"))),null}},[gs]),Is=j.useCallback(async()=>{var Fn,bn;W(!0),Ae(null);const kn=v&&D;console.log("[VideoRecorder] initCamera start",{isMobile:v,usePortraitMode:D,shouldBePortrait:kn,facingMode:ue});try{if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)throw new Error("Camera not available in this browser or context. Try opening in a new tab.");d.current&&(console.log("[VideoRecorder] stopping existing stream"),d.current.getTracks().forEach(Un=>Un.stop()));const xs=v&&kn?{width:{ideal:720},height:{ideal:1280}}:{width:{ideal:1280},height:{ideal:720}},Lr=Yt?{...xs,deviceId:{exact:Yt}}:{...xs,facingMode:{ideal:ue}},Or={echoCancellation:!0,noiseSuppression:!0,...gt?{deviceId:{exact:gt}}:{}};console.log("[VideoRecorder] requesting getUserMedia",Lr);const la=await navigator.mediaDevices.getUserMedia({video:Lr,audio:Or});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 Cr=la.getVideoTracks()[0].getSettings();if(console.log("[VideoRecorder] Camera initialized with dimensions:",Cr.width,"x",Cr.height),o.current){const Un=o.current;Un.srcObject=la,Un.muted=!0,Un.playsInline=!0,Un.autoplay=!0,Un.setAttribute("muted",""),Un.setAttribute("playsinline",""),Un.setAttribute("autoplay","");try{(Fn=Un.load)==null||Fn.call(Un)}catch(Pa){console.warn("[VideoRecorder] videoEl.load failed",Pa)}const dr=async()=>{try{return await Un.play(),console.log("[VideoRecorder] preview play ok"),Ve(!1),setTimeout(()=>{console.debug("[VideoRecorder] preview metrics",{readyState:Un.readyState,videoWidth:Un.videoWidth,videoHeight:Un.videoHeight})},300),!0}catch(Pa){return console.warn("[VideoRecorder] preview play blocked",Pa),Ve(!0),!1}};await new Promise(Pa=>{let ii=!1;const $i=()=>{ii||(ii=!0,Pa())},Rn=()=>{dr().finally($i)};Un.onloadedmetadata=Rn,Un.onloadeddata=Rn,setTimeout($i,1500)})}try{g.current=new AudioContext;const Un=g.current.createMediaStreamSource(la);x.current=g.current.createAnalyser(),x.current.fftSize=256,Un.connect(x.current);const dr=()=>{if(x.current){const Pa=new Uint8Array(x.current.frequencyBinCount);x.current.getByteFrequencyData(Pa);const ii=Pa.reduce(($i,Rn)=>$i+Rn)/Pa.length;Se(Math.min(100,ii/128*100))}y.current=requestAnimationFrame(dr)};dr()}catch(Un){console.warn("Audio context not available:",Un)}}catch(xs){console.error("Camera initialization error:",xs),G(!1);let Lr="Failed to access camera or microphone.";xs.name==="NotAllowedError"?Lr="Camera permission denied. Please allow camera access in your browser settings.":xs.name==="NotFoundError"?Lr="No camera found. Please connect a camera and try again.":xs.name==="NotReadableError"?Lr="Camera is in use by another application. Please close other apps using the camera.":xs.message&&(Lr=xs.message),Ae(Lr),(bn=kt.current)==null||bn.call(kt,Lr)}finally{W(!1)}},[ue,v,D,gt,Yt]);j.useEffect(()=>{wt.current!==D&&V&&!Y&&!J&&(wt.current=D,Is())},[D,V,Y,J,Is]),j.useEffect(()=>(Is(),()=>{d.current&&d.current.getTracks().forEach(kn=>kn.stop()),f.current&&clearInterval(f.current),y.current&&cancelAnimationFrame(y.current),g.current&&g.current.close(),dt.current&&clearInterval(dt.current),J&&URL.revokeObjectURL(J),gs()}),[Is,J]),j.useEffect(()=>{if(U||V!==!0||J)return;const kn=d.current,Fn=o.current;!kn||!Fn||as||(Fn.srcObject!==kn&&(Fn.srcObject=kn,Fn.muted=!0,Fn.playsInline=!0,Fn.autoplay=!0,Fn.setAttribute("muted",""),Fn.setAttribute("playsinline",""),Fn.setAttribute("autoplay","")),Fn.play().then(()=>Ve(!1)).catch(bn=>{Ve(!0),console.warn("Live preview play blocked on mount:",bn)}))},[V,U,J,as]),j.useEffect(()=>{r==null||r(Y)},[Y,r]);const Xs=j.useCallback(async()=>{if(J)return;const kn=o.current;if(kn)try{await kn.play(),Ve(!1)}catch(Fn){Ve(!0),console.warn("Live preview still blocked (needs user gesture):",Fn)}},[J]),ds=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]),Ss=j.useCallback(async()=>{let kn=null;if(b==="screen"){if(kn=await ks(),!kn)return}else kn=as&&Bt?Bt:d.current;if(!kn)return;Xs(),m.current=[],he(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(Lr=>MediaRecorder.isTypeSupported(Lr)),xs=new MediaRecorder(kn,bn?{mimeType:bn,videoBitsPerSecond:b==="screen"?4e6:25e5,audioBitsPerSecond:128e3}:{videoBitsPerSecond:b==="screen"?4e6:25e5,audioBitsPerSecond:128e3});xs.ondataavailable=Lr=>{Lr.data.size>0&&m.current.push(Lr.data)},xs.onstop=()=>{var Qn;const Lr=xs.mimeType||bn||((Qn=m.current[0])==null?void 0:Qn.type)||"video/webm",Or=new Blob(m.current,{type:Lr});te(Or);const la=URL.createObjectURL(Or);ce(la)},c.current=xs,xs.start(1e3),X(!0),f.current=setInterval(()=>{he(Lr=>Lr>=s-1?(ds(),s):Lr+1)},1e3)},[Xs,s,ds,as,Bt,b,ks]),yn=j.useCallback(()=>{dt.current&&(clearInterval(dt.current),dt.current=null),qe(3);let kn=3;dt.current=setInterval(()=>{kn-=1,kn<=0?(dt.current&&clearInterval(dt.current),dt.current=null,qe(null),Ss()):qe(kn)},1e3)},[Ss]),Js=j.useCallback(()=>{c.current&&c.current.state==="recording"&&(c.current.pause(),le(!0),f.current&&clearInterval(f.current))},[]),Ut=j.useCallback(()=>{c.current&&c.current.state==="paused"&&(c.current.resume(),le(!1),f.current=setInterval(()=>{he(kn=>kn>=s-1?(ds(),s):kn+1)},1e3))},[s,ds]),hn=j.useCallback(()=>{J&&URL.revokeObjectURL(J),te(null),ce(null),he(0),Fe(!1),Be(!0),o.current&&d.current&&!as&&(o.current.srcObject=d.current,o.current.muted=!0,Xs())},[Xs,J,as]),hr=j.useCallback(()=>{ve(kn=>kn==="user"?"environment":"user")},[]),Rs=j.useCallback(()=>{ne&&t(ne,_e)},[ne,_e,t]),jr=j.useCallback(()=>{o.current&&J&&(Le?o.current.pause():(Be(!1),o.current.muted=!1,o.current.play()),Fe(!Le))},[J,Le]);j.useEffect(()=>{if(!J)return;const kn=o.current;if(!kn)return;Be(!1),kn.pause(),kn.removeAttribute("src"),kn.srcObject=null,kn.load(),kn.src=J,kn.currentTime=0,kn.playsInline=!0,kn.muted=!1,kn.onended=()=>Fe(!1);const Fn=()=>{var Lr;const bn=kn.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),(Lr=kt.current)==null||Lr.call(kt,xs)};return kn.addEventListener("error",Fn),kn.load(),()=>{kn.removeEventListener("error",Fn)}},[J]);const kr=kn=>{const Fn=Math.floor(kn/60),bn=kn%60;return`${Fn}:${bn.toString().padStart(2,"0")}`},$n=b==="screen"?"aspect-video":v&&D?"aspect-[9/16]":"aspect-video";return U?e.jsx("div",{className:Pt("flex items-center justify-center bg-black rounded-lg",$n,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",$n,i),children:e.jsxs("div",{className:"text-center text-white p-8 max-w-md",children:[e.jsx(ll,{className:"h-12 w-12 mx-auto mb-4 text-destructive"}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Camera Access Required"}),e.jsx("p",{className:"text-gray-400 mb-4 text-sm",children:Ne||"Please allow camera and microphone access to record videos."}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs($,{onClick:()=>Is(),variant:"secondary",className:"w-full",children:[e.jsx(ro,{className:"h-4 w-4 mr-2"}),"Try Again"]}),e.jsx("p",{className:"text-xs text-gray-500 mt-3",children:"💡 Tip: If you're viewing this in an embedded preview, try opening the app in a new browser tab for full camera access."})]})]})}):e.jsxs("div",{className:Pt("flex flex-col gap-2",i),children:[!Y&&!J&&e.jsxs("div",{className:"flex items-center justify-center gap-1 p-1 bg-muted rounded-lg",children:[e.jsxs($,{variant:b==="camera"?"default":"ghost",size:"sm",className:"gap-1.5 flex-1",onClick:()=>w("camera"),children:[e.jsx(Sx,{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(Yz,{className:"h-4 w-4"}),"Screen"]})]}),a&&b==="camera"&&!Y&&!J&&e.jsx(nqn,{value:Xe,onChange:at,isLoading:Ft,disabled:Y}),!Y&&!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(Kz,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs(ms,{value:gt||"default",onValueChange:kn=>ss(kn==="default"?"":kn),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(kn=>e.jsx(Ge,{value:kn.deviceId,children:kn.label||`Microphone ${kn.deviceId.slice(0,6)}`},kn.deviceId))]})]})]}),Je.length>1&&b==="camera"&&e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-[200px]",children:[e.jsx(Sx,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs(ms,{value:Yt||"default",onValueChange:kn=>ts(kn==="default"?"":kn),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(kn=>e.jsx(Ge,{value:kn.deviceId,children:kn.label||`Camera ${kn.deviceId.slice(0,6)}`},kn.deviceId))]})]})]})]}),b==="camera"&&v&&!Y&&!J&&e.jsxs("div",{className:"flex items-center justify-center gap-3 py-2 bg-muted/50 rounded-lg",children:[e.jsx(XN,{className:Pt("h-4 w-4",D?"text-muted-foreground":"text-primary")}),e.jsx(ee,{htmlFor:"orientation-toggle",className:"text-sm text-muted-foreground",children:"Landscape"}),e.jsx(Sn,{id:"orientation-toggle",checked:D,onCheckedChange:Ks}),e.jsx(ee,{htmlFor:"orientation-toggle",className:"text-sm text-muted-foreground",children:"Portrait"}),e.jsx(x1,{className:Pt("h-4 w-4",D?"text-primary":"text-muted-foreground")})]}),b==="screen"&&!Y&&!J&&e.jsxs("div",{className:"flex items-center justify-center gap-2 py-3 px-4 bg-muted/50 rounded-lg text-sm text-muted-foreground",children:[e.jsx(Yz,{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:()=>{Xs()},children:[e.jsx("video",{ref:o,src:J??void 0,className:Pt("w-full bg-black",D&&!J?"object-contain":"object-cover",$n,!J&&ue==="user"!==(Xe.mirror??!1)&&"scale-x-[-1]",as&&!J&&"hidden"),playsInline:!0,controls:!!J,muted:J?ke:!0,autoPlay:!J},J??"live"),as&&!J&&e.jsx("canvas",{ref:ys,className:Pt("w-full bg-black",D?"object-contain":"object-cover",$n,ue==="user"!==(Xe.mirror??!1)&&"scale-x-[-1]")}),as&&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 Xs(),className:"bg-white/20 hover:bg-white/30 text-white",children:"Tap to enable preview"})}),l&&!J&&e.jsx("div",{className:"absolute inset-0 pointer-events-none",children:l}),ze!==null&&!J&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center z-30 pointer-events-none",children:e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx("div",{className:"text-white font-bold drop-shadow-lg animate-scale-in",style:{fontSize:"96px",lineHeight:1,textShadow:"0 4px 16px rgba(0,0,0,0.8)"},children:ze},ze),e.jsx("p",{className:"text-white/80 text-lg font-medium drop-shadow-md",children:"Get ready…"})]})}),Y&&e.jsxs("div",{className:"absolute top-4 left-4 flex items-center gap-2 bg-black/50 px-3 py-1.5 rounded-full",children:[e.jsx("div",{className:Pt("w-3 h-3 rounded-full",ae?"bg-yellow-500":"bg-red-500 animate-pulse")}),e.jsxs("span",{className:"text-white text-sm font-medium",children:[kr(_e)," / ",kr(s)]})]}),Y&&e.jsx("div",{className:"absolute top-0 left-0 right-0",children:e.jsx(Yi,{value:_e/s*100,className:"h-1 rounded-none"})}),!J&&e.jsxs("div",{className:"absolute bottom-20 left-4 flex items-center gap-2 bg-black/50 px-3 py-1.5 rounded-full",children:[e.jsx(Kz,{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:hn,children:[e.jsx(ro,{className:"h-5 w-5 mr-2"}),"Re-record"]}),e.jsx($,{variant:"secondary",size:"icon",className:"h-12 w-12 rounded-full bg-white/20 hover:bg-white/30 text-white",onClick:jr,children:Le?e.jsx(Av,{className:"h-5 w-5"}):e.jsx(zu,{className:"h-5 w-5"})}),e.jsxs($,{size:"lg",className:"bg-green-500 hover:bg-green-600 text-white",onClick:Rs,children:[e.jsx(ca,{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:hr,disabled:Y||ze!==null,children:e.jsx(Ax,{className:"h-5 w-5"})}):e.jsx("div",{className:"h-12 w-12"}),!Y&&ze===null?e.jsx($,{size:"icon",className:"h-16 w-16 rounded-full bg-red-500 hover:bg-red-600 text-white",onClick:b==="screen"?Ss:yn,children:b==="screen"?e.jsx(Yz,{className:"h-6 w-6"}):e.jsx(ua,{className:"h-6 w-6"})}):e.jsxs(e.Fragment,{children:[e.jsx($,{size:"icon",className:"h-12 w-12 rounded-full bg-white/20 hover:bg-white/30 text-white",onClick:ae?Ut:Js,children:ae?e.jsx(zu,{className:"h-5 w-5"}):e.jsx(Av,{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:ds,children:e.jsx(j_,{className:"h-6 w-6 fill-current"})})]}),e.jsx("div",{className:"h-12 w-12"})]})})]})]})}function WVn({open:s,onOpenChange:t,onUploaded:n}){const{user:r}=bs(),{toast:a}=Bi(),[i,l]=j.useState(!1),o=async(c,d)=>{if(r){l(!0);try{const u=c.type.includes("mp4")?"mp4":"webm",h=`${r.id}/${crypto.randomUUID()}.${u}`,{error:m}=await q.storage.from("cma-videos").upload(h,c,{contentType:c.type||"video/webm",upsert:!1});if(m)throw m;const{data:f,error:g}=await q.storage.from("cma-videos").createSignedUrl(h,60*60*24*365*5);if(g||!(f!=null&&f.signedUrl))throw g||new Error("Could not sign video URL");n(f.signedUrl,Math.round(d)),a({title:"Video added to your CMA"}),t(!1)}catch(u){a({title:"Upload failed",description:u==null?void 0:u.message,variant:"destructive"})}finally{l(!1)}}};return e.jsx(zs,{open:s,onOpenChange:c=>!i&&t(c),children:e.jsxs(Os,{className:"max-w-2xl",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Record a personal message"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"A 30-second hello goes a long way. Welcome your client, explain the price, and invite their reply."})]}),i?e.jsxs("div",{className:"py-12 flex flex-col items-center gap-3",children:[e.jsx(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(FT,{maxDurationSeconds:180,onRecordingComplete:o})]})})}function KVn({value:s,onChange:t}){const{user:n}=bs(),[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(ua,{className:"w-4 h-4"}),"Personal Video Message"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Adds the human touch your client will remember. Plays right at the top of the CMA."})]}),e.jsxs(Ie,{className:"space-y-3",children:[s!=null&&s.url?e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"relative rounded-lg overflow-hidden bg-black aspect-video group",children:[e.jsx("video",{src:s.url,poster:s.thumb,controls:!0,className:"w-full h-full object-cover"}),e.jsx("button",{className:"absolute top-2 right-2 bg-black/60 text-white rounded-full p-1.5 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>t(null),"aria-label":"Remove video",type:"button",children:e.jsx(pr,{className:"w-3.5 h-3.5"})})]}),e.jsxs("p",{className:"text-xs text-emerald-700 flex items-center gap-1",children:[e.jsx(zu,{className:"w-3 h-3"})," Video attached"]})]}):e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(s9,{userId:n==null?void 0:n.id,triggerLabel:"Pick from Library",triggerVariant:"outline",triggerSize:"default",triggerClassName:"w-full justify-center gap-2",onSelect:()=>{},onSelectVideo:i=>t({url:i.playback_url,thumb:i.thumbnail_url,label:i.title||i.recipient_name})}),e.jsxs($,{variant:"outline",onClick:()=>a(!0),className:"gap-2",children:[e.jsx(ua,{className:"w-4 h-4"}),"Record New"]})]}),e.jsx(WVn,{open:r,onOpenChange:a,onUploaded:i=>t({url:i,label:"Personal message"})})]})]})}function DS(s){const t=Number(String(s).replace(/[^0-9.]/g,""));return Number.isFinite(t)&&t>0?t:null}function YVn({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:DS(i.bedrooms),bathrooms:DS(i.bathrooms),sqft:DS(i.sqft),yearBuilt:DS(i.yearBuilt),propertyType:i.propertyType||null,propertySubType:i.propertySubType||null}),t(!1)};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-lg",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Fill in the subject property basics"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"When the MLS feed does not return the home details, add the basics here and LevelUp will keep the CMA moving."}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Beds"}),e.jsx(pe,{inputMode:"decimal",value:i.bedrooms,onChange:c=>l(d=>({...d,bedrooms:c.target.value})),placeholder:"3"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Baths"}),e.jsx(pe,{inputMode:"decimal",value:i.bathrooms,onChange:c=>l(d=>({...d,bathrooms:c.target.value})),placeholder:"2"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Sq Ft"}),e.jsx(pe,{inputMode:"numeric",value:i.sqft,onChange:c=>l(d=>({...d,sqft:c.target.value})),placeholder:"1850"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Year Built"}),e.jsx(pe,{inputMode:"numeric",value:i.yearBuilt,onChange:c=>l(d=>({...d,yearBuilt:c.target.value})),placeholder:"2006"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Property Type"}),e.jsx(pe,{value:i.propertyType,onChange:c=>l(d=>({...d,propertyType:c.target.value})),placeholder:"Residential"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Subtype"}),e.jsx(pe,{value:i.propertySubType,onChange:c=>l(d=>({...d,propertySubType:c.target.value})),placeholder:"Single Family"})]})]}),e.jsxs($,{className:"w-full",onClick:o,disabled:a,children:[a?e.jsx(Ct,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(tl,{className:"w-4 h-4 mr-2"}),"Save subject details"]})]})]})})}function ZVn({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=DS(a.price),c=DS(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:DS(a.bedrooms),bathrooms:DS(a.bathrooms),sqft:c,yearBuilt:DS(a.yearBuilt),photos:[]}),t(!1))};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-2xl",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Add a comparable manually"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Use this when the MLS feed misses a property or you already know the best comp. Add at least the address, price, and square footage."}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-3",children:[e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(ee,{className:"text-xs",children:"Address"}),e.jsx(pe,{value:a.address,onChange:o=>i(c=>({...c,address:o.target.value})),placeholder:"123 Comparable St"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"City"}),e.jsx(pe,{value:a.city,onChange:o=>i(c=>({...c,city:o.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"State"}),e.jsx(pe,{maxLength:2,value:a.state,onChange:o=>i(c=>({...c,state:o.target.value.toUpperCase()}))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Status"}),e.jsx(pe,{value:a.status,onChange:o=>i(c=>({...c,status:o.target.value})),placeholder:"Closed"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Price"}),e.jsx(pe,{inputMode:"numeric",value:a.price,onChange:o=>i(c=>({...c,price:o.target.value})),placeholder:"525000"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Sq Ft"}),e.jsx(pe,{inputMode:"numeric",value:a.sqft,onChange:o=>i(c=>({...c,sqft:o.target.value})),placeholder:"1800"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Beds"}),e.jsx(pe,{inputMode:"decimal",value:a.bedrooms,onChange:o=>i(c=>({...c,bedrooms:o.target.value})),placeholder:"3"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Baths"}),e.jsx(pe,{inputMode:"decimal",value:a.bathrooms,onChange:o=>i(c=>({...c,bathrooms:o.target.value})),placeholder:"2"})]})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Year Built"}),e.jsx(pe,{className:"max-w-[180px]",inputMode:"numeric",value:a.yearBuilt,onChange:o=>i(c=>({...c,yearBuilt:o.target.value})),placeholder:"2005"})]}),e.jsxs($,{className:"w-full",onClick:l,disabled:!a.address.trim()||!DS(a.price)||!DS(a.sqft),children:[e.jsx(dn,{className:"w-4 h-4 mr-2"}),"Add comp to CMA"]})]})]})})}function XVn(){var ue,ve,Ee,Se,Le,Fe,ke;const{id:s}=Wi(),t=Xn(),{toast:n}=Bi(),{data:r,isLoading:a}=Y$n(s),{data:i}=Z$n(s),l=X$n(),o=eUn(),c=tUn(),{leadSite:d,isLoading:u}=ng(),[h,m]=j.useState([]),[f,g]=j.useState({sqftPct:.2,monthsBack:6,maxMiles:5,statuses:["Active","Pending","Closed"]}),[x,y]=j.useState(null),[v,b]=j.useState(!1),[w,S]=j.useState({low:"",likely:"",high:"",note:""}),[A,E]=j.useState(!1),[I,P]=j.useState(!1),[R,D]=j.useState(!1),[O,U]=j.useState(null),W=async Be=>{var qe,dt;if(!r||!(Be!=null&&Be.address)||!(Be!=null&&Be.city)||!(Be!=null&&Be.state))return Be;let Ne={...Be};const Ae=async Xe=>{const{data:at,error:rt}=await q.functions.invoke("cma-subject-lookup",{body:{address:Xe.address,city:Xe.city,state:Xe.state,zip:Xe.zip,latitude:Xe.latitude,longitude:Xe.longitude,leadSiteId:(d==null?void 0:d.id)??r.lead_site_id}});if(rt)throw rt;return(at==null?void 0:at.matches)||[]},Ce=Xe=>{const rt=Xe.find(gt=>Number.isFinite(Number(gt.latitude))&&Number.isFinite(Number(gt.longitude)))||Xe[0];if(!rt)return;const Ke=typeof rt.match_type=="string"&&rt.match_type.startsWith("nearby-"),Je=Ke&&Number.isFinite(Number(Ne.latitude))&&Number.isFinite(Number(Ne.longitude)),pt=gt=>rt[gt]!==void 0&&rt[gt]!==null&&rt[gt]!==""&&rt[gt]!==0?rt[gt]:Ne[gt];Ne={...Ne,bedrooms:pt("bedrooms"),bathrooms:pt("bathrooms"),sqft:pt("sqft"),yearBuilt:pt("yearBuilt"),lotSize:pt("lotSize"),propertyType:pt("propertyType"),propertySubType:pt("propertySubType"),source_provider:rt.source_provider??Ne.source_provider,match_type:rt.match_type??Ne.match_type,matched_mls_address:Ke?rt.address:Ne.matched_mls_address,latitude:Je?Ne.latitude:rt.latitude??Ne.latitude,longitude:Je?Ne.longitude:rt.longitude??Ne.longitude,mlsNumber:Ke?Ne.mlsNumber:rt.mlsNumber??Ne.mlsNumber,photos:!Ke&&Array.isArray(rt.photos)&&rt.photos.length?rt.photos:Ne.photos}};Ce(await Ae(Ne));const Ve=()=>Number.isFinite(Number(Ne.latitude))&&Number.isFinite(Number(Ne.longitude));if(!Ve()){const{data:Xe}=await q.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle(),at=Xe==null?void 0:Xe.value;if(at){const rt=encodeURIComponent(`${Ne.address}, ${Ne.city}, ${Ne.state} ${Ne.zip||""}`.trim()),Je=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${rt}.json?access_token=${at}&limit=1&country=us`)).json(),pt=(dt=(qe=Je==null?void 0:Je.features)==null?void 0:qe[0])==null?void 0:dt.center;Array.isArray(pt)&&pt.length===2&&(Ne.longitude=pt[0],Ne.latitude=pt[1])}}if((!Ne.bedrooms||!Ne.bathrooms||!Ne.sqft||!Ne.yearBuilt)&&Ve())try{Ce(await Ae(Ne))}catch(Xe){console.warn("second-pass subject lookup failed",Xe)}return JSON.stringify(Ne)!==JSON.stringify(Be)&&await l.mutateAsync({id:r.id,patch:{subject:Ne}}),Ne};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 Ne=(Ce=r==null?void 0:r.settings)==null?void 0:Ce.personalVideo;Ne!=null&&Ne.url&&U({url:Ne.url,thumb:Ne.thumb,label:Ne.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||{},Ne=Number.isFinite(Number(Be.latitude))&&Number.isFinite(Number(Be.longitude)),Ae=!!(Number(Be.bedrooms)||Number(Be.bathrooms)||Number(Be.sqft)||Number(Be.yearBuilt));if(Ne&&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(Ve){console.warn("subject enrich failed",Ve)}})()))},[r==null?void 0:r.id,r==null?void 0:r.lead_site_id,d==null?void 0:d.id,u]);const Y=j.useMemo(()=>r?wCt(r.subject,h):null,[r,h]),X=async()=>{if(r)try{const Be=await W(r.subject),Ne=await o.mutateAsync({subject:Be,filters:f,leadSiteId:(d==null?void 0:d.id)??r.lead_site_id});m(Ne.comps.map(Ae=>({...Ae,selected:!0})).slice(0,12)),n({title:`Found ${Ne.comps.length} comps`,description:`Top ${Math.min(12,Ne.comps.length)} auto-selected.`})}catch(Be){n({title:"Search failed",description:Be.message,variant:"destructive"})}},ae=Be=>{m(Ne=>Ne.map((Ae,Ce)=>Ce===Be?{...Ae,selected:!Ae.selected}:Ae))},le=Be=>{m(Ne=>Ne.filter((Ae,Ce)=>Ce!==Be))},ne=async Be=>{if(!r)return;const Ne=Object.fromEntries(Object.entries(Be).filter(([,Ce])=>Ce!=null&&Ce!=="")),Ae={...r.subject,...Ne,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(Ne=>[{...Be,selected:!0,manual:!0},...Ne]),n({title:"Manual comp added"})},J=async(Be=!1)=>{if(!r)return;const Ne=wCt(r.subject,h),Ae=dt=>{const Xe=Number(String(dt).replace(/[^0-9.]/g,""));return Number.isFinite(Xe)&&Xe>0?Math.round(Xe):null},Ce=v?Ae(w.likely):null,Ve=v?Ae(w.low):null,ze=v?Ae(w.high):null,qe=v&&Ce;await l.mutateAsync({id:r.id,patch:{settings:{...f,priceOverride:{enabled:v,low:Ve,likely:Ce,high:ze,note:w.note||null},personalVideo:O},price_low:qe?Ve??Ce:Ne.low??null,price_likely:qe?Ce:Ne.likely??null,price_high:qe?ze??Ce:Ne.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 _e=h.filter(Be=>Be.selected).length,he=!((ue=r.subject)!=null&&ue.bedrooms)||!((ve=r.subject)!=null&&ve.bathrooms)||!((Ee=r.subject)!=null&&Ee.sqft)||!((Se=r.subject)!=null&&Se.yearBuilt);return e.jsx(Vs,{children:e.jsxs("div",{className:"container mx-auto p-4 md:p-6 max-w-7xl",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4 gap-2 flex-wrap",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>t("/mission-control/cma"),children:[e.jsx(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(Fd,{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(Fr,{className:"w-4 h-4 mr-1"}),"Copy Link"]}),e.jsxs($,{onClick:()=>E(!0),children:[e.jsx(mn,{className:"w-4 h-4 mr-1"}),"Send to Contact"]})]})]})]}),e.jsxs("div",{className:"grid lg:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"lg:col-span-1 space-y-4",children:[e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-base",children:"Subject Property"})}),e.jsxs(Ie,{className:"space-y-2 text-sm",children:[e.jsx("div",{className:"font-semibold",children:r.subject.address}),e.jsxs("div",{className:"text-muted-foreground",children:[r.subject.city,", ",r.subject.state," ",r.subject.zip]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 pt-2",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Beds:"})," ",r.subject.bedrooms??"—"]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Baths:"})," ",r.subject.bathrooms??"—"]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"SqFt:"})," ",((Le=r.subject.sqft)==null?void 0:Le.toLocaleString())??"—"]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Year:"})," ",r.subject.yearBuilt??"—"]})]}),he&&e.jsxs("div",{className:"rounded-lg border border-amber-200 bg-amber-50 p-3 text-amber-950 space-y-2",children:[e.jsx("p",{className:"font-medium",children:"No panic — we can still build this."}),e.jsx("p",{className:"text-xs leading-relaxed",children:"If the MLS/feed does not return beds, baths, sqft, or year, add them manually and LevelUp will use them for comps and pricing."}),e.jsxs($,{size:"sm",variant:"outline",className:"bg-white",onClick:()=>P(!0),children:[e.jsx(pi,{className:"w-3.5 h-3.5 mr-1"}),"Fill in property details"]})]}),!he&&e.jsxs($,{size:"sm",variant:"ghost",className:"px-0",onClick:()=>P(!0),children:[e.jsx(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 Ne=Number(Be.target.value);Ne>0&&await l.mutateAsync({id:r.id,patch:{subject:{...r.subject,sqft:Ne}}})}})]})]})]}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsxs(Et,{className:"text-base flex items-center gap-2",children:[e.jsx(a2,{className:"w-4 h-4"}),"Suggested Price"]})}),e.jsxs(Ie,{className:"space-y-3",children:[Y!=null&&Y.likely?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"text-3xl font-bold",children:["$",(v&&Number(w.likely)>0?Number(w.likely):Y.likely).toLocaleString()]}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-1",children:["Comps suggest: $",(Fe=Y.low)==null?void 0:Fe.toLocaleString()," – $",(ke=Y.high)==null?void 0:ke.toLocaleString()]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["$",Y.ppsf,"/sqft median · ",_e," comps"]})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Add comps with sqft + price to see suggested pricing."}),e.jsxs("div",{className:"pt-3 border-t space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{htmlFor:"override-toggle",className:"text-sm font-medium",children:"Override with my price"}),e.jsx(Sn,{id:"override-toggle",checked:v,onCheckedChange:b})]}),v&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"My suggested price"}),e.jsx(pe,{type:"number",placeholder:"e.g. 750000",value:w.likely,onChange:Be=>S(Ne=>({...Ne,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(Ne=>({...Ne,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(Ne=>({...Ne,high:Be.target.value}))})]})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Why this price (optional)"}),e.jsx(Ls,{rows:2,maxLength:500,placeholder:"Notes shown to your client",value:w.note,onChange:Be=>S(Ne=>({...Ne,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(KVn,{value:O,onChange:U}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-base",children:"Filters"})}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsxs(ee,{className:"text-xs",children:["SqFt tolerance: ±",Math.round(f.sqftPct*100),"%"]}),e.jsx(Nx,{value:[f.sqftPct*100],min:5,max:50,step:5,onValueChange:([Be])=>g(Ne=>({...Ne,sqftPct:Be/100}))})]}),e.jsxs("div",{children:[e.jsxs(ee,{className:"text-xs",children:["Search radius: ",f.maxMiles," mi"]}),e.jsx(Nx,{value:[f.maxMiles],min:1,max:25,step:1,onValueChange:([Be])=>g(Ne=>({...Ne,maxMiles:Be}))})]}),e.jsxs("div",{children:[e.jsxs(ee,{className:"text-xs",children:["Sold within: ",f.monthsBack," months"]}),e.jsx(Nx,{value:[f.monthsBack],min:1,max:24,step:1,onValueChange:([Be])=>g(Ne=>({...Ne,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:Ne=>g(Ae=>({...Ae,statuses:Ne?[...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(Nn,{className:"w-4 h-4 mr-2"}),"Find Comps"]}),e.jsxs($,{variant:"outline",className:"w-full",onClick:()=>D(!0),children:[e.jsx(dn,{className:"w-4 h-4 mr-2"}),"Add a comp manually"]})]})]})]}),e.jsxs("div",{className:"lg:col-span-2 space-y-3",children:[e.jsx(tqn,{subject:r.subject,comps:h,radiusMiles:f.maxMiles,onMarkerClick:Be=>y(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:[_e," selected"]})]}),h.length?e.jsx("div",{className:"space-y-2",children:h.map((Be,Ne)=>{var Ae;return e.jsx(je,{className:Be.selected?"":"opacity-50",children:e.jsxs(Ie,{className:"p-3 flex gap-3 items-center",children:[e.jsx(ai,{checked:Be.selected,onCheckedChange:()=>ae(Ne)}),e.jsxs("button",{type:"button",onClick:()=>y(Ne),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(UEe,{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:()=>y(Ne),title:"View details",children:e.jsx(Ca,{className:"w-4 h-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>le(Ne),title:"Remove",children:e.jsx(Hn,{className:"w-4 h-4"})})]})},Ne)})}):e.jsx(je,{children:e.jsx(Ie,{className:"py-12 text-center text-muted-foreground",children:e.jsxs("div",{className:"max-w-md mx-auto space-y-3",children:[e.jsxs("p",{children:["Click ",e.jsx("strong",{children:"Find Comps"})," to auto-pull from your MLS."]}),e.jsx("p",{className:"text-sm",children:"If nothing comes back, you are not stuck — use LevelUp's fallback template: enter the subject details, add 2–3 known comps, then set your suggested price."}),e.jsxs("div",{className:"flex flex-wrap justify-center gap-2",children:[he&&e.jsx($,{variant:"outline",size:"sm",onClick:()=>P(!0),children:"Fill subject details"}),e.jsx($,{variant:"outline",size:"sm",onClick:()=>D(!0),children:"Add manual comp"})]})]})})})]})]}),e.jsx(r$t,{comp:x!=null?h[x]:null,open:x!=null,onClose:()=>y(null)}),e.jsx(YVn,{open:I,onOpenChange:P,subject:r.subject,onSave:ne,isSaving:l.isPending}),e.jsx(ZVn,{open:R,onOpenChange:D,subject:r.subject,onAdd:te}),e.jsx(nJt,{open:A,onOpenChange:E,cma:r})]})})}const zL="listing-presentations";function lts(){const{user:s}=bs(),t=Wt(),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(),re.success("Template saved")},onError:o=>re.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(),re.success("Template updated")},onError:o=>re.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(),re.success("Template deleted")},onError:o=>re.error(o.message||"Could not delete the template")});return{savedTemplates:n.data??[],isLoading:n.isLoading,save:a,update:i,remove:l}}function QVn(){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 cts(){const{user:s}=bs(),t=Wt(),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=>re.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=>re.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(zL).copy(c.property_photo_path,d);m||await q.from("listing_presentations").update({property_photo_path:d}).eq("id",u.id)}return u},onSuccess:()=>{r(),re.success("Presentation duplicated")},onError:c=>re.error(c.message||"Could not duplicate")}),o=mt({mutationFn:async c=>{const d=[c.property_photo_path,c.pdf_path,c.thumbnail_path].filter(Boolean);d.length&&await q.storage.from(zL).remove(d);const{error:u}=await q.from("listing_presentations").delete().eq("id",c.id);if(u)throw u},onSuccess:()=>{r(),re.success("Presentation deleted")},onError:c=>re.error(c.message||"Could not delete")});return{presentations:n.data??[],isLoading:n.isLoading,create:a,update:i,duplicate:l,remove:o}}function JVn(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 eHn(s,t=3600){if(!s)return null;const{data:n,error:r}=await q.storage.from(zL).createSignedUrl(s,t);return r?null:(n==null?void 0:n.signedUrl)??null}const QYe={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."}},tHn={cover:"Cover",welcome:"Marketing commitment",agent:"About your agent",overview:"Marketing plan overview",closing:"Closing commitment"};function dts(s,t){var i;const n=((i=s==null?void 0:s.copy)==null?void 0:i[t])||{},r=QYe[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 uts={enabled:!1,name:"",title:null,headshotUrl:null,phone:null,email:null,brokerageName:null,licenseNumber:null,bio:null};function hts(s){return{...uts,...s||{}}}const i$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."}],mts=()=>typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`cp_${Math.random().toString(36).slice(2)}`;function xot(s,t=0){const n={id:mts(),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 fts(s){return Array.isArray(s)?s.filter(t=>t&&typeof t=="object").map((t,n)=>({...xot(t.layout||"story",n),...t,id:t.id||mts(),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 JYe={hidden:["overview"]},eZe={x:.5,y:.5},tu=(s,t,n=!0)=>({key:s,label:t,enabled:n}),iPe=[{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:[tu("hdr","Full HDR interior and exterior photo set"),tu("drone","Aerial drone photography of the home and lot"),tu("twilight","Twilight exterior session for the hero image"),tu("staging","Virtual staging for vacant or transitional rooms",!1),tu("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:[tu("walkthrough","Cinematic full-property walkthrough video"),tu("reels","Vertical short-form cuts for Reels, Shorts, and TikTok"),tu("oncamera","On-camera agent introduction to the home"),tu("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:[tu("data","Complete, accurate MLS data so your home shows in every filter"),tu("copy","Copywriting that leads with the features buyers pay for"),tu("pricing","Pricing built on live comparable and absorption data"),tu("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:[tu("zillow","Zillow — the highest-traffic buyer search portal"),tu("realtor","Realtor.com — direct MLS-sourced listing feed"),tu("homes","Homes.com — agent-attributed listing exposure"),tu("others","Redfin, Trulia, Movoto, and hundreds of partner sites"),tu("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:[tu("gallery","Full-screen gallery, video, and floor plan in one place"),tu("mobile","Mobile-first design with a one-tap inquiry form"),tu("link","Shareable link used across ads, email, and QR signage"),tu("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:[tu("organic","Just-listed launch across feed, stories, and reels"),tu("ads","Geo-targeted paid campaigns aimed at active buyers"),tu("retarget","Retargeting so interested viewers keep seeing your home"),tu("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:[tu("database","Direct email to my buyer and past-client database"),tu("agents","Broadcast to area agents with matching buyers"),tu("referral","Referral partner network notified at launch"),tu("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:[tu("public","Strategically timed public open houses"),tu("broker","Broker open house for agents with active buyers"),tu("signin","Digital sign-in that captures every visitor"),tu("neighbors","Neighbor invitations and just-listed mailers"),tu("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:[tu("weekly","Weekly seller report on the schedule you prefer"),tu("feedback","Showing feedback delivered as it comes in"),tu("analytics","Online traffic and engagement analytics"),tu("access","Direct access to me by call, text, or email")]}],sHn=Object.fromEntries(iPe.map(s=>[s.key,(s.options||[]).map(t=>t.label)]));function tZe(s){return s!=null&&s.length?iPe.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}}):iPe.map(t=>{var n;return{...t,options:(n=t.options)==null?void 0:n.map(r=>({...r}))}})}const nHn={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 yC=Uint8Array,Jj=Uint16Array,yot=Int32Array,vot=new yC([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]),bot=new yC([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]),P5t=new yC([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),pts=function(s,t){for(var n=new Jj(31),r=0;r<31;++r)n[r]=t+=1<>1|(Np&21845)<<1;CM=(CM&52428)>>2|(CM&13107)<<2,CM=(CM&61680)>>4|(CM&3855)<<4,nZe[Np]=((CM&65280)>>8|(CM&255)<<8)>>1}var Jee=function(s,t,n){for(var r=s.length,a=0,i=new Jj(t);a>c]=d}else for(o=new Jj(r),a=0;a>15-s[a]);return o},uB=new yC(288);for(var Np=0;Np<144;++Np)uB[Np]=8;for(var Np=144;Np<256;++Np)uB[Np]=9;for(var Np=256;Np<280;++Np)uB[Np]=7;for(var Np=280;Np<288;++Np)uB[Np]=8;var oPe=new yC(32);for(var Np=0;Np<32;++Np)oPe[Np]=5;var iHn=Jee(uB,9,0),oHn=Jee(oPe,5,0),xts=function(s){return(s+7)/8|0},lHn=function(s,t,n){return(n==null||n>s.length)&&(n=s.length),new yC(s.subarray(t,n))},iA=function(s,t,n){n<<=t&7;var r=t/8|0;s[r]|=n,s[r+1]|=n>>8},iX=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},o$e=function(s,t){for(var n=[],r=0;rm&&(m=i[r].s);var f=new Jj(m+1),g=rZe(n[u-1],f,0);if(g>t){var r=0,x=0,y=g-t,v=1<t)x+=v-(1<>=y;x>0;){var w=i[r].s;f[w]=0&&x;--r){var S=i[r].s;f[S]==t&&(--f[S],++x)}g=t}return{t:new yC(f),l:g}},rZe=function(s,t,n){return s.s==-1?Math.max(rZe(s.l,t,n+1),rZe(s.r,t,n+1)):t[s.s]=n},L5t=function(s){for(var t=s.length;t&&!s[--t];);for(var n=new Jj(++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}},oX=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[P5t[U-1]];--U);var W=d+5<<3,V=oX(a,uB)+oX(i,oPe)+l,G=oX(a,m)+oX(i,x)+l+14+3*U+oX(I,D)+2*I[16]+3*I[17]+7*I[18];if(c>=0&&W<=V&&W<=G)return yts(t,u,s.subarray(c,c+d));var Y,X,ae,le;if(iA(t,u,1+(G15&&(iA(t,u,ce[P]>>5&127),u+=ce[P]>>12)}}else Y=iHn,X=uB,ae=oHn,le=oPe;for(var P=0;P255){var _e=he>>18&31;iX(t,u,Y[_e+257]),u+=X[_e+257],_e>7&&(iA(t,u,he>>23&31),u+=vot[_e]);var ue=he&31;iX(t,u,ae[ue]),u+=le[ue],ue>3&&(iX(t,u,he>>5&8191),u+=bot[ue])}else iX(t,u,Y[he]),u+=X[he]}return iX(t,u,Y[256]),u+X[256]},cHn=new yot([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),vts=new yC(0),dHn=function(s,t,n,r,a,i){var l=i.z||s.length,o=new yC(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=cHn[t-1],m=h>>13,f=h&8191,g=(1<7e3||D>24576)&&(Y>423||!d)){u=R5t(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,ne=f,te=V-G&32767;if(Y>2&&W==w(R-te))for(var J=Math.min(m,Y)-1,ce=Math.min(32767,R),_e=Math.min(258,Y);te<=ce&&--ne&&V!=G;){if(s[R+ae]==s[R+ae-te]){for(var he=0;he<_e&&s[R+he]==s[R+he-te];++he);if(he>ae){if(ae=he,le=te,he>J)break;for(var ue=Math.min(te,he-2),ve=0,X=0;Xve&&(ve=Le,G=Ee)}}}V=G,G=x[V],te+=V-G&32767}if(le){S[D++]=268435456|sZe[ae]<<18|I5t[le];var Fe=sZe[ae]&31,ke=I5t[le]&31;P+=vot[Fe]+bot[ke],++A[257+Fe],++E[ke],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=yts(c,u+1,s.subarray(R,Be))}i.i=l}return lHn(o,0,r+xts(u)+a)},bts=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}}},uHn=function(s,t,n,r,a){if(!a&&(a={l:1},t.dictionary)){var i=t.dictionary.subarray(-32768),l=new yC(i.length+s.length);l.set(i),l.set(s,i.length),s=l,a.w=i.length}return dHn(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)},_ts=function(s,t,n){for(;n;++t)s[t]=n,n>>>=8},hHn=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=bts();a.p(t.dictionary),_ts(s,2,a.d())}};function aZe(s,t){t||(t={});var n=bts();n.p(s);var r=uHn(s,t,t.dictionary?6:2,4);return hHn(r,t),_ts(r,r.length-4,n.d()),r}var mHn=typeof TextDecoder<"u"&&new TextDecoder,fHn=0;try{mHn.decode(vts,{stream:!0}),fHn=1}catch{}function pHn(s){if(Array.isArray(s))return s}function gHn(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 D5t(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])})(),l$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 _ot{constructor(t=_Hn,n={}){Nr(this,"buffer");Nr(this,"byteLength");Nr(this,"byteOffset");Nr(this,"length");Nr(this,"offset");Nr(this,"lastWrittenByte");Nr(this,"littleEndian");Nr(this,"_data");Nr(this,"_mark");Nr(this,"_marks");let r=!1;typeof t=="number"?t=new ArrayBuffer(t):(r=!0,this.lastWrittenByte=t.byteLength);const a=n.offset?n.offset>>>0:0,i=t.byteLength-a;let l=a;(ArrayBuffer.isView(t)||t instanceof _ot)&&(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=l$e[n].BYTES_PER_ELEMENT*t,a=this.byteOffset+this.offset,i=this.buffer.slice(a,a+r);if(this.littleEndian===wHn&&n!=="uint8"&&n!=="int8"){const o=new Uint8Array(this.buffer.slice(a,a+r));o.reverse();const c=new l$e[n](o.buffer);return this.offset+=r,c.reverse(),c}const l=new l$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 XK(s){let t=s.length;for(;--t>=0;)s[t]=0}const jHn=3,NHn=258,wts=29,kHn=256,SHn=kHn+1+wts,jts=30,CHn=512,AHn=new Array((SHn+2)*2);XK(AHn);const EHn=new Array(jts*2);XK(EHn);const THn=new Array(CHn);XK(THn);const MHn=new Array(NHn-jHn+1);XK(MHn);const PHn=new Array(wts);XK(PHn);const IHn=new Array(jts);XK(IHn);const LHn=(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 iZe=LHn;const RHn=()=>{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},DHn=new Uint32Array(RHn()),FHn=(s,t,n,r)=>{const a=DHn,i=r+n;s^=-1;for(let l=r;l>>8^a[(s^t[l])&255];return s^-1};var a5=FHn,oZe={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"},Nts={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 OHn=(s,t)=>Object.prototype.hasOwnProperty.call(s,t);var zHn=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)OHn(n,r)&&(s[r]=n[r])}}return s},BHn=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;gne[254]=gne[255]=1;var $Hn=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 UHn=(s,t)=>{if(t<65534&&s.subarray&&Sts)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 UHn(i,a)},VHn=(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+gne[s[n]]>t?n:t},lZe={string2buf:$Hn,buf2string:qHn,utf8border:VHn};function HHn(){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 GHn=HHn;const bue=16209,WHn=16191;var KHn=function(t,n){let r,a,i,l,o,c,d,u,h,m,f,g,x,y,v,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,y=O.distcode,v=(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=bue;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=bue;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=bue;break e}else{w=y[(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,y=0,v=0,b=0,w,S,A,E,I,P=null,R;const D=new Uint16Array($$+1),O=new Uint16Array($$+1);let U=null,W,V,G;for(d=0;d<=$$;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===$5t||m!==1))return-1;for(O[1]=0,d=1;d<$$;d++)O[d+1]=O[d]+D[d];for(u=0;uz5t||s===U5t&&v>B5t)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,y=1<z5t||s===U5t&&v>B5t)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 ete=JHn;const eGn=0,Cts=1,Ats=2,{Z_FINISH:q5t,Z_BLOCK:tGn,Z_TREES:_ue,Z_OK:hB,Z_STREAM_END:sGn,Z_NEED_DICT:nGn,Z_STREAM_ERROR:fk,Z_DATA_ERROR:Ets,Z_MEM_ERROR:Tts,Z_BUF_ERROR:rGn,Z_DEFLATED:V5t}=Nts,TDe=16180,H5t=16181,G5t=16182,W5t=16183,K5t=16184,Y5t=16185,Z5t=16186,X5t=16187,Q5t=16188,J5t=16189,lPe=16190,oA=16191,d$e=16192,e4t=16193,u$e=16194,t4t=16195,s4t=16196,n4t=16197,r4t=16198,wue=16199,jue=16200,a4t=16201,i4t=16202,o4t=16203,l4t=16204,c4t=16205,h$e=16206,d4t=16207,u4t=16208,Fp=16209,Mts=16210,Pts=16211,aGn=852,iGn=592,oGn=15,lGn=oGn,h4t=s=>(s>>>24&255)+(s>>>8&65280)+((s&65280)<<8)+((s&255)<<24);function cGn(){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 i9=s=>{if(!s)return 1;const t=s.state;return!t||t.strm!==s||t.modePts?1:0},Its=s=>{if(i9(s))return fk;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=TDe,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(aGn),t.distcode=t.distdyn=new Int32Array(iGn),t.sane=1,t.back=-1,hB},Lts=s=>{if(i9(s))return fk;const t=s.state;return t.wsize=0,t.whave=0,t.wnext=0,Its(s)},Rts=(s,t)=>{let n;if(i9(s))return fk;const r=s.state;return t<0?(n=0,t=-t):(n=(t>>4)+5,t<48&&(t&=15)),t&&(t<8||t>15)?fk:(r.window!==null&&r.wbits!==t&&(r.window=null),r.wrap=n,r.wbits=t,Lts(s))},Dts=(s,t)=>{if(!s)return fk;const n=new cGn;s.state=n,n.strm=s,n.window=null,n.mode=TDe;const r=Rts(s,t);return r!==hB&&(s.state=null),r},dGn=s=>Dts(s,lGn);let m4t=!0,m$e,f$e;const uGn=s=>{if(m4t){m$e=new Int32Array(512),f$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(ete(Cts,s.lens,0,288,m$e,0,s.work,{bits:9}),t=0;t<32;)s.lens[t++]=5;ete(Ats,s.lens,0,32,f$e,0,s.work,{bits:5}),m4t=!1}s.lencode=m$e,s.lenbits=9,s.distcode=f$e,s.distbits=5},Fts=(s,t,n,r)=>{let a;const i=s.state;return i.window===null&&(i.window=new Uint8Array(1<=i.wsize?(i.window.set(t.subarray(n-i.wsize,n),0),i.wnext=0,i.whave=i.wsize):(a=i.wsize-i.wnext,a>r&&(a=r),i.window.set(t.subarray(n-r,n-r+a),i.wnext),r-=a,r?(i.window.set(t.subarray(n-r,n),0),i.wnext=r,i.whave=i.wsize):(i.wnext+=a,i.wnext===i.wsize&&(i.wnext=0),i.whave{let n,r,a,i,l,o,c,d,u,h,m,f,g,x,y=0,v,b,w,S,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(i9(s)||!s.output||!s.input&&s.avail_in!==0)return fk;n=s.state,n.mode===oA&&(n.mode=d$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=hB;e:for(;;)switch(n.mode){case TDe:if(n.wrap===0){n.mode=d$e;break}for(;u<16;){if(o===0)break e;o--,d+=r[i++]<>>8&255,n.check=a5(n.check,R,2,0),d=0,u=0,n.mode=H5t;break}if(n.head&&(n.head.done=!1),!(n.wrap&1)||(((d&255)<<8)+(d>>8))%31){s.msg="incorrect header check",n.mode=Fp;break}if((d&15)!==V5t){s.msg="unknown compression method",n.mode=Fp;break}if(d>>>=4,u-=4,I=(d&15)+8,n.wbits===0&&(n.wbits=I),I>15||I>n.wbits){s.msg="invalid window size",n.mode=Fp;break}n.dmax=1<>8&1),n.flags&512&&n.wrap&4&&(R[0]=d&255,R[1]=d>>>8&255,n.check=a5(n.check,R,2,0)),d=0,u=0,n.mode=G5t;case G5t: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=a5(n.check,R,4,0)),d=0,u=0,n.mode=W5t;case W5t: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=a5(n.check,R,2,0)),d=0,u=0,n.mode=K5t;case K5t:if(n.flags&1024){for(;u<16;){if(o===0)break e;o--,d+=r[i++]<>>8&255,n.check=a5(n.check,R,2,0)),d=0,u=0}else n.head&&(n.head.extra=null);n.mode=Y5t;case Y5t: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=a5(n.check,r,f,i)),o-=f,i+=f,n.length-=f),n.length))break e;n.length=0,n.mode=Z5t;case Z5t: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=oA;break;case J5t: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=e4t;break;case 1:if(uGn(n),n.mode=wue,t===_ue){d>>>=2,u-=2;break e}break;case 2:n.mode=s4t;break;case 3:s.msg="invalid block type",n.mode=Fp}d>>>=2,u-=2;break;case e4t:for(d>>>=u&7,u-=u&7;u<32;){if(o===0)break e;o--,d+=r[i++]<>>16^65535)){s.msg="invalid stored block lengths",n.mode=Fp;break}if(n.length=d&65535,d=0,u=0,n.mode=u$e,t===_ue)break e;case u$e:n.mode=t4t;case t4t: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=oA;break;case s4t:for(;u<14;){if(o===0)break e;o--,d+=r[i++]<>>=5,u-=5,n.ndist=(d&31)+1,d>>>=5,u-=5,n.ncode=(d&15)+4,d>>>=4,u-=4,n.nlen>286||n.ndist>30){s.msg="too many length or distance symbols",n.mode=Fp;break}n.have=0,n.mode=n4t;case n4t: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=ete(eGn,n.lens,0,19,n.lencode,0,n.work,D),n.lenbits=D.bits,P){s.msg="invalid code lengths set",n.mode=Fp;break}n.have=0,n.mode=r4t;case r4t:for(;n.have>>24,b=y>>>16&255,w=y&65535,!(v<=u);){if(o===0)break e;o--,d+=r[i++]<>>=v,u-=v,n.lens[n.have++]=w;else{if(w===16){for(O=v+2;u>>=v,u-=v,n.have===0){s.msg="invalid bit length repeat",n.mode=Fp;break}I=n.lens[n.have-1],f=3+(d&3),d>>>=2,u-=2}else if(w===17){for(O=v+3;u>>=v,u-=v,I=0,f=3+(d&7),d>>>=3,u-=3}else{for(O=v+7;u>>=v,u-=v,I=0,f=11+(d&127),d>>>=7,u-=7}if(n.have+f>n.nlen+n.ndist){s.msg="invalid bit length repeat",n.mode=Fp;break}for(;f--;)n.lens[n.have++]=I}}if(n.mode===Fp)break;if(n.lens[256]===0){s.msg="invalid code -- missing end-of-block",n.mode=Fp;break}if(n.lenbits=9,D={bits:n.lenbits},P=ete(Cts,n.lens,0,n.nlen,n.lencode,0,n.work,D),n.lenbits=D.bits,P){s.msg="invalid literal/lengths set",n.mode=Fp;break}if(n.distbits=6,n.distcode=n.distdyn,D={bits:n.distbits},P=ete(Ats,n.lens,n.nlen,n.ndist,n.distcode,0,n.work,D),n.distbits=D.bits,P){s.msg="invalid distances set",n.mode=Fp;break}if(n.mode=wue,t===_ue)break e;case wue:n.mode=jue;case jue: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,KHn(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===oA&&(n.back=-1);break}for(n.back=0;y=n.lencode[d&(1<>>24,b=y>>>16&255,w=y&65535,!(v<=u);){if(o===0)break e;o--,d+=r[i++]<>S)],v=y>>>24,b=y>>>16&255,w=y&65535,!(S+v<=u);){if(o===0)break e;o--,d+=r[i++]<>>=S,u-=S,n.back+=S}if(d>>>=v,u-=v,n.back+=v,n.length=w,b===0){n.mode=c4t;break}if(b&32){n.back=-1,n.mode=oA;break}if(b&64){s.msg="invalid literal/length code",n.mode=Fp;break}n.extra=b&15,n.mode=a4t;case a4t:if(n.extra){for(O=n.extra;u>>=n.extra,u-=n.extra,n.back+=n.extra}n.was=n.length,n.mode=i4t;case i4t:for(;y=n.distcode[d&(1<>>24,b=y>>>16&255,w=y&65535,!(v<=u);){if(o===0)break e;o--,d+=r[i++]<>S)],v=y>>>24,b=y>>>16&255,w=y&65535,!(S+v<=u);){if(o===0)break e;o--,d+=r[i++]<>>=S,u-=S,n.back+=S}if(d>>>=v,u-=v,n.back+=v,b&64){s.msg="invalid distance code",n.mode=Fp;break}n.offset=w,n.extra=b&15,n.mode=o4t;case o4t:if(n.extra){for(O=n.extra;u>>=n.extra,u-=n.extra,n.back+=n.extra}if(n.offset>n.dmax){s.msg="invalid distance too far back",n.mode=Fp;break}n.mode=l4t;case l4t:if(c===0)break e;if(f=m-c,n.offset>f){if(f=n.offset-f,f>n.whave&&n.sane){s.msg="invalid distance too far back",n.mode=Fp;break}f>n.wnext?(f-=n.wnext,g=n.wsize-f):g=n.wnext-f,f>n.length&&(f=n.length),x=n.window}else x=a,g=l-n.offset,f=n.length;f>c&&(f=c),c-=f,n.length-=f;do a[l++]=x[g++];while(--f);n.length===0&&(n.mode=jue);break;case c4t:if(c===0)break e;a[l++]=n.length,c--,n.mode=jue;break;case h$e:if(n.wrap){for(;u<32;){if(o===0)break e;o--,d|=r[i++]<{if(i9(s))return fk;let t=s.state;return t.window&&(t.window=null),s.state=null,hB},fGn=(s,t)=>{if(i9(s))return fk;const n=s.state;return n.wrap&2?(n.head=t,t.done=!1,hB):fk},pGn=(s,t)=>{const n=t.length;let r,a,i;return i9(s)||(r=s.state,r.wrap!==0&&r.mode!==lPe)?fk:r.mode===lPe&&(a=1,a=iZe(a,t,n,0),a!==r.check)?Ets:(i=Fts(s,t,n,n),i?(r.mode=Mts,Tts):(r.havedict=1,hB))};var gGn=Lts,xGn=Rts,yGn=Its,vGn=dGn,bGn=Dts,_Gn=hGn,wGn=mGn,jGn=fGn,NGn=pGn,kGn="pako inflate (from Nodeca project)",T5={inflateReset:gGn,inflateReset2:xGn,inflateResetKeep:yGn,inflateInit:vGn,inflateInit2:bGn,inflate:_Gn,inflateEnd:wGn,inflateGetHeader:jGn,inflateSetDictionary:NGn,inflateInfo:kGn};function SGn(){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=SGn;const Ots=Object.prototype.toString,{Z_NO_FLUSH:AGn,Z_FINISH:f4t,Z_OK:LV,Z_STREAM_END:p$e,Z_NEED_DICT:g$e,Z_STREAM_ERROR:EGn,Z_DATA_ERROR:p4t,Z_MEM_ERROR:TGn,Z_BUF_ERROR:g4t}=Nts,MGn={chunkSize:1024*64,windowBits:15,to:""};function Uie(s){this.options=kts.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 GHn,this.strm.avail_out=0;let n=T5.inflateInit2(this.strm,t.windowBits);if(n!==LV)throw new Error(oZe[n]);if(this.header=new CGn,T5.inflateGetHeader(this.strm,this.header),t.dictionary&&(typeof t.dictionary=="string"?t.dictionary=lZe.string2buf(t.dictionary):Ots.call(t.dictionary)==="[object ArrayBuffer]"&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(n=T5.inflateSetDictionary(this.strm,t.dictionary),n!==LV)))throw new Error(oZe[n])}Uie.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?f4t:AGn,Ots.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=T5.inflate(n,l),i===g$e&&a&&(i=T5.inflateSetDictionary(n,a),i===LV?i=T5.inflate(n,l):i===p4t&&(i=g$e));n.avail_in>0&&i===p$e&&n.state.wrap&2&&n.state.flags!==0&&n.input[n.next_in]!==0;)T5.inflateReset(n),i=T5.inflate(n,l);switch(i){case EGn:case p4t:case g$e:case TGn:return this.onEnd(i),this.ended=!0,!1}if(o=n.avail_out,n.next_out&&(n.avail_out===0||i===p$e||l>0))if(this.options.to==="string"){let c=lZe.utf8border(n.output,n.next_out),d=n.next_out-c,u=lZe.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===LV||i===g4t)&&o===0)){if(i===p$e)return i=T5.inflateEnd(this.strm),this.onEnd(i),this.ended=!0,!0;if(n.avail_in===0){if(l===f4t)return i=T5.inflateEnd(this.strm),this.onEnd(i===LV?g4t:i),this.ended=!0,!1;break}}}return!0};Uie.prototype.onData=function(s){this.chunks.push(s)};Uie.prototype.onEnd=function(s){s===LV&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=kts.flattenChunks(this.chunks)),this.chunks=[],this.err=s,this.msg=this.strm.msg};function PGn(s,t){const n=new Uie(t);if(n.push(s,!0),n.err)throw n.msg||oZe[n.err];return n.result}var IGn=Uie,LGn=PGn,RGn={Inflate:IGn,inflate:LGn};const{Inflate:DGn,inflate:FGn}=RGn;var x4t=DGn,OGn=FGn;const zts=[];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;zts[s]=t}const y4t=4294967295;function zGn(s,t,n){let r=s;for(let a=0;a>>8;return r}function BGn(s,t){return(zGn(y4t,s,t)^y4t)>>>0}function v4t(s,t,n){const r=s.readUint32(),a=BGn(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 Bts(s,t,n){for(let r=0;r>1)&255}else{for(;i>1)&255;for(;i>1)&255}}function Vts(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 KGn=new Uint16Array([255]),YGn=new Uint8Array(KGn.buffer),ZGn=YGn[0]===255,XGn=new Uint8Array(0);function b4t(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=XGn,u=0,h,m;for(let f=0;f>8&255}const A3e=Uint8Array.of(137,80,78,71,13,10,26,10);function _4t(s){if(!JGn(s.readBytes(A3e.length)))throw new Error("wrong PNG signature")}function JGn(s){if(s.length79)throw new Error("keyword length must be between 1 and 79")}const nWn=/^[\u0000-\u00FF]*$/;function rWn(s){if(!nWn.test(s))throw new Error("invalid latin1 text")}function aWn(s,t,n){const r=Gts(t);s[r]=iWn(t,n-r.length-1)}function Gts(s){for(s.mark();s.readByte()!==tWn;);const t=s.offset;s.reset();const n=Hts.decode(s.readBytes(t-s.offset-1));return s.skip(1),sWn(n),n}function iWn(s,t){return Hts.decode(s.readBytes(t))}const yj={UNKNOWN:-1,GREYSCALE:0,TRUECOLOUR:2,INDEXED_COLOUR:3,GREYSCALE_ALPHA:4,TRUECOLOUR_ALPHA:6},x$e={UNKNOWN:-1,DEFLATE:0},w4t={UNKNOWN:-1,ADAPTIVE:0},y$e={UNKNOWN:-1,NO_INTERLACE:0,ADAM7:1},Nue={NONE:0,BACKGROUND:1,PREVIOUS:2},v$e={SOURCE:0,OVER:1};class oWn extends _ot{constructor(n,r={}){super(n);Nr(this,"_checkCrc");Nr(this,"_inflator");Nr(this,"_png");Nr(this,"_apng");Nr(this,"_end");Nr(this,"_hasPalette");Nr(this,"_palette");Nr(this,"_hasTransparency");Nr(this,"_transparency");Nr(this,"_compressionMethod");Nr(this,"_filterMethod");Nr(this,"_interlaceMethod");Nr(this,"_colorType");Nr(this,"_isAnimated");Nr(this,"_numberOfFrames");Nr(this,"_numberOfPlays");Nr(this,"_frames");Nr(this,"_writingDataChunks");const{checkCrc:a=!1}=r;this._checkCrc=a,this._inflator=new x4t,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=x$e.UNKNOWN,this._filterMethod=w4t.UNKNOWN,this._interlaceMethod=y$e.UNKNOWN,this._colorType=yj.UNKNOWN,this._isAnimated=!1,this._numberOfFrames=1,this._numberOfPlays=0,this._frames=[],this._writingDataChunks=!1,this.setBigEndian()}decode(){for(_4t(this);!this._end;){const n=this.readUint32(),r=this.readChars(4);this.decodeChunk(n,r)}return this.decodeImage(),this._png}decodeApng(){for(_4t(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 eWn:aWn(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?v4t(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?v4t(this,n+4,r):this.skip(4)}decodeIHDR(){const n=this._png;n.width=this.readUint32(),n.height=this.readUint32(),n.depth=lWn(this.readUint8());const r=this.readUint8();this._colorType=r;let a;switch(r){case yj.GREYSCALE:a=1;break;case yj.TRUECOLOUR:a=3;break;case yj.INDEXED_COLOUR:a=1;break;case yj.GREYSCALE_ALPHA:a=2;break;case yj.TRUECOLOUR_ALPHA:a=4;break;case yj.UNKNOWN:default:throw new Error(`Unknown color type: ${r}`)}if(this._png.channels=a,this._compressionMethod=this.readUint8(),this._compressionMethod!==x$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 v$e.SOURCE:for(let l=0;l=200&&t.status<=299}function kue(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 zO=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?N4t(a.href)?_$e(s,t,n):kue(a,a.target="_blank"):kue(a)):(a.href=r.createObjectURL(s),setTimeout(function(){r.revokeObjectURL(a.href)},4e4),setTimeout(function(){kue(a)},0))}:"msSaveOrOpenBlob"in navigator?function(s,t,n){if(t=t||s.name||"download",typeof s=="string")if(N4t(s))_$e(s,t,n);else{var r=document.createElement("a");r.href=s,r.target="_blank",setTimeout(function(){kue(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 _$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 Wts(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 E3e=Dc.atob.bind(Dc),k4t=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 w$e(s,t){var n=s[0],r=s[1],a=s[2],i=s[3];n=Yb(n,r,a,i,t[0],7,-680876936),i=Yb(i,n,r,a,t[1],12,-389564586),a=Yb(a,i,n,r,t[2],17,606105819),r=Yb(r,a,i,n,t[3],22,-1044525330),n=Yb(n,r,a,i,t[4],7,-176418897),i=Yb(i,n,r,a,t[5],12,1200080426),a=Yb(a,i,n,r,t[6],17,-1473231341),r=Yb(r,a,i,n,t[7],22,-45705983),n=Yb(n,r,a,i,t[8],7,1770035416),i=Yb(i,n,r,a,t[9],12,-1958414417),a=Yb(a,i,n,r,t[10],17,-42063),r=Yb(r,a,i,n,t[11],22,-1990404162),n=Yb(n,r,a,i,t[12],7,1804603682),i=Yb(i,n,r,a,t[13],12,-40341101),a=Yb(a,i,n,r,t[14],17,-1502002290),n=Zb(n,r=Yb(r,a,i,n,t[15],22,1236535329),a,i,t[1],5,-165796510),i=Zb(i,n,r,a,t[6],9,-1069501632),a=Zb(a,i,n,r,t[11],14,643717713),r=Zb(r,a,i,n,t[0],20,-373897302),n=Zb(n,r,a,i,t[5],5,-701558691),i=Zb(i,n,r,a,t[10],9,38016083),a=Zb(a,i,n,r,t[15],14,-660478335),r=Zb(r,a,i,n,t[4],20,-405537848),n=Zb(n,r,a,i,t[9],5,568446438),i=Zb(i,n,r,a,t[14],9,-1019803690),a=Zb(a,i,n,r,t[3],14,-187363961),r=Zb(r,a,i,n,t[8],20,1163531501),n=Zb(n,r,a,i,t[13],5,-1444681467),i=Zb(i,n,r,a,t[2],9,-51403784),a=Zb(a,i,n,r,t[7],14,1735328473),n=Xb(n,r=Zb(r,a,i,n,t[12],20,-1926607734),a,i,t[5],4,-378558),i=Xb(i,n,r,a,t[8],11,-2022574463),a=Xb(a,i,n,r,t[11],16,1839030562),r=Xb(r,a,i,n,t[14],23,-35309556),n=Xb(n,r,a,i,t[1],4,-1530992060),i=Xb(i,n,r,a,t[4],11,1272893353),a=Xb(a,i,n,r,t[7],16,-155497632),r=Xb(r,a,i,n,t[10],23,-1094730640),n=Xb(n,r,a,i,t[13],4,681279174),i=Xb(i,n,r,a,t[0],11,-358537222),a=Xb(a,i,n,r,t[3],16,-722521979),r=Xb(r,a,i,n,t[6],23,76029189),n=Xb(n,r,a,i,t[9],4,-640364487),i=Xb(i,n,r,a,t[12],11,-421815835),a=Xb(a,i,n,r,t[15],16,530742520),n=Qb(n,r=Xb(r,a,i,n,t[2],23,-995338651),a,i,t[0],6,-198630844),i=Qb(i,n,r,a,t[7],10,1126891415),a=Qb(a,i,n,r,t[14],15,-1416354905),r=Qb(r,a,i,n,t[5],21,-57434055),n=Qb(n,r,a,i,t[12],6,1700485571),i=Qb(i,n,r,a,t[3],10,-1894986606),a=Qb(a,i,n,r,t[10],15,-1051523),r=Qb(r,a,i,n,t[1],21,-2054922799),n=Qb(n,r,a,i,t[8],6,1873313359),i=Qb(i,n,r,a,t[15],10,-30611744),a=Qb(a,i,n,r,t[6],15,-1560198380),r=Qb(r,a,i,n,t[13],21,1309151649),n=Qb(n,r,a,i,t[4],6,-145523070),i=Qb(i,n,r,a,t[11],10,-1120210379),a=Qb(a,i,n,r,t[2],15,718787259),r=Qb(r,a,i,n,t[9],21,-343485551),s[0]=jI(n,s[0]),s[1]=jI(r,s[1]),s[2]=jI(a,s[2]),s[3]=jI(i,s[3])}function MDe(s,t,n,r,a,i){return t=jI(jI(t,s),jI(r,i)),jI(t<>>32-a,n)}function Yb(s,t,n,r,a,i,l){return MDe(t&n|~t&r,s,t,a,i,l)}function Zb(s,t,n,r,a,i,l){return MDe(t&r|n&~r,s,t,a,i,l)}function Xb(s,t,n,r,a,i,l){return MDe(t^n^r,s,t,a,i,l)}function Qb(s,t,n,r,a,i,l){return MDe(n^(t|~r),s,t,a,i,l)}function Kts(s){var t,n=s.length,r=[1732584193,-271733879,-1732584194,271733878];for(t=64;t<=s.length;t+=64)w$e(r,dWn(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(w$e(r,a),t=0;t<16;t++)a[t]=0;return a[14]=8*n,w$e(r,a),r}function dWn(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 S4t="0123456789abcdef".split("");function uWn(s){for(var t="",n=0;n<4;n++)t+=S4t[s>>8*n+4&15]+S4t[s>>8*n&15];return t}function hWn(s){return String.fromCharCode(255&s,(65280&s)>>8,(16711680&s)>>16,(4278190080&s)>>24)}function cZe(s){return Kts(s).map(hWn).join("")}var mWn=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 dZe(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=cZe(i+this.O+this.lsbFirstWord(this.P)+this.hexToBytes(r)).substr(0,5),this.U=dZe(this.encryptionKey,this.padding)}function wU(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 A4t(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 cPe(s){if(!(this instanceof cPe))return new cPe(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 Yts(s,t){this.gState=s,this.matrix=t,this.id="",this.objectNumber=-1}function XO(s,t,n,r,a){if(!(this instanceof XO))return new XO(s,t,n,r,a);this.type=s==="axial"?2:3,this.coords=t,this.colors=n,Yts.call(this,r,a)}function dq(s,t,n,r,a){if(!(this instanceof dq))return new dq(s,t,n,r,a);this.boundingBox=s,this.xStep=t,this.yStep=n,this.stream="",this.cloneIndex=0,Yts.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=A4t;var g="1.3",x=f.__private__.getPdfVersion=function(){return g};f.__private__.setPdfVersion=function(et){g=et};var y={a0:[2383.94,3370.39],a1:[1683.78,2383.94],a2:[1190.55,1683.78],a3:[841.89,1190.55],a4:[595.28,841.89],a5:[419.53,595.28],a6:[297.64,419.53],a7:[209.76,297.64],a8:[147.4,209.76],a9:[104.88,147.4],a10:[73.7,104.88],b0:[2834.65,4008.19],b1:[2004.09,2834.65],b2:[1417.32,2004.09],b3:[1000.63,1417.32],b4:[708.66,1000.63],b5:[498.9,708.66],b6:[354.33,498.9],b7:[249.45,354.33],b8:[175.75,249.45],b9:[124.72,175.75],b10:[87.87,124.72],c0:[2599.37,3676.54],c1:[1836.85,2599.37],c2:[1298.27,1836.85],c3:[918.43,1298.27],c4:[649.13,918.43],c5:[459.21,649.13],c6:[323.15,459.21],c7:[229.61,323.15],c8:[161.57,229.61],c9:[113.39,161.57],c10:[79.37,113.39],dl:[311.81,623.62],letter:[612,792],"government-letter":[576,756],legal:[612,1008],"junior-legal":[576,360],ledger:[1224,792],tabloid:[792,1224],"credit-card":[153,243]};f.__private__.getPageFormats=function(){return y};var v=f.__private__.getPageFormat=function(et){return y[et]};a=a||"a4";var b="compat",w="advanced",S=b;function A(){this.saveGraphicsState(),Ae(new Rs(ts,0,0,-ts,0,yr()*ts).toString()+" cm"),this.setFontSize(this.getFontSize()/ts),d="n",S=w}function E(){this.restoreGraphicsState(),d="S",S=b}var I=f.__private__.combineFontStyleAndFontWeight=function(et,Vt){if(et=="bold"&&Vt=="normal"||et=="bold"&&Vt==400||et=="normal"&&Vt=="italic"||et=="bold"&&Vt=="italic")throw new Error("Invalid Combination of fontweight and fontstyle");return Vt&&(et=Vt==400||Vt==="normal"?et==="italic"?"italic":"normal":Vt!=700&&Vt!=="bold"||et!=="normal"?(Vt==700?"bold":Vt)+""+et:"bold"),et};f.advancedAPI=function(et){var Vt=S===b;return Vt&&A.call(this),typeof et!="function"||(et(this),Vt&&E.call(this)),this},f.compatAPI=function(et){var Vt=S===w;return Vt&&E.call(this),typeof et!="function"||(et(this),Vt&&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,Vt){var Es=t||Vt;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*ts:S===w?et:void 0},V=function(et){return W(function(Vt){return S===b?yr()-Vt:S===w?Vt:void 0}(et))};f.__private__.setPrecision=f.setPrecision=function(et){typeof parseInt(et,10)=="number"&&(t=parseInt(et,10))};var G,Y="00000000000000000000000000000000",X=f.__private__.getFileId=function(){return Y},ae=f.__private__.setFileId=function(et){return Y=et!==void 0&&/^[a-fA-F0-9]{32}$/.test(et)?et.toUpperCase():Y.split("").map(function(){return"ABCDEF0123456789".charAt(Math.floor(16*Math.random()))}).join(""),u!==null&&(yc=new _U(u.userPermissions,u.userPassword,u.ownerPassword,Y)),Y};f.setFileId=function(et){return ae(et),this},f.getFileId=function(){return X()};var le=f.__private__.convertDateToPDFDate=function(et){var Vt=et.getTimezoneOffset(),Es=Vt<0?"+":"-",ln=Math.floor(Math.abs(Vt/60)),tn=Math.abs(Vt%60),sr=[Es,_e(ln),"'",_e(tn),"'"].join("");return["D:",et.getFullYear(),_e(et.getMonth()+1),_e(et.getDate()),_e(et.getHours()),_e(et.getMinutes()),_e(et.getSeconds()),sr].join("")},ne=f.__private__.convertPDFDateToDate=function(et){var Vt=parseInt(et.substr(2,4),10),Es=parseInt(et.substr(6,2),10)-1,ln=parseInt(et.substr(8,2),10),tn=parseInt(et.substr(10,2),10),sr=parseInt(et.substr(12,2),10),nr=parseInt(et.substr(14,2),10);return new Date(Vt,Es,ln,tn,sr,nr,0)},te=f.__private__.setCreationDate=function(et){var Vt;if(et===void 0&&(et=new Date),et instanceof Date)Vt=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");Vt=et}return G=Vt},J=f.__private__.getCreationDate=function(et){var Vt=G;return et==="jsDate"&&(Vt=ne(G)),Vt};f.setCreationDate=function(et){return te(et),this},f.getCreationDate=function(et){return J(et)};var ce,_e=f.__private__.padd2=function(et){return("0"+parseInt(et)).slice(-2)},he=f.__private__.padd2Hex=function(et){return("00"+(et=et.toString())).substr(et.length)},ue=0,ve=[],Ee=[],Se=0,Le=[],Fe=[],ke=!1,Be=Ee;f.__private__.setCustomOutputDestination=function(et){ke=!0,Be=et};var Ne=function(et){ke||(Be=et)};f.__private__.resetCustomOutputDestination=function(){ke=!1,Be=Ee};var Ae=f.__private__.out=function(et){return et=et.toString(),Se+=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," "))},Ve=f.__private__.getArrayBuffer=function(et){for(var Vt=et.length,Es=new ArrayBuffer(Vt),ln=new Uint8Array(Es);Vt--;)ln[Vt]=et.charCodeAt(Vt);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 qe=s.fontSize||16;f.__private__.setFontSize=f.setFontSize=function(et){return qe=S===w?et/ts:et,this};var dt,Xe=f.__private__.getFontSize=f.getFontSize=function(){return S===b?qe:qe*ts},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))dt=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.');dt=et}else dt=parseInt(et,10)};f.__private__.getZoomMode=function(){return dt};var Je,pt=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,Vt,Es){return Ke(et),gt(Vt),pt(Es),this};var ss={title:"",subject:"",author:"",keywords:"",creator:""};f.__private__.getDocumentProperty=function(et){if(Object.keys(ss).indexOf(et)===-1)throw new Error("Invalid argument passed to jsPDF.getDocumentProperty");return ss[et]},f.__private__.getDocumentProperties=function(){return ss},f.__private__.setDocumentProperties=f.setProperties=f.setDocumentProperties=function(et){for(var Vt in ss)ss.hasOwnProperty(Vt)&&et[Vt]&&(ss[Vt]=et[Vt]);return this},f.__private__.setDocumentProperty=function(et,Vt){if(Object.keys(ss).indexOf(et)===-1)throw new Error("Invalid arguments passed to jsPDF.setDocumentProperty");return ss[et]=Vt};var Yt,ts,ys,Bt,Ft,as={},kt={},Ks=[],wt={},gs={},ks={},Is={},Xs=null,ds=0,Ss=[],yn=new A4t(f),Js=s.hotfixes||[],Ut={},hn={},hr=[],Rs=function et(Vt,Es,ln,tn,sr,nr){if(!(this instanceof et))return new et(Vt,Es,ln,tn,sr,nr);isNaN(Vt)&&(Vt=1),isNaN(Es)&&(Es=0),isNaN(ln)&&(ln=0),isNaN(tn)&&(tn=1),isNaN(sr)&&(sr=0),isNaN(nr)&&(nr=0),this._matrix=[Vt,Es,ln,tn,sr,nr]};Object.defineProperty(Rs.prototype,"sx",{get:function(){return this._matrix[0]},set:function(et){this._matrix[0]=et}}),Object.defineProperty(Rs.prototype,"shy",{get:function(){return this._matrix[1]},set:function(et){this._matrix[1]=et}}),Object.defineProperty(Rs.prototype,"shx",{get:function(){return this._matrix[2]},set:function(et){this._matrix[2]=et}}),Object.defineProperty(Rs.prototype,"sy",{get:function(){return this._matrix[3]},set:function(et){this._matrix[3]=et}}),Object.defineProperty(Rs.prototype,"tx",{get:function(){return this._matrix[4]},set:function(et){this._matrix[4]=et}}),Object.defineProperty(Rs.prototype,"ty",{get:function(){return this._matrix[5]},set:function(et){this._matrix[5]=et}}),Object.defineProperty(Rs.prototype,"a",{get:function(){return this._matrix[0]},set:function(et){this._matrix[0]=et}}),Object.defineProperty(Rs.prototype,"b",{get:function(){return this._matrix[1]},set:function(et){this._matrix[1]=et}}),Object.defineProperty(Rs.prototype,"c",{get:function(){return this._matrix[2]},set:function(et){this._matrix[2]=et}}),Object.defineProperty(Rs.prototype,"d",{get:function(){return this._matrix[3]},set:function(et){this._matrix[3]=et}}),Object.defineProperty(Rs.prototype,"e",{get:function(){return this._matrix[4]},set:function(et){this._matrix[4]=et}}),Object.defineProperty(Rs.prototype,"f",{get:function(){return this._matrix[5]},set:function(et){this._matrix[5]=et}}),Object.defineProperty(Rs.prototype,"rotation",{get:function(){return Math.atan2(this.shx,this.sx)}}),Object.defineProperty(Rs.prototype,"scaleX",{get:function(){return this.decompose().scale.sx}}),Object.defineProperty(Rs.prototype,"scaleY",{get:function(){return this.decompose().scale.sy}}),Object.defineProperty(Rs.prototype,"isIdentity",{get:function(){return this.sx===1&&this.shy===0&&this.shx===0&&this.sy===1&&this.tx===0&&this.ty===0}}),Rs.prototype.join=function(et){return[this.sx,this.shy,this.shx,this.sy,this.tx,this.ty].map(P).join(et)},Rs.prototype.multiply=function(et){var Vt=et.sx*this.sx+et.shy*this.shx,Es=et.sx*this.shy+et.shy*this.sy,ln=et.shx*this.sx+et.sy*this.shx,tn=et.shx*this.shy+et.sy*this.sy,sr=et.tx*this.sx+et.ty*this.shx+this.tx,nr=et.tx*this.shy+et.ty*this.sy+this.ty;return new Rs(Vt,Es,ln,tn,sr,nr)},Rs.prototype.decompose=function(){var et=this.sx,Vt=this.shy,Es=this.shx,ln=this.sy,tn=this.tx,sr=this.ty,nr=Math.sqrt(et*et+Vt*Vt),Qr=(et/=nr)*Es+(Vt/=nr)*ln;Es-=et*Qr,ln-=Vt*Qr;var na=Math.sqrt(Es*Es+ln*ln);return Qr/=na,et*(ln/=na)>16&255,ln=na>>8&255,tn=255&na}if(ln===void 0||sr===void 0&&Es===ln&&ln===tn)Vt=typeof Es=="string"?Es+" "+nr[0]:et.precision===2?O(Es/255)+" "+nr[0]:U(Es/255)+" "+nr[0];else if(sr===void 0||Tm(sr)==="object"){if(sr&&!isNaN(sr.a)&&sr.a===0)return["1.","1.","1.",nr[1]].join(" ");Vt=typeof Es=="string"?[Es,ln,tn,nr[1]].join(" "):et.precision===2?[O(Es/255),O(ln/255),O(tn/255),nr[1]].join(" "):[U(Es/255),U(ln/255),U(tn/255),nr[1]].join(" ")}else Vt=typeof Es=="string"?[Es,ln,tn,sr,nr[2]].join(" "):et.precision===2?[O(Es),O(ln),O(tn),O(sr),nr[2]].join(" "):[U(Es),U(ln),U(tn),U(sr),nr[2]].join(" ");return Vt},Un=f.__private__.getFilters=function(){return l},dr=f.__private__.putStream=function(et){var Vt=(et=et||{}).data||"",Es=et.filters||Un(),ln=et.alreadyAppliedFilters||[],tn=et.addLength1||!1,sr=Vt.length,nr=et.objectId,Qr=function(Lo){return Lo};if(u!==null&&nr===void 0)throw new Error("ObjectId must be passed to putStream for file encryption");u!==null&&(Qr=yc.encryptor(nr,0));var na={};Es===!0&&(Es=["FlateEncode"]);var $a=et.additionalKeyValues||[],Na=(na=Go.API.processDataByFilters!==void 0?Go.API.processDataByFilters(Vt,Es):{data:Vt,reverseChain:[]}).reverseChain+(Array.isArray(ln)?ln.join(" "):ln.toString());if(na.data.length!==0&&($a.push({key:"Length",value:na.data.length}),tn===!0&&$a.push({key:"Length1",value:sr})),Na.length!=0)if(Na.split("/").length-1==1)$a.push({key:"Filter",value:Na});else{$a.push({key:"Filter",value:"["+Na+"]"});for(var La=0;La<$a.length;La+=1)if($a[La].key==="DecodeParms"){for(var to=[],xo=0;xo>"),na.data.length!==0&&(Ae("stream"),Ae(Qr(na.data)),Ae("endstream"))},Pa=f.__private__.putPage=function(et){var Vt=et.number,Es=et.data,ln=et.objId,tn=et.contentsObjId;xs(ln,!0),Ae("<>"),Ae("endobj");var sr=Es.join(` `);return S===w&&(sr+=` Q`),xs(tn,!0),dr({data:sr,filters:Un(),objectId:tn}),Ae("endobj"),ln},ii=f.__private__.putPages=function(){var et,Vt,Es=[];for(et=1;et<=ds;et++)Ss[et].objId=bn(),Ss[et].contentsObjId=bn();for(et=1;et<=ds;et++)Es.push(Pa({number:et,data:Fe[et],objId:Ss[et].objId,contentsObjId:Ss[et].contentsObjId,mediaBox:Ss[et].mediaBox,cropBox:Ss[et].cropBox,bleedBox:Ss[et].bleedBox,trimBox:Ss[et].trimBox,artBox:Ss[et].artBox,userUnit:Ss[et].userUnit,rootDictionaryObjId:Or,resourceDictionaryObjId:la}));xs(Or,!0),Ae("<>"),Ae("endobj"),yn.publish("postPutPages")},$i=function(et){yn.publish("putFont",{font:et,out:Ae,newObject:Fn,putStream:dr}),et.isAlreadyPutted!==!0&&(et.objectNumber=Fn(),Ae("<<"),Ae("/Type /Font"),Ae("/BaseFont /"+wU(et.postScriptName)),Ae("/Subtype /Type1"),typeof et.encoding=="string"&&Ae("/Encoding /"+et.encoding),Ae("/FirstChar 32"),Ae("/LastChar 255"),Ae(">>"),Ae("endobj"))},Rn=function(et){et.objectNumber=Fn();var Vt=[];Vt.push({key:"Type",value:"/XObject"}),Vt.push({key:"Subtype",value:"/Form"}),Vt.push({key:"BBox",value:"["+[P(et.x),P(et.y),P(et.x+et.width),P(et.y+et.height)].join(" ")+"]"}),Vt.push({key:"Matrix",value:"["+et.matrix.toString()+"]"});var Es=et.pages[1].join(` `);dr({data:Es,additionalKeyValues:Vt,objectId:et.objectNumber}),Ae("endobj")},xa=function(et,Vt){Vt||(Vt=21);var Es=Fn(),ln=function(nr,Qr){var na,$a=[],Na=1/(Qr-1);for(na=0;na<1;na+=Na)$a.push(na);if($a.push(1),nr[0].offset!=0){var La={offset:0,color:nr[0].color};nr.unshift(La)}if(nr[nr.length-1].offset!=1){var to={offset:1,color:nr[nr.length-1].color};nr.push(to)}for(var xo="",oo=0,Lo=0;Lo<$a.length;Lo++){for(na=$a[Lo];na>nr[oo+1].offset;)oo++;var Ul=nr[oo].offset,po=(na-Ul)/(nr[oo+1].offset-Ul),nl=nr[oo].color,Pl=nr[oo+1].color;xo+=he(Math.round((1-po)*nl[0]+po*Pl[0]).toString(16))+he(Math.round((1-po)*nl[1]+po*Pl[1]).toString(16))+he(Math.round((1-po)*nl[2]+po*Pl[2]).toString(16))}return xo.trim()}(et.colors,Vt),tn=[];tn.push({key:"FunctionType",value:"0"}),tn.push({key:"Domain",value:"[0.0 1.0]"}),tn.push({key:"Size",value:"["+Vt+"]"}),tn.push({key:"BitsPerSample",value:"8"}),tn.push({key:"Range",value:"[0.0 1.0 0.0 1.0 0.0 1.0]"}),tn.push({key:"Decode",value:"[0.0 1.0 0.0 1.0 0.0 1.0]"}),dr({data:ln,additionalKeyValues:tn,alreadyAppliedFilters:["/ASCIIHexDecode"],objectId:Es}),Ae("endobj"),et.objectNumber=Fn(),Ae("<< /ShadingType "+et.type),Ae("/ColorSpace /DeviceRGB");var sr="/Coords ["+P(parseFloat(et.coords[0]))+" "+P(parseFloat(et.coords[1]))+" ";et.type===2?sr+=P(parseFloat(et.coords[2]))+" "+P(parseFloat(et.coords[3])):sr+=P(parseFloat(et.coords[2]))+" "+P(parseFloat(et.coords[3]))+" "+P(parseFloat(et.coords[4]))+" "+P(parseFloat(et.coords[5])),Ae(sr+="]"),et.matrix&&Ae("/Matrix ["+et.matrix.toString()+"]"),Ae("/Function "+Es+" 0 R"),Ae("/Extend [true true]"),Ae(">>"),Ae("endobj")},Ya=function(et,Vt){var Es=bn(),ln=Fn();Vt.push({resourcesOid:Es,objectOid:ln}),et.objectNumber=ln;var tn=[];tn.push({key:"Type",value:"/Pattern"}),tn.push({key:"PatternType",value:"1"}),tn.push({key:"PaintType",value:"1"}),tn.push({key:"TilingType",value:"1"}),tn.push({key:"BBox",value:"["+et.boundingBox.map(P).join(" ")+"]"}),tn.push({key:"XStep",value:P(et.xStep)}),tn.push({key:"YStep",value:P(et.yStep)}),tn.push({key:"Resources",value:Es+" 0 R"}),et.matrix&&tn.push({key:"Matrix",value:"["+et.matrix.toString()+"]"}),dr({data:et.stream,additionalKeyValues:tn,objectId:et.objectNumber}),Ae("endobj")},ho=function(et){for(var Vt in et.objectNumber=Fn(),Ae("<<"),et)switch(Vt){case"opacity":Ae("/ca "+O(et[Vt]));break;case"stroke-opacity":Ae("/CA "+O(et[Vt]))}Ae(">>"),Ae("endobj")},Tc=function(et){xs(et.resourcesOid,!0),Ae("<<"),Ae("/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]"),function(){for(var Vt in Ae("/Font <<"),as)as.hasOwnProperty(Vt)&&(h===!1||h===!0&&m.hasOwnProperty(Vt))&&Ae("/"+Vt+" "+as[Vt].objectNumber+" 0 R");Ae(">>")}(),function(){if(Object.keys(wt).length>0){for(var Vt in Ae("/Shading <<"),wt)wt.hasOwnProperty(Vt)&&wt[Vt]instanceof XO&&wt[Vt].objectNumber>=0&&Ae("/"+Vt+" "+wt[Vt].objectNumber+" 0 R");yn.publish("putShadingPatternDict"),Ae(">>")}}(),function(Vt){if(Object.keys(wt).length>0){for(var Es in Ae("/Pattern <<"),wt)wt.hasOwnProperty(Es)&&wt[Es]instanceof f.TilingPattern&&wt[Es].objectNumber>=0&&wt[Es].objectNumber>")}}(et.objectOid),function(){if(Object.keys(ks).length>0){var Vt;for(Vt in Ae("/ExtGState <<"),ks)ks.hasOwnProperty(Vt)&&ks[Vt].objectNumber>=0&&Ae("/"+Vt+" "+ks[Vt].objectNumber+" 0 R");yn.publish("putGStateDict"),Ae(">>")}}(),function(){for(var Vt in Ae("/XObject <<"),Ut)Ut.hasOwnProperty(Vt)&&Ut[Vt].objectNumber>=0&&Ae("/"+Vt+" "+Ut[Vt].objectNumber+" 0 R");yn.publish("putXobjectDict"),Ae(">>")}(),Ae(">>"),Ae("endobj")},zd=function(et){kt[et.fontName]=kt[et.fontName]||{},kt[et.fontName][et.fontStyle]=et.id},Nl=function(et,Vt,Es,ln,tn){var sr={id:"F"+(Object.keys(as).length+1).toString(10),postScriptName:et,fontName:Vt,fontStyle:Es,encoding:ln,isStandardFont:tn||!1,metadata:{}};return yn.publish("addFont",{font:sr,instance:this}),as[sr.id]=sr,zd(sr),sr.id},Ho=f.__private__.pdfEscape=f.pdfEscape=function(et,Vt){return function(Es,ln){var tn,sr,nr,Qr,na,$a,Na,La,to;if(nr=(ln=ln||{}).sourceEncoding||"Unicode",na=ln.outputEncoding,(ln.autoencode||na)&&as[Yt].metadata&&as[Yt].metadata[nr]&&as[Yt].metadata[nr].encoding&&(Qr=as[Yt].metadata[nr].encoding,!na&&as[Yt].encoding&&(na=as[Yt].encoding),!na&&Qr.codePages&&(na=Qr.codePages[0]),typeof na=="string"&&(na=Qr[na]),na)){for(Na=!1,$a=[],tn=0,sr=Es.length;tn>8&&(Na=!0);Es=$a.join("")}for(tn=Es.length;Na===void 0&&tn!==0;)Es.charCodeAt(tn-1)>>8&&(Na=!0),tn--;if(!Na)return Es;for($a=ln.noBOM?[]:[254,255],tn=0,sr=Es.length;tn>8)>>8)throw new Error("Character at position "+tn+" of string '"+Es+"' exceeds 16bits. Cannot be encoded into UCS-2 BE");$a.push(to),$a.push(La-(to<<8))}return String.fromCharCode.apply(void 0,$a)}(et,Vt).replace(/\\/g,"\\\\").replace(/\(/g,"\\(").replace(/\)/g,"\\)")},ti=f.__private__.beginPage=function(et){Fe[++ds]=[],Ss[ds]={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(ds),Ne(Fe[ce])},Xr=function(et,Vt){var Es,ln,tn;switch(n=Vt||n,typeof et=="string"&&(Es=v(et.toLowerCase()),Array.isArray(Es)&&(ln=Es[0],tn=Es[1])),Array.isArray(et)&&(ln=et[0]*ts,tn=et[1]*ts),isNaN(ln)&&(ln=a[0],tn=a[1]),(ln>14400||tn>14400)&&(yf.warn("A page in a PDF can not be wider or taller than 14400 userUnit. jsPDF limits the width/height to 14400"),ln=Math.min(14400,ln),tn=Math.min(14400,tn)),a=[ln,tn],n.substr(0,1)){case"l":tn>ln&&(a=[tn,ln]);break;case"p":ln>tn&&(a=[tn,ln])}ti(a),Fl(vo),Ae(gh),zt!==0&&Ae(zt+" J"),Ht!==0&&Ae(Ht+" j"),yn.publish("addPage",{pageNumber:ds})},Eo=function(et){et>0&&et<=ds&&(Fe.splice(et,1),Ss.splice(et,1),ds--,ce>ds&&(ce=ds),this.setPage(ce))},Th=function(et){et>0&&et<=ds&&(ce=et)},ah=f.__private__.getNumberOfPages=f.getNumberOfPages=function(){return Fe.length-1},ao=function(et,Vt,Es){var ln,tn=void 0;return Es=Es||{},et=et!==void 0?et:as[Yt].fontName,Vt=Vt!==void 0?Vt:as[Yt].fontStyle,ln=et.toLowerCase(),kt[ln]!==void 0&&kt[ln][Vt]!==void 0?tn=kt[ln][Vt]:kt[et]!==void 0&&kt[et][Vt]!==void 0?tn=kt[et][Vt]:Es.disableWarning===!1&&yf.warn("Unable to look up font label for font '"+et+"', '"+Vt+"'. Refer to getFontList() for available fonts."),tn||Es.noFallback||(tn=kt.times[Vt])==null&&(tn=kt.times.normal),tn},ta=f.__private__.putInfo=function(){var et=Fn(),Vt=function(ln){return ln};for(var Es in u!==null&&(Vt=yc.encryptor(et,0)),Ae("<<"),Ae("/Producer ("+Ho(Vt("jsPDF "+Go.version))+")"),ss)ss.hasOwnProperty(Es)&&ss[Es]&&Ae("/"+Es.substr(0,1).toUpperCase()+Es.substr(1)+" ("+Ho(Vt(ss[Es]))+")");Ae("/CreationDate ("+Ho(Vt(G))+")"),Ae(">>"),Ae("endobj")},xc=f.__private__.putCatalog=function(et){var Vt=(et=et||{}).rootDictionaryObjId||Or;switch(Fn(),Ae("<<"),Ae("/Type /Catalog"),Ae("/Pages "+Vt+" 0 R"),dt||(dt="fullwidth"),dt){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=""+dt;Es.substr(Es.length-1)==="%"&&(dt=parseInt(dt)/100),typeof dt=="number"&&Ae("/OpenAction [3 0 R /XYZ null null "+O(dt)+"]")}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),yn.publish("putCatalog"),Ae(">>"),Ae("endobj")},fl=f.__private__.putTrailer=function(){Ae("trailer"),Ae("<<"),Ae("/Size "+(ue+1)),Ae("/Root "+ue+" 0 R"),Ae("/Info "+(ue-1)+" 0 R"),u!==null&&Ae("/Encrypt "+yc.oid+" 0 R"),Ae("/ID [ <"+Y+"> <"+Y+"> ]"),Ae(">>")},Co=f.__private__.putHeader=function(){Ae("%PDF-"+g),Ae("%ºß¬à")},fu=f.__private__.putXRef=function(){var et="0000000000";Ae("xref"),Ae("0 "+(ue+1)),Ae("0000000000 65535 f ");for(var Vt=1;Vt<=ue;Vt++)typeof ve[Vt]=="function"?Ae((et+ve[Vt]()).slice(-10)+" 00000 n "):ve[Vt]!==void 0?Ae((et+ve[Vt]).slice(-10)+" 00000 n "):Ae("0000000000 00000 n ")},cc=f.__private__.buildDocument=function(){var et;ue=0,Se=0,Ee=[],ve=[],Le=[],Or=bn(),la=bn(),Ne(Ee),yn.publish("buildDocument"),Co(),ii(),function(){yn.publish("putAdditionalObjects");for(var Es=0;Es"),Ae("/O <"+yc.toHexString(yc.O)+">"),Ae("/P "+yc.P),Ae(">>"),Ae("endobj")),ta(),xc();var Vt=Se;return fu(),fl(),Ae("startxref"),Ae(""+Vt),Ae("%%EOF"),Ne(Fe[ce]),Ee.join(` `)},nd=f.__private__.getBlob=function(et){return new Blob([Ve(et)],{type:"application/pdf"})},zr=function(et){for(;et.firstChild;)et.removeChild(et.firstChild)},Hi=function(et){var Vt,Es=et.document,ln=Es.documentElement,tn=Es.head,sr=Es.body;return tn||(tn=Es.createElement("head"),ln.appendChild(tn)),sr||(sr=Es.createElement("body"),ln.appendChild(sr)),zr(tn),zr(sr),(Vt=Es.createElement("style")).appendChild(Es.createTextNode("html, body { padding: 0; margin: 0; } iframe { width: 100%; height: 100%; border: 0;}")),tn.appendChild(Vt),{document:Es,body:sr}},zc=f.output=f.__private__.output=(kn=function(et,Vt){switch(typeof(Vt=Vt||{})=="string"?Vt={filename:Vt}:Vt.filename=Vt.filename||"generated.pdf",et){case void 0:return cc();case"save":f.save(Vt.filename);break;case"arraybuffer":return Ve(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="",ln=cc();try{Es=k4t(ln)}catch{Es=k4t(unescape(encodeURIComponent(ln)))}return"data:application/pdf;filename="+encodeURIComponent(Vt.filename)+";base64,"+Es;case"pdfobjectnewwindow":if(Object.prototype.toString.call(Dc)==="[object Window]"){var tn="https://cdnjs.cloudflare.com/ajax/libs/pdfobject/2.1.1/pdfobject.min.js",sr=!Vt.pdfObjectUrl;sr||(tn=Vt.pdfObjectUrl);var nr=Dc.open();if(nr!==null){var Qr=Hi(nr),na=Qr.document.createElement("script"),$a=this;na.src=tn,sr&&(na.integrity="sha512-4ze/a9/4jqu+tX9dfOqJYSvyYd5M6qum/3HpCLr+/Jqf0whc37VUbkpNGHR7/8pSnCFw47T1fmIpwBV7UySh3g==",na.crossOrigin="anonymous"),na.onload=function(){nr.PDFObject.embed($a.output("dataurlstring"),Vt)},Qr.body.appendChild(na)}return nr}throw new Error("The option pdfobjectnewwindow just works in a browser-environment.");case"pdfjsnewwindow":if(Object.prototype.toString.call(Dc)==="[object Window]"){var Na=Vt.pdfJsUrl||"examples/PDF.js/web/viewer.html",La=Dc.open();if(La!==null){var to=Hi(La),xo=to.document.createElement("iframe"),oo=Na.indexOf("?")===-1?"?":"&";$a=this,xo.id="pdfViewer",xo.width="500px",xo.height="400px",xo.src=Na+oo+"file=&downloadName="+encodeURIComponent(Vt.filename),xo.onload=function(){La.document.title=Vt.filename,xo.contentWindow.PDFViewerApplication.open($a.output("bloburl"))},to.body.appendChild(xo)}return La}throw new Error("The option pdfjsnewwindow just works in a browser-environment.");case"dataurlnewwindow":if(Object.prototype.toString.call(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),po=Ul.document.createElement("iframe");po.src=this.output("datauristring",Vt),Ul.body.appendChild(po),Lo.document.title=Vt.filename}if(Lo||typeof safari>"u")return Lo;break;case"datauri":case"dataurl":return Dc.document.location.href=this.output("datauristring",Vt);default:return null}},kn.foo=function(){try{return kn.apply(this,arguments)}catch(Es){var et=Es.stack||"";~et.indexOf(" at ")&&(et=et.split(" at ")[1]);var Vt="Error in function "+et.split(` `)[0].split("<")[0]+": "+Es.message;if(!Dc.console)throw new Error(Vt);Dc.console.error(Vt,Es),Dc.alert&&alert(Vt)}},kn.foo.bar=kn,kn.foo),Bc=function(et){return Array.isArray(Js)===!0&&Js.indexOf(et)>-1};switch(r){case"pt":ts=1;break;case"mm":ts=72/25.4;break;case"cm":ts=72/2.54;break;case"in":ts=72;break;case"px":ts=Bc("px_scaling")==1?.75:96/72;break;case"pc":case"em":ts=12;break;case"ex":ts=6;break;default:if(typeof r!="number")throw new Error("Invalid unit: "+r);ts=r}var yc=null;te(),ae();var $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:Ss[et].objId,pageNumber:et,pageContext:Ss[et]}},rg=f.__private__.getPageInfoByObjId=function(et){if(isNaN(et)||et%1!=0)throw new Error("Invalid argument passed to jsPDF.getPageInfoByObjId");for(var Vt in Ss)if(Ss[Vt].objId===et)break;return $l(Vt)},Ix=f.__private__.getCurrentPageInfo=f.getCurrentPageInfo=function(){return{objId:Ss[ce].objId,pageNumber:ce,pageContext:Ss[ce]}};f.addPage=function(){return Xr.apply(this,arguments),this},f.setPage=function(){return Th.apply(this,arguments),Ne.call(this,Fe[ce]),this},f.insertPage=function(et){return this.addPage(),this.movePage(ce,et),this},f.movePage=function(et,Vt){var Es,ln;if(et>Vt){Es=Fe[et],ln=Ss[et];for(var tn=et;tn>Vt;tn--)Fe[tn]=Fe[tn-1],Ss[tn]=Ss[tn-1];Fe[Vt]=Es,Ss[Vt]=ln,this.setPage(Vt)}else if(et0&&(typeof et=="string"?et=oo.splitTextToSize(et,Na):Object.prototype.toString.call(et)==="[object Array]"&&(et=et.reduce(function(Ro,kl){return Ro.concat(oo.splitTextToSize(kl,Na))},[]))),sr={text:et,x:Vt,y:Es,options:ln,mutex:{pdfEscape:Ho,activeFontKey:Yt,fonts:as,activeFontSize:qe}},yn.publish("preProcessText",sr),et=sr.text,Qr=(ln=sr.options).angle,xo instanceof Rs==0&&Qr&&typeof Qr=="number"){Qr*=Math.PI/180,ln.rotationDirection===0&&(Qr=-Qr),S===w&&(Qr=-Qr);var el=Math.cos(Qr),zo=Math.sin(Qr);xo=new Rs(el,zo,-zo,el,0,0)}else Qr&&Qr instanceof Rs&&(xo=Qr);S!==w||xo||(xo=kr),($a=ln.charSpace||jt)!==void 0&&(po+=P(W($a))+` Tc `,this.setCharSpace(this.getCharSpace()||0)),(to=ln.horizontalScale)!==void 0&&(po+=P(100*to)+` Tz `),ln.lang;var Pc=-1,Tu=ln.renderingMode!==void 0?ln.renderingMode:ln.stroke,iu=oo.internal.getCurrentPageInfo().pageContext;switch(Tu){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?po+=Pc+` Tr `:dm!==-1&&(po+=`0 Tr `),Pc!==-1&&(iu.usedRenderingMode=Pc),na=ln.align||"left";var Ad,pu=qe*nl,Zc=oo.internal.pageSize.getWidth(),rd=as[Yt];$a=ln.charSpace||jt,Na=ln.maxWidth||0,La=Object.assign({autoencode:!0,noBOM:!0},ln.flags);var oh=[],Pf=function(Ro){return oo.getStringUnitWidth(Ro,{font:rd,charSpace:$a,fontSize:qe,doKerning:!1})*qe/Pl};if(Object.prototype.toString.call(et)==="[object Array]"){var Bd;nr=au(et),na!=="left"&&(Ad=nr.map(Pf));var ad,Ph=0;if(na==="right"){Vt-=Ad[0],et=[],Aa=nr.length;for(var Hu=0;Hu0?(Na-Ad[Xi])/Ep:0;Xi":")"),ya=parseFloat(nr[Gu][1]),Yy=parseFloat(nr[Gu][2]);break;case 0:Ci=(Ul?"<":"(")+nr[Gu]+(Ul?">":")"),ya=Vh(Vt),Yy=cf(Es)}oh!==void 0&&oh[Gu]!==void 0&&(Om=oh[Gu]+` Tw `),Gu===0?et.push(Om+Rx(ya,Yy,xo)+Ci):Xg===0?et.push(Om+Ci):Xg===1&&et.push(Om+Rx(ya,Yy,xo)+Ci)}et=Xg===0?et.join(` Tj T* `):et.join(` Tj `),et+=` Tj `;var kc=`BT /`;return kc+=Yt+" "+qe+` Tf `,kc+=P(qe*nl)+` TL `,kc+=We+` `,kc+=po,kc+=et,Ae(kc+="ET"),m[Yt]=!0,oo};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 Vt=!1;return[void 0,null,"S","D","F","DF","FD","f","f*","B","B*","n"].indexOf(et)!==-1&&(Vt=!0),Vt};f.__private__.setDefaultPathOperation=f.setDefaultPathOperation=function(et){return Mc(et)&&(d=et),this};var Mh=f.__private__.getStyle=f.getStyle=function(et){var Vt=d;switch(et){case"D":case"S":Vt="S";break;case"F":Vt="f";break;case"FD":case"DF":Vt="B";break;case"f":case"f*":case"B":case"B*":Vt=et}return Vt},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,Vt){Tm(Vt)==="object"?No(Vt,et):Ae(et)},_s=function(et){et===null||S===w&&et===void 0||(et=Mh(et),Ae(et))};function Xa(et,Vt,Es,ln,tn){var sr=new dq(Vt||this.boundingBox,Es||this.xStep,ln||this.yStep,this.gState,tn||this.matrix);sr.stream=this.stream;var nr=et+"$$"+this.cloneIndex+++"$$";return $n(nr,sr),sr}var No=function(et,Vt){var Es=gs[et.key],ln=wt[Es];if(ln instanceof XO)Ae("q"),Ae(Ba(Vt)),ln.gState&&f.setGState(ln.gState),Ae(et.matrix.toString()+" cm"),Ae("/"+Es+" sh"),Ae("Q");else if(ln instanceof dq){var tn=new Rs(1,0,0,-1,0,yr());et.matrix&&(tn=tn.multiply(et.matrix||kr),Es=Xa.call(ln,et.key,et.boundingBox,et.xStep,et.yStep,tn).id),Ae("q"),Ae("/Pattern cs"),Ae("/"+Es+" scn"),ln.gState&&f.setGState(ln.gState),Ae(Vt),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"}},io=f.moveTo=function(et,Vt){return Ae(P(W(et))+" "+P(V(Vt))+" m"),this},ko=f.lineTo=function(et,Vt){return Ae(P(W(et))+" "+P(V(Vt))+" l"),this},qi=f.curveTo=function(et,Vt,Es,ln,tn,sr){return Ae([P(W(et)),P(V(Vt)),P(W(Es)),P(V(ln)),P(W(tn)),P(V(sr)),"c"].join(" ")),this};f.__private__.line=f.line=function(et,Vt,Es,ln,tn){if(isNaN(et)||isNaN(Vt)||isNaN(Es)||isNaN(ln)||!Mc(tn))throw new Error("Invalid arguments passed to jsPDF.line");return S===b?this.lines([[Es-et,ln-Vt]],et,Vt,[1,1],tn||"S"):this.lines([[Es-et,ln-Vt]],et,Vt,[1,1]).stroke()},f.__private__.lines=f.lines=function(et,Vt,Es,ln,tn,sr){var nr,Qr,na,$a,Na,La,to,xo,oo,Lo,Ul,po;if(typeof et=="number"&&(po=Es,Es=Vt,Vt=et,et=po),ln=ln||[1,1],sr=sr||!1,isNaN(Vt)||isNaN(Es)||!Array.isArray(et)||!Array.isArray(ln)||!Mc(tn)||typeof sr!="boolean")throw new Error("Invalid arguments passed to jsPDF.lines");for(io(Vt,Es),nr=ln[0],Qr=ln[1],$a=et.length,Lo=Vt,Ul=Es,na=0;na<$a;na++)(Na=et[na]).length===2?(Lo=Na[0]*nr+Lo,Ul=Na[1]*Qr+Ul,ko(Lo,Ul)):(La=Na[0]*nr+Lo,to=Na[1]*Qr+Ul,xo=Na[2]*nr+Lo,oo=Na[3]*Qr+Ul,Lo=Na[4]*nr+Lo,Ul=Na[5]*Qr+Ul,qi(La,to,xo,oo,Lo,Ul));return sr&&lm(),_s(tn),this},f.path=function(et){for(var Vt=0;Vt>8&255,s>>16&255,s>>24&255)},_U.prototype.toHexString=function(s){return s.split("").map(function(t){return("0"+(255&t.charCodeAt(0)).toString(16)).slice(-2)}).join("")},_U.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 dZe(n,r)}},cPe.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 mx=Go.API,wot=1,o9=function(s){return s.replace(/\\/g,"\\\\").replace(/\(/g,"\\(").replace(/\)/g,"\\)")},U$=function(s){return s.replace(/\\\\/g,"\\").replace(/\\\(/g,"(").replace(/\\\)/g,")")},mB=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)},AM=function(s){return s.toFixed(5)};mx.__acroform__={};var Ww=function(s,t){s.prototype=Object.create(t.prototype),s.prototype.constructor=s},E4t=function(s){return s*wot},y5=function(s){var t=new Xts,n=$o.internal.getHeight(s)||0,r=$o.internal.getWidth(s)||0;return t.BBox=[0,0,Number(od(r)),Number(od(n))],t},fWn=mx.__acroform__.setBit=function(s,t){if(s=s||0,t=t||0,isNaN(s)||isNaN(t))throw new Error("Invalid arguments passed to jsPDF.API.__acroform__.setBit");return s|1<0;){t="",i--;var d,u,h=Sue("3",s,i).height,m=s.multiline?l-i:(l-h)/2,f=m+=2,g=0,x=0,y=0;if(i<=0){t=`(...) Tj `,t+="% Width of Text: "+Sue(t,s,i=12).width+", FieldWidth:"+o+` `;break}for(var v="",b=0,w=0;wl)continue e;v+=a[w][y],S=!0,x=w,w--}else{v=(v+=a[w][y]+" ").substr(v.length-1)==" "?v.substr(0,v.length-1):v;var A=parseInt(w),E=c(A,v,i),I=w>=a.length-1;if(E&&!I){v+=" ",y=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[y]+" ",y=(y+1)%D.length;continue}if(R===g){P+=D[D.length-1]+" ";continue}}P+=D[0]+" "}switch(P=P.substr(P.length-1)==" "?P.substr(0,P.length-1):P,u=Sue(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+="("+o9(P)+`) Tj `,t+=-od(d)+` 0 Td `,f=-(i+2),u=0,g=S?x:x+1,b++,v=""}break}return r.text=t,r.fontSize=i,r},Sue=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}},vWn={fields:[],xForms:[],acroFormDictionaryRoot:null,printedOut:!1,internal:null,isInitialized:!1},bWn=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)},_Wn=function(s,t){if(t.scope=s,s.internal!==void 0&&(s.internal.acroformPlugin===void 0||s.internal.acroformPlugin.isInitialized===!1)){if(EC.FieldNum=0,s.internal.acroformPlugin=JSON.parse(JSON.stringify(vWn)),s.internal.acroformPlugin.acroFormDictionaryRoot)throw new Error("Exception while creating AcroformDictionary");wot=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&&bWn(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=xWn(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=yWn(o);c.push({key:"AP",value:"<>"}),a.internal.acroformPlugin.xForms.push(u)}if(o.appearanceStreamContent){var h="";for(var m in o.appearanceStreamContent)if(o.appearanceStreamContent.hasOwnProperty(m)){var f=o.appearanceStreamContent[m];if(h+="/"+m+" ",h+="<<",Object.keys(f).length>=1||Array.isArray(f)){for(var l in f)if(f.hasOwnProperty(l)){var g=f[l];typeof g=="function"&&(g=g.call(a,o)),h+="/"+l+" "+g+" ",a.internal.acroformPlugin.xForms.indexOf(g)>=0||a.internal.acroformPlugin.xForms.push(g)}}else typeof(g=f)=="function"&&(g=g.call(a,o)),h+="/"+l+" "+g,a.internal.acroformPlugin.xForms.indexOf(g)>=0||a.internal.acroformPlugin.xForms.push(g);h+=">>"}c.push({key:"AP",value:`<< `+h+">>"})}a.internal.putStream({additionalKeyValues:c,objectId:o.objId}),a.internal.out("endobj")}i&&function(x,y){for(var v in x)if(x.hasOwnProperty(v)){var b=v,w=x[v];y.internal.newObjectDeferredBegin(w.objId,!0),Tm(w)==="object"&&typeof w.putStream=="function"&&w.putStream(),delete x[b]}}(a.internal.acroformPlugin.xForms,a)})(n,s)}),s.internal.acroformPlugin.isInitialized=!0}},Zts=mx.__acroform__.arrayToPdfArray=function(s,t,n){var r=function(l){return l};if(Array.isArray(s)){for(var a="[",i=0;i0?t:void 0}}),Object.defineProperty(this,"Fields",{enumerable:!1,configurable:!1,get:function(){return t}}),Object.defineProperty(this,"DA",{enumerable:!1,configurable:!1,get:function(){if(s){var n=function(r){return r};return this.scope&&(n=this.scope.internal.getEncryptor(this.objId)),"("+o9(n(s))+")"}},set:function(n){s=n}})};Ww(Qts,b4);var EC=function s(){b4.call(this);var t=4;Object.defineProperty(this,"F",{enumerable:!1,configurable:!1,get:function(){return t},set:function(v){if(isNaN(v))throw new Error('Invalid value "'+v+'" for attribute F supplied.');t=v}}),Object.defineProperty(this,"showWhenPrinted",{enumerable:!0,configurable:!0,get:function(){return!!ty(t,3)},set:function(v){v?this.F=sy(t,3):this.F=ny(t,3)}});var n=0;Object.defineProperty(this,"Ff",{enumerable:!1,configurable:!1,get:function(){return n},set:function(v){if(isNaN(v))throw new Error('Invalid value "'+v+'" for attribute Ff supplied.');n=v}});var r=[];Object.defineProperty(this,"Rect",{enumerable:!1,configurable:!1,get:function(){if(r.length!==0)return r},set:function(v){r=v!==void 0?v:[]}}),Object.defineProperty(this,"x",{enumerable:!0,configurable:!0,get:function(){return!r||isNaN(r[0])?0:r[0]},set:function(v){r[0]=v}}),Object.defineProperty(this,"y",{enumerable:!0,configurable:!0,get:function(){return!r||isNaN(r[1])?0:r[1]},set:function(v){r[1]=v}}),Object.defineProperty(this,"width",{enumerable:!0,configurable:!0,get:function(){return!r||isNaN(r[2])?0:r[2]},set:function(v){r[2]=v}}),Object.defineProperty(this,"height",{enumerable:!0,configurable:!0,get:function(){return!r||isNaN(r[3])?0:r[3]},set:function(v){r[3]=v}});var a="";Object.defineProperty(this,"FT",{enumerable:!0,configurable:!1,get:function(){return a},set:function(v){switch(v){case"/Btn":case"/Tx":case"/Ch":case"/Sig":a=v;break;default:throw new Error('Invalid value "'+v+'" for attribute FT supplied.')}}});var i=null;Object.defineProperty(this,"T",{enumerable:!0,configurable:!1,get:function(){if(!i||i.length<1){if(this instanceof dPe)return;i="FieldObject"+s.FieldNum++}var v=function(b){return b};return this.scope&&(v=this.scope.internal.getEncryptor(this.objId)),"("+o9(v(i))+")"},set:function(v){i=v.toString()}}),Object.defineProperty(this,"fieldName",{configurable:!0,enumerable:!0,get:function(){return i},set:function(v){i=v}});var l="helvetica";Object.defineProperty(this,"fontName",{enumerable:!0,configurable:!0,get:function(){return l},set:function(v){l=v}});var o="normal";Object.defineProperty(this,"fontStyle",{enumerable:!0,configurable:!0,get:function(){return o},set:function(v){o=v}});var c=0;Object.defineProperty(this,"fontSize",{enumerable:!0,configurable:!0,get:function(){return c},set:function(v){c=v}});var d=void 0;Object.defineProperty(this,"maxFontSize",{enumerable:!0,configurable:!0,get:function(){return d===void 0?50/wot:d},set:function(v){d=v}});var u="black";Object.defineProperty(this,"color",{enumerable:!0,configurable:!0,get:function(){return u},set:function(v){u=v}});var h="/F1 0 Tf 0 g";Object.defineProperty(this,"DA",{enumerable:!0,configurable:!1,get:function(){if(!(!h||this instanceof dPe||this instanceof C7))return j$e(h,this.objId,this.scope)},set:function(v){v=v.toString(),h=v}});var m=null;Object.defineProperty(this,"DV",{enumerable:!1,configurable:!1,get:function(){if(m)return this instanceof mv==0?j$e(m,this.objId,this.scope):m},set:function(v){v=v.toString(),m=this instanceof mv==0?v.substr(0,1)==="("?U$(v.substr(1,v.length-2)):U$(v):v}}),Object.defineProperty(this,"defaultValue",{enumerable:!0,configurable:!0,get:function(){return this instanceof mv==1?U$(m.substr(1,m.length-1)):m},set:function(v){v=v.toString(),m=this instanceof mv==1?"/"+mB(v):v}});var f=null;Object.defineProperty(this,"_V",{enumerable:!1,configurable:!1,get:function(){if(f)return f},set:function(v){this.V=v}}),Object.defineProperty(this,"V",{enumerable:!1,configurable:!1,get:function(){if(f)return this instanceof mv==0?j$e(f,this.objId,this.scope):f},set:function(v){v=v.toString(),f=this instanceof mv==0?v.substr(0,1)==="("?U$(v.substr(1,v.length-2)):U$(v):v}}),Object.defineProperty(this,"value",{enumerable:!0,configurable:!0,get:function(){return this instanceof mv==1?U$(f.substr(1,f.length-1)):f},set:function(v){v=v.toString(),f=this instanceof mv==1?"/"+mB(v):v}}),Object.defineProperty(this,"hasAnnotation",{enumerable:!0,configurable:!0,get:function(){return this.Rect}}),Object.defineProperty(this,"Type",{enumerable:!0,configurable:!1,get:function(){return this.hasAnnotation?"/Annot":null}}),Object.defineProperty(this,"Subtype",{enumerable:!0,configurable:!1,get:function(){return this.hasAnnotation?"/Widget":null}});var g,x=!1;Object.defineProperty(this,"hasAppearanceStream",{enumerable:!0,configurable:!0,get:function(){return x},set:function(v){v=!!v,x=v}}),Object.defineProperty(this,"page",{enumerable:!0,configurable:!0,get:function(){if(g)return g},set:function(v){g=v}}),Object.defineProperty(this,"readOnly",{enumerable:!0,configurable:!0,get:function(){return!!ty(this.Ff,1)},set:function(v){v?this.Ff=sy(this.Ff,1):this.Ff=ny(this.Ff,1)}}),Object.defineProperty(this,"required",{enumerable:!0,configurable:!0,get:function(){return!!ty(this.Ff,2)},set:function(v){v?this.Ff=sy(this.Ff,2):this.Ff=ny(this.Ff,2)}}),Object.defineProperty(this,"noExport",{enumerable:!0,configurable:!0,get:function(){return!!ty(this.Ff,3)},set:function(v){v?this.Ff=sy(this.Ff,3):this.Ff=ny(this.Ff,3)}});var y=null;Object.defineProperty(this,"Q",{enumerable:!0,configurable:!1,get:function(){if(y!==null)return y},set:function(v){if([0,1,2].indexOf(v)===-1)throw new Error('Invalid value "'+v+'" for attribute Q supplied.');y=v}}),Object.defineProperty(this,"textAlign",{get:function(){var v;switch(y){case 0:default:v="left";break;case 1:v="center";break;case 2:v="right"}return v},configurable:!0,enumerable:!0,set:function(v){switch(v){case"right":case 2:y=2;break;case"center":case 1:y=1;break;default:y=0}}})};Ww(EC,b4);var RV=function(){EC.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 Zts(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!!ty(this.Ff,18)},set:function(n){n?this.Ff=sy(this.Ff,18):this.Ff=ny(this.Ff,18)}}),Object.defineProperty(this,"edit",{enumerable:!0,configurable:!0,get:function(){return!!ty(this.Ff,19)},set:function(n){this.combo===!0&&(n?this.Ff=sy(this.Ff,19):this.Ff=ny(this.Ff,19))}}),Object.defineProperty(this,"sort",{enumerable:!0,configurable:!0,get:function(){return!!ty(this.Ff,20)},set:function(n){n?(this.Ff=sy(this.Ff,20),t.sort()):this.Ff=ny(this.Ff,20)}}),Object.defineProperty(this,"multiSelect",{enumerable:!0,configurable:!0,get:function(){return!!ty(this.Ff,22)},set:function(n){n?this.Ff=sy(this.Ff,22):this.Ff=ny(this.Ff,22)}}),Object.defineProperty(this,"doNotSpellCheck",{enumerable:!0,configurable:!0,get:function(){return!!ty(this.Ff,23)},set:function(n){n?this.Ff=sy(this.Ff,23):this.Ff=ny(this.Ff,23)}}),Object.defineProperty(this,"commitOnSelChange",{enumerable:!0,configurable:!0,get:function(){return!!ty(this.Ff,27)},set:function(n){n?this.Ff=sy(this.Ff,27):this.Ff=ny(this.Ff,27)}}),this.hasAppearanceStream=!1};Ww(RV,EC);var DV=function(){RV.call(this),this.fontName="helvetica",this.combo=!1};Ww(DV,RV);var FV=function(){DV.call(this),this.combo=!0};Ww(FV,DV);var T3e=function(){FV.call(this),this.edit=!0};Ww(T3e,FV);var mv=function(){EC.call(this),this.FT="/Btn",Object.defineProperty(this,"noToggleToOff",{enumerable:!0,configurable:!0,get:function(){return!!ty(this.Ff,15)},set:function(n){n?this.Ff=sy(this.Ff,15):this.Ff=ny(this.Ff,15)}}),Object.defineProperty(this,"radio",{enumerable:!0,configurable:!0,get:function(){return!!ty(this.Ff,16)},set:function(n){n?this.Ff=sy(this.Ff,16):this.Ff=ny(this.Ff,16)}}),Object.defineProperty(this,"pushButton",{enumerable:!0,configurable:!0,get:function(){return!!ty(this.Ff,17)},set:function(n){n?this.Ff=sy(this.Ff,17):this.Ff=ny(this.Ff,17)}}),Object.defineProperty(this,"radioIsUnison",{enumerable:!0,configurable:!0,get:function(){return!!ty(this.Ff,26)},set:function(n){n?this.Ff=sy(this.Ff,26):this.Ff=ny(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+" ("+o9(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="/"+mB(r)}}),Object.defineProperty(this,"appearanceState",{enumerable:!0,configurable:!0,get:function(){return s.substr(1,s.length-1)},set:function(n){s="/"+mB(n)}})};Ww(mv,EC);var M3e=function(){mv.call(this),this.pushButton=!0};Ww(M3e,mv);var OV=function(){mv.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:[]}})};Ww(OV,mv);var dPe=function(){var s,t;EC.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+" ("+o9(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="/"+mB(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="/"+mB(i)}}),this.caption="l",this.appearanceState="Off",this._AppearanceType=$o.RadioButton.Circle,this.appearanceStreamContent=this._AppearanceType.createAppearanceStream(this.optionName)};Ww(dPe,EC),OV.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()}},OV.prototype.createOption=function(s){var t=new dPe;return t.Parent=this,t.optionName=s,this.Kids.push(t),wWn.call(this.scope,t),t};var P3e=function(){mv.call(this),this.fontName="zapfdingbats",this.caption="3",this.appearanceState="On",this.value="On",this.textAlign="center",this.appearanceStreamContent=$o.CheckBox.createAppearanceStream()};Ww(P3e,mv);var C7=function(){EC.call(this),this.FT="/Tx",Object.defineProperty(this,"multiline",{enumerable:!0,configurable:!0,get:function(){return!!ty(this.Ff,13)},set:function(t){t?this.Ff=sy(this.Ff,13):this.Ff=ny(this.Ff,13)}}),Object.defineProperty(this,"fileSelect",{enumerable:!0,configurable:!0,get:function(){return!!ty(this.Ff,21)},set:function(t){t?this.Ff=sy(this.Ff,21):this.Ff=ny(this.Ff,21)}}),Object.defineProperty(this,"doNotSpellCheck",{enumerable:!0,configurable:!0,get:function(){return!!ty(this.Ff,23)},set:function(t){t?this.Ff=sy(this.Ff,23):this.Ff=ny(this.Ff,23)}}),Object.defineProperty(this,"doNotScroll",{enumerable:!0,configurable:!0,get:function(){return!!ty(this.Ff,24)},set:function(t){t?this.Ff=sy(this.Ff,24):this.Ff=ny(this.Ff,24)}}),Object.defineProperty(this,"comb",{enumerable:!0,configurable:!0,get:function(){return!!ty(this.Ff,25)},set:function(t){t?this.Ff=sy(this.Ff,25):this.Ff=ny(this.Ff,25)}}),Object.defineProperty(this,"richText",{enumerable:!0,configurable:!0,get:function(){return!!ty(this.Ff,26)},set:function(t){t?this.Ff=sy(this.Ff,26):this.Ff=ny(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}})};Ww(C7,EC);var I3e=function(){C7.call(this),Object.defineProperty(this,"password",{enumerable:!0,configurable:!0,get:function(){return!!ty(this.Ff,14)},set:function(s){s?this.Ff=sy(this.Ff,14):this.Ff=ny(this.Ff,14)}}),this.password=!0};Ww(I3e,C7);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=y5(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=uZe(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=y5(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=uZe(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=y5(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=y5(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 "+AM($o.internal.getWidth(s)/2)+" "+AM($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=y5(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 "+AM($o.internal.getWidth(s)/2)+" "+AM($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 "+AM($o.internal.getWidth(s)/2)+" "+AM($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=y5(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 "+AM($o.internal.getWidth(s)/2)+" "+AM($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=y5(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=y5(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=y5(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=E4t(s.Rect[2])),t},$o.internal.getHeight=function(s){var t=0;return Tm(s)==="object"&&(t=E4t(s.Rect[3])),t};var wWn=mx.addField=function(s){if(_Wn(this,s),!(s instanceof EC))throw new Error("Invalid argument passed to jsPDF.addField.");var t;return(t=s).scope.internal.acroformPlugin.printedOut&&(t.scope.internal.acroformPlugin.printedOut=!1,t.scope.internal.acroformPlugin.acroFormDictionaryRoot=null),t.scope.internal.acroformPlugin.acroFormDictionaryRoot.Fields.push(t),s.page=s.scope.internal.getCurrentPageInfo().pageNumber,this};mx.AcroFormChoiceField=RV,mx.AcroFormListBox=DV,mx.AcroFormComboBox=FV,mx.AcroFormEditBox=T3e,mx.AcroFormButton=mv,mx.AcroFormPushButton=M3e,mx.AcroFormRadioButton=OV,mx.AcroFormCheckBox=P3e,mx.AcroFormTextField=C7,mx.AcroFormPasswordField=I3e,mx.AcroFormAppearance=$o,mx.AcroForm={ChoiceField:RV,ListBox:DV,ComboBox:FV,EditBox:T3e,Button:mv,PushButton:M3e,RadioButton:OV,CheckBox:P3e,TextField:C7,PasswordField:I3e,Appearance:$o},Go.AcroForm={ChoiceField:RV,ListBox:DV,ComboBox:FV,EditBox:T3e,Button:mv,PushButton:M3e,RadioButton:OV,CheckBox:P3e,TextField:C7,PasswordField:I3e,Appearance:$o};Go.AcroForm;function Jts(s){return s.reduce(function(t,n,r){return t[n]=r,t},{})}(function(s){var t="addImage_";s.__addimage__={};var n="UNKNOWN",r={PNG:[[137,80,78,71]],TIFF:[[77,77,0,42],[73,73,42,0]],JPEG:[[255,216,255,224,void 0,void 0,74,70,73,70,0],[255,216,255,225,void 0,void 0,69,120,105,102,0,0],[255,216,255,219],[255,216,255,238]],JPEG2000:[[0,0,0,12,106,80,32,32]],GIF87a:[[71,73,70,56,55,97]],GIF89a:[[71,73,70,56,57,97]],WEBP:[[82,73,70,70,void 0,void 0,void 0,void 0,87,69,66,80]],BMP:[[66,77],[66,65],[67,73],[67,80],[73,67],[80,84]]},a=s.__addimage__.getImageFileTypeByImageData=function(O,U){var W,V,G,Y,X,ae=n;if((U=U||n)==="RGBA"||O.data!==void 0&&O.data instanceof Uint8ClampedArray&&"height"in O&&"width"in O)return"RGBA";if(E(O))for(X in r)for(G=r[X],W=0;W>"}),"transparency"in U&&Array.isArray(U.transparency)&&U.transparency.length>0){for(var X="",ae=0,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 y=0,v=n,b="",w=0;for(y=0;y>"),this.internal.out("endobj")}),this.internal.events.subscribe("putCatalog",function(){this.internal.out("/OpenAction "+t+" 0 R")})),this},function(s){var t=function(){var n=void 0;Object.defineProperty(this,"pdf",{get:function(){return n},set:function(o){n=o}});var r=150;Object.defineProperty(this,"width",{get:function(){return r},set:function(o){r=isNaN(o)||Number.isInteger(o)===!1||o<0?150:o,this.getContext("2d").pageWrapXEnabled&&(this.getContext("2d").pageWrapX=r+1)}});var a=300;Object.defineProperty(this,"height",{get:function(){return a},set:function(o){a=isNaN(o)||Number.isInteger(o)===!1||o<0?300:o,this.getContext("2d").pageWrapYEnabled&&(this.getContext("2d").pageWrapY=a+1)}});var i=[];Object.defineProperty(this,"childNodes",{get:function(){return i},set:function(o){i=o}});var l={};Object.defineProperty(this,"style",{get:function(){return l},set:function(o){l=o}}),Object.defineProperty(this,"parentNode",{})};t.prototype.getContext=function(n,r){var a;if((n=n||"2d")!=="2d")return null;for(a in r)this.pdf.context2d.hasOwnProperty(a)&&(this.pdf.context2d[a]=r[a]);return this.pdf.context2d._canvas=this,this.pdf.context2d},t.prototype.toDataURL=function(){throw new Error("toDataURL is not implemented.")},s.events.push(["initialized",function(){this.canvas=new t,this.canvas.pdf=this}])}(Go.API),function(s){var t={left:0,top:0,bottom:0,right:0},n=!1,r=function(){this.internal.__cell__===void 0&&(this.internal.__cell__={},this.internal.__cell__.padding=3,this.internal.__cell__.headerFunction=void 0,this.internal.__cell__.margins=Object.assign({},t),this.internal.__cell__.margins.width=this.getPageWidth(),a.call(this))},a=function(){this.internal.__cell__.lastCell=new i,this.internal.__cell__.pages=1},i=function(){var c=arguments[0];Object.defineProperty(this,"x",{enumerable:!0,get:function(){return c},set:function(x){c=x}});var d=arguments[1];Object.defineProperty(this,"y",{enumerable:!0,get:function(){return d},set:function(x){d=x}});var u=arguments[2];Object.defineProperty(this,"width",{enumerable:!0,get:function(){return u},set:function(x){u=x}});var h=arguments[3];Object.defineProperty(this,"height",{enumerable:!0,get:function(){return h},set:function(x){h=x}});var m=arguments[4];Object.defineProperty(this,"text",{enumerable:!0,get:function(){return m},set:function(x){m=x}});var f=arguments[5];Object.defineProperty(this,"lineNumber",{enumerable:!0,get:function(){return f},set:function(x){f=x}});var g=arguments[6];return Object.defineProperty(this,"align",{enumerable:!0,get:function(){return g},set:function(x){g=x}}),this};i.prototype.clone=function(){return new i(this.x,this.y,this.width,this.height,this.text,this.lineNumber,this.align)},i.prototype.toArray=function(){return[this.x,this.y,this.width,this.height,this.text,this.lineNumber,this.align]},s.setHeaderFunction=function(c){return r.call(this),this.internal.__cell__.headerFunction=typeof c=="function"?c:void 0,this},s.getTextDimensions=function(c,d){r.call(this);var u=(d=d||{}).fontSize||this.getFontSize(),h=d.font||this.getFont(),m=d.scaleFactor||this.internal.scaleFactor,f=0,g=0,x=0,y=this;if(!Array.isArray(c)&&typeof c!="string"){if(typeof c!="number")throw new Error("getTextDimensions expects text-parameter to be of type String or type Number or an Array of Strings.");c=String(c)}var v=d.maxWidth;v>0?typeof c=="string"?c=this.splitTextToSize(c,v):Object.prototype.toString.call(c)==="[object Array]"&&(c=c.reduce(function(w,S){return w.concat(y.splitTextToSize(S,v))},[])):c=Array.isArray(c)?c:[c];for(var b=0;bthis.getPageHeight()?(this.cellAddPage(),c.y=h.top,f&&m&&(this.printHeaderRow(c.lineNumber,!0),c.y+=m[0].height)):c.y=d.y+d.height||c.y),c.text[0]!==void 0&&(this.rect(c.x,c.y,c.width,c.height,n===!0?"FD":void 0),c.align==="right"?this.text(c.text,c.x+c.width-u,c.y+u,{align:"right",baseline:"top"}):c.align==="center"?this.text(c.text,c.x+c.width/2,c.y+u,{align:"center",baseline:"top",maxWidth:c.width-u-u}):this.text(c.text,c.x+u,c.y+u,{align:"left",baseline:"top",maxWidth:c.width-u-u})),this.internal.__cell__.lastCell=c,this};s.table=function(c,d,u,h,m){if(r.call(this),!u)throw new Error("No data for PDF table.");var f,g,x,y,v=[],b=[],w=[],S={},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=v=Object.keys(u[0]),w=v.map(function(){return"left"});else if(Array.isArray(h)&&Tm(h[0])==="object")for(v=h.map(function(ne){return ne.name}),b=h.map(function(ne){return ne.prompt||ne.name||""}),w=h.map(function(ne){return ne.align||"left"}),f=0;f0&&this.setTableHeaderRow(m),this.setFont(void 0,"normal"),n=!1}}(Go.API);var ess={italic:["italic","oblique","normal"],oblique:["oblique","italic","normal"],normal:["normal","oblique","italic"]},tss=["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded"],hZe=Jts(tss),sss=[100,200,300,400,500,600,700,800,900],jWn=Jts(sss);function N$e(s){var t=s.family.replace(/"|'/g,"").toLowerCase(),n=function(i){return ess[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 hZe[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 T4t(s,t,n,r){var a;for(a=n;a>=0&&a=0&&a>>1)&255}return a}function $4t(s,t,n){var r=s.length,a=[];a[0]=4;for(var i=0;i>i&l}function U4t(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,nss(s,i)&~(o<>7,l=1<<1+(7&a);s[t++],s[t++];var o=null,c=null;i&&(o=t,c=l,t+=3*l);var d=!0,u=[],h=0,m=null,f=0,g=null;for(this.width=n,this.height=r;d&&t=0))throw Error("Invalid block size");if(O===0)break;t+=O}break;case 249:if(s[t++]!==4||s[t+4]!==0)throw new Error("Invalid graphics extension block.");var x=s[t++];h=s[t++]|s[t++]<<8,m=s[t++],1&x||(m=null),f=x>>2&7,t++;break;case 254:for(;;){if(!((O=s[t++])>=0))throw Error("Invalid block size");if(O===0)break;t+=O}break;default:throw new Error("Unknown graphic control label: 0x"+s[t-1].toString(16))}break;case 44:var y=s[t++]|s[t++]<<8,v=s[t++]|s[t++]<<8,b=s[t++]|s[t++]<<8,w=s[t++]|s[t++]<<8,S=s[t++],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:y,y:v,width:b,height:w,has_local_palette:R,palette_offset:I,palette_size:P,data_offset:D,data_length:t-D,transparent_index:m,interlaced:!!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 Y=new Uint8Array(G);q4t(s,V.data_offset,Y,G);var X=V.palette_offset,ae=V.transparent_index;ae===null&&(ae=256);var le=V.width,ne=n-le,te=le,J=4*(V.y*n+V.x),ce=4*((V.y+V.height)*n+V.x),_e=J,he=4*ne;V.interlaced===!0&&(he+=4*n*7);for(var ue=8,ve=0,Ee=Y.length;ve=ce&&(he=4*ne+4*n*(ue-1),_e=J+(le+ne)*(ue<<1),ue>>=1)),Se===ae)_e+=4;else{var Le=s[X+3*Se],Fe=s[X+3*Se+1],ke=s[X+3*Se+2];W[_e++]=ke,W[_e++]=Fe,W[_e++]=Le,W[_e++]=255}--te}},this.decodeAndBlitFrameRGBA=function(U,W){var V=this.frameInfo(U),G=V.width*V.height;if(G>536870912)throw new Error("Image dimensions exceed 512MB, which is too large.");var Y=new Uint8Array(G);q4t(s,V.data_offset,Y,G);var X=V.palette_offset,ae=V.transparent_index;ae===null&&(ae=256);var le=V.width,ne=n-le,te=le,J=4*(V.y*n+V.x),ce=4*((V.y+V.height)*n+V.x),_e=J,he=4*ne;V.interlaced===!0&&(he+=4*n*7);for(var ue=8,ve=0,Ee=Y.length;ve=ce&&(he=4*ne+4*n*(ue-1),_e=J+(le+ne)*(ue<<1),ue>>=1)),Se===ae)_e+=4;else{var Le=s[X+3*Se],Fe=s[X+3*Se+1],ke=s[X+3*Se+2];W[_e++]=Le,W[_e++]=Fe,W[_e++]=ke,W[_e++]=255}--te}}}function q4t(s,t,n,r){for(var a=s[t++],i=1<>=c,u-=c,y!==i){if(y===l)break;for(var v=yi;)w=g[w]>>8,++b;var S=w;if(m+b+(v!==y?1:0)>r)return void yf.log("Warning, gif stream longer than expected.");n[m++]=S;var A=m+=b;for(v!==y&&(n[m++]=S),w=v;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=y}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 C$e(s){var t,n,r,a,i,l=Math.floor,o=new Array(64),c=new Array(64),d=new Array(64),u=new Array(64),h=new Array(65535),m=new Array(65535),f=new Array(64),g=new Array(64),x=[],y=0,v=7,b=new Array(64),w=new Array(64),S=new Array(64),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 Y(J,ce){for(var _e=0,he=0,ue=new Array,ve=1;ve<=16;ve++){for(var Ee=1;Ee<=J[ve];Ee++)ue[ce[he]]=[],ue[ce[he]][0]=_e,ue[ce[he]][1]=ve,he++,_e++;_e*=2}return ue}function X(J){for(var ce=J[0],_e=J[1]-1;_e>=0;)ce&1<<_e&&(y|=1<>8&255),ae(255&J)}function ne(J,ce,_e,he,ue){for(var ve,Ee=ue[0],Se=ue[240],Le=function(qe,dt){var Xe,at,rt,Ke,Je,pt,gt,ss,Yt,ts,ys=0;for(Yt=0;Yt<8;++Yt){Xe=qe[ys],at=qe[ys+1],rt=qe[ys+2],Ke=qe[ys+3],Je=qe[ys+4],pt=qe[ys+5],gt=qe[ys+6];var Bt=Xe+(ss=qe[ys+7]),Ft=Xe-ss,as=at+gt,kt=at-gt,Ks=rt+pt,wt=rt-pt,gs=Ke+Je,ks=Ke-Je,Is=Bt+gs,Xs=Bt-gs,ds=as+Ks,Ss=as-Ks;qe[ys]=Is+ds,qe[ys+4]=Is-ds;var yn=.707106781*(Ss+Xs);qe[ys+2]=Xs+yn,qe[ys+6]=Xs-yn;var Js=.382683433*((Is=ks+wt)-(Ss=kt+Ft)),Ut=.5411961*Is+Js,hn=1.306562965*Ss+Js,hr=.707106781*(ds=wt+kt),Rs=Ft+hr,jr=Ft-hr;qe[ys+5]=jr+Ut,qe[ys+3]=jr-Ut,qe[ys+1]=Rs+hn,qe[ys+7]=Rs-hn,ys+=8}for(ys=0,Yt=0;Yt<8;++Yt){Xe=qe[ys],at=qe[ys+8],rt=qe[ys+16],Ke=qe[ys+24],Je=qe[ys+32],pt=qe[ys+40],gt=qe[ys+48];var kr=Xe+(ss=qe[ys+56]),$n=Xe-ss,kn=at+gt,Fn=at-gt,bn=rt+pt,xs=rt-pt,Lr=Ke+Je,Or=Ke-Je,la=kr+Lr,Qn=kr-Lr,Cr=kn+bn,Un=kn-bn;qe[ys]=la+Cr,qe[ys+32]=la-Cr;var dr=.707106781*(Un+Qn);qe[ys+16]=Qn+dr,qe[ys+48]=Qn-dr;var Pa=.382683433*((la=Or+xs)-(Un=Fn+$n)),ii=.5411961*la+Pa,$i=1.306562965*Un+Pa,Rn=.707106781*(Cr=xs+Fn),xa=$n+Rn,Ya=$n-Rn;qe[ys+40]=Ya+ii,qe[ys+24]=Ya-ii,qe[ys+8]=xa+$i,qe[ys+56]=xa-$i,ys++}for(Yt=0;Yt<64;++Yt)ts=qe[Yt]*dt[Yt],f[Yt]=ts>0?ts+.5|0:ts-.5|0;return f}(J,ce),Fe=0;Fe<64;++Fe)g[I[Fe]]=Le[Fe];var ke=g[0]-_e;_e=g[0],ke==0?X(he[0]):(X(he[m[ve=32767+ke]]),X(h[ve]));for(var Be=63;Be>0&&g[Be]==0;)Be--;if(Be==0)return X(Ee),_e;for(var Ne,Ae=1;Ae<=Be;){for(var Ce=Ae;g[Ae]==0&&Ae<=Be;)++Ae;var Ve=Ae-Ce;if(Ve>=16){Ne=Ve>>4;for(var ze=1;ze<=Ne;++ze)X(Se);Ve&=15}ve=32767+g[Ae],X(ue[(Ve<<4)+m[ve]]),X(h[ve]),Ae++}return Be!=63&&X(Ee),_e}function te(J){J=Math.min(Math.max(J,1),100),i!=J&&(function(ce){for(var _e=[16,11,10,16,24,40,51,61,12,12,14,19,26,58,60,55,14,13,16,24,40,57,69,56,14,17,22,29,51,87,80,62,18,22,37,56,68,109,103,77,24,35,55,64,81,104,113,92,49,64,78,87,103,121,120,101,72,92,95,98,112,100,103,99],he=0;he<64;he++){var ue=l((_e[he]*ce+50)/100);ue=Math.min(Math.max(ue,1),255),o[I[he]]=ue}for(var ve=[17,18,24,47,99,99,99,99,18,21,26,66,99,99,99,99,24,26,56,99,99,99,99,99,47,66,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99],Ee=0;Ee<64;Ee++){var Se=l((ve[Ee]*ce+50)/100);Se=Math.min(Math.max(Se,1),255),c[I[Ee]]=Se}for(var Le=[1,1.387039845,1.306562965,1.175875602,1,.785694958,.5411961,.275899379],Fe=0,ke=0;ke<8;ke++)for(var Be=0;Be<8;Be++)d[Fe]=1/(o[I[Fe]]*Le[ke]*Le[Be]*8),u[Fe]=1/(c[I[Fe]]*Le[ke]*Le[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,y=0,v=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 pt=0;pt<16;pt++)ae(U[pt+1]);for(var gt=0;gt<=11;gt++)ae(W[gt]);ae(17);for(var ss=0;ss<16;ss++)ae(V[ss+1]);for(var Yt=0;Yt<=161;Yt++)ae(G[Yt])}(),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 _e=0,he=0,ue=0;y=0,v=7,this.encode.displayName="_encode_";for(var ve,Ee,Se,Le,Fe,ke,Be,Ne,Ae,Ce=J.data,Ve=J.width,ze=J.height,qe=4*Ve,dt=0;dt>3)*qe+(Be=4*(7&Ae)),dt+Ne>=ze&&(ke-=qe*(dt+1+Ne-ze)),ve+Be>=qe&&(ke-=ve+Be-qe+4),Ee=Ce[ke++],Se=Ce[ke++],Le=Ce[ke++],b[Ae]=(E[Ee]+E[Se+256|0]+E[Le+512|0]>>16)-128,w[Ae]=(E[Ee+768|0]+E[Se+1024|0]+E[Le+1280|0]>>16)-128,S[Ae]=(E[Ee+1280|0]+E[Se+1536|0]+E[Le+1792|0]>>16)-128;_e=ne(b,d,_e,t,r),he=ne(w,u,he,n,a),ue=ne(S,u,ue,n,a),ve+=32}dt+=8}if(v>=0){var Xe=[];Xe[1]=v+1,Xe[0]=(1<U;U++)if(R[D+U]!=O.charCodeAt(U))return!0;return!1}function r(R,D,O,U,W){for(var V=0;VV+1?[]:new D),!(G.length>>0;Pe&ft;)ft>>>=1;return ft?(Pe&ft-1)+ft:Pe}function O(Pe,He,ft,Tt,ls){t(!(Tt%ft));do Pe[He+(Tt-=ft)]=ls;while(0=ls),512>=ls)var Ns=i(512);else if((Ns=i(ls))==null)return 0;return function(As,Ds,qs,on,Zn,Ar){var Qs,or,br=Ds,aa=1<Qs;++Qs){if(ur[Qs]>1<(bl-=ur[Qs]))return 0;for(;0=Qs;++Qs,Zn<<=1){if(Fi+=bl<<=1,0>(bl-=ur[Qs]))return 0;for(;0Ua&&!(0>=(cr-=ur[Ua]));)++Ua,cr<<=1;aa+=lo=1<<(cr=Ua-qs),As[Ds+(Ua=_o&Ea)].g=cr+qs,As[Ds+Ua].value=br-Ds-Ua}on.g=Qs-qs,on.value=Ar[or++],O(As,br+(_o>>qs),Zn,lo,on),_o=D(_o,Qs)}}return Fi!=2*pa[15]-1?0:aa}(Pe,He,ft,Tt,ls,Ns)}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 Y(Pe,He,ft,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=ft,Pe.Jd=He,Pe.Yc=ft+Tt,Pe.Zc=4<=Tt?ft+Tt-4+1:ft,Ee(Pe)}function X(Pe,He){for(var ft=0;0Tt),Pe.Sb=Tt,Pe.Ra=0,Pe.u=0,Pe.h=0,4>>=8,Pe.Ra+=Pe.oa[Pe.pa+Pe.bb]<>>0,++Pe.bb,Pe.u-=8;he(Pe)&&(Pe.h=1,Pe.u=0)}function te(Pe,He){if(t(0<=He),!Pe.h&&He<=Pf){var ft=_e(Pe)&oh[He];return Pe.u+=He,ne(Pe),ft}return Pe.h=1,Pe.u=0}function J(){this.b=this.Ca=this.I=0,this.oa=[],this.pa=0,this.Jd=[],this.Yc=0,this.Zc=[],this.Ka=0}function ce(){this.Ra=0,this.oa=[],this.h=this.u=this.bb=this.Sb=this.pa=0}function _e(Pe){return Pe.Ra>>>(Pe.u&Bd-1)>>>0}function he(Pe){return t(Pe.bb<=Pe.Sb),Pe.h||Pe.bb==Pe.Sb&&Pe.u>Bd}function ue(Pe,He){Pe.u=He,Pe.h=he(Pe)}function ve(Pe){Pe.u>=ad&&(t(Pe.u>=ad),ne(Pe))}function Ee(Pe){t(Pe!=null&&Pe.oa!=null),Pe.pa>>0,Pe.b+=8):(t(Pe!=null&&Pe.oa!=null),Pe.paPe.b&&Ee(Pe);var Tt=Pe.b,ls=ft*He>>>8,Ns=(Pe.I>>>Tt>ls)+0;for(Ns?(ft-=ls,Pe.I-=ls+1<>>0):ft=ls+1,Tt=ft,ls=0;256<=Tt;)ls+=8,Tt>>=8;return Tt=7^ls+Ph[Tt],Pe.b-=Tt,Pe.Ca=(ft<>24&255,Pe[He+1]=ft>>16&255,Pe[He+2]=ft>>8&255,Pe[He+3]=255&ft}function ke(Pe,He){return Pe[He+0]|Pe[He+1]<<8}function Be(Pe,He){return ke(Pe,He)|Pe[He+2]<<16}function Ne(Pe,He){return ke(Pe,He)|ke(Pe,He+2)<<16}function Ae(Pe,He){var ft=1<=ls||0>=Ns?0:(ft[0]=ls,Tt[0]=Ns,1)}function qe(Pe,He){return Pe+(1<>>He}function dt(Pe,He){return((4278255360&Pe)+(4278255360&He)>>>0&4278255360)+((16711935&Pe)+(16711935&He)>>>0&16711935)>>>0}function Xe(Pe,He){R[He]=function(ft,Tt,ls,Ns,As,Ds,qs){var on;for(on=0;on>>1)+(Pe&He)>>>0}function Ke(Pe){return 0<=Pe&&256>Pe?Pe:0>Pe?0:255>1))}function pt(Pe,He,ft){return Math.abs(He-ft)-Math.abs(Pe-ft)}function gt(Pe,He,ft,Tt,ls,Ns,As){for(Tt=Ns[As-1],ft=0;ft>8&255,qs=16711935&(qs=(qs=16711935&As)+((Ds<<16)+Ds));Tt[ls+Ns]=(4278255360&As)+qs>>>0}}function Yt(Pe,He){He.jd=255&Pe,He.hd=Pe>>8&255,He.ud=Pe>>16&255}function ts(Pe,He,ft,Tt,ls,Ns){var As;for(As=0;As>>8,on=Ds,Zn=255&(Zn=(Zn=Ds>>>16)+((Pe.jd<<24>>24)*(qs<<24>>24)>>>5));on=255&(on=(on+=(Pe.hd<<24>>24)*(qs<<24>>24)>>>5)+((Pe.ud<<24>>24)*(Zn<<24>>24)>>>5)),ls[Ns+As]=(4278255360&Ds)+(Zn<<16)+on}}function ys(Pe,He,ft,Tt,ls){R[He]=function(Ns,As,Ds,qs,on,Zn,Ar,Qs,or){for(qs=Ar;qs>Ns.b,or=Ns.Ea,br=Ns.K[0],aa=Ns.w;if(8>Qs)for(Ns=(1<>=Qs}else R["VP8LMapColor"+ft](qs,on,br,aa,Zn,Ar,As,Ds,or)}}function Bt(Pe,He,ft,Tt,ls){for(ft=He+ft;He>16&255,Tt[ls++]=Ns>>8&255,Tt[ls++]=255&Ns}}function Ft(Pe,He,ft,Tt,ls){for(ft=He+ft;He>16&255,Tt[ls++]=Ns>>8&255,Tt[ls++]=255&Ns,Tt[ls++]=Ns>>24&255}}function as(Pe,He,ft,Tt,ls){for(ft=He+ft;He>16&240|As>>12&15,As=240&As|As>>28&15;Tt[ls++]=Ns,Tt[ls++]=As}}function kt(Pe,He,ft,Tt,ls){for(ft=He+ft;He>16&248|As>>13&7,As=As>>5&224|As>>3&31;Tt[ls++]=Ns,Tt[ls++]=As}}function Ks(Pe,He,ft,Tt,ls){for(ft=He+ft;He>8&255,Tt[ls++]=Ns>>16&255}}function wt(Pe,He,ft,Tt,ls,Ns){if(Ns==0)for(ft=He+ft;He>24|Ns[1]>>8&65280|Ns[2]<<8&16711680|Ns[3]<<24)>>>0),ls+=32;else r(Tt,ls,Pe,He,ft)}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 ks(Pe){return Pe==L1||Pe==R1||Pe==Yw||Pe==Zw}function Is(){this.eb=[],this.size=this.A=this.fb=0}function Xs(){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 ds(){this.Rd=this.height=this.width=this.S=0,this.f={},this.f.RGBA=new Is,this.f.kb=new Xs,this.sd=null}function Ss(){this.width=[0],this.height=[0],this.Pd=[0],this.Qd=[0],this.format=[0]}function yn(){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 Js(Pe){return alert("todo:WebPSamplerProcessPlane"),Pe.T}function Ut(Pe,He){var ft=Pe.T,Tt=He.ba.f.RGBA,ls=Tt.eb,Ns=Tt.fb+Pe.ka*Tt.A,As=ip[He.ba.S],Ds=Pe.y,qs=Pe.O,on=Pe.f,Zn=Pe.N,Ar=Pe.ea,Qs=Pe.W,or=He.cc,br=He.dc,aa=He.Mc,ur=He.Nc,pa=Pe.ka,cr=Pe.ka+Pe.T,Ua=Pe.U,Ea=Ua+1>>1;for(pa==0?As(Ds,qs,null,null,on,Zn,Ar,Qs,on,Zn,Ar,Qs,ls,Ns,null,null,Ua):(As(He.ec,He.fc,Ds,qs,or,br,aa,ur,on,Zn,Ar,Qs,ls,Ns-Tt.A,ls,Ns,Ua),++ft);pa+2ft,ls=ft==np||ft==ch||ft==Ic||ft==Jg||ft==12||ks(ft);if(He.memory=null,He.Ib=null,He.Jb=null,He.Nd=null,!Ad(He.Oa,Pe,ls?11:12))return 0;if(ls&&ks(ft)&&Pl(),Pe.da)alert("todo:use_scaling");else{if(Tt){if(He.Ib=Js,Pe.Kb){if(ft=Pe.U+1>>1,He.memory=i(Pe.U+2*ft),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+ft,He.Ib=Ut,Pl()}}else alert("todo:EmitYUV");ls&&(He.Jb=hn,Tt&&po())}if(Tt&&!Dk){for(Pe=0;256>Pe;++Pe)Fk[Pe]=89858*(Pe-128)+V0>>q0,z_[Pe]=-22014*(Pe-128)+V0,Qw[Pe]=-45773*(Pe-128),O_[Pe]=113618*(Pe-128)+V0>>q0;for(Pe=Ox;Pe>q0,DC[Pe-Ox]=ta(He,255),G2[Pe-Ox]=ta(He+8>>4,15);Dk=1}return 1}function Rs(Pe){var He=Pe.ma,ft=Pe.U,Tt=Pe.T;return t(!(1&Pe.ka)),0>=ft||0>=Tt?0:(ft=He.Ib(Pe,He),He.Jb!=null&&He.Jb(Pe,He,ft),He.Dc+=ft,1)}function jr(Pe){Pe.ma.memory=null}function kr(Pe,He,ft,Tt){return te(Pe,8)!=47?0:(He[0]=te(Pe,14)+1,ft[0]=te(Pe,14)+1,Tt[0]=te(Pe,1),te(Pe,3)!=0?0:!Pe.h)}function $n(Pe,He){if(4>Pe)return Pe+1;var ft=Pe-2>>1;return(2+(1&Pe)<>4)*Pe+(8-(15&ft)))?ft:1;var ft}function Fn(Pe,He,ft){var Tt=_e(ft),ls=Pe[He+=255&Tt].g-8;return 0>>0,t(8>=ft.g),Pe.g}function xs(Pe,He,ft){var Tt=Pe.xc;return t((He=Tt==0?0:Pe.vc[Pe.md*(ft>>Tt)+(He>>Tt)])>lo.b)*Fi;aaUa&&(yo=Ua),(0,Xc[Lc[hf++]>>8&15])(Qs,or+ +Xl,pa,cr+Xl-Ua,yo-Xl,pa,cr+Xl),Xl=yo}or+=Ua,cr+=Ua,++aa&_o||(lo+=Fi)}Ar!=on.nc&&r(qs,Ds-br,qs,Ds+(Ar-Zn-1)*br,br);break;case 1:for(br=Qs,ur=or,Ua=(Qs=on.Ea)-(cr=Qs&~(pa=(or=1<>on.b)*aa;Zn=ls),0Ns.o&&(Tt=Ns.o),ft=Tt?ft=0:(ls[0]+=4*Ns.v,Ns.ka=ft-Ns.j,Ns.U=Ns.va-Ns.v,Ns.T=Tt-ft,ft=1),ft){if(Ds=Ds[0],11>(ft=Pe.ca).S){var Zn=ft.f.RGBA,Ar=(Tt=ft.S,ls=Ns.U,Ns=Ns.T,on=Zn.eb,Zn.A),Qs=Ns;for(Zn=Zn.fb+Pe.Ma*Zn.A;0Tt){var ls=Pe.l.width,Ns=ft.ca,As=ft.tb+ls*Tt,Ds=Pe.V,qs=Pe.Ba+Pe.c*Tt,on=Pe.gc;t(Pe.ab==1),t(on[0].hc==3),Ed(on[0],Tt,He,Ds,qs,Ns,As),Qn(ft,Tt,He,Ns,As,ls)}Pe.C=Pe.Ma=He}function Un(Pe,He,ft,Tt,ls,Ns,As){var Ds=Pe.$/Tt,qs=Pe.$%Tt,on=Pe.m,Zn=Pe.s,Ar=ft+Pe.$,Qs=Ar;ls=ft+Tt*ls;var or=ft+Tt*Ns,br=280+Zn.ua,aa=Pe.Pb?Ds:16777216,ur=0=aa){var _o=Ar-ft;t((aa=Pe).Pb),aa.wd=aa.m,aa.xd=_o,0bl.g?(ue(Ea,Ea.u+bl.g),_o[Fi]=bl.value,Ea=0):(ue(Ea,Ea.u+bl.g-256),t(256<=bl.value),Ea=bl.value),Ea==0&&(Ua=!0)}else Ea=Fn(cr.G[0],cr.H[0],on);if(on.h)break;if(Ua||256>Ea){if(!Ua)if(cr.nd)He[Ar]=(cr.qb|Ea<<8)>>>0;else{if(ve(on),Ua=Fn(cr.G[1],cr.H[1],on),ve(on),_o=Fn(cr.G[2],cr.H[2],on),Fi=Fn(cr.G[3],cr.H[3],on),on.h)break;He[Ar]=(Fi<<24|Ua<<16|Ea<<8|_o)>>>0}if(Ua=!1,++Ar,++qs>=Tt&&(qs=0,++Ds,As!=null&&Ds<=Ns&&!(Ds%16)&&As(Pe,Ds),ur!=null))for(;Qs>>ur.Mb]=Ea}else if(280>Ea){if(Ea=$n(Ea-256,on),_o=Fn(cr.G[4],cr.H[4],on),ve(on),_o=kn(Tt,_o=$n(_o,on)),on.h)break;if(Ar-ft<_o||ls-Ar=Tt;)qs-=Tt,++Ds,As!=null&&Ds<=Ns&&!(Ds%16)&&As(Pe,Ds);if(t(Ar<=ls),qs&pa&&(cr=xs(Zn,qs,Ds)),ur!=null)for(;Qs>>ur.Mb]=Ea}else{if(!(Ea>>ur.Mb]=Ea;Ea=Ar,t(!(Ua>>>(_o=ur).Xa)),He[Ea]=_o.X[Ua],Ua=!0}Ua||t(on.h==he(on))}if(Pe.Pb&&on.h&&ArNs?Ns:Ds),Pe.a=0,Pe.$=Ar-ft}return 1}return Pe.a=3,0}function dr(Pe){t(Pe!=null),Pe.vc=null,Pe.yc=null,Pe.Ya=null;var He=Pe.Wa;He!=null&&(He.X=null),Pe.vb=null,t(Pe!=null)}function Pa(){var Pe=new Qr;return Pe==null?null:(Pe.a=0,Pe.xb=C3,gs("Predictor","VP8LPredictors"),gs("Predictor","VP8LPredictors_C"),gs("PredictorAdd","VP8LPredictorsAdd"),gs("PredictorAdd","VP8LPredictorsAdd_C"),dd=ss,vd=ts,Ep=Bt,Fv=Ft,Lx=as,ya=kt,Yy=Ks,R.VP8LMapColor32b=Xi,R.VP8LMapColor8b=ou,Pe)}function ii(Pe,He,ft,Tt,ls){var Ns=1,As=[Pe],Ds=[He],qs=Tt.m,on=Tt.s,Zn=null,Ar=0;e:for(;;){if(ft)for(;Ns&&te(qs,1);){var Qs=As,or=Ds,br=Tt,aa=1,ur=br.m,pa=br.gc[br.ab],cr=te(ur,2);if(br.Oc&1<=br.ab),cr){case 0:case 1:pa.b=te(ur,3)+2,aa=ii(qe(pa.Ea,pa.b),qe(pa.nc,pa.b),0,br,pa.K),pa.K=pa.K[0];break;case 3:var Ua,Ea=te(ur,8)+1,_o=16>lo.b),hf=i(Lc);if(hf==null)Ua=0;else{var Xl=lo.K[0],yo=lo.w;for(hf[0]=lo.K[0][0],Fi=1;Fi<1*bl;++Fi)hf[Fi]=dt(Xl[yo+Fi],hf[Fi-1]);for(;Fi<4*Lc;++Fi)hf[Fi]=0;lo.K[0]=null,lo.K[0]=hf,Ua=1}}aa=Ua;break;case 2:break;default:t(0)}Ns=aa}}if(As=As[0],Ds=Ds[0],Ns&&te(qs,1)&&!(Ns=1<=(Ar=te(qs,4))&&11>=Ar)){Tt.a=3;break e}var bi;if(bi=Ns)t:{var hm,To,Ql,$c=Tt,If=As,ig=Ds,Xd=Ar,og=ft,Lh=$c.m,mf=$c.s,ud=[null],lu=1,dh=0,cu=rp[Xd];s:for(;;){if(og&&te(Lh,1)){var Lf=te(Lh,3)+2,op=qe(If,Lf),uh=qe(ig,Lf),vh=op*uh;if(!ii(op,uh,0,$c,ud))break s;for(ud=ud[0],mf.xc=Lf,hm=0;hm>8&65535;ud[hm]=vc,vc>=lu&&(lu=vc+1)}}if(Lh.h)break s;for(To=0;5>To;++To){var Rh=Ib[To];!To&&0=Rf),nx=Mp;var Pp=i(dh);if(nx==null||Pp==null||Bm==null){$c.a=1;break s}var rx=Bm;for(hm=Ql=0;hmTo;++To){Rh=Ib[To],ff[To]=rx,Td[To]=Ql,!To&&0Zy)break n}else Bx=Zy;for(U1=0;U1V1)Bk[U1++]=V1,V1!=0&&(cp=V1);else{var A3=V1==16,$k=V1-16,HT=Pk[$k],$v=te(Xy,F_[$k])+HT;if(U1+$v>Zy)break n;for(var Uv=A3?cp:0;0<$v--;)Bk[U1++]=Uv}}tj=1;break n}tj||(lp.a=3),yy=tj}(yy=yy&&!lg.h)&&($1=U(Ok,B1,8,bm,zx)),yy&&$1!=0?Fb=$1:(z1.a=3,Fb=0)}if(Fb==0)break s;if(Vd&&zv[To]==1&&(Vd=rx[Ql].g==0),Jl+=rx[Ql].g,Ql+=Fb,3>=To){var H0,U_=Pp[0];for(H0=1;H0U_&&(U_=Pp[H0]);bd+=U_}}if(Qd.nd=Vd,Qd.Qb=0,Vd&&(Qd.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&&(Qd.Qb=1,Qd.qb+=ff[0][Td[0]+0].value<<8)),Qd.jc=!Qd.Qb&&6>bd,Qd.jc){var cg,G0=Qd;for(cg=0;cg>=bn(qv,8,up),Qy>>=bn(G0.G[1][G0.H[1]+Qy],16,up),Qy>>=bn(G0.G[2][G0.H[2]+Qy],0,up),bn(G0.G[3][G0.H[3]+Qy],24,up))}}}mf.vc=ud,mf.Wb=lu,mf.Ya=nx,mf.yc=Bm,bi=1;break t}bi=0}if(!(Ns=bi)){Tt.a=3;break e}if(0Tt+1?[]:0),!(ls.lengthPe?0:Pe>He?He:Pe}function xc(){this.T=this.U=this.ka=this.height=this.width=0,this.y=[],this.f=[],this.ea=[],this.Rc=this.fa=this.W=this.N=this.O=0,this.ma="void",this.put="VP8IoPutHook",this.ac="VP8IoSetupHook",this.bc="VP8IoTeardownHook",this.ha=this.Kb=0,this.data=[],this.hb=this.ib=this.da=this.o=this.j=this.va=this.v=this.Da=this.ob=this.w=0,this.F=[],this.J=0}function fl(){var Pe=new ao;return Pe!=null&&(Pe.a=0,Pe.sc="OK",Pe.cb=0,Pe.Xb=0,ap||(ap=nd)),Pe}function Co(Pe,He,ft){return Pe.a==0&&(Pe.a=He,Pe.sc=ft,Pe.cb=0),0}function fu(Pe,He,ft){return 3<=ft&&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 ft=He.data,Tt=He.w,ls=He.ha;if(4>ls)return Co(Pe,7,"Truncated header.");var Ns=ft[Tt+0]|ft[Tt+1]<<8|ft[Tt+2]<<16,As=Pe.Od;if(As.Rb=!(1&Ns),As.td=Ns>>1&7,As.yd=Ns>>4&1,As.ub=Ns>>5,3ls)return Co(Pe,7,"cannot parse picture header");if(!fu(ft,Tt,ls))return Co(Pe,3,"Bad code word");Ds.c=16383&(ft[Tt+4]<<8|ft[Tt+3]),Ds.Td=ft[Tt+4]>>6,Ds.i=16383&(ft[Tt+6]<<8|ft[Tt+5]),Ds.Ud=ft[Tt+6]>>6,Tt+=7,ls-=7,Pe.za=Ds.c+15>>4,Pe.Ub=Ds.i+15>>4,He.width=Ds.c,He.height=Ds.i,He.Da=0,He.j=0,He.v=0,He.va=He.width,He.o=He.height,He.da=0,He.ib=He.width,He.hb=He.height,He.U=He.width,He.T=He.height,a((Ns=Pe.Pa).jb,0,255,Ns.jb.length),t((Ns=Pe.Qa)!=null),Ns.Cb=0,Ns.Bb=0,Ns.Fb=1,a(Ns.Zb,0,0,Ns.Zb.length),a(Ns.Lb,0,0,Ns.Lb)}if(As.ub>ls)return Co(Pe,7,"bad partition length");Y(Ns=Pe.m,ft,Tt,As.ub),Tt+=As.ub,ls-=As.ub,As.Rb&&(Ds.Ld=Se(Ns),Ds.Kd=Se(Ns)),Ds=Pe.Qa;var qs,on=Pe.Pa;if(t(Ns!=null),t(Ds!=null),Ds.Cb=Se(Ns),Ds.Cb){if(Ds.Bb=Se(Ns),Se(Ns)){for(Ds.Fb=Se(Ns),qs=0;4>qs;++qs)Ds.Zb[qs]=Se(Ns)?ae(Ns,7):0;for(qs=0;4>qs;++qs)Ds.Lb[qs]=Se(Ns)?ae(Ns,6):0}if(Ds.Bb)for(qs=0;3>qs;++qs)on.jb[qs]=Se(Ns)?X(Ns,8):255}else Ds.Bb=0;if(Ns.Ka)return Co(Pe,3,"cannot parse segment header");if((Ds=Pe.ed).zd=Se(Ns),Ds.Tb=X(Ns,6),Ds.wb=X(Ns,3),Ds.Pc=Se(Ns),Ds.Pc&&Se(Ns)){for(on=0;4>on;++on)Se(Ns)&&(Ds.vd[on]=ae(Ns,6));for(on=0;4>on;++on)Se(Ns)&&(Ds.od[on]=ae(Ns,6))}if(Pe.L=Ds.Tb==0?0:Ds.zd?1:2,Ns.Ka)return Co(Pe,3,"cannot parse filter header");var Zn=ls;if(ls=qs=Tt,Tt=qs+Zn,Ds=Zn,Pe.Xb=(1<Ds&&(Ar=Ds),Y(Pe.Jc[+Zn],ft,qs,Ar),qs+=Ar,Ds-=Ar,ls+=3}Y(Pe.Jc[+on],ft,qs,Ds),ft=qsAr;++Ar){if(Zn.Cb){var Qs=Zn.Zb[Ar];Zn.Fb||(Qs+=ft)}else{if(0>16,8>or.Eb[1]&&(or.Eb[1]=8),or.Qc[0]=D1[ta(Qs+on,117)],or.Qc[1]=ex[ta(Qs+qs,127)],or.lc=Qs+qs}if(!As.Rb)return Co(Pe,4,"Not a key frame.");for(Se(Ns),As=Pe.Pa,ft=0;4>ft;++ft){for(ls=0;8>ls;++ls)for(Tt=0;3>Tt;++Tt)for(Ds=0;11>Ds;++Ds)on=Le(Ns,VT[ft][ls][Tt][Ds])?X(Ns,8):IC[ft][ls][Tt][Ds],As.Wc[ft][ls].Yb[Tt][Ds]=on;for(ls=0;17>ls;++ls)As.Xc[ft][ls]=As.Wc[ft][S3[ls]]}return Pe.kc=Se(Ns),Pe.kc&&(Pe.Bd=X(Ns,8)),Pe.cb=1}function nd(Pe,He,ft,Tt,ls,Ns,As){var Ds=He[ls].Yb[ft];for(ft=0;16>ls;++ls){if(!Le(Pe,Ds[ft+0]))return ls;for(;!Le(Pe,Ds[ft+1]);)if(Ds=He[++ls].Yb[0],ft=0,ls==16)return 16;var qs=He[ls+1].Yb;if(Le(Pe,Ds[ft+2])){var on=Pe,Zn=0;if(Le(on,(Qs=Ds)[(Ar=ft)+3]))if(Le(on,Qs[Ar+6])){for(Ds=0,Ar=2*(Zn=Le(on,Qs[Ar+8]))+(Qs=Le(on,Qs[Ar+9+Zn])),Zn=0,Qs=Fx[Ar];Qs[Ds];++Ds)Zn+=Zn+Le(on,Qs[Ds]);Zn+=3+(8<(on=Pe).b&&Ee(on);var Ar,Qs=on.b,or=(Ar=on.Ca>>1)-(on.I>>Qs)>>31;--on.b,on.Ca+=or,on.Ca|=1,on.I-=(Ar+1&or)<>3),Pe[He+ft+32*Tt]=-256&ls?0>ls?0:255:ls}function zc(Pe,He,ft,Tt,ls,Ns){Hi(Pe,He,0,ft,Tt+ls),Hi(Pe,He,1,ft,Tt+Ns),Hi(Pe,He,2,ft,Tt-Ns),Hi(Pe,He,3,ft,Tt-ls)}function Bc(Pe){return(20091*Pe>>16)+Pe}function yc(Pe,He,ft,Tt){var ls,Ns=0,As=i(16);for(ls=0;4>ls;++ls){var Ds=Pe[He+0]+Pe[He+8],qs=Pe[He+0]-Pe[He+8],on=(35468*Pe[He+4]>>16)-Bc(Pe[He+12]),Zn=Bc(Pe[He+4])+(35468*Pe[He+12]>>16);As[Ns+0]=Ds+Zn,As[Ns+1]=qs+on,As[Ns+2]=qs-on,As[Ns+3]=Ds-Zn,Ns+=4,He++}for(ls=Ns=0;4>ls;++ls)Ds=(Pe=As[Ns+0]+4)+As[Ns+8],qs=Pe-As[Ns+8],on=(35468*As[Ns+4]>>16)-Bc(As[Ns+12]),Hi(ft,Tt,0,0,Ds+(Zn=Bc(As[Ns+4])+(35468*As[Ns+12]>>16))),Hi(ft,Tt,1,0,qs+on),Hi(ft,Tt,2,0,qs-on),Hi(ft,Tt,3,0,Ds-Zn),Ns++,Tt+=32}function $l(Pe,He,ft,Tt){var ls=Pe[He+0]+4,Ns=35468*Pe[He+4]>>16,As=Bc(Pe[He+4]),Ds=35468*Pe[He+1]>>16;zc(ft,Tt,0,ls+As,Pe=Bc(Pe[He+1]),Ds),zc(ft,Tt,1,ls+Ns,Pe,Ds),zc(ft,Tt,2,ls-Ns,Pe,Ds),zc(ft,Tt,3,ls-As,Pe,Ds)}function rg(Pe,He,ft,Tt,ls){yc(Pe,He,ft,Tt),ls&&yc(Pe,He+16,ft,Tt+4)}function Ix(Pe,He,ft,Tt){Xg(Pe,He+0,ft,Tt,1),Xg(Pe,He+32,ft,Tt+128,1)}function Yo(Pe,He,ft,Tt){var ls;for(Pe=Pe[He+0]+4,ls=0;4>ls;++ls)for(He=0;4>He;++He)Hi(ft,Tt,He,ls,Pe)}function Mc(Pe,He,ft,Tt){Pe[He+0]&&Gu(Pe,He+0,ft,Tt),Pe[He+16]&&Gu(Pe,He+16,ft,Tt+4),Pe[He+32]&&Gu(Pe,He+32,ft,Tt+128),Pe[He+48]&&Gu(Pe,He+48,ft,Tt+128+4)}function Mh(Pe,He,ft,Tt){var ls,Ns=i(16);for(ls=0;4>ls;++ls){var As=Pe[He+0+ls]+Pe[He+12+ls],Ds=Pe[He+4+ls]+Pe[He+8+ls],qs=Pe[He+4+ls]-Pe[He+8+ls],on=Pe[He+0+ls]-Pe[He+12+ls];Ns[0+ls]=As+Ds,Ns[8+ls]=As-Ds,Ns[4+ls]=on+qs,Ns[12+ls]=on-qs}for(ls=0;4>ls;++ls)As=(Pe=Ns[0+4*ls]+3)+Ns[3+4*ls],Ds=Ns[1+4*ls]+Ns[2+4*ls],qs=Ns[1+4*ls]-Ns[2+4*ls],on=Pe-Ns[3+4*ls],ft[Tt+0]=As+Ds>>3,ft[Tt+16]=on+qs>>3,ft[Tt+32]=As-Ds>>3,ft[Tt+48]=on-qs>>3,Tt+=64}function lm(Pe,He,ft){var Tt,ls=He-32,Ns=Ui,As=255-Pe[ls-1];for(Tt=0;Ttft;++ft)r(Pe,He+32*ft,Pe,He-32,16)}function Ba(Pe,He){var ft;for(ft=16;0Tt;++Tt)a(He,ft+32*Tt,Pe,16)}function ko(Pe,He){var ft,Tt=16;for(ft=0;16>ft;++ft)Tt+=Pe[He-1+32*ft]+Pe[He+ft-32];io(Tt>>5,Pe,He)}function qi(Pe,He){var ft,Tt=8;for(ft=0;16>ft;++ft)Tt+=Pe[He-1+32*ft];io(Tt>>4,Pe,He)}function cm(Pe,He){var ft,Tt=8;for(ft=0;16>ft;++ft)Tt+=Pe[He+ft-32];io(Tt>>4,Pe,He)}function Zo(Pe,He){io(128,Pe,He)}function vo(Pe,He,ft){return Pe+2*He+ft+2>>2}function Zg(Pe,He){var ft,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])]),ft=0;4>ft;++ft)r(Pe,He+32*ft,Tt,0,Tt.length)}function Fl(Pe,He){var ft=Pe[He-1],Tt=Pe[He-1+32],ls=Pe[He-1+64],Ns=Pe[He-1+96];Fe(Pe,He+0,16843009*vo(Pe[He-1-32],ft,Tt)),Fe(Pe,He+32,16843009*vo(ft,Tt,ls)),Fe(Pe,He+64,16843009*vo(Tt,ls,Ns)),Fe(Pe,He+96,16843009*vo(ls,Ns,Ns))}function Ol(Pe,He){var ft,Tt=4;for(ft=0;4>ft;++ft)Tt+=Pe[He+ft-32]+Pe[He-1+32*ft];for(Tt>>=3,ft=0;4>ft;++ft)a(Pe,He+32*ft,Tt,4)}function xy(Pe,He){var ft=Pe[He-1+0],Tt=Pe[He-1+32],ls=Pe[He-1+64],Ns=Pe[He-1-32],As=Pe[He+0-32],Ds=Pe[He+1-32],qs=Pe[He+2-32],on=Pe[He+3-32];Pe[He+0+96]=vo(Tt,ls,Pe[He-1+96]),Pe[He+1+96]=Pe[He+0+64]=vo(ft,Tt,ls),Pe[He+2+96]=Pe[He+1+64]=Pe[He+0+32]=vo(Ns,ft,Tt),Pe[He+3+96]=Pe[He+2+64]=Pe[He+1+32]=Pe[He+0+0]=vo(As,Ns,ft),Pe[He+3+64]=Pe[He+2+32]=Pe[He+1+0]=vo(Ds,As,Ns),Pe[He+3+32]=Pe[He+2+0]=vo(qs,Ds,As),Pe[He+3+0]=vo(on,qs,Ds)}function Zd(Pe,He){var ft=Pe[He+1-32],Tt=Pe[He+2-32],ls=Pe[He+3-32],Ns=Pe[He+4-32],As=Pe[He+5-32],Ds=Pe[He+6-32],qs=Pe[He+7-32];Pe[He+0+0]=vo(Pe[He+0-32],ft,Tt),Pe[He+1+0]=Pe[He+0+32]=vo(ft,Tt,ls),Pe[He+2+0]=Pe[He+1+32]=Pe[He+0+64]=vo(Tt,ls,Ns),Pe[He+3+0]=Pe[He+2+32]=Pe[He+1+64]=Pe[He+0+96]=vo(ls,Ns,As),Pe[He+3+32]=Pe[He+2+64]=Pe[He+1+96]=vo(Ns,As,Ds),Pe[He+3+64]=Pe[He+2+96]=vo(As,Ds,qs),Pe[He+3+96]=vo(Ds,qs,qs)}function Vh(Pe,He){var ft=Pe[He-1+0],Tt=Pe[He-1+32],ls=Pe[He-1+64],Ns=Pe[He-1-32],As=Pe[He+0-32],Ds=Pe[He+1-32],qs=Pe[He+2-32],on=Pe[He+3-32];Pe[He+0+0]=Pe[He+1+64]=Ns+As+1>>1,Pe[He+1+0]=Pe[He+2+64]=As+Ds+1>>1,Pe[He+2+0]=Pe[He+3+64]=Ds+qs+1>>1,Pe[He+3+0]=qs+on+1>>1,Pe[He+0+96]=vo(ls,Tt,ft),Pe[He+0+64]=vo(Tt,ft,Ns),Pe[He+0+32]=Pe[He+1+96]=vo(ft,Ns,As),Pe[He+1+32]=Pe[He+2+96]=vo(Ns,As,Ds),Pe[He+2+32]=Pe[He+3+96]=vo(As,Ds,qs),Pe[He+3+32]=vo(Ds,qs,on)}function cf(Pe,He){var ft=Pe[He+0-32],Tt=Pe[He+1-32],ls=Pe[He+2-32],Ns=Pe[He+3-32],As=Pe[He+4-32],Ds=Pe[He+5-32],qs=Pe[He+6-32],on=Pe[He+7-32];Pe[He+0+0]=ft+Tt+1>>1,Pe[He+1+0]=Pe[He+0+64]=Tt+ls+1>>1,Pe[He+2+0]=Pe[He+1+64]=ls+Ns+1>>1,Pe[He+3+0]=Pe[He+2+64]=Ns+As+1>>1,Pe[He+0+32]=vo(ft,Tt,ls),Pe[He+1+32]=Pe[He+0+96]=vo(Tt,ls,Ns),Pe[He+2+32]=Pe[He+1+96]=vo(ls,Ns,As),Pe[He+3+32]=Pe[He+2+96]=vo(Ns,As,Ds),Pe[He+3+64]=vo(As,Ds,qs),Pe[He+3+96]=vo(Ds,qs,on)}function Ky(Pe,He){var ft=Pe[He-1+0],Tt=Pe[He-1+32],ls=Pe[He-1+64],Ns=Pe[He-1+96];Pe[He+0+0]=ft+Tt+1>>1,Pe[He+2+0]=Pe[He+0+32]=Tt+ls+1>>1,Pe[He+2+32]=Pe[He+0+64]=ls+Ns+1>>1,Pe[He+1+0]=vo(ft,Tt,ls),Pe[He+3+0]=Pe[He+1+32]=vo(Tt,ls,Ns),Pe[He+3+32]=Pe[He+1+64]=vo(ls,Ns,Ns),Pe[He+3+64]=Pe[He+2+64]=Pe[He+0+96]=Pe[He+1+96]=Pe[He+2+96]=Pe[He+3+96]=Ns}function ih(Pe,He){var ft=Pe[He-1+0],Tt=Pe[He-1+32],ls=Pe[He-1+64],Ns=Pe[He-1+96],As=Pe[He-1-32],Ds=Pe[He+0-32],qs=Pe[He+1-32],on=Pe[He+2-32];Pe[He+0+0]=Pe[He+2+32]=ft+As+1>>1,Pe[He+0+32]=Pe[He+2+64]=Tt+ft+1>>1,Pe[He+0+64]=Pe[He+2+96]=ls+Tt+1>>1,Pe[He+0+96]=Ns+ls+1>>1,Pe[He+3+0]=vo(Ds,qs,on),Pe[He+2+0]=vo(As,Ds,qs),Pe[He+1+0]=Pe[He+3+32]=vo(ft,As,Ds),Pe[He+1+32]=Pe[He+3+64]=vo(Tt,ft,As),Pe[He+1+64]=Pe[He+3+96]=vo(ls,Tt,ft),Pe[He+1+96]=vo(Ns,ls,Tt)}function gh(Pe,He){var ft;for(ft=0;8>ft;++ft)r(Pe,He+32*ft,Pe,He-32,8)}function xt(Pe,He){var ft;for(ft=0;8>ft;++ft)a(Pe,He,Pe[He-1],8),He+=32}function We(Pe,He,ft){var Tt;for(Tt=0;8>Tt;++Tt)a(He,ft+32*Tt,Pe,8)}function ct(Pe,He){var ft,Tt=8;for(ft=0;8>ft;++ft)Tt+=Pe[He+ft-32]+Pe[He-1+32*ft];We(Tt>>4,Pe,He)}function jt(Pe,He){var ft,Tt=4;for(ft=0;8>ft;++ft)Tt+=Pe[He+ft-32];We(Tt>>3,Pe,He)}function Rt(Pe,He){var ft,Tt=4;for(ft=0;8>ft;++ft)Tt+=Pe[He-1+32*ft];We(Tt>>3,Pe,He)}function zt(Pe,He){We(128,Pe,He)}function Ht(Pe,He,ft){var Tt=Pe[He-ft],ls=Pe[He+0],Ns=3*(ls-Tt)+Ih[1020+Pe[He-2*ft]-Pe[He+ft]],As=yh[112+(Ns+4>>3)];Pe[He-ft]=Ui[255+Tt+yh[112+(Ns+3>>3)]],Pe[He+0]=Ui[255+ls-As]}function ws(Pe,He,ft,Tt){var ls=Pe[He+0],Ns=Pe[He+ft];return um[255+Pe[He-2*ft]-Pe[He-ft]]>Tt||um[255+Ns-ls]>Tt}function Ts(Pe,He,ft,Tt){return 4*um[255+Pe[He-ft]-Pe[He+0]]+um[255+Pe[He-2*ft]-Pe[He+ft]]<=Tt}function js(Pe,He,ft,Tt,ls){var Ns=Pe[He-3*ft],As=Pe[He-2*ft],Ds=Pe[He-ft],qs=Pe[He+0],on=Pe[He+ft],Zn=Pe[He+2*ft],Ar=Pe[He+3*ft];return 4*um[255+Ds-qs]+um[255+As-on]>Tt?0:um[255+Pe[He-4*ft]-Ns]<=ls&&um[255+Ns-As]<=ls&&um[255+As-Ds]<=ls&&um[255+Ar-Zn]<=ls&&um[255+Zn-on]<=ls&&um[255+on-qs]<=ls}function Ms(Pe,He,ft,Tt){var ls=2*Tt+1;for(Tt=0;16>Tt;++Tt)Ts(Pe,He+Tt,ft,ls)&&Ht(Pe,He+Tt,ft)}function fn(Pe,He,ft,Tt){var ls=2*Tt+1;for(Tt=0;16>Tt;++Tt)Ts(Pe,He+Tt*ft,1,ls)&&Ht(Pe,He+Tt*ft,1)}function gn(Pe,He,ft,Tt){var ls;for(ls=3;0>7,pa=18*cr+63>>7,cr=9*cr+63>>7;qs[on-3*Zn]=Ui[255+qs[on-3*Zn]+cr],qs[on-2*Zn]=Ui[255+Ar+pa],qs[on-Zn]=Ui[255+Qs+ur],qs[on+0]=Ui[255+or-ur],qs[on+Zn]=Ui[255+br-pa],qs[on+2*Zn]=Ui[255+aa-cr]}He+=Tt}}function ir(Pe,He,ft,Tt,ls,Ns,As,Ds){for(Ns=2*Ns+1;0>3)],aa=yh[112+(aa+3>>3)],ur=br+1>>1;qs[on-2*Zn]=Ui[255+qs[on-2*Zn]+ur],qs[on-Zn]=Ui[255+Ar+aa],qs[on+0]=Ui[255+Qs-br],qs[on+Zn]=Ui[255+or-ur]}He+=Tt}}function er(Pe,He,ft,Tt,ls,Ns){Pn(Pe,He,ft,1,16,Tt,ls,Ns)}function tr(Pe,He,ft,Tt,ls,Ns){Pn(Pe,He,1,ft,16,Tt,ls,Ns)}function vr(Pe,He,ft,Tt,ls,Ns){var As;for(As=3;0on?0:255:on)&255,on=qs,ls[Ns+Ds]=Zn}}function to(Pe,He,ft,Tt){var ls=He.width,Ns=He.o;if(t(Pe!=null&&He!=null),0>ft||0>=Tt||ft+Tt>Ns)return null;if(!Pe.Cc){if(Pe.ga==null){var As;if(Pe.ga=new na,(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 Ds=Pe.Fa,qs=Pe.P,on=Pe.qc,Zn=Pe.mb,Ar=Pe.nb,Qs=qs+1,or=on-1,br=As.l;if(t(Ds!=null&&Zn!=null&&He!=null),Rb[0]=null,Rb[1]=$a,Rb[2]=Na,Rb[3]=La,As.ca=Zn,As.tb=Ar,As.c=He.width,As.i=He.height,t(0=on)He=0;else if(As.$a=3&Ds[qs+0],As.Z=Ds[qs+0]>>2&3,As.Lc=Ds[qs+0]>>4&3,qs=Ds[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=Ns-ft}t(Pe.ga!=null),t(ft+Tt<=Ns);e:{if(He=(Ds=Pe.ga).c,Ns=Ds.l.o,Ds.$a==0){if(Qs=Pe.rc,or=Pe.Vc,br=Pe.Fa,qs=Pe.P+1+ft*He,on=Pe.mb,Zn=Pe.nb+ft*He,t(qs<=Pe.P+Pe.qc),Ds.Z!=0)for(t(Rb[Ds.Z]!=null),As=0;As=He)He=1;else if(Ds.ic||po(),Ds.ic){Ds=As.V,Qs=As.Ba,or=As.c;var aa=As.i,ur=(br=1,qs=As.$/or,on=As.$%or,Zn=As.m,Ar=As.s,As.$),pa=or*aa,cr=or*He,Ua=Ar.wc,Ea=ur(aa=Fn(Ea.G[0],Ea.H[0],Zn)))Ds[Qs+ur]=aa,++ur,++on>=or&&(on=0,++qs<=He&&!(qs%16)&&Cr(As,qs));else{if(!(280>aa)){br=0;break t}aa=$n(aa-256,Zn);var _o,Fi=Fn(Ea.G[4],Ea.H[4],Zn);if(ve(Zn),!(ur>=(Fi=kn(or,Fi=$n(Fi,Zn)))&&pa-ur>=aa)){br=0;break t}for(_o=0;_o=or;)on-=or,++qs<=He&&!(qs%16)&&Cr(As,qs);urHe?He:qs);break t}!br||Zn.h&&ur=Ns&&(Pe.Cc=1),Tt=1}if(!Tt)return null;if(Pe.Cc&&((Tt=Pe.ga)!=null&&(Tt.mc=null),Pe.ga=null,0>23,Ds[qs+4*As+1]=Ds[qs+4*As+1]*Ar>>23,Ds[qs+4*As+2]=Ds[qs+4*As+2]*Ar>>23)}He+=Ns}}function oo(Pe,He,ft,Tt,ls){for(;0>4)*qs>>16;Pe[He+2*Ns+0]=(240&As|As>>4)*qs>>16&240|(15&As|As<<4)*qs>>16>>4&15,Pe[He+2*Ns+1]=240&on|Ds}He+=ls}}function Lo(Pe,He,ft,Tt,ls,Ns,As,Ds){var qs,on,Zn=255;for(on=0;on>8}function po(){Ud=xo,xu=oo,D_=Lo,Ov=Ul}function nl(Pe,He,ft){R[Pe]=function(Tt,ls,Ns,As,Ds,qs,on,Zn,Ar,Qs,or,br,aa,ur,pa,cr,Ua){var Ea,_o=Ua-1>>1,Fi=Ds[qs+0]|on[Zn+0]<<16,bl=Ar[Qs+0]|or[br+0]<<16;t(Tt!=null);var lo=3*Fi+bl+131074>>2;for(He(Tt[ls+0],255&lo,lo>>16,aa,ur),Ns!=null&&(lo=3*bl+Fi+131074>>2,He(Ns[As+0],255&lo,lo>>16,pa,cr)),Ea=1;Ea<=_o;++Ea){var Lc=Ds[qs+Ea]|on[Zn+Ea]<<16,hf=Ar[Qs+Ea]|or[br+Ea]<<16,Xl=Fi+Lc+bl+hf+524296,yo=Xl+2*(Lc+bl)>>3;lo=yo+Fi>>1,Fi=(Xl=Xl+2*(Fi+hf)>>3)+Lc>>1,He(Tt[ls+2*Ea-1],255&lo,lo>>16,aa,ur+(2*Ea-1)*ft),He(Tt[ls+2*Ea-0],255&Fi,Fi>>16,aa,ur+(2*Ea-0)*ft),Ns!=null&&(lo=Xl+bl>>1,Fi=yo+hf>>1,He(Ns[As+2*Ea-1],255&lo,lo>>16,pa,cr+(2*Ea-1)*ft),He(Ns[As+2*Ea+0],255&Fi,Fi>>16,pa,cr+(2*Ea+0)*ft)),Fi=Lc,bl=hf}1&Ua||(lo=3*Fi+bl+131074>>2,He(Tt[ls+Ua-1],255&lo,lo>>16,aa,ur+(Ua-1)*ft),Ns!=null&&(lo=3*bl+Fi+131074>>2,He(Ns[As+Ua-1],255&lo,lo>>16,pa,cr+(Ua-1)*ft)))}}function Pl(){ip[lh]=Xw,ip[np]=Lk,ip[Qg]=Dr,ip[ch]=RC,ip[Ic]=tx,ip[Jg]=uf,ip[I1]=F1,ip[L1]=Lk,ip[R1]=RC,ip[Yw]=tx,ip[Zw]=uf}function Cd(Pe){return Pe&-16384?0>Pe?0:255:Pe>>H2}function au(Pe,He){return Cd((19077*Pe>>8)+(26149*He>>8)-14234)}function qt(Pe,He,ft){return Cd((19077*Pe>>8)-(6419*He>>8)-(13320*ft>>8)+8708)}function Cn(Pe,He){return Cd((19077*Pe>>8)+(33050*He>>8)-17685)}function rr(Pe,He,ft,Tt,ls){Tt[ls+0]=au(Pe,ft),Tt[ls+1]=qt(Pe,He,ft),Tt[ls+2]=Cn(Pe,He)}function ra(Pe,He,ft,Tt,ls){Tt[ls+0]=Cn(Pe,He),Tt[ls+1]=qt(Pe,He,ft),Tt[ls+2]=au(Pe,ft)}function Yr(Pe,He,ft,Tt,ls){var Ns=qt(Pe,He,ft);He=Ns<<3&224|Cn(Pe,He)>>3,Tt[ls+0]=248&au(Pe,ft)|Ns>>5,Tt[ls+1]=He}function Aa(Pe,He,ft,Tt,ls){var Ns=240&Cn(Pe,He)|15;Tt[ls+0]=240&au(Pe,ft)|qt(Pe,He,ft)>>4,Tt[ls+1]=Ns}function gi(Pe,He,ft,Tt,ls){Tt[ls+0]=255,rr(Pe,He,ft,Tt,ls+1)}function Ia(Pe,He,ft,Tt,ls){ra(Pe,He,ft,Tt,ls),Tt[ls+3]=255}function el(Pe,He,ft,Tt,ls){rr(Pe,He,ft,Tt,ls),Tt[ls+3]=255}function zo(Pe,He,ft){R[Pe]=function(Tt,ls,Ns,As,Ds,qs,on,Zn,Ar){for(var Qs=Zn+(-2&Ar)*ft;Zn!=Qs;)He(Tt[ls+0],Ns[As+0],Ds[qs+0],on,Zn),He(Tt[ls+1],Ns[As+0],Ds[qs+0],on,Zn+ft),ls+=2,++As,++qs,Zn+=2*ft;1&Ar&&He(Tt[ls+0],Ns[As+0],Ds[qs+0],on,Zn)}}function Pc(Pe,He,ft){return ft==0?Pe==0?He==0?6:5:He==0?4:0:ft}function Tu(Pe,He,ft,Tt,ls){switch(Pe>>>30){case 3:Xg(He,ft,Tt,ls,0);break;case 2:Om(He,ft,Tt,ls);break;case 1:Gu(He,ft,Tt,ls)}}function iu(Pe,He){var ft,Tt,ls=He.M,Ns=He.Nb,As=Pe.oc,Ds=Pe.pc+40,qs=Pe.oc,on=Pe.pc+584,Zn=Pe.oc,Ar=Pe.pc+600;for(ft=0;16>ft;++ft)As[Ds+32*ft-1]=129;for(ft=0;8>ft;++ft)qs[on+32*ft-1]=129,Zn[Ar+32*ft-1]=129;for(0ft;++ft)r(As,Ds+32*ft-4,As,Ds+32*ft+12,4);for(ft=-1;8>ft;++ft)r(qs,on+32*ft-4,qs,on+32*ft+4,4),r(Zn,Ar+32*ft-4,Zn,Ar+32*ft+4,4)}var or=Pe.Gd,br=Pe.Hd+Tt,aa=Qs.ad,ur=Qs.Hc;if(0=Pe.za-1?a(pa,cr,or[br].y[15],4):r(pa,cr,or[br+1].y,0,4)),ft=0;4>ft;ft++)pa[cr+128+ft]=pa[cr+256+ft]=pa[cr+384+ft]=pa[cr+0+ft];for(ft=0;16>ft;++ft,ur<<=2)pa=As,cr=Ds+B_[ft],Tp[Qs.Ob[ft]](pa,cr),Tu(ur,aa,16*+ft,pa,cr)}else if(pa=Pc(Tt,ls,Qs.Ob[0]),Lb[pa](As,Ds),ur!=0)for(ft=0;16>ft;++ft,ur<<=2)Tu(ur,aa,16*+ft,As,Ds+B_[ft]);for(ft=Qs.Gc,pa=Pc(Tt,ls,Qs.Dd),U0[pa](qs,on),U0[pa](Zn,Ar),ur=aa,pa=qs,cr=on,255&(Qs=0|ft)&&(170&Qs?Rx(ur,256,pa,cr):kc(ur,256,pa,cr)),Qs=Zn,ur=Ar,255&(ft>>=8)&&(170&ft?Rx(aa,320,Qs,ur):kc(aa,320,Qs,ur)),lsft;++ft)r(or,br+ft*Pe.R,As,Ds+32*ft,16);for(ft=0;8>ft;++ft)r(aa,Qs+ft*Pe.B,qs,on+32*ft,8),r(ur,pa+ft*Pe.B,Zn,Ar+32*ft,8)}}function dm(Pe,He,ft,Tt,ls,Ns,As,Ds,qs){var on=[0],Zn=[0],Ar=0,Qs=qs!=null?qs.kd:0,or=qs??new tn;if(Pe==null||12>ft)return 7;or.data=Pe,or.w=He,or.ha=ft,He=[He],ft=[ft],or.gb=[or.gb];e:{var br=He,aa=ft,ur=or.gb;if(t(Pe!=null),t(aa!=null),t(ur!=null),ur[0]=0,12<=aa[0]&&!n(Pe,br[0],"RIFF")){if(n(Pe,br[0]+8,"WEBP")){ur=3;break e}var pa=Ne(Pe,br[0]+4);if(12>pa||4294967286aa[0]-8){ur=7;break e}ur[0]=pa,br[0]+=12,aa[0]-=12}ur=0}if(ur!=0)return ur;for(pa=0ur[0])ur=7;else{if(!n(cr,aa[0],"VP8X")){if(Ne(cr,aa[0]+4)!=10){ur=3;break e}if(18>ur[0]){ur=7;break e}var Fi=Ne(cr,aa[0]+8),bl=1+Be(cr,aa[0]+12);if(2147483648<=bl*(cr=1+Be(cr,aa[0]+15))){ur=3;break e}_o!=null&&(_o[0]=Fi),Ua!=null&&(Ua[0]=bl),Ea!=null&&(Ea[0]=cr),aa[0]+=18,ur[0]-=18,lo[0]=1}ur=0}}if(Ar=Ar[0],br=br[0],ur!=0)return ur;if(aa=!!(2&br),!pa&&Ar)return 3;if(Ns!=null&&(Ns[0]=!!(16&br)),As!=null&&(As[0]=aa),Ds!=null&&(Ds[0]=0),As=on[0],br=Zn[0],Ar&&aa&&qs==null){ur=0;break}if(4>ft){ur=7;break}if(pa&&Ar||!pa&&!Ar&&!n(Pe,He[0],"ALPH")){ft=[ft],or.na=[or.na],or.P=[or.P],or.Sa=[or.Sa];e:{Fi=Pe,ur=He,pa=ft;var lo=or.gb;Ua=or.na,Ea=or.P,_o=or.Sa,bl=22,t(Fi!=null),t(pa!=null),cr=ur[0];var Lc=pa[0];for(t(Ua!=null),t(_o!=null),Ua[0]=null,Ea[0]=null,_o[0]=0;;){if(ur[0]=cr,pa[0]=Lc,8>Lc){ur=7;break e}var hf=Ne(Fi,cr+4);if(4294967286lo){ur=3;break e}if(!n(Fi,cr,"VP8 ")||!n(Fi,cr,"VP8L")){ur=0;break e}if(Lc[0]pa[0])ur=7;else{if(cr||bl){if(lo=Ne(lo,Fi+4),12<=Ua&&lo>Ua-12){ur=3;break e}if(Qs&&lo>pa[0]-8){ur=7;break e}Ea[0]=lo,ur[0]+=8,pa[0]-=8,_o[0]=bl}else _o[0]=5<=pa[0]&&lo[Fi+0]==47&&!(lo[Fi+4]>>5),Ea[0]=pa[0];ur=0}if(ft=ft[0],or.Ja=or.Ja[0],or.xa=or.xa[0],He=He[0],ur!=0)break;if(4294967286ft){ur=7;break}Ds=As,Qs=br,aa=Ns,Pe==null||5>ft?Pe=0:5<=ft&&Pe[He+0]==47&&!(Pe[He+4]>>5)?(pa=[0],lo=[0],Ua=[0],le(Ea=new ce,Pe,He,ft),kr(Ea,pa,lo,Ua)?(Ds!=null&&(Ds[0]=pa[0]),Qs!=null&&(Qs[0]=lo[0]),aa!=null&&(aa[0]=Ua[0]),Pe=1):Pe=0):Pe=0}else{if(10>ft){ur=7;break}Ds=br,Pe==null||10>ft||!fu(Pe,He+3,ft-3)?Pe=0:(Qs=Pe[He+0]|Pe[He+1]<<8|Pe[He+2]<<16,aa=16383&(Pe[He+7]<<8|Pe[He+6]),Pe=16383&(Pe[He+9]<<8|Pe[He+8]),1&Qs||3<(Qs>>1&7)||!(Qs>>4&1)||Qs>>5>=or.Ja||!aa||!Pe?Pe=0:(As&&(As[0]=aa),Ds&&(Ds[0]=Pe),Pe=1))}if(!Pe||(As=As[0],br=br[0],Ar&&(on[0]!=As||Zn[0]!=br)))return 3;qs!=null&&(qs[0]=or,qs.offset=He-qs.w,t(4294967286>He-qs.w),t(qs.offset==qs.ha-ft));break}return ur==0||ur==7&&Ar&&qs==null?(Ns!=null&&(Ns[0]|=or.na!=null&&0ft||(Ns&=-2,As&=-2),0>Ns||0>As||0>=Ds||0>=qs||Ns+Ds>Tt||As+qs>ls))return 0;if(He.v=Ns,He.j=As,He.va=Ns+Ds,He.o=As+qs,He.U=Ds,He.T=qs,He.da=Pe!=null&&0Pe.S){var He=Pe.f.RGBA;He.fb+=(Pe.height-1)*He.A,He.A=-He.A}else He=Pe.f.kb,Pe=Pe.height,He.O+=(Pe-1)*He.fa,He.fa=-He.fa,He.N+=(Pe-1>>1)*He.Ab,He.Ab=-He.Ab,He.W+=(Pe-1>>1)*He.Db,He.Db=-He.Db,He.F!=null&&(He.J+=(Pe-1)*He.lb,He.lb=-He.lb);return 0}function Zc(Pe,He,ft,Tt){if(Tt==null||0>=Pe||0>=He)return 2;if(ft!=null){if(ft.Da){var ls=ft.cd,Ns=ft.bd,As=-2&ft.v,Ds=-2&ft.j;if(0>As||0>Ds||0>=ls||0>=Ns||As+ls>Pe||Ds+Ns>He)return 2;Pe=ls,He=Ns}if(ft.da){if(!ze(Pe,He,ls=[ft.ib],Ns=[ft.hb]))return 2;Pe=ls[0],He=Ns[0]}}Tt.width=Pe,Tt.height=He;e:{var qs=Tt.width,on=Tt.height;if(Pe=Tt.S,0>=qs||0>=on||!(Pe>=lh&&13>Pe))Pe=2;else{if(0>=Tt.Rd&&Tt.sd==null){As=Ns=ls=He=0;var Zn=(Ds=qs*Jw[Pe])*on;if(11>Pe||(Ns=(on+1)/2*(He=(qs+1)/2),Pe==12&&(As=(ls=qs)*on)),(on=i(Zn+2*Ns+As))==null){Pe=1;break e}Tt.sd=on,11>Pe?((qs=Tt.f.RGBA).eb=on,qs.fb=0,qs.A=Ds,qs.size=Zn):((qs=Tt.f.kb).y=on,qs.O=0,qs.fa=Ds,qs.Fd=Zn,qs.f=on,qs.N=0+Zn,qs.Ab=He,qs.Cd=Ns,qs.ea=on,qs.W=0+Zn+Ns,qs.Db=He,qs.Ed=Ns,Pe==12&&(qs.F=on,qs.J=0+Zn+2*Ns),qs.Tc=As,qs.lb=ls)}if(He=1,ls=Tt.S,Ns=Tt.width,As=Tt.height,ls>=lh&&13>ls)if(11>ls)Pe=Tt.f.RGBA,He&=(Ds=Math.abs(Pe.A))*(As-1)+Ns<=Pe.size,He&=Ds>=Ns*Jw[ls],He&=Pe.eb!=null;else{Pe=Tt.f.kb,Ds=(Ns+1)/2,Zn=(As+1)/2,qs=Math.abs(Pe.fa),on=Math.abs(Pe.Ab);var Ar=Math.abs(Pe.Db),Qs=Math.abs(Pe.lb),or=Qs*(As-1)+Ns;He&=qs*(As-1)+Ns<=Pe.Fd,He&=on*(Zn-1)+Ds<=Pe.Cd,He=(He&=Ar*(Zn-1)+Ds<=Pe.Ed)&qs>=Ns&on>=Ds&Ar>=Ds,He&=Pe.y!=null,He&=Pe.f!=null,He&=Pe.ea!=null,ls==12&&(He&=Qs>=Ns,He&=or<=Pe.Tc,He&=Pe.F!=null)}else He=0;Pe=He?0:2}}return Pe!=0||ft!=null&&ft.fd&&(Pe=pu(Tt)),Pe}var rd=64,oh=[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,Bd=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];Xe("Predictor0","PredictorAdd0"),R.Predictor0=function(){return 4278190080},R.Predictor1=function(Pe){return Pe},R.Predictor2=function(Pe,He,ft){return He[ft+0]},R.Predictor3=function(Pe,He,ft){return He[ft+1]},R.Predictor4=function(Pe,He,ft){return He[ft-1]},R.Predictor5=function(Pe,He,ft){return rt(rt(Pe,He[ft+1]),He[ft+0])},R.Predictor6=function(Pe,He,ft){return rt(Pe,He[ft-1])},R.Predictor7=function(Pe,He,ft){return rt(Pe,He[ft+0])},R.Predictor8=function(Pe,He,ft){return rt(He[ft-1],He[ft+0])},R.Predictor9=function(Pe,He,ft){return rt(He[ft+0],He[ft+1])},R.Predictor10=function(Pe,He,ft){return rt(rt(Pe,He[ft-1]),rt(He[ft+0],He[ft+1]))},R.Predictor11=function(Pe,He,ft){var Tt=He[ft+0];return 0>=pt(Tt>>24&255,Pe>>24&255,(He=He[ft-1])>>24&255)+pt(Tt>>16&255,Pe>>16&255,He>>16&255)+pt(Tt>>8&255,Pe>>8&255,He>>8&255)+pt(255&Tt,255&Pe,255&He)?Tt:Pe},R.Predictor12=function(Pe,He,ft){var Tt=He[ft+0];return(Ke((Pe>>24&255)+(Tt>>24&255)-((He=He[ft-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,ft){var Tt=He[ft-1];return(Je((Pe=rt(Pe,He[ft+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,Xe("Predictor2","PredictorAdd2"),Xe("Predictor3","PredictorAdd3"),Xe("Predictor4","PredictorAdd4"),Xe("Predictor5","PredictorAdd5"),Xe("Predictor6","PredictorAdd6"),Xe("Predictor7","PredictorAdd7"),Xe("Predictor8","PredictorAdd8"),Xe("Predictor9","PredictorAdd9"),Xe("Predictor10","PredictorAdd10"),Xe("Predictor11","PredictorAdd11"),Xe("Predictor12","PredictorAdd12"),Xe("Predictor13","PredictorAdd13");var $d=R.PredictorAdd2;ys("ColorIndexInverseTransform","MapARGB","32b",function(Pe){return Pe>>8&255},function(Pe){return Pe}),ys("VP8LColorIndexInverseTransformAlpha","MapAlpha","8b",function(Pe){return Pe},function(Pe){return Pe>>8&255});var 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,Ep,Fv,Lx,ya,Yy,Ci,Xg,Om,Rx,Gu,kc,Ro,kl,gu,fa,Ao,pl,Qc,ag,Wo,$0,xh,df,Ud,xu,D_,Ov,Dx=i(511),Pb=i(2041),Kw=i(225),zm=i(767),yu=0,Ih=Pb,yh=Kw,Ui=zm,um=Dx,lh=0,np=1,Qg=2,ch=3,Ic=4,Jg=5,I1=6,L1=7,R1=8,Yw=9,Zw=10,F_=[2,3,7],Pk=[3,3,11],Ib=[280,256,256,256,40],zv=[0,1,1,1,0],k3=[17,18,0,1,2,3,4,5,16,6,7,8,9,10,11,12,13,14,15],V2=[24,7,23,25,40,6,39,41,22,26,38,42,56,5,55,57,21,27,54,58,37,43,72,4,71,73,20,28,53,59,70,74,36,44,88,69,75,52,60,3,87,89,19,29,86,90,35,45,68,76,85,91,51,61,104,2,103,105,18,30,102,106,34,46,84,92,67,77,101,107,50,62,120,1,119,121,83,93,17,31,100,108,66,78,118,122,33,47,117,123,49,63,99,109,82,94,0,116,124,65,79,16,32,98,110,48,115,125,81,95,64,114,126,97,111,80,113,127,96,112],rp=[2954,2956,2958,2962,2970,2986,3018,3082,3212,3468,3980,5004],Ik=8,D1=[4,5,6,7,8,9,10,10,11,12,13,14,15,16,17,17,18,19,20,20,21,21,22,22,23,23,24,25,25,26,27,28,29,30,31,32,33,34,35,36,37,37,38,39,40,41,42,43,44,45,46,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,76,77,78,79,80,81,82,83,84,85,86,87,88,89,91,93,95,96,98,100,101,102,104,106,108,110,112,114,116,118,122,124,126,128,130,132,134,136,138,140,143,145,148,151,154,157],ex=[4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,119,122,125,128,131,134,137,140,143,146,149,152,155,158,161,164,167,170,173,177,181,185,189,193,197,201,205,209,213,217,221,225,229,234,239,245,249,254,259,264,269,274,279,284],ap=null,Fx=[[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]],qd=[0,1,4,8,5,2,3,6,9,12,13,10,7,11,14,15],Bv=[-0,1,-1,2,-2,3,4,6,-3,5,-4,-5,-6,7,-7,8,-8,-9],IC=[[[[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]]]],qT=[[[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]]],VT=[[[[255,255,255,255,255,255,255,255,255,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]]]],S3=[0,1,2,3,6,4,5,6,6,6,6,6,6,6,6,7,0],Lb=[],Tp=[],U0=[],LC=1,C3=2,Rb=[],ip=[];nl("UpsampleRgbLinePair",rr,3),nl("UpsampleBgrLinePair",ra,3),nl("UpsampleRgbaLinePair",el,4),nl("UpsampleBgraLinePair",Ia,4),nl("UpsampleArgbLinePair",gi,4),nl("UpsampleRgba4444LinePair",Aa,2),nl("UpsampleRgb565LinePair",Yr,2);var Xw=R.UpsampleRgbLinePair,Dr=R.UpsampleBgrLinePair,Lk=R.UpsampleRgbaLinePair,RC=R.UpsampleBgraLinePair,tx=R.UpsampleArgbLinePair,uf=R.UpsampleRgba4444LinePair,F1=R.UpsampleRgb565LinePair,q0=16,V0=1<Tt.ca.S||(alert("todo:WebPInitConvertARGBToYUV"),Tt.ca.f.kb.F!=null&&po()),Tt.Pb&&0(qs=ft.Md)?0:100on;++on)12>(Ar=ls.pb[on]).lc&&(Ar.ia=qs*FC[0>Ar.lc?0:Ar.lc]>>3),Zn|=Ar.ia;Zn&&(alert("todo:VP8InitRandom"),ls.ia=1)}ls.Ga=ft.Id,100ls.Ga&&(ls.Ga=0)}(function(Qs,or){if(Qs==null)return 0;if(or==null)return Co(Qs,2,"NULL VP8Io parameter in VP8Decode().");if(!Qs.cb&&!cc(Qs,or))return 0;if(t(Qs.cb),or.ac==null||or.ac(or)){or.ob&&(Qs.L=0);var br=sx[Qs.L];if(Qs.L==2?(Qs.yb=0,Qs.zb=0):(Qs.yb=or.v-br>>4,Qs.zb=or.j-br>>4,0>Qs.yb&&(Qs.yb=0),0>Qs.zb&&(Qs.zb=0)),Qs.Va=or.o+15+br>>4,Qs.Hb=or.va+15+br>>4,Qs.Hb>Qs.za&&(Qs.Hb=Qs.za),Qs.Va>Qs.Ub&&(Qs.Va=Qs.Ub),0br;++br){var ur;if(Qs.Qa.Cb){var pa=Qs.Qa.Lb[br];Qs.Qa.Fb||(pa+=aa.Tb)}else pa=aa.Tb;for(ur=0;1>=ur;++ur){var cr=Qs.gd[br][ur],Ua=pa;if(aa.Pc&&(Ua+=aa.vd[0],ur&&(Ua+=aa.od[0])),0<(Ua=0>Ua?0:63>2:Ea>>1)>9-aa.wb&&(Ea=9-aa.wb),1>Ea&&(Ea=1),cr.dd=Ea,cr.tc=2*Ua+Ea,cr.ld=40<=Ua?2:15<=Ua?1:0}else cr.tc=0;cr.La=ur}}}br=0}else Co(Qs,6,"Frame setup failed"),br=Qs.a;if(br=br==0){if(br){Qs.$c=0,0Qs.Vb){if(Qs.Vb=0,Qs.Ec=i(cr),Qs.Fc=0,Qs.Ec==null){br=Co(Qs,1,"no memory during frame initialization.");break t}Qs.Vb=cr}cr=Qs.Ec,Ua=Qs.Fc,Qs.Ac=cr,Qs.Bc=Ua,Ua+=aa,Qs.Gd=l(_o,ah),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=br;++br)Dx[255+br]=0>br?-br:br;for(br=-1020;1020>=br;++br)Pb[1020+br]=-128>br?-128:127=br;++br)Kw[112+br]=-16>br?-16:15=br;++br)zm[255+br]=0>br?0:255Ql;++Ql){var mf,ud=ig[0+Ql];for(mf=0;4>mf;++mf){ud=qT[$c[If+mf]][ud];for(var lu=Bv[Le(To,ud[0])];0>3;for(lu=0;256>lu;lu+=16)Ql[og+lu]=vh}Lf=1,op=If[0]}var vc=15&To.la,Rh=15&Lh.la;for(lu=0;4>lu;++lu){var Bm=1&Rh;for(vh=cu=0;4>vh;++vh)vc=vc>>1|(Bm=(uh=ap($c,op,uh=Bm+(1&vc),Xd.Sc,Lf,Ql,og))>Lf)<<7,cu=cu<<2|(3>=4,Rh=Rh>>1|Bm<<7,mf=(mf<<8|cu)>>>0}for(op=vc,Lf=Rh>>4,dh=0;4>dh;dh+=2){for(cu=0,vc=To.la>>4+dh,Rh=Lh.la>>4+dh,lu=0;2>lu;++lu){for(Bm=1&Rh,vh=0;2>vh;++vh)uh=Bm+(1&vc),vc=vc>>1|(Bm=0<(uh=ap($c,If[2],uh,Xd.Qc,0,Ql,og)))<<3,cu=cu<<2|(3>=2,Rh=Rh>>1|Bm<<5}ud|=cu<<4*dh,op|=vc<<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=sx[yo.L])*yo.R,$c=ud/2*yo.B,lu=16*Xl*yo.R,vh=8*Xl*yo.B,If=yo.sa,ig=yo.ta-To+lu,Xd=yo.qa,Ql=yo.ra-$c+vh,og=yo.Ha,Lh=yo.Ia-$c+vh,Rh=(vc=cu.M)==0,mf=vc>=yo.Va-1,yo.Aa==2&&iu(yo,cu),cu.uc)for(Bm=(uh=yo).D.M,t(uh.D.uc),cu=uh.yb;cubi.o&&(vc=bi.o),bi.F=null,bi.J=null,yo.Fa!=null&&0>1),bi.W+=yo.B*(ud>>1),bi.F!=null&&(bi.J+=bi.width*ud)),cu>1,bi.W+=bi.v>>1,bi.F!=null&&(bi.J+=bi.v),bi.ka=cu-bi.j,bi.U=bi.va-bi.v,bi.T=vc-cu,hm=bi.put(bi))}Xl+1!=yo.Ic||mf||(r(yo.sa,yo.ta-To,If,ig+16*yo.R,To),r(yo.qa,yo.ra-$c,Xd,Ql+8*yo.B,$c),r(yo.Ha,yo.Ia-$c,og,Lh+8*yo.B,$c))}if(!hm)return Co(Lc,6,"Output aborted.")}return 1}(Qs,or)),or.bc!=null&&or.bc(or),br&=1}return br?(Qs.cb=0,br):0})(Pe,Tt)||(He=Pe.a)}}else He=Pe.a}He==0&&As.Oa!=null&&As.Oa.fd&&(He=pu(As.ba))}As=He}Ns=As!=0?null:11>Ns?Ds.f.RGBA.eb:Ds.f.kb.y}else Ns=null;return Ns};var Jw=[3,4,3,4,4,2,2,4,4,4,2,1,1]};function d(R,D){for(var O="",U=0;U<4;U++)O+=String.fromCharCode(R[D++]);return O}function u(R,D){return R[D+0]|R[D+1]<<8}function h(R,D){return(R[D+0]|R[D+1]<<8|R[D+2]<<16)>>>0}function m(R,D){return(R[D+0]|R[D+1]<<8|R[D+2]<<16|R[D+3]<<24)>>>0}new c;var f=[0],g=[0],x=[],y=new c,v=s,b=function(R,D){var O={},U=0,W=!1,V=0,G=0;if(O.frames=[],!function(J,ce){for(var _e=0;_e<4;_e++)if(J[ce+_e]!="RIFF".charCodeAt(_e))return!0;return!1}(R,D)){for(m(R,D+=4),D+=8;D>1&1}Y!="ANMF"&&(D+=ae)}return O}}(v,0);b.response=v,b.rgbaoutput=!0,b.dataurl=!1;var w=b.header?b.header:null,S=b.frames?b.frames:null;if(w){w.loop_counter=w.loop_count,f=[w.canvas_height],g=[w.canvas_width];for(var 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 PWn(){this.internal.__metadata__.metadataObjectNumber&&this.internal.write("/Metadata "+this.internal.__metadata__.metadataObjectNumber+" 0 R")}(function(s){var t,n,r,a,i,l,o,c,d,u=function(J){return J=J||{},this.isStrokeTransparent=J.isStrokeTransparent||!1,this.strokeOpacity=J.strokeOpacity||1,this.strokeStyle=J.strokeStyle||"#000000",this.fillStyle=J.fillStyle||"#000000",this.isFillTransparent=J.isFillTransparent||!1,this.fillOpacity=J.fillOpacity||1,this.font=J.font||"10px sans-serif",this.textBaseline=J.textBaseline||"alphabetic",this.textAlign=J.textAlign||"left",this.lineWidth=J.lineWidth||1,this.lineJoin=J.lineJoin||"miter",this.lineCap=J.lineCap||"butt",this.path=J.path||[],this.transform=J.transform!==void 0?J.transform.clone():new c,this.globalCompositeOperation=J.globalCompositeOperation||"normal",this.globalAlpha=J.globalAlpha||1,this.clip_path=J.clip_path||[],this.currentPoint=J.currentPoint||new l,this.miterLimit=J.miterLimit||10,this.lastPoint=J.lastPoint||new l,this.lineDashOffset=J.lineDashOffset||0,this.lineDash=J.lineDash||[],this.margin=J.margin||[0,0,0,0],this.prevPageLastElemOffset=J.prevPageLastElemOffset||0,this.ignoreClearRect=typeof J.ignoreClearRect!="boolean"||J.ignoreClearRect,this};s.events.push(["initialized",function(){this.context2d=new h(this),t=this.internal.f2,n=this.internal.getCoordinateString,r=this.internal.getVerticalCoordinateString,a=this.internal.getHorizontalCoordinate,i=this.internal.getVerticalCoordinate,l=this.internal.Point,o=this.internal.Rectangle,c=this.internal.Matrix,d=new u}]);var h=function(J){Object.defineProperty(this,"canvas",{get:function(){return{parentNode:!1,style:!1}}});var ce=J;Object.defineProperty(this,"pdf",{get:function(){return ce}});var _e=!1;Object.defineProperty(this,"pageWrapXEnabled",{get:function(){return _e},set:function(Ae){_e=!!Ae}});var he=!1;Object.defineProperty(this,"pageWrapYEnabled",{get:function(){return he},set:function(Ae){he=!!Ae}});var ue=0;Object.defineProperty(this,"posX",{get:function(){return ue},set:function(Ae){isNaN(Ae)||(ue=Ae)}});var ve=0;Object.defineProperty(this,"posY",{get:function(){return ve},set:function(Ae){isNaN(Ae)||(ve=Ae)}}),Object.defineProperty(this,"margin",{get:function(){return d.margin},set:function(Ae){var Ce;typeof Ae=="number"?Ce=[Ae,Ae,Ae,Ae]:((Ce=new Array(4))[0]=Ae[0],Ce[1]=Ae.length>=2?Ae[1]:Ce[0],Ce[2]=Ae.length>=3?Ae[2]:Ce[0],Ce[3]=Ae.length>=4?Ae[3]:Ce[1]),d.margin=Ce}});var Ee=!1;Object.defineProperty(this,"autoPaging",{get:function(){return Ee},set:function(Ae){Ee=Ae}});var Se=0;Object.defineProperty(this,"lastBreak",{get:function(){return Se},set:function(Ae){Se=Ae}});var Le=[];Object.defineProperty(this,"pageBreaks",{get:function(){return Le},set:function(Ae){Le=Ae}}),Object.defineProperty(this,"ctx",{get:function(){return d},set:function(Ae){Ae instanceof u&&(d=Ae)}}),Object.defineProperty(this,"path",{get:function(){return d.path},set:function(Ae){d.path=Ae}});var Fe=[];Object.defineProperty(this,"ctxStack",{get:function(){return Fe},set:function(Ae){Fe=Ae}}),Object.defineProperty(this,"fillStyle",{get:function(){return this.ctx.fillStyle},set:function(Ae){var Ce;Ce=m(Ae),this.ctx.fillStyle=Ce.style,this.ctx.isFillTransparent=Ce.a===0,this.ctx.fillOpacity=Ce.a,this.pdf.setFillColor(Ce.r,Ce.g,Ce.b,{a:Ce.a}),this.pdf.setTextColor(Ce.r,Ce.g,Ce.b,{a:Ce.a})}}),Object.defineProperty(this,"strokeStyle",{get:function(){return this.ctx.strokeStyle},set:function(Ae){var Ce=m(Ae);this.ctx.strokeStyle=Ce.style,this.ctx.isStrokeTransparent=Ce.a===0,this.ctx.strokeOpacity=Ce.a,Ce.a===0?this.pdf.setDrawColor(255,255,255):(Ce.a,this.pdf.setDrawColor(Ce.r,Ce.g,Ce.b))}}),Object.defineProperty(this,"lineCap",{get:function(){return this.ctx.lineCap},set:function(Ae){["butt","round","square"].indexOf(Ae)!==-1&&(this.ctx.lineCap=Ae,this.pdf.setLineCap(Ae))}}),Object.defineProperty(this,"lineWidth",{get:function(){return this.ctx.lineWidth},set:function(Ae){isNaN(Ae)||(this.ctx.lineWidth=Ae,this.pdf.setLineWidth(Ae))}}),Object.defineProperty(this,"lineJoin",{get:function(){return this.ctx.lineJoin},set:function(Ae){["bevel","round","miter"].indexOf(Ae)!==-1&&(this.ctx.lineJoin=Ae,this.pdf.setLineJoin(Ae))}}),Object.defineProperty(this,"miterLimit",{get:function(){return this.ctx.miterLimit},set:function(Ae){isNaN(Ae)||(this.ctx.miterLimit=Ae,this.pdf.setMiterLimit(Ae))}}),Object.defineProperty(this,"textBaseline",{get:function(){return this.ctx.textBaseline},set:function(Ae){this.ctx.textBaseline=Ae}}),Object.defineProperty(this,"textAlign",{get:function(){return this.ctx.textAlign},set:function(Ae){["right","end","center","left","start"].indexOf(Ae)!==-1&&(this.ctx.textAlign=Ae)}});var ke=null,Be=null,Ne=null;Object.defineProperty(this,"fontFaces",{get:function(){return Ne},set:function(Ae){ke=null,Be=null,Ne=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 Ve=Ce[1];Ce[2];var ze=Ce[3],qe=Ce[4];Ce[5];var dt=Ce[6],Xe=/^([.\d]+)((?:%|in|[cem]m|ex|p[ctx]))$/i.exec(qe)[2];qe=Math.floor(Xe==="px"?parseFloat(qe)*this.pdf.internal.scaleFactor:Xe==="em"?parseFloat(qe)*this.pdf.getFontSize():parseFloat(qe)*this.pdf.internal.scaleFactor),this.pdf.setFontSize(qe);var at=function(ys){var Bt,Ft,as=[],kt=ys.trim();if(kt==="")return k$e;if(kt in M4t)return[M4t[kt]];for(;kt!=="";){switch(Ft=null,Bt=(kt=I4t(kt)).charAt(0)){case'"':case"'":Ft=kWn(kt.substring(1),Bt);break;default:Ft=SWn(kt)}if(Ft===null||(as.push(Ft[0]),(kt=I4t(Ft[1]))!==""&&kt.charAt(0)!==","))return k$e;kt=kt.replace(/^,/,"")}return as}(dt);if(this.fontFaces){var rt=function(ys,Bt){var Ft=ys.getFontList(),as=JSON.stringify(Ft);if(ke===null||Be!==as){var kt=function(Ks){var wt=[];return Object.keys(Ks).forEach(function(gs){Ks[gs].forEach(function(ks){var Is=null;switch(ks){case"bold":Is={family:gs,weight:"bold"};break;case"italic":Is={family:gs,style:"italic"};break;case"bolditalic":Is={family:gs,weight:"bold",style:"italic"};break;case"":case"normal":Is={family:gs}}Is!==null&&(Is.ref={name:gs,style:ks},wt.push(Is))})}),wt}(Ft);ke=function(Ks){for(var wt={},gs=0;gs=700||Ve==="bold")&&(pt="bold"),Ve==="italic"&&(pt+="italic"),pt.length===0&&(pt="normal");for(var gt="",ss={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"},Yt=0;Yt=2*Math.PI&&(he=0,ue=2*Math.PI),this.path.push({type:"arc",x:J,y:ce,radius:_e,startAngle:he,endAngle:ue,counterclockwise:ve})},h.prototype.arcTo=function(J,ce,_e,he,ue){throw new Error("arcTo not implemented.")},h.prototype.rect=function(J,ce,_e,he){if(isNaN(J)||isNaN(ce)||isNaN(_e)||isNaN(he))throw yf.error("jsPDF.context2d.rect: Invalid arguments",arguments),new Error("Invalid arguments passed to jsPDF.context2d.rect");this.moveTo(J,ce),this.lineTo(J+_e,ce),this.lineTo(J+_e,ce+he),this.lineTo(J,ce+he),this.lineTo(J,ce),this.lineTo(J+_e,ce),this.lineTo(J,ce)},h.prototype.fillRect=function(J,ce,_e,he){if(isNaN(J)||isNaN(ce)||isNaN(_e)||isNaN(he))throw 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,_e,he),this.fill(),ue.hasOwnProperty("lineCap")&&(this.lineCap=ue.lineCap),ue.hasOwnProperty("lineJoin")&&(this.lineJoin=ue.lineJoin)}},h.prototype.strokeRect=function(J,ce,_e,he){if(isNaN(J)||isNaN(ce)||isNaN(_e)||isNaN(he))throw 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,_e,he),this.stroke())},h.prototype.clearRect=function(J,ce,_e,he){if(isNaN(J)||isNaN(ce)||isNaN(_e)||isNaN(he))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,_e,he))},h.prototype.save=function(J){J=typeof J!="boolean"||J;for(var ce=this.pdf.internal.getCurrentPageInfo().pageNumber,_e=0;_e0||this.margin[1]>0||this.margin[2]>0||this.margin[3]>0};h.prototype.drawImage=function(J,ce,_e,he,ue,ve,Ee,Se,Le){var Fe=this.pdf.getImageProperties(J),ke=1,Be=1,Ne=1,Ae=1;he!==void 0&&Se!==void 0&&(Ne=Se/he,Ae=Le/ue,ke=Fe.width/he*Se/he,Be=Fe.height/ue*Le/ue),ve===void 0&&(ve=ce,Ee=_e,ce=0,_e=0),he!==void 0&&Se===void 0&&(Se=he,Le=ue),he===void 0&&Se===void 0&&(Se=Fe.width,Le=Fe.height);var Ce=this.ctx.transform.decompose(),Ve=ae(Ce.rotate.shx),ze=new c,qe=(ze=(ze=(ze=ze.multiply(Ce.translate)).multiply(Ce.skew)).multiply(Ce.scale)).applyToRectangle(new o(ve-ce*Ne,Ee-_e*Ae,he*ke,ue*Be));if(this.autoPaging){for(var dt,Xe=y.call(this,qe),at=[],rt=0;rtKe||ptqe||Xe0)){for(;Le>=0;Le--)if(ue[Le-1].close!==!0&&ue[Le-1].begin!==!0){ue[Le-1].deltas.push(_e),ue[Le-1].abs.push(Se);break}}break;case"bct":_e=[Se.x1-ve[Ee-1].x,Se.y1-ve[Ee-1].y,Se.x2-ve[Ee-1].x,Se.y2-ve[Ee-1].y,Se.x-ve[Ee-1].x,Se.y-ve[Ee-1].y],ue[ue.length-1].deltas.push(_e);break;case"qct":var Fe=ve[Ee-1].x+2/3*(Se.x1-ve[Ee-1].x),ke=ve[Ee-1].y+2/3*(Se.y1-ve[Ee-1].y),Be=Se.x+2/3*(Se.x1-Se.x),Ne=Se.y+2/3*(Se.y1-Se.y),Ae=Se.x,Ce=Se.y;_e=[Fe-ve[Ee-1].x,ke-ve[Ee-1].y,Be-ve[Ee-1].x,Ne-ve[Ee-1].y,Ae-ve[Ee-1].x,Ce-ve[Ee-1].y],ue[ue.length-1].deltas.push(_e);break;case"arc":ue.push({deltas:[],abs:[],arc:!0}),Array.isArray(ue[ue.length-1].abs)&&ue[ue.length-1].abs.push(Se)}}he=ce?null:J==="stroke"?"stroke":"fill";for(var Ve=!1,ze=0;ze=.01&&(he=this.pdf.internal.getFontSize(),this.pdf.setFontSize(he*J.scale),ue=this.lineWidth,this.lineWidth=ue*J.scale);var ts=this.autoPaging!=="text";if(ts||Yt.y+Yt.h<=rt){if(ts||Yt.y>=Xe&&Yt.x<=Je){var ys=ts?J.text:this.pdf.splitTextToSize(J.text,J.maxWidth||Je-Yt.x)[0],Bt=b([JSON.parse(JSON.stringify(Be))],this.posX+this.margin[3],-gt+Xe+this.ctx.prevPageLastElemOffset)[0],Ft=ts&&(dt>ze||dt=.01&&(this.pdf.setFontSize(he),this.lineWidth=ue)}}else J.scale>=.01&&(he=this.pdf.internal.getFontSize(),this.pdf.setFontSize(he*J.scale),ue=this.lineWidth,this.lineWidth=ue*J.scale),this.pdf.text(J.text,Le.x+this.posX,Le.y+this.posY,{angle:J.angle,align:ce,renderingMode:J.renderingMode,maxWidth:J.maxWidth}),J.scale>=.01&&(this.pdf.setFontSize(he),this.lineWidth=ue)},W=function(J,ce,_e,he){_e=_e||0,he=he||0,this.pdf.internal.out(n(J+_e)+" "+r(ce+he)+" l")},V=function(J,ce,_e){return this.pdf.lines(J,ce,_e,null,null)},G=function(J,ce,_e,he,ue,ve,Ee,Se){this.pdf.internal.out([t(a(_e+J)),t(i(he+ce)),t(a(ue+J)),t(i(ve+ce)),t(a(Ee+J)),t(i(Se+ce)),"c"].join(" "))},Y=function(J,ce,_e,he){for(var ue=2*Math.PI,ve=Math.PI/2;ce>_e;)ce-=ue;var Ee=Math.abs(_e-ce);Ee1e-5;){var ke=Fe+Le*Math.min(Ee,ve);Se.push(X.call(this,J,Fe,ke)),Ee-=Math.abs(ke-Fe),Fe=ke}return Se},X=function(J,ce,_e){var he=(_e-ce)/2,ue=J*Math.cos(he),ve=J*Math.sin(he),Ee=ue,Se=-ve,Le=Ee*Ee+Se*Se,Fe=Le+Ee*ue+Se*ve,ke=4/3*(Math.sqrt(2*Le*Fe)-Fe)/(Ee*ve-Se*ue),Be=Ee-ke*Se,Ne=Se+ke*Ee,Ae=Be,Ce=-Ne,Ve=he+ce,ze=Math.cos(Ve),qe=Math.sin(Ve);return{x1:J*Math.cos(ce),y1:J*Math.sin(ce),x2:Be*ze-Ne*qe,y2:Be*qe+Ne*ze,x3:Ae*ze-Ce*qe,y3:Ae*qe+Ce*ze,x4:J*Math.cos(_e),y4:J*Math.sin(_e)}},ae=function(J){return 180*J/Math.PI},le=function(J,ce,_e,he,ue,ve){var Ee=J+.5*(_e-J),Se=ce+.5*(he-ce),Le=ue+.5*(_e-ue),Fe=ve+.5*(he-ve),ke=Math.min(J,ue,Ee,Le),Be=Math.max(J,ue,Ee,Le),Ne=Math.min(ce,ve,Se,Fe),Ae=Math.max(ce,ve,Se,Fe);return new o(ke,Ne,Be-ke,Ae-Ne)},ne=function(J,ce,_e,he,ue,ve,Ee,Se){var Le,Fe,ke,Be,Ne,Ae,Ce,Ve,ze,qe,dt,Xe,at,rt,Ke=_e-J,Je=he-ce,pt=ue-_e,gt=ve-he,ss=Ee-ue,Yt=Se-ve;for(Fe=0;Fe<41;Fe++)ze=(Ce=(ke=J+(Le=Fe/40)*Ke)+Le*((Ne=_e+Le*pt)-ke))+Le*(Ne+Le*(ue+Le*ss-Ne)-Ce),qe=(Ve=(Be=ce+Le*Je)+Le*((Ae=he+Le*gt)-Be))+Le*(Ae+Le*(ve+Le*Yt-Ae)-Ve),Fe==0?(dt=ze,Xe=qe,at=ze,rt=qe):(dt=Math.min(dt,ze),Xe=Math.min(Xe,qe),at=Math.max(at,ze),rt=Math.max(rt,qe));return new o(Math.round(dt),Math.round(Xe),Math.round(at-dt),Math.round(rt-Xe))},te=function(){if(this.prevLineDash||this.ctx.lineDash.length||this.ctx.lineDashOffset){var J,ce,_e=(J=this.ctx.lineDash,ce=this.ctx.lineDashOffset,JSON.stringify({lineDash:J,lineDashOffset:ce}));this.prevLineDash!==_e&&(this.pdf.setLineDash(this.ctx.lineDash,this.ctx.lineDashOffset),this.prevLineDash=_e)}}})(Go.API),function(s){var t=function(l){var o,c,d,u,h,m,f,g,x,y;for(c=[],d=0,u=(l+=o="\0\0\0\0".slice(l.length%4||4)).length;u>d;d+=4)(h=(l.charCodeAt(d)<<24)+(l.charCodeAt(d+1)<<16)+(l.charCodeAt(d+2)<<8)+l.charCodeAt(d+3))!==0?(m=(h=((h=((h=((h=(h-(y=h%85))/85)-(x=h%85))/85)-(g=h%85))/85)-(f=h%85))/85)%85,c.push(m+33,f+33,g+33,x+33,y+33)):c.push(122);return function(v,b){for(var w=b;w>0;w--)v.pop()}(c,o.length),String.fromCharCode.apply(String,c)+"~>"},n=function(l){var o,c,d,u,h,m=String,f="length",g=255,x="charCodeAt",y="slice",v="replace";for(l[y](-2),l=l[y](0,-2)[v](/\s/g,"")[v]("z","!!!!!"),d=[],u=0,h=(l+=o="uuuuu"[y](l[f]%5||5))[f];h>u;u+=5)c=52200625*(l[x](u)-33)+614125*(l[x](u+1)-33)+7225*(l[x](u+2)-33)+85*(l[x](u+3)-33)+(l[x](u+4)-33),d.push(g&c>>24,g&c>>16,g&c>>8,g&c);return function(b,w){for(var S=w;S>0;S--)b.pop()}(d,o[f]),m.fromCharCode.apply(m,d)},r=function(l){return l.split("").map(function(o){return("0"+o.charCodeAt().toString(16)).slice(-2)}).join("")+">"},a=function(l){var o=new RegExp(/^([0-9A-Fa-f]{2})+$/);if((l=l.replace(/\s/g,"")).indexOf(">")!==-1&&(l=l.substr(0,l.indexOf(">"))),l.length%2&&(l+="0"),o.test(l)===!1)return"";for(var c="",d=0;dimport("./html2canvas.esm-CBrSDip1.js"),[])).catch(function(o){return Promise.reject(new Error("Could not load html2canvas: "+o))}).then(function(o){return o.default?o.default:o})}function n(){return(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=y,y=x,x=g);else{if(o!=="l"&&o!=="landscape")throw"Invalid orientation: "+o;o="l",x>y&&(g=y,y=x,x=g)}return{width:y,height:x,unit:c,k:h,orientation:o}},s.html=function(o,c){(c=c||{}).callback=c.callback||function(){},c.html2canvas=c.html2canvas||{},c.html2canvas.canvas=c.html2canvas.canvas||this.canvas,c.jsPDF=c.jsPDF||this,c.fontFaces=c.fontFaces?c.fontFaces.map(N$e):null;var d=new l(c);return c.worker?d:d.from(o).doCallback()}}(Go.API),Go.API.addJS=function(s){var t,n,r=function(a){for(var i="",l=0;l=0&&a[d]==="\\";d--)c++;i+=c%2==0?"\\"+o:o}else i+=o}return i}(s);return this.internal.events.subscribe("postPutResources",function(){t=this.internal.newObject(),this.internal.out("<<"),this.internal.out("/Names [(EmbeddedJS) "+(t+1)+" 0 R]"),this.internal.out(">>"),this.internal.out("endobj"),n=this.internal.newObject(),this.internal.out("<<"),this.internal.out("/S /JavaScript"),this.internal.out("/JS ("+r+")"),this.internal.out(">>"),this.internal.out("endobj")}),this.internal.events.subscribe("putCatalog",function(){t!==void 0&&n!==void 0&&this.internal.out("/Names <>")}),this},function(s){var t;s.events.push(["postPutResources",function(){var n=this,r=/^(\d+) 0 obj$/;if(this.outline.root.children.length>0)for(var a=n.outline.render().split(/\r\n/),i=0;i> endobj")}var f=n.internal.newObject();for(n.internal.write("<< /Names [ "),i=0;i>","endobj"),t=n.internal.newObject(),n.internal.write("<< /Dests "+f+" 0 R"),n.internal.write(">>","endobj")}}]),s.events.push(["putCatalog",function(){var n=this;n.outline.root.children.length>0&&(n.internal.write("/Outlines",this.outline.makeRef(this.outline.root)),this.outline.createNamedDestinations&&n.internal.write("/Names "+t+" 0 R"))}]),s.events.push(["initialized",function(){var n=this;n.outline={createNamedDestinations:!1,root:{children:[]}},n.outline.add=function(r,a,i){var l={title:a,options:i,children:[]};return r==null&&(r=this.root),r.children.push(l),l},n.outline.render=function(){return this.ctx={},this.ctx.val="",this.ctx.pdf=n,this.genIds_r(this.root),this.renderRoot(this.root),this.renderItems(this.root),this.ctx.val},n.outline.genIds_r=function(r){r.id=n.internal.newObjectDeferred();for(var a=0;a0&&(this.line("/First "+this.makeRef(r.children[0])),this.line("/Last "+this.makeRef(r.children[r.children.length-1]))),this.line("/Count "+this.count_r({count:0},r)),this.objEnd()},n.outline.renderItems=function(r){for(var a=this.ctx.pdf.internal.getVerticalCoordinateString,i=0;i0&&this.line("/Prev "+this.makeRef(r.children[i-1])),i0&&(this.line("/First "+this.makeRef(l.children[0])),this.line("/Last "+this.makeRef(l.children[l.children.length-1])));var o=this.count=this.count_r({count:0},l);if(o>0&&this.line("/Count "+o),l.options&&l.options.pageNumber){var c=n.internal.getPageInfo(l.options.pageNumber);this.line("/Dest ["+c.objId+" 0 R /XYZ 0 "+a(0)+" 0]")}this.objEnd()}for(var d=0;d> \r endobj\r `},n.outline.count_r=function(r,a){for(var i=0;i1){V=!0,Y=void 0;var ue=R*D;X=new Uint8Array(ue);for(var ve=new DataView(O.buffer),Ee=0;Ee536870912)throw new Error("Image dimensions exceed 512MB, which is too large.");this.data=new Uint8Array(t);try{this[s]()}catch(n){yf.log("bit decode error:"+n)}},tS.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)}},tS.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)}},tS.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}},tS.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}},tS.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},D4t=function(s,t,n){n||(n={});var r,a,i,l,o,c,d,u=[],h=[u],m=n.textIndent||0,f=0,g=0,x=s.split(" "),y=Cue.apply(this,[" ",n])[0];if(c=n.lineIndent===-1?x[0].length+2:n.lineIndent||0){var v=Array(c).join(" "),b=[];x.map(function(S){(S=S.split(/\s*\n/)).length>1?b=b.concat(S.map(function(A,E){return(E&&A.length?` `:"")+A})):b.push(S[0])}),x=b,c=L4t.apply(this,[v,n])}for(i=0,l=x.length;it||w){if(g>t){for(o=R4t.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=y}else u.push(r),m+=f+g,f=y}return d=c?function(S,A){return(A?v:"")+S.join(" ")}:function(S){return S.join(" ")},h.map(d)},q$.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-vDeBW0FU.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",PWn),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 /"+wU(o.fontName)),c("/FontDescriptor "+v+" 0 R"),c("/W "+s.API.PDFObject.convert(h)),c("/CIDToGIDMap /Identity"),c("/DW 1000"),c("/Subtype /CIDFontType2"),c("/CIDSystemInfo"),c("<<"),c("/Supplement 0"),c("/Registry (Adobe)"),c("/Ordering ("+o.encoding+")"),c(">>"),c(">>"),c("endobj"),o.objectNumber=d(),c("<<"),c("/Type /Font"),c("/Subtype /Type0"),c("/ToUnicode "+y+" 0 R"),c("/BaseFont /"+wU(o.fontName)),c("/Encoding /"+o.encoding),c("/DescendantFonts ["+b+" 0 R]"),c(">>"),c("endobj"),o.isAlreadyPutted=!0}})(i)}]),t.events.push(["putFont",function(i){(function(l){var o=l.font,c=l.out,d=l.newObject,u=l.putStream;if(o.metadata instanceof s.API.TTFFont&&o.encoding==="WinAnsiEncoding"){for(var h=o.metadata.rawData,m="",f=0;f>"),c("endobj"),o.objectNumber=d();for(var v=0;v>"),c("endobj"),o.isAlreadyPutted=!0}})(i)}]);var a=function(i){var l,o=i.text||"",c=i.x,d=i.y,u=i.options||{},h=i.mutex||{},m=h.pdfEscape,f=h.activeFontKey,g=h.fonts,x=f,y="",v=0,b="",w=g[x].encoding;if(g[x].encoding!=="Identity-H")return{text:o,x:c,y:d,options:u,mutex:h};for(b=o,x=f,Array.isArray(o)&&(b=o[0]),v=0;v","<","[","]","[","{","}","{","«","»","«","‹","›","‹","⁅","⁆","⁅","⁽","⁾","⁽","₍","₎","₍","≤","≥","≤","〈","〉","〈","﹙","﹚","﹙","﹛","﹜","﹛","﹝","﹞","﹝","﹤","﹥","﹤"],v=new RegExp(/^([1-4|9]|1[0-9]|2[0-9]|3[0168]|4[04589]|5[012]|7[78]|159|16[0-9]|17[0-2]|21[569]|22[03489]|250)$/),b=!1,w=0;this.__bidiEngine__={};var S=function(O){var U=O.charCodeAt(),W=U>>8,V=x[W];return V!==void 0?h[256*V+(255&U)]:W===252||W===253?"AL":v.test(W)?"L":W===8?"R":"N"},A=function(O){for(var U,W=0;W=U.length||(G=W[V-1])!=="EN"&&G!=="AN"||(Y=U[V+1])!=="EN"&&Y!=="AN"?le="N":b&&(Y="AN"),le=Y===G?Y:"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&&ne<=2303||ne===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,Y,X,ae,le=-1,ne=O.length,te=0,J=[],ce=w?f:m,_e=[];for(b=!1,a=!1,i=!1,G=0;G0)if(V===16){for(G=le;G-1){for(G=le;G=0&&he[Se]==="WS";Se--)ue[Se]=w}}(_e,U,ne)},R=function(O,U,W,V,G){if(!(G.hiLevel=O){for(ae=te+1;ae=O;)ae++;for(le=te,X=ae-1;le=0&&(Y[ne]=y[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,Y){if(Y)for(var X=0;X>16)&&(n=-(1+(65535^n))),this.italicAngle=+(n+"."+r)):this.italicAngle=0,this.ascender=Math.round(this.ascender*this.scaleFactor),this.decender=Math.round(this.decender*this.scaleFactor),this.lineGap=Math.round(this.lineGap*this.scaleFactor),this.capHeight=this.os2.exists&&this.os2.capHeight||this.ascender,this.xHeight=this.os2.exists&&this.os2.xHeight||0,this.familyClass=(this.os2.exists&&this.os2.familyClass||0)>>8,this.isSerif=(i=this.familyClass)===1||i===2||i===3||i===4||i===5||i===7,this.isScript=this.familyClass===10,this.flags=0,this.post.isFixedPitch&&(this.flags|=1),this.isSerif&&(this.flags|=2),this.isScript&&(this.flags|=8),this.italicAngle!==0&&(this.flags|=64),this.flags|=32,!this.cmap.unicode)throw new Error("No unicode cmap for font")},s.prototype.characterToGlyph=function(t){var n;return((n=this.cmap.unicode)!=null?n.codeMap[t]:void 0)||0},s.prototype.widthOfGlyph=function(t){var n;return n=1e3/this.head.unitsPerEm,this.hmtx.forGlyph(t).advance*n},s.prototype.widthOfString=function(t,n,r){var a,i,l,o;for(l=0,i=0,o=(t=""+t).length;0<=o?io;i=0<=o?++i:--i)a=t.charCodeAt(i),l+=this.widthOfGlyph(this.characterToGlyph(a))+r*(1e3/n)||0;return l*(n/1e3)},s.prototype.lineHeight=function(t,n){var r;return n==null&&(n=!1),r=n?this.lineGap:0,(this.ascender+r-this.decender)/1e3*t},s}();var TC,BL=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 BL).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=ass.call(n);n.length%4;)n.push(0);for(i=new BL(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=v=0,w=i.length;v=y;r=g<=y?++b:--b)u[c]===0?l=r+d[c]:(l=o[u[c]/2+(r-g)-(m-c)]||0)!==0&&(l+=d[c]),this.codeMap[r]=65535&l}t.pos=h}return s.encode=function(t,n){var r,a,i,l,o,c,d,u,h,m,f,g,x,y,v,b,w,S,A,E,I,P,R,D,O,U,W,V,G,Y,X,ae,le,ne,te,J,ce,_e,he,ue,ve,Ee,Se,Le,Fe,ke;switch(V=new BL,l=Object.keys(t).sort(function(Be,Ne){return Be-Ne}),n){case"macroman":for(x=0,y=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),ve=0,J=h.length;vea;r=0<=a?++r:--r)n=new H4t(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=H4t.encode(t,n),(a=new BL).writeUInt16(0),a.writeUInt16(1),r.table=a.data.concat(r.subtable),r},s}(),DWn=function(){function s(){return s.__super__.constructor.apply(this,arguments)}return _3(s,TC),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}(),FWn=function(){function s(){return s.__super__.constructor.apply(this,arguments)}return _3(s,TC),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}(),OWn=function(){function s(){return s.__super__.constructor.apply(this,arguments)}return _3(s,TC),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}(),zWn=function(s,t){this.raw=s,this.length=s.length,this.platformID=t.platformID,this.encodingID=t.encodingID,this.languageID=t.languageID},BWn=function(){function s(){return s.__super__.constructor.apply(this,arguments)}return _3(s,TC),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}(),ass=[].slice,qWn=function(){function s(){return s.__super__.constructor.apply(this,arguments)}return _3(s,TC),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 BL(n.read(a))).readShort(),d=o.readShort(),h=o.readShort(),c=o.readShort(),u=o.readShort(),this.cache[t]=l===-1?new HWn(o,d,h,c,u):new VWn(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}(),WWn=function(){function s(t){this.font=t,this.subset={},this.unicodes={},this.next=33}return s.prototype.generateCmap=function(){var t,n,r,a,i;for(n in a=this.font.cmap.tables[0].codeMap,t={},i=this.subset)r=i[n],t[n]=a[r];return t},s.prototype.glyphsFor=function(t){var n,r,a,i,l,o,c;for(a={},l=0,o=t.length;l0)for(i in c=this.glyphsFor(n))r=c[i],a[i]=r;return a},s.prototype.encode=function(t,n){var r,a,i,l,o,c,d,u,h,m,f,g,x,y,v;for(a in r=rss.encode(this.generateCmap(),"unicode"),l=this.glyphsFor(t),f={0:0},v=r.charMap)f[(c=v[a]).old]=c.new;for(g in m=r.maxGlyphID,l)g in f||(f[g]=m++);return u=function(b){var w,S;for(w in S={},b)S[b[w]]=w;return S}(f),h=Object.keys(u).sort(function(b,w){return b-w}),x=function(){var b,w,S;for(S=[],b=0,w=h.length;b>"),i.join(` `)}return""+n},t}();const mZe=[{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}],KWn="signature";function YWn(s){return mZe.find(t=>t.id===s)||mZe[0]}const xd=792,Hf=612,wa=52;function V$(s){const t=(s||"").replace("#","").padEnd(6,"0");return[parseInt(t.slice(0,2),16)||0,parseInt(t.slice(2,4),16)||0,parseInt(t.slice(4,6),16)||0]}function Lg(s,t,n){return[Math.round(s[0]+(t[0]-s[0])*n),Math.round(s[1]+(t[1]-s[1])*n),Math.round(s[2]+(t[2]-s[2])*n)]}const w3=[22,24,28],k_=[124,128,136],Xo=[255,255,255];function ZWn(s){return s==null||!Number.isFinite(Number(s))?null:new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(Number(s))}const A$e="https://relzejiswnotikjgvjhz.supabase.co";function XWn(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(A$e).origin?s:`${A$e}/functions/v1/image-proxy?url=${encodeURIComponent(t.toString())}`}catch{return s}}async function lX(s,t=2e3){if(!s)return null;try{const n=await fetch(XWn(s),{mode:"cors"});if(!n.ok)return null;const r=await n.blob(),a=URL.createObjectURL(r),i=await new Promise((x,y)=>{const v=new Image;v.crossOrigin="anonymous",v.onload=()=>x(v),v.onerror=y,v.src=a}),l=Math.min(1,t/i.naturalWidth),o=Math.max(1,Math.round(i.naturalWidth*l)),c=Math.max(1,Math.round(i.naturalHeight*l)),d=document.createElement("canvas");d.width=o,d.height=c,d.getContext("2d").drawImage(i,0,0,o,c),URL.revokeObjectURL(a);const h=r.type.includes("png"),m=h?"PNG":"JPEG",f=d.toDataURL(h?"image/png":"image/jpeg",.92);return{el:await new Promise(x=>{const y=new Image;y.onload=()=>x(y),y.onerror=()=>x(y),y.src=f}),dataUrl:f,w:o,h:c,format:m}}catch{return null}}let iss={x:.5,y:.5};function QWn(s){iss={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 qie(s,t,n,r,a,i,l={}){const o=l.dpi??2,c=Math.max(1,Math.round(a*o)),d=Math.max(1,Math.round(i*o)),u=document.createElement("canvas");u.width=c,u.height=d;const h=u.getContext("2d"),m=t.w/t.h,f=a/i;let g=0,x=0,y=t.w,v=t.h;const b=l.focal??iss;if(m>f?(y=t.h*f,g=Math.min(Math.max(0,t.w*b.x-y/2),t.w-y)):(v=t.w/f,x=Math.min(Math.max(0,t.h*b.y-v/2),t.h-v)),l.radius&&l.radius>0){const 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,y,v,0,0,c,d)}catch{h.fillStyle="#e9e6e0",h.fillRect(0,0,c,d)}if(h.filter="none",l.tint&&l.tint.amount>0){const[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 A7(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 jot(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 dw(s,t){const n=s.GState;n&&s.setGState(new n({opacity:t}))}function JWn(s,t,n,r,a,i={font:"helvetica",size:10,color:w3}){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 QK(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=JWn(s,c,n+13,l,a-13,{font:i.font,size:i.size,color:i.color,leading:o})+(i.gap??7)}),l}function S1(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 l9='',c9='',eKn={title:"Facebook",slug:"facebook",get svg(){return l9+"Facebook"+c9+this.path+d9},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"},tKn={title:"Instagram",slug:"instagram",get svg(){return l9+"Instagram"+c9+this.path+d9},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"},sKn={title:"Pinterest",slug:"pinterest",get svg(){return l9+"Pinterest"+c9+this.path+d9},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"},nKn={title:"TikTok",slug:"tiktok",get svg(){return l9+"TikTok"+c9+this.path+d9},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"},rKn={title:"trulia",slug:"trulia",get svg(){return l9+"trulia"+c9+this.path+d9},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"},aKn={title:"YouTube",slug:"youtube",get svg(){return l9+"YouTube"+c9+this.path+d9},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"},iKn={title:"Zillow",slug:"zillow",get svg(){return l9+"Zillow"+c9+this.path+d9},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"},oKn={facebook:eKn,instagram:tKn,youtube:aKn,tiktok:nKn,pinterest:sKn,zillow:iKn,trulia:rKn},G4t=new Map;function lKn(s,t,n){return`${s}|${t}|${n}`}function cKn(s,t,n=128){const r=s.toLowerCase().replace(/[^a-z]/g,""),a=oKn[r];if(!a)return null;const i=lKn(r,t,n),l=G4t.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 G4t.set(i,d),d}catch{return null}}const Bu="helvetica";let wW="helvetica";function oss(s,t,n,r,a,i){const l=`#${n.map(d=>Math.round(d).toString(16).padStart(2,"0")).join("")}`,o=cKn(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(Bu,"bold"),s.setFontSize(c*1.15),s.setTextColor(...Xo),s.text(t.charAt(0).toUpperCase(),r,a+c*.42,{align:"center"})}let Vie=[252,251,248],fB=[244,247,250],Rw=[223,228,234],Tb=[72,78,88];function Hie(s,t){return dts(s.data.pages,t)}function Not(s){var n;const t=s.coAgent;return t!=null&&t.enabled&&((n=t.name)!=null&&n.trim())?t:null}function lss(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 dKn(s){return[s.agent.brokerageName,s.agent.phone,s.agent.email].filter(Boolean).join(" | ")}function ry(s,t,n,r,a,i,l){const o=l.font||Bu,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(Bu,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 JK(s,t,n,r,a,i){const{doc:l}=s;l.setFont(Bu,"bold"),l.setFontSize(7.5),l.setTextColor(...a||s.accent),l.text(t.toUpperCase(),n,r,{charSpace:1.8,align:i})}function Rv(s,t=Vie){s.doc.addPage("letter","landscape"),s.pageNo+=1,s.doc.setFillColor(...t),s.doc.rect(0,0,xd,Hf,"F")}function Mb(s,t,n,r,a={}){const{doc:i}=s,l=!!a.dark,o=a.width??xd-wa*2-60;JK(s,t,wa,62,s.accent),i.setFont(wW,"bold"),i.setFontSize(wW==="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?Lg(Xo,s.deep,.28):k_,leading:15,maxLines:2})),d+34}function Dv(s,t=!1){const{doc:n,data:r}=s,a=t?Lg(Xo,s.deep,.7):Rw;n.setDrawColor(...a),n.setLineWidth(.6),n.line(wa,Hf-46,xd-wa,Hf-46);const i=Hf-30;n.setFont(Bu,"bold"),n.setFontSize(7),n.setTextColor(...t?Xo:s.brand),t&&dw(n,.9),n.text((r.agent.name||"").toUpperCase(),wa,i,{charSpace:1.4});const l=dKn(r);l&&(n.setFont(Bu,"normal"),n.setFontSize(7),n.setTextColor(...t?Xo:k_),ry(n,l,xd/2,i,xd/2-wa-40,7,{color:t?Xo:k_,align:"center"})),n.setFont(Bu,"normal"),n.setFontSize(7),n.setTextColor(...t?Xo:k_),n.text(String(s.pageNo).padStart(2,"0"),xd-wa,i,{align:"right"}),t&&dw(n,1)}function css(s,t,n,r,a){const{doc:i}=s;i.setFont(Bu,"bold"),i.setFontSize(8);const l=i.splitTextToSize(t,a-28),o=16+l.length*12;return S1(i,n,r,a,o,6,Lg(s.accent,Xo,.86)),i.setTextColor(...Lg(s.brand,w3,.2)),l.forEach((c,d)=>i.text(c,n+14,r+20+d*12)),r+o}function kot(s,t,n,r,a,i={}){const{doc:l}=s;s.hero?qie(l,s.hero,t,n,r,a,{radius:10,dpi:s.dpi,tint:i.tint?{color:s.deep,amount:i.tint}:void 0}):S1(l,t,n,r,a,10,Lg(s.deep,Xo,.12))}function uKn(s){const{doc:t,data:n}=s,{line1:r,line2:a}=lss(n),i=336;s.hero?qie(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=Hie(s,"cover");JK(s,l.kicker,wa,66),t.setFont(wW,"bold"),t.setFontSize(wW==="times"?29:26),t.setTextColor(...Xo);const o=t.splitTextToSize(r,i-wa*2).slice(0,3);o.forEach((y,v)=>t.text(y,wa,102+v*30));let c=102+(o.length-1)*30;a&&(t.setFont(Bu,"normal"),t.setFontSize(9),dw(t,.9),ry(t,a.toUpperCase(),wa,c+22,i-wa*2,9,{color:Xo,charSpace:1.4}),dw(t,1),c+=22),c=im(t,l.body,wa,c+34,i-wa*2,{size:10,color:Lg(Xo,s.deep,.22),leading:16});const d=[ZWn(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),ry(t,d.join(" · "),wa,c+54,i-wa*2,10,{style:"bold",color:Xo,charSpace:1}));const u=Not(n),h=Hf-(u?152:128);let m=wa;s.headshot&&(A7(t,s.headshot,wa+22,h+18,22),u&&s.coHeadshot?(A7(t,s.coHeadshot,wa+56,h+18,22),m=wa+90):m=wa+56),ry(t,u?`${n.agent.name} + ${u.name}`:n.agent.name,m,h+12,i-m-24,14,{style:"bold",color:Xo}),t.setFont(Bu,"normal"),t.setFontSize(8),dw(t,.85);const f=[n.agent.brokerageName].filter(Boolean).join("");f&&ry(t,f,m,h+26,i-m-24,8,{color:Xo});const g=[n.agent.phone,n.agent.email].filter(Boolean).join(" · ");if(g&&ry(t,g,m,h+38,i-m-24,8,{color:Xo}),u){const y=[u.title||"Co-listing agent",u.phone].filter(Boolean).join(" · ");y&&ry(t,y,wa,h+56,i-wa-24,8,{color:Xo})}dw(t,1),s.logo&&(dw(t,.95),jot(t,s.logo,wa,Hf-74,132,30,"left"),dw(t,1));const x=n.sellerName?`PREPARED FOR ${n.sellerName.toUpperCase()}`:"PREPARED FOR YOUR HOME";t.setFont(Bu,"bold"),t.setFontSize(7.5),t.setTextColor(...Xo),dw(t,.9),t.text(x,xd-wa,Hf-34,{align:"right",charSpace:1.6}),dw(t,1)}function hKn(s){Rv(s);const{doc:t}=s,n=Hie(s,"welcome"),r=Mb(s,n.kicker,n.headline,n.subhead||null),a=[["Make it look irresistible","Professional visuals help buyers stop, click, and imagine themselves at home."],["Put it everywhere buyers search","MLS distribution, property portals, mobile search, and a dedicated online showcase."],["Create demand beyond the portals","Social campaigns, email, database outreach, and local promotion keep momentum moving."]];let i=r+10;a.forEach(([l,o],c)=>{t.setFillColor(...Lg(s.accent,Xo,.85)),t.circle(wa+13,i-3,13,"F"),t.setFont(Bu,"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(Bu,"bold"),t.setFontSize(11.5),t.setTextColor(...w3),t.text(l,d,i),im(t,o,d,i+18,u,{size:9.5,color:Tb,leading:14,maxLines:2}),i+=88}),Dv(s)}function mKn(s){Rv(s,Xo);const{doc:t,data:n}=s,r=Hie(s,"agent"),a=Mb(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=Not(n),l=xd-wa-260,o=a-6,c=262;if(i){const g=(x,y,v,b)=>{S1(t,l,x,260,124,10,fB,"FD",Rw),t.setFillColor(...s.accent),t.rect(l,x,260,3,"F");let w=l+18;v&&(A7(t,v,l+48,x+62+2,30),w=l+90);const S=260-(w-l)-18;ry(t,y,w,x+40,S,13,{style:"bold",color:s.brand});let A=x+56;b.filter(Boolean).slice(0,4).forEach(E=>{ry(t,String(E),w,A,S,8,{color:k_}),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{S1(t,l,o,260,c,10,fB,"FD",Rw),t.setFillColor(...s.accent),t.rect(l,o,260,3,"F"),s.headshot&&A7(t,s.headshot,l+130,o+72,42),ry(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=>{ry(t,String(f),l+130,m,220,8.5,{color:k_,align:"center"}),m+=14}),s.logo&&jot(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:Tb,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(Bu,"bold"),t.setFontSize(7),t.setTextColor(...k_),t.text(m.toUpperCase(),wa,u,{charSpace:1.4}),ry(t,f,wa+86,u,d-86,10.5,{color:w3}),t.setDrawColor(...Rw),t.setLineWidth(.5),t.line(wa,u+11,wa+d,u+11),u+=36}),Dv(s)}function fKn(s,t){Rv(s);const{doc:n}=s,r=Hie(s,"overview"),a=Mb(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);S1(n,h,m,o,c,8,Xo,"FD",Rw),n.setFillColor(...s.accent),n.rect(h,m,3,c,"F"),n.setFont(Bu,"bold"),n.setFontSize(15),n.setTextColor(...Lg(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:w3,leading:13,maxLines:3})}),Dv(s)}function M6(s,t=5){var n;return(((n=s.options)==null?void 0:n.filter(r=>r.enabled).map(r=>r.label))??sHn[s.key]??[]).slice(0,t)}function W4t(s,t,n){Rv(s,n.dark?s.deep:Vie);const{doc:r}=s,a=Mb(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;kot(s,c,a,i,l,{tint:n.dark?.1:0}),JK(s,t.title,d,a+12);let h=im(r,t.body,d,a+32,u,{size:9.5,color:n.dark?Lg(Xo,s.deep,.2):Tb,leading:15,maxLines:4});const m=M6(t,5);if(m.length&&(h=QK(r,m,d,h+28,u,{font:Bu,size:9.5,color:n.dark?Xo:w3,accent:s.accent,gap:7})),n.note&&!n.dark){const f=Math.min(h+14,Hf-120);css(s,n.note,d,f,u)}else n.note&&(r.setFont(Bu,"bold"),r.setFontSize(9.5),r.setTextColor(...Xo),dw(r,.9),im(r,n.note,wa,Hf-78,xd-wa*2,{size:9.5,style:"bold",color:Xo,leading:13,maxLines:1}),dw(r,1));Dv(s,n.dark)}function pKn(s,t){Rv(s);const{doc:n}=s,r=Mb(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=M6(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);S1(n,m,r,c,d,8,Xo,"FD",Rw),n.setFont(Bu,"bold"),n.setFontSize(16),n.setTextColor(...s.accent),n.text(String(h+1),m+16,r+34),n.setFont(Bu,"bold"),n.setFontSize(7.5),n.setTextColor(...k_),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:Tb,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}),Dv(s)}function gKn(s,t){Rv(s);const{doc:n}=s,r=Mb(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);S1(n,f,g,o,c,8,Xo,"FD",Rw),oss(n,u,h,f+28,g+c/2,20),ry(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:Tb,leading:14,maxLines:3}),n.setFont(Bu,"normal"),n.setFontSize(7.5),n.setTextColor(...k_),n.text("Distribution varies by MLS, market, and portal policies.",wa,Hf-62),Dv(s)}function xKn(s,t){Rv(s,fB);const{doc:n,data:r}=s,{line1:a}=lss(r),i=Mb(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;S1(n,wa,i,l,o,10,Xo,"FD",Rw),S1(n,wa,i,l,22,10,s.deep),n.setFillColor(...s.deep),n.rect(wa,i+12,l,10,"F"),n.setFont(Bu,"bold"),n.setFontSize(7),n.setTextColor(...Xo);const c=(r.agent.website||`${a}`).replace(/^https?:\/\//,"").toUpperCase();ry(n,c,wa+14,i+15,l-28,7,{style:"bold",color:Xo,charSpace:1}),kot(s,wa+14,i+36,186,142);const d=wa+214,u=l-228;ry(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:Tb,leading:12,maxLines:5}),css(s,"Shareable. Trackable. Memorable.",wa+14,i+o-46,l-28);const h=wa+l+40,m=xd-h-wa;JK(s,t.title,h,i+12);let f=im(n,t.body,h,i+32,m,{size:9.5,color:Tb,leading:15,maxLines:5});const g=M6(t,5);g.length&&QK(n,g,h,f+26,m,{font:Bu,size:9,color:w3,accent:s.accent,gap:7}),Dv(s)}function yKn(s,t){Rv(s,s.deep);const{doc:n}=s,r=Mb(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);S1(n,m,r,i,i,12,Xo),oss(n,d,u,m+i/2,r+i/2-4,30),n.setFont(Bu,"bold"),n.setFontSize(6.5),n.setTextColor(...k_),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;JK(s,"The campaign can include",o,r+12),QK(n,M6(t,5),o,r+32,c,{font:Bu,size:9,color:Xo,accent:s.accent,gap:7}),im(n,t.body,wa,r+i+44,420,{size:9.5,color:Lg(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}),Dv(s,!0)}function vKn(s,t){Rv(s);const{doc:n}=s,r=Mb(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=M6(t,4),i=["Email announcement","Agent-to-agent outreach","Database follow-up","Local community visibility"];let l=r+6;a.forEach((o,c)=>{S1(n,wa,l-14,34,34,8,Lg(s.accent,Xo,.85)),n.setFont(Bu,"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(Bu,"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:Tb,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:k_,leading:14,maxLines:2}),Dv(s)}function bKn(s,t){Rv(s);const{doc:n}=s,r=Mb(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=M6(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);S1(n,m,f,c,d,8,fB,"FD",Rw),n.setFont(Bu,"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:Tb,leading:14,maxLines:3})}),Dv(s)}function _Kn(s,t){Rv(s,fB);const{doc:n}=s,r=Mb(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=M6(t,4),i=["Weekly update","Market check","Smart adjustments","Direct access"];let l=r+10;a.forEach((o,c)=>{n.setFont(Bu,"bold"),n.setFontSize(11),n.setTextColor(...s.accent),n.text(String(c+1).padStart(2,"0"),wa,l),n.setFont(Bu,"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:Tb,leading:13,maxLines:2}),n.setDrawColor(...Rw),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}),Dv(s)}function wKn(s){Rv(s,s.deep);const{doc:t,data:n}=s;s.hero&&qie(t,s.hero,0,0,xd,Hf,{tint:{color:s.deep,amount:.92},darken:.25,dpi:s.dpi});const r=Hie(s,"closing"),a=Mb(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:Lg(Xo,s.deep,.18),leading:17});l+=30,QK(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:Bu,size:9.5,color:Xo,accent:s.accent,gap:8});const o=Not(n),c=250,d=xd-wa-c,u=a-20,h=o?300:258;S1(t,d,u,c,h,10,Xo),t.setFillColor(...s.accent),t.rect(d,u,c,3,"F"),s.headshot&&(o&&s.coHeadshot?(A7(t,s.headshot,d+c/2-34,u+70,32),A7(t,s.coHeadshot,d+c/2+34,u+70,32)):A7(t,s.headshot,d+c/2,u+70,38)),ry(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=>{ry(t,String(f),d+c/2,m,c-30,8.5,{color:k_,align:"center"}),m+=14}),o?(m+=6,t.setDrawColor(...Rw),t.setLineWidth(.5),t.line(d+24,m-8,d+c-24,m-8),ry(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=>{ry(t,String(f),d+c/2,m,c-30,8.5,{color:k_,align:"center"}),m+=13})):s.logo&&jot(t,s.logo,d+c/2-50,u+h-44,100,28,"left"),t.setFont(Bu,"bold"),t.setFontSize(9),t.setTextColor(...Xo),dw(t,.9),t.text("LET'S MAKE YOUR HOME THE ONE BUYERS REMEMBER.",wa,Hf-72,{charSpace:1.4}),dw(t,1),Dv(s,!0)}function Sot(s,t){return s.customImages[t.id]||null}function dss(s,t,n,r,a,i){const l=Sot(s,t);l?qie(s.doc,l,n,r,a,i,{radius:10,dpi:s.dpi}):kot(s,n,r,a,i)}function jKn(s,t){Rv(s,t.dark?s.deep:Vie);const{doc:n}=s,r=Mb(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;dss(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?Lg(Xo,s.deep,.2):Tb,leading:16,maxLines:7}),u+=26}),t.bullets.length&&QK(n,t.bullets.slice(0,5),o,Math.min(u,Hf-150),c,{font:Bu,size:9.5,color:t.dark?Xo:w3,accent:s.accent,gap:7}),Dv(s,t.dark)}function NKn(s,t){Rv(s,t.dark?s.deep:fB);const{doc:n}=s,r=Mb(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);S1(n,g,x,o,u,10,t.dark?Lg(s.deep,Xo,.08):Xo,"FD",Rw),n.setFillColor(...s.accent),n.rect(g,x,3,u,"F"),n.setFont(wW,"bold"),n.setFontSize(30),n.setTextColor(...Lg(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?Lg(Xo,s.deep,.2):Tb,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(Bu,"bold"),n.setFontSize(8),n.setTextColor(...s.brand);const y=[m.name,m.detail].filter(Boolean).join(" · ");y&&ry(n,y.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?Lg(Xo,s.deep,.2):k_,leading:14,maxLines:2}),Dv(s,t.dark)}function kKn(s,t){Rv(s,t.dark?s.deep:Vie);const{doc:n}=s,r=Mb(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);S1(n,u,r,l,o,10,t.dark?Lg(s.deep,Xo,.1):Xo,"FD",Rw),n.setFillColor(...s.accent),n.rect(u,r,l,3,"F"),ry(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?Lg(Xo,s.deep,.3):k_,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?Lg(Xo,s.deep,.2):Tb,leading:15,maxLines:3})}else t.body&&im(n,t.body,wa,r,xd-wa*2-140,{size:10.5,color:t.dark?Xo:Tb,leading:16});Dv(s,t.dark)}function SKn(s,t){Rv(s,t.dark?s.deep:Xo);const{doc:n}=s,r=Mb(s,t.kicker||"Our promise",t.headline,t.subhead||null,{dark:t.dark}),i=!!Sot(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?Lg(Xo,s.deep,.2):Tb,leading:15,maxLines:3})+28),t.bullets.filter(d=>d==null?void 0:d.trim()).slice(0,7).forEach(d=>{S1(n,wa,o-9,14,14,4,s.accent),n.setFont(Bu,"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:w3,leading:14,maxLines:2})+22}),i&&dss(s,t,xd-wa-240,r,240,250),Dv(s,t.dark)}function CKn(s,t){Rv(s,s.deep);const{doc:n}=s,r=Sot(s,t)||s.hero;r&&qie(n,r,0,0,xd,Hf,{tint:{color:s.deep,amount:.82},darken:.28,dpi:s.dpi}),JK(s,t.kicker||"Our approach",wa,Hf/2-84),n.setFont(Bu,"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:Lg(Xo,s.deep,.2),leading:16,maxLines:4}),Dv(s,!0)}function K4t(s,t){switch(t.layout){case"testimonials":return NKn(s,t);case"stats":return kKn(s,t);case"checklist":return SKn(s,t);case"statement":return CKn(s,t);case"story":default:return jKn(s,t)}}async function AKn(s,t,n){var I,P,R,D;const r=n==="print"?4:2,a=n==="print"?2600:1600,i=YWn((I=t.pages)==null?void 0:I.theme);Vie=V$(i.paper),fB=V$(i.paperCool),Rw=V$(i.softLine),Tb=V$(i.bodyInk),wW=i.headFont;const l=V$((i.useAgentColors?t.agent.brandColor:i.brand)||i.brand||"#0E1B2C"),o=V$((i.useAgentColors?t.agent.accentColor:i.accent)||i.accent||"#B8965A"),c=Lg(l,[0,0,0],i.id==="luxury"?.35:.2),d=(P=t.coAgent)!=null&&P.enabled&&((R=t.coAgent.name)!=null&&R.trim())?t.coAgent:null,u=(t.customPages||[]).filter(O=>O.enabled).sort((O,U)=>O.order-U.order),[h,m,f,g,...x]=await Promise.all([lX(t.property.photoUrl,a),lX(t.agent.headshotUrl,700),lX(t.agent.brokerageLogoUrl,800),lX((d==null?void 0:d.headshotUrl)||null,700),...u.map(O=>lX(O.imageUrl||null,a))]),y={};u.forEach((O,U)=>{y[O.id]=x[U]??null}),QWn(t.focal);const v={doc:s,data:t,brand:l,accent:o,deep:c,hero:h,headshot:m,coHeadshot:g,logo:f,customImages:y,dpi:r,pageNo:1},b=new Set(((D=t.pages)==null?void 0:D.hidden)||[]),w=[...t.services].filter(O=>O.enabled).sort((O,U)=>O.order-U.order),S=O=>w.find(U=>U.key===O);uKn(v),b.has("welcome")||hKn(v),b.has("agent")||mKn(v),u.filter(O=>O.placement!=="end").forEach(O=>K4t(v,O)),b.has("overview")||fKn(v,w);const A=new Set,E=(O,U)=>{const W=S(O);W&&(A.add(O),U(W))};E("photography",O=>W4t(v,O,{kicker:"First impressions",headline:"Buyers will see your home at its absolute best.",sub:"Strong presentation earns the click before a showing is ever scheduled.",note:"Every image has one job: earn the next click."})),E("video",O=>W4t(v,O,{kicker:"More ways to experience it",headline:"Photos introduce the home. Video helps buyers feel it.",sub:"A cinematic walk-through gives the listing movement, emotion, and shareability.",note:"The right format for every screen.",dark:!0,flip:!0})),E("mls",O=>pKn(v,O)),E("syndication",O=>gKn(v,O)),E("website",O=>xKn(v,O)),E("social",O=>yKn(v,O)),E("email",O=>vKn(v,O)),E("openhouse",O=>bKn(v,O)),E("communication",O=>_Kn(v,O)),w.filter(O=>!A.has(O.key)).forEach(O=>{Rv(v);const U=Mb(v,"Marketing",O.title,null),W=M6(O,6),V=im(s,O.body,wa,U,xd-wa*2-160,{size:10.5,color:Tb,leading:16});W.length&&QK(s,W,wa,V+30,xd-wa*2-160,{font:Bu,size:9.5,color:w3,accent:v.accent,gap:8}),Dv(v)}),u.filter(O=>O.placement==="end").forEach(O=>K4t(v,O)),b.has("closing")||wKn(v)}const Y4t=[{id:"signature",name:"Signature",description:"Editorial full-bleed cover with a brand-tinted photo motif throughout.",render:AKn}];function EKn(s){return Y4t.find(t=>t.id===s)||Y4t[0]}async function uss(s,t,n="screen"){const r=new Go({unit:"pt",format:"letter",orientation:"landscape",compress:!0});return await EKn(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 TKn(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 uPe(s){if(!s)return null;const{data:t}=await q.storage.from(zL).createSignedUrl(s,3600);return(t==null?void 0:t.signedUrl)??null}function hPe(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:hts(s.co_agent),customPages:fts(s.custom_pages),services:tZe(s.services),pages:s.page_settings&&Object.keys(s.page_settings).length?s.page_settings:JYe,focal:s.photo_focal||eZe}}async function hss(s,t){if(s.property.photoUrl||!t)return s;const n=await uPe(t);return{...s,property:{...s.property,photoUrl:n}}}async function mss(s,t,n){const r=await hss(s,n);return(await uss(r,t,"screen")).output("blob")}async function fss(s,t,n="print",r){const a=await hss(s,r),l=(await uss(a,t,n)).output("blob"),o=URL.createObjectURL(l),c=document.createElement("a");return c.href=o,c.download=TKn(a),document.body.appendChild(c),c.click(),c.remove(),setTimeout(()=>URL.revokeObjectURL(o),4e3),l}async function pss(s,t,n){const r=`${s}/${t}/presentation.pdf`,{error:a}=await q.storage.from(zL).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 gss(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 PKn(s,t,n){const r=await gss(n),a=`${s}/${t}/photo.jpg`,{error:i}=await q.storage.from(zL).upload(a,r,{upsert:!0,contentType:"image/jpeg"});if(i)throw i;return a}async function IKn(s,t,n="presentation",r=1800){const a=await gss(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 LKn({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 eHn(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 Z4t=60*60*24*30;function xss({open:s,onOpenChange:t,row:n,brand:r,photoUrl:a}){const{user:i}=bs(),[l,o]=j.useState([]),[c,d]=j.useState(""),[u,h]=j.useState([]),[m,f]=j.useState(!1),[g,x]=j.useState(""),[y,v]=j.useState(""),[b,w]=j.useState(!1),S=j.useRef(null),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}`),v(`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)){re.error("Enter a valid email address");return}E({email:D})},P=j.useMemo(()=>!!n&&l.length>0&&g.trim().length>0&&!b,[n,l,g,b]),R=async()=>{if(!(!n||!i)){if(!n.property_photo_path){re.error("Add the primary exterior photo before emailing the presentation");return}w(!0);try{const D=await mss(hPe(n,r,a??null),n.template_id,n.property_photo_path),O=await pss(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(zL).createSignedUrl(O,Z4t);if(W||!(U!=null&&U.signedUrl))throw new Error("Could not create a share link");const V=await uPe(n.property_photo_path).then(ae=>ae).catch(()=>null),{data:G}=await q.storage.from(zL).createSignedUrl(n.property_photo_path,Z4t),{data:Y,error:X}=await q.functions.invoke("listing-presentation-email",{body:{presentation_id:n.id,subject:g,message:y,pdf_url:U.signedUrl,photo_url:(G==null?void 0:G.signedUrl)||V,recipients:l}});if(X)throw X;if(!(Y!=null&&Y.success))throw new Error((Y==null?void 0:Y.error)||"Could not send the email");re.success(Y.failed?`Sent to ${Y.sent} · ${Y.failed} failed`:`Presentation emailed to ${Y.sent} ${Y.sent===1?"contact":"contacts"}`),t(!1)}catch(D){re.error((D==null?void 0:D.message)||"Could not send the presentation")}finally{w(!1)}}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-lg",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(mn,{className:"h-4 w-4"})," Email this presentation"]}),e.jsxs(Pr,{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(pr,{className:"h-3 w-3"})})]},D.email))}),e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{value:c,onChange:D=>d(D.target.value),onKeyDown:D=>{D.key==="Enter"&&(D.preventDefault(),I())},placeholder:"Search contacts or type an email"}),e.jsx($,{type:"button",variant:"outline",size:"icon",onClick:I,children:e.jsx(dn,{className:"h-4 w-4"})})]}),(u.length>0||m)&&e.jsxs("div",{className:"absolute z-50 mt-1 w-full overflow-hidden rounded-md border bg-popover shadow-lg",children:[m&&e.jsxs("div",{className:"flex items-center gap-2 p-3 text-sm text-muted-foreground",children:[e.jsx(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(Ls,{id:"pres-message",rows:7,value:y,onChange:D=>v(D.target.value)})]})]}),e.jsxs(Sr,{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(Kr,{className:"h-4 w-4"}),b?"Sending…":`Send${l.length?` (${l.length})`:""}`]})]})]})})}const RKn=()=>{const s=Xn(),{presentations:t,isLoading:n,create:r,duplicate:a,remove:i,update:l}=cts(),{data:o}=QVn(),{data:c}=N6e(),{savedTemplates:d,remove:u}=lts(),[h,m]=j.useState(null),[f,g]=j.useState(""),[x,y]=j.useState(null),[v,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:iPe},[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 fss(hPe(R,c),R.template_id,"print",R.property_photo_path)}catch(D){re.error((D==null?void 0:D.message)||"Could not build the PDF")}finally{b(null)}};return e.jsxs(Vs,{children:[e.jsxs("div",{className:"space-y-8",children:[e.jsx("div",{className:"relative overflow-hidden rounded-2xl border bg-gradient-to-br from-primary/10 via-background to-accent/10 p-8",children:e.jsxs("div",{className:"flex flex-col gap-6 md:flex-row md:items-center md:justify-between",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs($e,{variant:"secondary",className:"gap-1",children:[e.jsx(Nn,{className:"h-3 w-3"})," Listing Presentation Studio"]}),e.jsx("h1",{className:"text-3xl font-semibold tracking-tight",children:"Win the listing before you walk in"}),e.jsx("p",{className:"max-w-2xl text-sm text-muted-foreground",children:"Enter an address, drop in one exterior photo, and get a beautiful 12-page seller presentation branded with your profile — ready to present or print in under two minutes."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{size:"lg",onClick:E,disabled:r.isPending||!c,className:"gap-2",children:[r.isPending?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(dn,{className:"h-4 w-4"}),"New presentation"]}),d.length>0&&e.jsxs($u,{children:[e.jsx(Uu,{asChild:!0,children:e.jsxs($,{size:"lg",variant:"outline",className:"gap-2",children:[e.jsx(E0,{className:"h-4 w-4"})," From template",e.jsx(wl,{className:"h-4 w-4"})]})}),e.jsx(Au,{align:"end",className:"w-64",children:d.map(R=>e.jsxs(ja,{onClick:()=>I(R),children:[e.jsx(E0,{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(Ie,{className:"flex items-start justify-between gap-3 p-4",children:[e.jsxs("button",{className:"min-w-0 flex-1 text-left",onClick:()=>I(R),disabled:r.isPending,children:[e.jsxs("p",{className:"flex items-center gap-2 truncate font-medium",children:[e.jsx(E0,{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(Hn,{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(Ie,{className:"flex flex-col items-center gap-4 py-16 text-center",children:[e.jsx("div",{className:"flex h-14 w-14 items-center justify-center rounded-full bg-muted",children:e.jsx(Jr,{className:"h-7 w-7 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"No presentations yet"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Create your first seller presentation — it takes about two minutes."})]}),e.jsxs($,{onClick:E,disabled:r.isPending||!c,className:"gap-2",children:[e.jsx(dn,{className:"h-4 w-4"})," New presentation"]})]})}):e.jsx("div",{className:"grid gap-5 sm:grid-cols-2 lg:grid-cols-3",children:t.map(R=>{const D=R.property_address_line1||"No address yet",O=[R.city,R.state].filter(Boolean).join(", ");return e.jsxs(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(LKn,{path:R.property_photo_path,alt:`${D} property photo`})}),e.jsxs(Ie,{className:"space-y-3 p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate font-medium",children:R.title}),e.jsxs("p",{className:"truncate text-xs text-muted-foreground",children:[D,O?` · ${O}`:""]})]}),e.jsxs($u,{children:[e.jsx(Uu,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0",children:e.jsx(Jx,{className:"h-4 w-4"})})}),e.jsxs(Au,{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(Jr,{className:"mr-2 h-4 w-4"})," Rename"]}),e.jsxs(ja,{onClick:()=>a.mutate(R),children:[e.jsx(Ha,{className:"mr-2 h-4 w-4"})," Duplicate"]}),e.jsxs(ja,{onClick:()=>P(R),children:[e.jsx(xi,{className:"mr-2 h-4 w-4"})," Download PDF"]}),e.jsxs(ja,{onClick:()=>S(R),children:[e.jsx(mn,{className:"mr-2 h-4 w-4"})," Email to a contact"]}),e.jsx(I0,{}),e.jsxs(ja,{className:"text-destructive",onClick:()=>y(R),children:[e.jsx(Hn,{className:"mr-2 h-4 w-4"})," Delete"]})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Updated ",en(new Date(R.updated_at),"MMM d, yyyy")]}),R.last_generated_at?e.jsx($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:v===R.id,onClick:()=>P(R),children:[v===R.id?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(xi,{className:"h-4 w-4"}),"Download PDF"]})]})]},R.id)})})]}),e.jsx(zs,{open:!!h,onOpenChange:R=>!R&&m(null),children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Rename presentation"})}),e.jsx(pe,{value:f,onChange:R=>g(R.target.value),autoFocus:!0}),e.jsxs(Sr,{children:[e.jsx($,{variant:"outline",onClick:()=>m(null),children:"Cancel"}),e.jsx($,{onClick:async()=>{h&&(await l.mutateAsync({id:h.id,title:f.trim()||"Untitled Presentation"}),m(null),re.success("Renamed"))},children:"Save"})]})]})}),e.jsx(fc,{open:!!x,onOpenChange:R=>!R&&y(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),y(null)},children:"Delete"})]})]})}),e.jsx(xss,{open:!!w,onOpenChange:R=>!R&&S(null),row:w,brand:c})]})};var tte={};tte.d=(s,t)=>{for(var n in t)tte.o(t,n)&&!tte.o(s,n)&&Object.defineProperty(s,n,{enumerable:!0,get:t[n]})};tte.o=(s,t)=>Object.prototype.hasOwnProperty.call(s,t);var cd=globalThis.pdfjsLib={};tte.d(cd,{AbortException:()=>h9,AnnotationEditorLayer:()=>NXe,AnnotationEditorParamsType:()=>td,AnnotationEditorType:()=>Dd,AnnotationEditorUIManager:()=>gB,AnnotationLayer:()=>IZn,AnnotationMode:()=>EP,ColorPicker:()=>gPe,DOMSVGFactory:()=>Oot,DrawLayer:()=>AXe,FeatureTest:()=>S_,GlobalWorkerOptions:()=>mE,ImageKind:()=>L3e,InvalidPDFException:()=>vss,MissingPDFException:()=>u9,OPS:()=>pS,OutputScale:()=>yZe,PDFDataRangeTransport:()=>pns,PDFDateString:()=>Mot,PDFWorker:()=>BV,PasswordResponses:()=>zKn,PermissionFlag:()=>OKn,PixelsPerInch:()=>$L,RenderingCancelledException:()=>Eot,TextLayer:()=>xne,UnexpectedResponseException:()=>RDe,Util:()=>ol,VerbosityLevel:()=>PDe,XfaLayer:()=>xns,build:()=>mZn,createValidAbsoluteUrl:()=>qKn,fetchData:()=>FDe,getDocument:()=>rZn,getFilenameFromUrl:()=>QKn,getPdfFilenameFromUrl:()=>JKn,getXfaPageViewport:()=>eYn,isDataScheme:()=>ODe,isPdfFile:()=>Tot,noContextMenu:()=>pk,normalizeUnicode:()=>YKn,setLayerDimensions:()=>pB,shadow:()=>eh,version:()=>hZn});const p1=typeof process=="object"&&process+""=="[object process]"&&!process.versions.nw&&!(process.versions.electron&&process.type&&process.type!=="browser"),yss=[1,0,0,1,0,0],fZe=[.001,0,0,.001,0,0],DKn=1e7,E$e=1.35,Oj={ANY:1,DISPLAY:2,PRINT:4,ANNOTATIONS_FORMS:16,ANNOTATIONS_STORAGE:32,ANNOTATIONS_DISABLE:64,IS_EDITING:128,OPLIST:256},EP={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},FKn="pdfjs_internal_editor_",Dd={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},OKn={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},Jb={FILL:0,STROKE:1,FILL_STROKE:2,INVISIBLE:3,FILL_STROKE_MASK:3,ADD_TO_PATH_FLAG:4},L3e={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},a0={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},cX={SOLID:1,DASHED:2,BEVELED:3,INSET:4,UNDERLINE:5},PDe={ERRORS:0,WARNINGS:1,INFOS:5},pS={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},zKn={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let IDe=PDe.WARNINGS;function BKn(s){Number.isInteger(s)&&(IDe=s)}function $Kn(){return IDe}function LDe(s){IDe>=PDe.INFOS&&console.log(`Info: ${s}`)}function su(s){IDe>=PDe.WARNINGS&&console.log(`Warning: ${s}`)}function kp(s){throw new Error(s)}function w0(s,t){s||kp(t)}function UKn(s){switch(s==null?void 0:s.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}function qKn(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=KKn(s)}catch{}}const r=t?new URL(s,t):new URL(s);if(UKn(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 P6=function(){function t(n,r){this.message=n,this.name=r}return t.prototype=new Error,t.constructor=t,t}();class pZe extends P6{constructor(t,n){super(t,"PasswordException"),this.code=n}}class gZe extends P6{constructor(t,n){super(t,"UnknownErrorException"),this.details=n}}class vss extends P6{constructor(t){super(t,"InvalidPDFException")}}class u9 extends P6{constructor(t){super(t,"MissingPDFException")}}class RDe extends P6{constructor(t,n){super(t,"UnexpectedResponseException"),this.status=n}}class VKn extends P6{constructor(t){super(t,"FormatError")}}class h9 extends P6{constructor(t){super(t,"AbortException")}}function bss(s){(typeof s!="object"||(s==null?void 0:s.length)===void 0)&&kp("Invalid argument for bytesToString");const t=s.length,n=8192;if(t>24&255,s>>16&255,s>>8&255,s&255)}function Cot(s){const t=Object.create(null);for(const[n,r]of s)t[n]=r;return t}function GKn(){const s=new Uint8Array(4);return s[0]=1,new Uint32Array(s.buffer,0,1)[0]===1}function WKn(){try{return new Function(""),!0}catch{return!1}}class S_{static get isLittleEndian(){return eh(this,"isLittleEndian",GKn())}static get isEvalSupported(){return eh(this,"isEvalSupported",WKn())}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 T$e=Array.from(Array(256).keys(),s=>s.toString(16).padStart(2,"0"));var tT,R3e,xZe;class ol{static makeHexColor(t,n,r){return`#${T$e[t]}${T$e[n]}${T$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)],cs(this,tT,xZe).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),cs(this,tT,xZe).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}}tT=new WeakSet,R3e=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)},xZe=function(t,n,r,a,i,l,o,c,d,u,h,m){if(Math.abs(d)<1e-12){Math.abs(u)>=1e-12&&cs(this,tT,R3e).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;cs(this,tT,R3e).call(this,t,n,r,a,i,l,o,c,(-u+g)/x,m),cs(this,tT,R3e).call(this,t,n,r,a,i,l,o,c,(-u-g)/x,m)},vs(ol,tT);function KKn(s){return decodeURIComponent(escape(s))}let M$e=null,X4t=null;function YKn(s){return M$e||(M$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,X4t=new Map([["ſt","ſt"]])),s.replaceAll(M$e,(t,n,r)=>n?n.normalize("NFKC"):X4t.get(r))}function ZKn(){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 bss(s)}const Aot="pdfjs_internal_id_",lA={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 XKn(s){return Uint8Array.prototype.toBase64?s.toBase64():btoa(bss(s))}const _A="http://www.w3.org/2000/svg",JO=class JO{};Nr(JO,"CSS",96),Nr(JO,"PDF",72),Nr(JO,"PDF_TO_CSS_UNITS",JO.CSS/JO.PDF);let $L=JO;async function FDe(s,t="text"){if(NQ(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 Gie{constructor({viewBox:t,scale:n,rotation:r,offsetX:a=0,offsetY:i=0,dontFlip:l=!1}){this.viewBox=t,this.scale=n,this.rotation=r,this.offsetX=a,this.offsetY=i;const o=(t[2]+t[0])/2,c=(t[3]+t[1])/2;let d,u,h,m;switch(r%=360,r<0&&(r+=360),r){case 180:d=-1,u=0,h=0,m=1;break;case 90:d=0,u=1,h=1,m=0;break;case 270:d=0,u=-1,h=-1,m=0;break;case 0:d=1,u=0,h=0,m=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}l&&(h=-h,m=-m);let f,g,x,y;d===0?(f=Math.abs(c-t[1])*n+a,g=Math.abs(o-t[0])*n+i,x=(t[3]-t[1])*n,y=(t[2]-t[0])*n):(f=Math.abs(o-t[0])*n+a,g=Math.abs(c-t[1])*n+i,x=(t[2]-t[0])*n,y=(t[3]-t[1])*n),this.transform=[d*n,u*n,h*n,m*n,f-d*n*o-h*n*c,g-u*n*o-m*n*c],this.width=x,this.height=y}get rawDims(){const{viewBox:t}=this;return 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 Gie({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 Eot extends P6{constructor(t,n=0){super(t,"RenderingCancelledException"),this.extraDelay=n}}function ODe(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))}}Zne=new WeakMap,vs(Mot,Zne);function eYn(s,{scale:t=1,rotation:n=0}){const{width:r,height:a}=s.attributes.style,i=[0,0,parseInt(r),parseInt(a)];return new Gie({viewBox:i,scale:t,rotation:n})}function Pot(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):(su(`Not a valid color format: "${s}"`),[0,0,0])}function tYn(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,Pot(r))}t.remove()}function wg(s){const{a:t,b:n,c:r,d:a,e:i,f:l}=s.getTransform();return[t,n,r,a,i,l]}function cA(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 pB(s,t,n=!1,r=!0){if(t instanceof Gie){const{pageWidth:a,pageHeight:i}=t.rawDims,{style:l}=s,o=S_.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 yZe{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 zP,D8,yS,F8,Xne,Qne,aIe,_ss,E_,wss,jss,D3e,Nss,bZe;const TA=class TA{constructor(t){vs(this,E_);vs(this,zP,null);vs(this,D8,null);vs(this,yS);vs(this,F8,null);vs(this,Xne,null);Kt(this,yS,t),ye(TA,Qne)||Kt(TA,Qne,Object.freeze({freetext:"pdfjs-editor-remove-freetext-button",highlight:"pdfjs-editor-remove-highlight-button",ink:"pdfjs-editor-remove-ink-button",stamp:"pdfjs-editor-remove-stamp-button"}))}render(){const t=Kt(this,zP,document.createElement("div"));t.classList.add("editToolbar","hidden"),t.setAttribute("role","toolbar");const n=ye(this,yS)._uiManager._signal;t.addEventListener("contextmenu",pk,{signal:n}),t.addEventListener("pointerdown",cs(TA,aIe,_ss),{signal:n});const r=Kt(this,F8,document.createElement("div"));r.className="buttons",t.append(r);const a=ye(this,yS).toolbarPosition;if(a){const{style:i}=t,l=ye(this,yS)._uiManager.direction==="ltr"?1-a[0]:a[0];i.insetInlineEnd=`${100*l}%`,i.top=`calc(${100*a[1]}% + var(--editor-toolbar-vert-offset))`}return cs(this,E_,Nss).call(this),t}get div(){return ye(this,zP)}hide(){var t;ye(this,zP).classList.add("hidden"),(t=ye(this,D8))==null||t.hideDropdown()}show(){var t;ye(this,zP).classList.remove("hidden"),(t=ye(this,Xne))==null||t.shown()}async addAltText(t){const n=await t.render();cs(this,E_,D3e).call(this,n),ye(this,F8).prepend(n,ye(this,E_,bZe)),Kt(this,Xne,t)}addColorPicker(t){Kt(this,D8,t);const n=t.renderButton();cs(this,E_,D3e).call(this,n),ye(this,F8).prepend(n,ye(this,E_,bZe))}remove(){var t;ye(this,zP).remove(),(t=ye(this,D8))==null||t.destroy(),Kt(this,D8,null)}};zP=new WeakMap,D8=new WeakMap,yS=new WeakMap,F8=new WeakMap,Xne=new WeakMap,Qne=new WeakMap,aIe=new WeakSet,_ss=function(t){t.stopPropagation()},E_=new WeakSet,wss=function(t){ye(this,yS)._focusEventsAllowed=!1,t.preventDefault(),t.stopPropagation()},jss=function(t){ye(this,yS)._focusEventsAllowed=!0,t.preventDefault(),t.stopPropagation()},D3e=function(t){const n=ye(this,yS)._uiManager._signal;t.addEventListener("focusin",cs(this,E_,wss).bind(this),{capture:!0,signal:n}),t.addEventListener("focusout",cs(this,E_,jss).bind(this),{capture:!0,signal:n}),t.addEventListener("contextmenu",pk,{signal:n})},Nss=function(){const{editorType:t,_uiManager:n}=ye(this,yS),r=document.createElement("button");r.className="delete",r.tabIndex=0,r.setAttribute("data-l10n-id",ye(TA,Qne)[t]),cs(this,E_,D3e).call(this,r),r.addEventListener("click",a=>{n.delete()},{signal:n._signal}),ye(this,F8).append(r)},bZe=function(){const t=document.createElement("div");return t.className="divider",t},vs(TA,aIe),vs(TA,Qne,null);let vZe=TA;var Jne,O8,z8,KL,kss,Sss,Css;class sYn{constructor(t){vs(this,KL);vs(this,Jne,null);vs(this,O8,null);vs(this,z8);Kt(this,z8,t)}show(t,n,r){const[a,i]=cs(this,KL,Sss).call(this,n,r),{style:l}=ye(this,O8)||Kt(this,O8,cs(this,KL,kss).call(this));t.append(ye(this,O8)),l.insetInlineEnd=`${100*a}%`,l.top=`calc(${100*i}% + var(--editor-toolbar-vert-offset))`}hide(){ye(this,O8).remove()}}Jne=new WeakMap,O8=new WeakMap,z8=new WeakMap,KL=new WeakSet,kss=function(){const t=Kt(this,O8,document.createElement("div"));t.className="editToolbar",t.setAttribute("role","toolbar"),t.addEventListener("contextmenu",pk,{signal:ye(this,z8)._signal});const n=Kt(this,Jne,document.createElement("div"));return n.className="buttons",t.append(n),cs(this,KL,Css).call(this),t},Sss=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,z8).highlightSelection("floating_button")},{signal:r}),ye(this,Jne).append(t)};function mPe(s,t,n){for(const r of n)t.addEventListener(r,s[r].bind(s))}function nYn(s){return Math.round(Math.min(255,Math.max(1,255*s))).toString(16).padStart(2,"0")}var iIe;class rYn{constructor(){vs(this,iIe,0)}get id(){return`${FKn}${X0(this,iIe)._++}`}}iIe=new WeakMap;var oH,ere,n1,lH,F3e;const Qct=class Qct{constructor(){vs(this,lH);vs(this,oH,ZKn());vs(this,ere,0);vs(this,n1,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 cs(this,lH,F3e).call(this,`${n}_${r}_${a}_${i}`,t)}async getFromUrl(t){return cs(this,lH,F3e).call(this,t,t)}async getFromBlob(t,n){const r=await n;return cs(this,lH,F3e).call(this,t,r)}async getFromId(t){ye(this,n1)||Kt(this,n1,new Map);const n=ye(this,n1).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,n1)||Kt(this,n1,new Map);let r=ye(this,n1).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,oH)}_${X0(this,ere)._++}`,refCounter:1,isSvg:!1},ye(this,n1).set(t,r),ye(this,n1).set(r.id,r),r}getSvgUrl(t){const n=ye(this,n1).get(t);return n!=null&&n.isSvg?n.svgUrl:null}deleteId(t){var a;ye(this,n1)||Kt(this,n1,new Map);const n=ye(this,n1).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,oH)}_`)}};oH=new WeakMap,ere=new WeakMap,n1=new WeakMap,lH=new WeakSet,F3e=async function(t,n){ye(this,n1)||Kt(this,n1,new Map);let r=ye(this,n1).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,oH)}_${X0(this,ere)._++}`,refCounter:0,isSvg:!1});let a;if(typeof n=="string"?(r.url=n,a=await FDe(n,"blob")):n instanceof File?a=r.file=n:n instanceof Blob&&(a=n),a.type==="image/svg+xml"){const i=Qct._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,n1).set(t,r),r&&ye(this,n1).set(r.id,r),r};let _Ze=Qct;var sv,BP,tre,nv;class aYn{constructor(t=128){vs(this,sv,[]);vs(this,BP,!1);vs(this,tre);vs(this,nv,-1);Kt(this,tre,t)}add({cmd:t,undo:n,post:r,mustExec:a,type:i=NaN,overwriteIfSameType:l=!1,keepUndo:o=!1}){if(a&&t(),ye(this,BP))return;const c={cmd:t,undo:n,post:r,type:i};if(ye(this,nv)===-1){ye(this,sv).length>0&&(ye(this,sv).length=0),Kt(this,nv,0),ye(this,sv).push(c);return}if(l&&ye(this,sv)[ye(this,nv)].type===i){o&&(c.undo=ye(this,sv)[ye(this,nv)].undo),ye(this,sv)[ye(this,nv)]=c;return}const d=ye(this,nv)+1;d===ye(this,tre)?ye(this,sv).splice(0,1):(Kt(this,nv,d),di===n[l]))return lIe._colorsMapping.get(r);return n}getHexCode(t){const n=this._colors.get(t);return n?ol.makeHexColor(...n):t}};Nr(lIe,"_colorsMapping",new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]));let wZe=lIe;var cH,Ej,l0,Xv,dH,$A,uH,vS,$P,hH,B8,D5,bS,$8,sre,nre,mH,rre,F5,UP,fH,qP,O5,cIe,VP,are,HP,U8,ire,ore,rv,Nm,UA,q8,lre,cre,GP,z5,qA,dre,yN,Ji,O3e,jZe,Ess,Tss,z3e,Mss,Pss,Iss,NZe,Lss,kZe,SZe,Rss,e_,ZM,Dss,Fss,CZe,Oss,kQ,AZe;const yq=class yq{constructor(t,n,r,a,i,l,o,c,d,u,h){vs(this,Ji);vs(this,cH,new AbortController);vs(this,Ej,null);vs(this,l0,new Map);vs(this,Xv,new Map);vs(this,dH,null);vs(this,$A,null);vs(this,uH,null);vs(this,vS,new aYn);vs(this,$P,null);vs(this,hH,0);vs(this,B8,new Set);vs(this,D5,null);vs(this,bS,null);vs(this,$8,new Set);vs(this,sre,!1);vs(this,nre,!1);vs(this,mH,!1);vs(this,rre,null);vs(this,F5,null);vs(this,UP,null);vs(this,fH,null);vs(this,qP,!1);vs(this,O5,null);vs(this,cIe,new rYn);vs(this,VP,!1);vs(this,are,!1);vs(this,HP,null);vs(this,U8,null);vs(this,ire,null);vs(this,ore,null);vs(this,rv,Dd.NONE);vs(this,Nm,new Set);vs(this,UA,null);vs(this,q8,null);vs(this,lre,null);vs(this,cre,{isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1});vs(this,GP,[0,0]);vs(this,z5,null);vs(this,qA,null);vs(this,dre,null);vs(this,yN,null);const m=this._signal=ye(this,cH).signal;Kt(this,qA,t),Kt(this,dre,n),Kt(this,dH,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}),cs(this,Ji,Mss).call(this),cs(this,Ji,Rss).call(this),cs(this,Ji,NZe).call(this),Kt(this,$A,i.annotationStorage),Kt(this,rre,i.filterFactory),Kt(this,q8,l),Kt(this,fH,o||null),Kt(this,sre,c),Kt(this,nre,d),Kt(this,mH,u),Kt(this,ore,h||null),this.viewParameters={realScale:$L.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1}static get _keyboardManager(){const t=yq.prototype,n=l=>ye(l,qA).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 Wie([[["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,qA).contains(o)&&!l.isEnterHandled}],[[" ","mac+ "],t.addNewEditorFromKeyboard,{checker:(l,{target:o})=>!(o instanceof HTMLButtonElement)&&ye(l,qA).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,yN))==null||t.resolve(),Kt(this,yN,null),(n=ye(this,cH))==null||n.abort(),Kt(this,cH,null),this._signal=null;for(const i of ye(this,Xv).values())i.destroy();ye(this,Xv).clear(),ye(this,l0).clear(),ye(this,$8).clear(),Kt(this,Ej,null),ye(this,Nm).clear(),ye(this,vS).destroy(),(r=ye(this,dH))==null||r.destroy(),(a=ye(this,O5))==null||a.hide(),Kt(this,O5,null),ye(this,F5)&&(clearTimeout(ye(this,F5)),Kt(this,F5,null)),ye(this,z5)&&(clearTimeout(ye(this,z5)),Kt(this,z5,null))}combinedSignal(t){return AbortSignal.any([this._signal,t.signal])}get mlManager(){return ye(this,ore)}get useNewAltTextFlow(){return ye(this,nre)}get useNewAltTextWhenAddingImage(){return ye(this,mH)}get hcmFilter(){return eh(this,"hcmFilter",ye(this,q8)?ye(this,rre).addHCMFilter(ye(this,q8).foreground,ye(this,q8).background):"none")}get direction(){return eh(this,"direction",getComputedStyle(ye(this,qA)).direction)}get highlightColors(){return eh(this,"highlightColors",ye(this,fH)?new Map(ye(this,fH).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){Kt(this,ire,t)}editAltText(t,n=!1){var r;(r=ye(this,dH))==null||r.editAltText(this,t,n)}switchToMode(t,n){this._eventBus.on("annotationeditormodechanged",n,{once:!0,signal:this._signal}),this._eventBus.dispatch("showannotationeditorui",{source:this,mode:t})}setPreference(t,n){this._eventBus.dispatch("setpreference",{source:this,name:t,value:n})}onSetPreference({name:t,value:n}){switch(t){case"enableNewAltTextWhenAddingImage":Kt(this,mH,n);break}}onPageChanging({pageNumber:t}){Kt(this,hH,t-1)}focusMainContainer(){ye(this,qA).focus()}findParent(t,n){for(const r of ye(this,Xv).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,dre).classList.toggle("noUserSelect",t)}addShouldRescale(t){ye(this,$8).add(t)}removeShouldRescale(t){ye(this,$8).delete(t)}onScaleChanging({scale:t}){this.commitOrRemove(),this.viewParameters.realScale=t*$L.PDF_TO_CSS_UNITS;for(const n of ye(this,$8))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=cs(this,Ji,O3e).call(this,n).closest(".textLayer"),u=this.getSelectionBoxes(d);if(!u)return;n.empty();const h=cs(this,Ji,jZe).call(this,d),m=ye(this,rv)===Dd.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(Dd.HIGHLIGHT,f);return}f()}addToAnnotationStorage(t){!t.isEmpty()&&ye(this,$A)&&!ye(this,$A).has(t.id)&&ye(this,$A).setValue(t.id,t)}blur(){if(this.isShiftKeyDown=!1,ye(this,qP)&&(Kt(this,qP,!1),cs(this,Ji,z3e).call(this,"main_toolbar")),!this.hasSelection)return;const{activeElement:t}=document;for(const n of ye(this,Nm))if(n.div.contains(t)){Kt(this,U8,[n,t]),n._focusEventsAllowed=!1;break}}focus(){if(!ye(this,U8))return;const[t,n]=ye(this,U8);Kt(this,U8,null),n.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this._signal}),n.focus()}addEditListeners(){cs(this,Ji,NZe).call(this),cs(this,Ji,kZe).call(this)}removeEditListeners(){cs(this,Ji,Lss).call(this),cs(this,Ji,SZe).call(this)}dragOver(t){for(const{type:n}of t.dataTransfer.items)for(const r of ye(this,bS))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,bS))if(r.isHandlingMimeForPasting(n.type)){r.paste(n,this.currentLayer),t.preventDefault();return}}copy(t){var r;if(t.preventDefault(),(r=ye(this,Ej))==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,bS))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){su(`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)cs(this,Ji,CZe).call(this,c);cs(this,Ji,AZe).call(this,i)},o=()=>{for(const c of i)c.remove()};this.addCommands({cmd:l,undo:o,mustExec:!0})}catch(i){su(`paste: "${i.message}".`)}}keydown(t){!this.isShiftKeyDown&&t.key==="Shift"&&(this.isShiftKeyDown=!0),ye(this,rv)!==Dd.NONE&&!this.isEditorHandlingKeyboard&&yq._keyboardManager.exec(this,t)}keyup(t){this.isShiftKeyDown&&t.key==="Shift"&&(this.isShiftKeyDown=!1,ye(this,qP)&&(Kt(this,qP,!1),cs(this,Ji,z3e).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?(cs(this,Ji,Pss).call(this),cs(this,Ji,kZe).call(this),cs(this,Ji,e_).call(this,{isEditing:ye(this,rv)!==Dd.NONE,isEmpty:cs(this,Ji,kQ).call(this),hasSomethingToUndo:ye(this,vS).hasSomethingToUndo(),hasSomethingToRedo:ye(this,vS).hasSomethingToRedo(),hasSelectedEditor:!1})):(cs(this,Ji,Iss).call(this),cs(this,Ji,SZe).call(this),cs(this,Ji,e_).call(this,{isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(t){if(!ye(this,bS)){Kt(this,bS,t);for(const n of ye(this,bS))cs(this,Ji,ZM).call(this,n.defaultPropertiesToUpdate)}}getId(){return ye(this,cIe).id}get currentLayer(){return ye(this,Xv).get(ye(this,hH))}getLayer(t){return ye(this,Xv).get(t)}get currentPageIndex(){return ye(this,hH)}addLayer(t){ye(this,Xv).set(t.pageIndex,t),ye(this,VP)?t.enable():t.disable()}removeLayer(t){ye(this,Xv).delete(t.pageIndex)}async updateMode(t,n=null,r=!1){if(ye(this,rv)!==t&&!(ye(this,yN)&&(await ye(this,yN).promise,!ye(this,yN)))){if(Kt(this,yN,Promise.withResolvers()),Kt(this,rv,t),t===Dd.NONE){this.setEditingState(!1),cs(this,Ji,Fss).call(this),ye(this,yN).resolve();return}this.setEditingState(!0),await cs(this,Ji,Dss).call(this),this.unselectAll();for(const a of ye(this,Xv).values())a.updateMode(t);if(!n){r&&this.addNewEditorFromKeyboard(),ye(this,yN).resolve();return}for(const a of ye(this,l0).values())a.annotationElementId===n?(this.setSelected(a),a.enterInEditMode()):a.unselect();ye(this,yN).resolve()}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(t){t!==ye(this,rv)&&this._eventBus.dispatch("switchannotationeditormode",{source:this,mode:t})}updateParams(t,n){var r;if(ye(this,bS)){switch(t){case td.CREATE:this.currentLayer.addNewEditor();return;case td.HIGHLIGHT_DEFAULT_COLOR:(r=ye(this,ire))==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,lre)||Kt(this,lre,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,bS))a.updateDefaultParams(t,n)}}showAllEditors(t,n,r=!1){var i;for(const l of ye(this,l0).values())l.editorType===t&&l.show(n);(((i=ye(this,lre))==null?void 0:i.get(td.HIGHLIGHT_SHOW_ALL))??!0)!==n&&cs(this,Ji,ZM).call(this,[[td.HIGHLIGHT_SHOW_ALL,n]])}enableWaiting(t=!1){if(ye(this,are)!==t){Kt(this,are,t);for(const n of ye(this,Xv).values())t?n.disableClick():n.enableClick(),n.div.classList.toggle("waiting",t)}}getEditors(t){const n=[];for(const r of ye(this,l0).values())r.pageIndex===t&&n.push(r);return n}getEditor(t){return ye(this,l0).get(t)}addEditor(t){ye(this,l0).set(t.id,t)}removeEditor(t){var n;t.div.contains(document.activeElement)&&(ye(this,F5)&&clearTimeout(ye(this,F5)),Kt(this,F5,setTimeout(()=>{this.focusMainContainer(),Kt(this,F5,null)},0))),ye(this,l0).delete(t.id),this.unselect(t),(!t.annotationElementId||!ye(this,B8).has(t.annotationElementId))&&((n=ye(this,$A))==null||n.remove(t.id))}addDeletedAnnotationElement(t){ye(this,B8).add(t.annotationElementId),this.addChangedExistingAnnotation(t),t.deleted=!0}isDeletedAnnotationElement(t){return ye(this,B8).has(t)}removeDeletedAnnotationElement(t){ye(this,B8).delete(t.annotationElementId),this.removeChangedExistingAnnotation(t),t.deleted=!1}setActiveEditor(t){ye(this,Ej)!==t&&(Kt(this,Ej,t),t&&cs(this,Ji,ZM).call(this,t.propertiesToUpdate))}updateUI(t){ye(this,Ji,Oss)===t&&cs(this,Ji,ZM).call(this,t.propertiesToUpdate)}toggleSelected(t){if(ye(this,Nm).has(t)){ye(this,Nm).delete(t),t.unselect(),cs(this,Ji,e_).call(this,{hasSelectedEditor:this.hasSelection});return}ye(this,Nm).add(t),t.select(),cs(this,Ji,ZM).call(this,t.propertiesToUpdate),cs(this,Ji,e_).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(),cs(this,Ji,ZM).call(this,t.propertiesToUpdate),cs(this,Ji,e_).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),cs(this,Ji,e_).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,vS).undo(),cs(this,Ji,e_).call(this,{hasSomethingToUndo:ye(this,vS).hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:cs(this,Ji,kQ).call(this)})}redo(){ye(this,vS).redo(),cs(this,Ji,e_).call(this,{hasSomethingToUndo:!0,hasSomethingToRedo:ye(this,vS).hasSomethingToRedo(),isEmpty:cs(this,Ji,kQ).call(this)})}addCommands(t){ye(this,vS).add(t),cs(this,Ji,e_).call(this,{hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:cs(this,Ji,kQ).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)cs(this,Ji,CZe).call(this,a)};this.addCommands({cmd:n,undo:r,mustExec:!0})}commitOrRemove(){var t;(t=ye(this,Ej))==null||t.commitOrRemove()}hasSomethingToControl(){return ye(this,Ej)||this.hasSelection}selectAll(){for(const t of ye(this,Nm))t.commit();cs(this,Ji,AZe).call(this,ye(this,l0).values())}unselectAll(){if(!(ye(this,Ej)&&(ye(this,Ej).commitOrRemove(),ye(this,rv)!==Dd.NONE))&&this.hasSelection){for(const t of ye(this,Nm))t.unselect();ye(this,Nm).clear(),cs(this,Ji,e_).call(this,{hasSelectedEditor:!1})}}translateSelectedEditors(t,n,r=!1){if(r||this.commitOrRemove(),!this.hasSelection)return;ye(this,GP)[0]+=t,ye(this,GP)[1]+=n;const[a,i]=ye(this,GP),l=[...ye(this,Nm)],o=1e3;ye(this,z5)&&clearTimeout(ye(this,z5)),Kt(this,z5,setTimeout(()=>{Kt(this,z5,null),ye(this,GP)[0]=ye(this,GP)[1]=0,this.addCommands({cmd:()=>{for(const c of l)ye(this,l0).has(c.id)&&c.translateInPage(a,i)},undo:()=>{for(const c of l)ye(this,l0).has(c.id)&&c.translateInPage(-a,-i)},mustExec:!1})},o));for(const c of l)c.translateInPage(t,n)}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0),Kt(this,D5,new Map);for(const t of ye(this,Nm))ye(this,D5).set(t,{savedX:t.x,savedY:t.y,savedPageIndex:t.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!ye(this,D5))return!1;this.disableUserSelect(!1);const t=ye(this,D5);Kt(this,D5,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,l0).has(a.id)){const c=ye(this,Xv).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,D5))for(const r of ye(this,D5).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,Ej)===t}getActive(){return ye(this,Ej)}getMode(){return ye(this,rv)}get imageManager(){return eh(this,"imageManager",new _Ze)}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"&&cs(this,Ji,z3e).call(this,"main_toolbar"))};window.addEventListener("pointerup",h,{signal:u}),window.addEventListener("blur",h,{signal:u})}},z3e=function(t=""){ye(this,rv)===Dd.HIGHLIGHT?this.highlightSelection(t):ye(this,sre)&&cs(this,Ji,Ess).call(this)},Mss=function(){document.addEventListener("selectionchange",cs(this,Ji,Tss).bind(this),{signal:this._signal})},Pss=function(){if(ye(this,UP))return;Kt(this,UP,new AbortController);const t=this.combinedSignal(ye(this,UP));window.addEventListener("focus",this.focus.bind(this),{signal:t}),window.addEventListener("blur",this.blur.bind(this),{signal:t})},Iss=function(){var t;(t=ye(this,UP))==null||t.abort(),Kt(this,UP,null)},NZe=function(){if(ye(this,HP))return;Kt(this,HP,new AbortController);const t=this.combinedSignal(ye(this,HP));window.addEventListener("keydown",this.keydown.bind(this),{signal:t}),window.addEventListener("keyup",this.keyup.bind(this),{signal:t})},Lss=function(){var t;(t=ye(this,HP))==null||t.abort(),Kt(this,HP,null)},kZe=function(){if(ye(this,$P))return;Kt(this,$P,new AbortController);const t=this.combinedSignal(ye(this,$P));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})},SZe=function(){var t;(t=ye(this,$P))==null||t.abort(),Kt(this,$P,null)},Rss=function(){const t=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:t}),document.addEventListener("drop",this.drop.bind(this),{signal:t})},e_=function(t){Object.entries(t).some(([r,a])=>ye(this,cre)[r]!==a)&&(this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(ye(this,cre),t)}),ye(this,rv)===Dd.HIGHLIGHT&&t.hasSelectedEditor===!1&&cs(this,Ji,ZM).call(this,[[td.HIGHLIGHT_FREE,!0]]))},ZM=function(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})},Dss=async function(){if(!ye(this,VP)){Kt(this,VP,!0);const t=[];for(const n of ye(this,Xv).values())t.push(n.enable());await Promise.all(t);for(const n of ye(this,l0).values())n.enable()}},Fss=function(){if(this.unselectAll(),ye(this,VP)){Kt(this,VP,!1);for(const t of ye(this,Xv).values())t.disable();for(const t of ye(this,l0).values())t.disable()}},CZe=function(t){const n=ye(this,Xv).get(t.pageIndex);n?n.addOrRebuild(t):(this.addEditor(t),this.addToAnnotationStorage(t))},Oss=function(){let t=null;for(t of ye(this,Nm));return t},kQ=function(){if(ye(this,l0).size===0)return!0;if(ye(this,l0).size===1)for(const t of ye(this,l0).values())return t.isEmpty();return!1},AZe=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());cs(this,Ji,e_).call(this,{hasSelectedEditor:this.hasSelection})},Nr(yq,"TRANSLATE_SMALL",1),Nr(yq,"TRANSLATE_BIG",10);let gB=yq;var av,B5,_S,pH,$5,Tj,gH,U5,aw,VA,V8,q5,WP,GS,SQ,B3e;const s_=class s_{constructor(t){vs(this,GS);vs(this,av,null);vs(this,B5,!1);vs(this,_S,null);vs(this,pH,null);vs(this,$5,null);vs(this,Tj,null);vs(this,gH,!1);vs(this,U5,null);vs(this,aw,null);vs(this,VA,null);vs(this,V8,null);vs(this,q5,!1);Kt(this,aw,t),Kt(this,q5,t._uiManager.useNewAltTextFlow),ye(s_,WP)||Kt(s_,WP,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){s_._l10n??(s_._l10n=t)}async render(){const t=Kt(this,_S,document.createElement("button"));t.className="altText",t.tabIndex="0";const n=Kt(this,pH,document.createElement("span"));t.append(n),ye(this,q5)?(t.classList.add("new"),t.setAttribute("data-l10n-id",ye(s_,WP).missing),n.setAttribute("data-l10n-id",ye(s_,WP)["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,aw)._uiManager._signal;t.addEventListener("contextmenu",pk,{signal:r}),t.addEventListener("pointerdown",i=>i.stopPropagation(),{signal:r});const a=i=>{i.preventDefault(),ye(this,aw)._uiManager.editAltText(ye(this,aw)),ye(this,q5)&&ye(this,aw)._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:ye(this,GS,SQ)}})};return t.addEventListener("click",a,{capture:!0,signal:r}),t.addEventListener("keydown",i=>{i.target===t&&i.key==="Enter"&&(Kt(this,gH,!0),a(i))},{signal:r}),await cs(this,GS,B3e).call(this),t}finish(){ye(this,_S)&&(ye(this,_S).focus({focusVisible:ye(this,gH)}),Kt(this,gH,!1))}isEmpty(){return ye(this,q5)?ye(this,av)===null:!ye(this,av)&&!ye(this,B5)}hasData(){return ye(this,q5)?ye(this,av)!==null||!!ye(this,VA):this.isEmpty()}get guessedText(){return ye(this,VA)}async setGuessedText(t){ye(this,av)===null&&(Kt(this,VA,t),Kt(this,V8,await s_._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer",{generatedAltText:t})),cs(this,GS,B3e).call(this))}toggleAltTextBadge(t=!1){var n;if(!ye(this,q5)||ye(this,av)){(n=ye(this,U5))==null||n.remove(),Kt(this,U5,null);return}if(!ye(this,U5)){const r=Kt(this,U5,document.createElement("div"));r.className="noAltTextBadge",ye(this,aw).div.append(r)}ye(this,U5).classList.toggle("hidden",!t)}serialize(t){let n=ye(this,av);return!t&&ye(this,VA)===n&&(n=ye(this,V8)),{altText:n,decorative:ye(this,B5),guessedText:ye(this,VA),textWithDisclaimer:ye(this,V8)}}get data(){return{altText:ye(this,av),decorative:ye(this,B5)}}set data({altText:t,decorative:n,guessedText:r,textWithDisclaimer:a,cancel:i=!1}){r&&(Kt(this,VA,r),Kt(this,V8,a)),!(ye(this,av)===t&&ye(this,B5)===n)&&(i||(Kt(this,av,t),Kt(this,B5,n)),cs(this,GS,B3e).call(this))}toggle(t=!1){ye(this,_S)&&(!t&&ye(this,Tj)&&(clearTimeout(ye(this,Tj)),Kt(this,Tj,null)),ye(this,_S).disabled=!t)}shown(){ye(this,aw)._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:ye(this,GS,SQ)}})}destroy(){var t,n;(t=ye(this,_S))==null||t.remove(),Kt(this,_S,null),Kt(this,pH,null),Kt(this,$5,null),(n=ye(this,U5))==null||n.remove(),Kt(this,U5,null)}};av=new WeakMap,B5=new WeakMap,_S=new WeakMap,pH=new WeakMap,$5=new WeakMap,Tj=new WeakMap,gH=new WeakMap,U5=new WeakMap,aw=new WeakMap,VA=new WeakMap,V8=new WeakMap,q5=new WeakMap,WP=new WeakMap,GS=new WeakSet,SQ=function(){return ye(this,av)&&"added"||ye(this,av)===null&&this.guessedText&&"review"||"missing"},B3e=async function(){var a,i,l;const t=ye(this,_S);if(!t)return;if(ye(this,q5)){if(t.classList.toggle("done",!!ye(this,av)),t.setAttribute("data-l10n-id",ye(s_,WP)[ye(this,GS,SQ)]),(a=ye(this,pH))==null||a.setAttribute("data-l10n-id",ye(s_,WP)[`${ye(this,GS,SQ)}-label`]),!ye(this,av)){(i=ye(this,$5))==null||i.remove();return}}else{if(!ye(this,av)&&!ye(this,B5)){t.classList.remove("done"),(l=ye(this,$5))==null||l.remove();return}t.classList.add("done"),t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-edit-button")}let n=ye(this,$5);if(!n){Kt(this,$5,n=document.createElement("span")),n.className="tooltip",n.setAttribute("role","tooltip"),n.id=`alt-text-tooltip-${ye(this,aw).id}`;const o=100,c=ye(this,aw)._uiManager._signal;c.addEventListener("abort",()=>{clearTimeout(ye(this,Tj)),Kt(this,Tj,null)},{once:!0}),t.addEventListener("mouseenter",()=>{Kt(this,Tj,setTimeout(()=>{Kt(this,Tj,null),ye(this,$5).classList.add("show"),ye(this,aw)._reportTelemetry({action:"alt_text_tooltip"})},o))},{signal:c}),t.addEventListener("mouseleave",()=>{var d;ye(this,Tj)&&(clearTimeout(ye(this,Tj)),Kt(this,Tj,null)),(d=ye(this,$5))==null||d.classList.remove("show")},{signal:c})}ye(this,B5)?n.setAttribute("data-l10n-id","pdfjs-editor-alt-text-decorative-tooltip"):(n.removeAttribute("data-l10n-id"),n.textContent=ye(this,av)),n.parentNode||t.append(n);const r=ye(this,aw).getImageForAltText();r==null||r.setAttribute("aria-describedby",n.id)},vs(s_,WP,null),Nr(s_,"_l10n",null);let fPe=s_;var H8,wS,vg,xH,G8,Qv,W8,KP,ure,K8,YP,hre,Y8,HA,V5,yH,vH,vN,mre,dIe,Gd,EZe,fre,TZe,MZe,zss,Bss,PZe,IZe,LZe,$ss,RZe,Uss,qss,Vss,DZe,CQ;const pm=class pm{constructor(t){vs(this,Gd);vs(this,H8,null);vs(this,wS,null);vs(this,vg,null);vs(this,xH,!1);vs(this,G8,!1);vs(this,Qv,null);vs(this,W8,null);vs(this,KP,null);vs(this,ure,"");vs(this,K8,!1);vs(this,YP,null);vs(this,hre,!1);vs(this,Y8,!1);vs(this,HA,!1);vs(this,V5,null);vs(this,yH,0);vs(this,vH,0);vs(this,vN,null);Nr(this,"_editToolbar",null);Nr(this,"_initialOptions",Object.create(null));Nr(this,"_initialData",null);Nr(this,"_isVisible",!0);Nr(this,"_uiManager",null);Nr(this,"_focusEventsAllowed",!0);vs(this,mre,!1);vs(this,dIe,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=gB.TRANSLATE_SMALL,r=gB.TRANSLATE_BIG;return eh(this,"_resizerKeyboardManager",new Wie([[["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 iYn({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){kp("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return ye(this,mre)}set _isDraggable(t){var n;Kt(this,mre,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,dIe)}setParent(t){t!==null?(this.pageIndex=t.pageIndex,this.pageDimensions=t.pageDimensions):cs(this,Gd,CQ).call(this),this.parent=t}focusin(t){this._focusEventsAllowed&&(ye(this,K8)?Kt(this,K8,!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){cs(this,Gd,EZe).call(this,this.parentDimensions,t,n)}translateInPage(t,n){ye(this,YP)||Kt(this,YP,[this.x,this.y]),cs(this,Gd,EZe).call(this,this.pageDimensions,t,n),this.div.scrollIntoView({block:"nearest"})}drag(t,n){ye(this,YP)||Kt(this,YP,[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,YP)&&(ye(this,YP)[0]!==this.x||ye(this,YP)[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 cs(r=pm,fre,TZe).call(r,t,n,this.parentRotation)}pageTranslationToScreen(t,n){var r;return cs(r=pm,fre,TZe).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,G8)||(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,G8)&&n.endsWith("%");if(a&&i)return;const[l,o]=this.parentDimensions;a||(t.width=`${(100*parseFloat(r)/l).toFixed(2)}%`),!ye(this,G8)&&!i&&(t.height=`${(100*parseFloat(n)/o).toFixed(2)}%`)}getInitialTranslation(){return[0,0]}altTextFinish(){var t;(t=ye(this,vg))==null||t.finish()}async addEditToolbar(){return this._editToolbar||ye(this,Y8)?this._editToolbar:(this._editToolbar=new vZe(this),this.div.append(this._editToolbar.render()),ye(this,vg)&&await this._editToolbar.addAltText(ye(this,vg)),this._editToolbar)}removeEditToolbar(){var t;this._editToolbar&&(this._editToolbar.remove(),this._editToolbar=null,(t=ye(this,vg))==null||t.destroy())}addContainer(t){var r;const n=(r=this._editToolbar)==null?void 0:r.div;n?n.before(t):this.div.append(t)}getClientDimensions(){return this.div.getBoundingClientRect()}async addAltTextButton(){ye(this,vg)||(fPe.initialize(pm._l10n),Kt(this,vg,new fPe(this)),ye(this,H8)&&(ye(this,vg).data=ye(this,H8),Kt(this,H8,null)),await this.addEditToolbar())}get altTextData(){var t;return(t=ye(this,vg))==null?void 0:t.data}set altTextData(t){ye(this,vg)&&(ye(this,vg).data=t)}get guessedAltText(){var t;return(t=ye(this,vg))==null?void 0:t.guessedText}async setGuessedAltText(t){var n;await((n=ye(this,vg))==null?void 0:n.setGuessedText(t))}serializeAltText(t){var n;return(n=ye(this,vg))==null?void 0:n.serialize(t)}hasAltText(){return!!ye(this,vg)&&!ye(this,vg).isEmpty()}hasAltTextData(){var t;return((t=ye(this,vg))==null?void 0:t.hasData())??!1}render(){this.div=document.createElement("div"),this.div.setAttribute("data-editor-rotation",(360-this.rotation)%360),this.div.className=this.name,this.div.setAttribute("id",this.id),this.div.tabIndex=ye(this,xH)?-1:0,this._isVisible||this.div.classList.add("hidden"),this.setInForeground(),cs(this,Gd,RZe).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),mPe(this,this.div,["pointerdown"]),this.div}pointerdown(t){const{isMac:n}=S_.platform;if(t.button!==0||t.ctrlKey&&n){t.preventDefault();return}if(Kt(this,K8,!0),this._isDraggable){cs(this,Gd,$ss).call(this,t);return}cs(this,Gd,LZe).call(this,t)}get isSelected(){return this._uiManager.isSelected(this)}moveInDOM(){ye(this,V5)&&clearTimeout(ye(this,V5)),Kt(this,V5,setTimeout(()=>{var t;Kt(this,V5,null),(t=this.parent)==null||t.moveEditorInDOM(this)},0))}_setParentAndPosition(t,n,r){t.changeParent(this),this.x=n,this.y=r,this.fixAndSetPosition()}getRect(t,n,r=this.rotation){const a=this.parentScale,[i,l]=this.pageDimensions,[o,c]=this.pageTranslation,d=t/a,u=n/a,h=this.x*i,m=this.y*l,f=this.width*i,g=this.height*l;switch(r){case 0:return[h+d+o,l-m-u-g+c,h+d+f+o,l-m-u+c];case 90:return[h+u+o,l-m+d+c,h+u+g+o,l-m+d+f+c];case 180:return[h-d-f+o,l-m+u+c,h-d+o,l-m+u+g+c];case 270:return[h-u-g+o,l-m-d-f+c,h-u+o,l-m-d+c];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(t,n){const[r,a,i,l]=t,o=i-r,c=l-a;switch(this.rotation){case 0:return[r,n-l,o,c];case 90:return[r,n-a,c,o];case 180:return[i,n-a,o,c];case 270:return[i,n-l,c,o];default:throw new Error("Invalid rotation")}}onceAdded(){}isEmpty(){return!1}enableEditMode(){Kt(this,Y8,!0)}disableEditMode(){Kt(this,Y8,!1)}isInEditMode(){return ye(this,Y8)}shouldGetKeyboardEvents(){return ye(this,HA)}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}rebuild(){cs(this,Gd,RZe).call(this)}rotate(t){}serializeDeleted(){var t;return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex,popupRef:((t=this._initialData)==null?void 0:t.popupRef)||""}}serialize(t=!1,n=null){kp("An editor must be serializable")}static async deserialize(t,n,r){const a=new this.prototype.constructor({parent:n,id:n.getNextId(),uiManager:r});a.rotation=t.rotation,Kt(a,H8,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,KP))==null||t.abort(),Kt(this,KP,null),this.isEmpty()||this.commit(),this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),ye(this,V5)&&(clearTimeout(ye(this,V5)),Kt(this,V5,null)),cs(this,Gd,CQ).call(this),this.removeEditToolbar(),ye(this,vN)){for(const n of ye(this,vN).values())clearTimeout(n);Kt(this,vN,null)}this.parent=null}get isResizable(){return!1}makeResizable(){this.isResizable&&(cs(this,Gd,zss).call(this),ye(this,Qv).classList.remove("hidden"),mPe(this,this.div,["keydown"]))}get toolbarPosition(){return null}keydown(t){if(!this.isResizable||t.target!==this.div||t.key!=="Enter")return;this._uiManager.setSelected(this),Kt(this,W8,{savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height});const n=ye(this,Qv).children;if(!ye(this,wS)){Kt(this,wS,Array.from(n));const l=cs(this,Gd,Uss).bind(this),o=cs(this,Gd,qss).bind(this),c=this._uiManager._signal;for(const d of ye(this,wS)){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",cs(this,Gd,Vss).bind(this,u),{signal:c}),d.setAttribute("data-l10n-id",pm._l10nResizer[u])}}const r=ye(this,wS)[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,wS).length/4);if(i!==a){if(ia)for(let o=0;o{var a,i;(a=this.div)!=null&&a.classList.contains("selectedEditor")&&((i=this._editToolbar)==null||i.show())});return}(n=this._editToolbar)==null||n.show(),(r=ye(this,vg))==null||r.toggleAltTextBadge(!1)}unselect(){var t,n,r,a,i;(t=ye(this,Qv))==null||t.classList.add("hidden"),(n=this.div)==null||n.classList.remove("selectedEditor"),(r=this.div)!=null&&r.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0}),(a=this._editToolbar)==null||a.hide(),(i=ye(this,vg))==null||i.toggleAltTextBadge(!0)}updateParams(t,n){}disableEditing(){}enableEditing(){}enterInEditMode(){}getImageForAltText(){return null}get contentDiv(){return this.div}get isEditing(){return ye(this,hre)}set isEditing(t){Kt(this,hre,t),this.parent&&(t?(this.parent.setSelected(this),this.parent.setActiveEditor(this)):this.parent.setActiveEditor(null))}setAspectRatio(t,n){Kt(this,G8,!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,vN)||Kt(this,vN,new Map);const{action:r}=t;let a=ye(this,vN).get(r);a&&clearTimeout(a),a=setTimeout(()=>{this._reportTelemetry(t),ye(this,vN).delete(r),ye(this,vN).size===0&&Kt(this,vN,null)},pm._telemetryTimeout),ye(this,vN).set(r,a);return}t.type||(t.type=this.editorType),this._uiManager._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:t}})}show(t=this._isVisible){this.div.classList.toggle("hidden",!t),this._isVisible=t}enable(){this.div&&(this.div.tabIndex=0),Kt(this,xH,!1)}disable(){this.div&&(this.div.tabIndex=-1),Kt(this,xH,!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()}};H8=new WeakMap,wS=new WeakMap,vg=new WeakMap,xH=new WeakMap,G8=new WeakMap,Qv=new WeakMap,W8=new WeakMap,KP=new WeakMap,ure=new WeakMap,K8=new WeakMap,YP=new WeakMap,hre=new WeakMap,Y8=new WeakMap,HA=new WeakMap,V5=new WeakMap,yH=new WeakMap,vH=new WeakMap,vN=new WeakMap,mre=new WeakMap,dIe=new WeakMap,Gd=new WeakSet,EZe=function([t,n],r,a){[r,a]=this.screenToPageTranslation(r,a),this.x+=r/t,this.y+=a/n,this.fixAndSetPosition()},fre=new WeakSet,TZe=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]}},MZe=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]}},zss=function(){if(ye(this,Qv))return;Kt(this,Qv,document.createElement("div")),ye(this,Qv).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,Qv).append(a),a.classList.add("resizer",r),a.setAttribute("data-resizer-name",r),a.addEventListener("pointerdown",cs(this,Gd,Bss).bind(this,r),{signal:n}),a.addEventListener("contextmenu",pk,{signal:n}),a.tabIndex=-1}this.div.prepend(ye(this,Qv))},Bss=function(t,n){var g;n.preventDefault();const{isMac:r}=S_.platform;if(n.button!==0||n.ctrlKey&&r)return;(g=ye(this,vg))==null||g.toggle(!1);const a=this._isDraggable;this._isDraggable=!1;const i=new AbortController,l=this._uiManager.combinedSignal(i);this.parent.togglePointerEvents(!1),window.addEventListener("pointermove",cs(this,Gd,IZe).bind(this,t),{passive:!0,capture:!0,signal:l}),window.addEventListener("contextmenu",pk,{signal:l});const o=this.x,c=this.y,d=this.width,u=this.height,h=this.parent.div.style.cursor,m=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(n.target).cursor;const f=()=>{var x;i.abort(),this.parent.togglePointerEvents(!0),(x=ye(this,vg))==null||x.toggle(!0),this._isDraggable=a,this.parent.div.style.cursor=h,this.div.style.cursor=m,cs(this,Gd,PZe).call(this,o,c,d,u)};window.addEventListener("pointerup",f,{signal:l}),window.addEventListener("blur",f,{signal:l})},PZe=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})},IZe=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=cs(this,Gd,MZe).call(this,this.rotation),f=(X,ae)=>[m[0]*X+m[2]*ae,m[1]*X+m[3]*ae],g=cs(this,Gd,MZe).call(this,360-this.rotation),x=(X,ae)=>[g[0]*X+g[2]*ae,g[1]*X+g[3]*ae];let y,v,b=!1,w=!1;switch(t){case"topLeft":b=!0,y=(X,ae)=>[0,0],v=(X,ae)=>[X,ae];break;case"topMiddle":y=(X,ae)=>[X/2,0],v=(X,ae)=>[X/2,ae];break;case"topRight":b=!0,y=(X,ae)=>[X,0],v=(X,ae)=>[0,ae];break;case"middleRight":w=!0,y=(X,ae)=>[X,ae/2],v=(X,ae)=>[0,ae/2];break;case"bottomRight":b=!0,y=(X,ae)=>[X,ae],v=(X,ae)=>[0,0];break;case"bottomMiddle":y=(X,ae)=>[X/2,ae],v=(X,ae)=>[X/2,0];break;case"bottomLeft":b=!0,y=(X,ae)=>[0,ae],v=(X,ae)=>[X,0];break;case"middleLeft":w=!0,y=(X,ae)=>[0,ae/2],v=(X,ae)=>[X,ae/2];break}const S=y(o,c),A=v(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(...v(W,V));const G=I-E[0],Y=P-E[1];this.width=W,this.height=V,this.x=G,this.y=Y,this.setDims(r*W,a*V),this.fixAndSetPosition()},LZe=function(t){const{isMac:n}=S_.platform;t.ctrlKey&&!n||t.shiftKey||t.metaKey&&n?this.parent.toggleSelected(this):this.parent.setSelected(this)},$ss=function(t){const{isSelected:n}=this;this._uiManager.setUpDragSession();const r=new AbortController,a=this._uiManager.combinedSignal(r);if(n){this.div.classList.add("moving"),Kt(this,yH,t.clientX),Kt(this,vH,t.clientY);const l=o=>{const{clientX:c,clientY:d}=o,[u,h]=this.screenToPageTranslation(c-ye(this,yH),d-ye(this,vH));Kt(this,yH,c),Kt(this,vH,d),this._uiManager.dragSelectedEditors(u,h)};window.addEventListener("pointermove",l,{passive:!0,capture:!0,signal:a})}const i=()=>{r.abort(),n&&this.div.classList.remove("moving"),Kt(this,K8,!1),this._uiManager.endDragSession()||cs(this,Gd,LZe).call(this,t)};window.addEventListener("pointerup",i,{signal:a}),window.addEventListener("blur",i,{signal:a})},RZe=function(){if(ye(this,KP)||!this.div)return;Kt(this,KP,new AbortController);const t=this._uiManager.combinedSignal(ye(this,KP));this.div.addEventListener("focusin",this.focusin.bind(this),{signal:t}),this.div.addEventListener("focusout",this.focusout.bind(this),{signal:t})},Uss=function(t){pm._resizerKeyboardManager.exec(this,t)},qss=function(t){var n;ye(this,HA)&&((n=t.relatedTarget)==null?void 0:n.parentNode)!==ye(this,Qv)&&cs(this,Gd,CQ).call(this)},Vss=function(t){Kt(this,ure,ye(this,HA)?t:"")},DZe=function(t){if(ye(this,wS))for(const n of ye(this,wS))n.tabIndex=t},CQ=function(){if(Kt(this,HA,!1),cs(this,Gd,DZe).call(this,-1),ye(this,W8)){const{savedX:t,savedY:n,savedWidth:r,savedHeight:a}=ye(this,W8);cs(this,Gd,PZe).call(this,t,n,r,a),Kt(this,W8,null)}},vs(pm,fre),Nr(pm,"_l10n",null),Nr(pm,"_l10nResizer",null),Nr(pm,"_borderLineWidth",-1),Nr(pm,"_colorManager",new wZe),Nr(pm,"_zIndex",1),Nr(pm,"_telemetryTimeout",1e3);let Cm=pm;class iYn extends Cm{constructor(t){super(t),this.annotationElementId=t.annotationElementId,this.deleted=!0}serialize(){return this.serializeDeleted()}}const e3t=3285377520,lN=4294901760,i5=65535;class Hss{constructor(t){this.h1=t?t&4294967295:e3t,this.h2=t?t&4294967295:e3t}update(t){let n,r;if(typeof t=="string"){n=new Uint8Array(t.length*2),r=0;for(let x=0,y=t.length;x>>8,n[r++]=v&255)}}else if(ArrayBuffer.isView(t))n=t.slice(),r=n.byteLength;else throw new Error("Invalid data format, must be a string or TypedArray.");const a=r>>2,i=r-a*4,l=new Uint32Array(n.buffer,0,a);let o=0,c=0,d=this.h1,u=this.h2;const h=3432918353,m=461845907,f=h&i5,g=m&i5;for(let x=0;x>>17,o=o*m&lN|o*g&i5,d^=o,d=d<<13|d>>>19,d=d*5+3864292196):(c=l[x],c=c*h&lN|c*f&i5,c=c<<15|c>>>17,c=c*m&lN|c*g&i5,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&lN|o*f&i5,o=o<<15|o>>>17,o=o*m&lN|o*g&i5,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&lN|t*36045&i5,n=n*4283543511&lN|((n<<16|t>>>16)*2950163797&lN)>>>16,t^=n>>>1,t=t*444984403&lN|t*60499&i5,n=n*3301882366&lN|((n<<16|t>>>16)*3120437893&lN)>>>16,t^=n>>>1,(t>>>0).toString(16).padStart(8,"0")+(n>>>0).toString(16).padStart(8,"0")}}const FZe=Object.freeze({map:null,hash:"",transfer:void 0});var Z8,X8,iv,uIe,Gss;class Iot{constructor(){vs(this,uIe);vs(this,Z8,!1);vs(this,X8,null);vs(this,iv,new Map);this.onSetModified=null,this.onResetModified=null,this.onAnnotationEditor=null}getValue(t,n){const r=ye(this,iv).get(t);return r===void 0?n:Object.assign(n,r)}getRawValue(t){return ye(this,iv).get(t)}remove(t){if(ye(this,iv).delete(t),ye(this,iv).size===0&&this.resetModified(),typeof this.onAnnotationEditor=="function"){for(const n of ye(this,iv).values())if(n instanceof Cm)return;this.onAnnotationEditor(null)}}setValue(t,n){const r=ye(this,iv).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,iv).set(t,n);a&&cs(this,uIe,Gss).call(this),n instanceof Cm&&typeof this.onAnnotationEditor=="function"&&this.onAnnotationEditor(n.constructor._type)}has(t){return ye(this,iv).has(t)}getAll(){return ye(this,iv).size>0?Cot(ye(this,iv)):null}setAll(t){for(const[n,r]of Object.entries(t))this.setValue(n,r)}get size(){return ye(this,iv).size}resetModified(){ye(this,Z8)&&(Kt(this,Z8,!1),typeof this.onResetModified=="function"&&this.onResetModified())}get print(){return new Wss(this)}get serializable(){if(ye(this,iv).size===0)return FZe;const t=new Map,n=new Hss,r=[],a=Object.create(null);let i=!1;for(const[l,o]of ye(this,iv)){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}:FZe}get editorStats(){let t=null;const n=new Map;for(const r of ye(this,iv).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(){Kt(this,X8,null)}get modifiedIds(){if(ye(this,X8))return ye(this,X8);const t=[];for(const n of ye(this,iv).values())!(n instanceof Cm)||!n.annotationElementId||!n.serialize()||t.push(n.annotationElementId);return Kt(this,X8,{ids:new Set(t),hash:t.join(",")})}}Z8=new WeakMap,X8=new WeakMap,iv=new WeakMap,uIe=new WeakSet,Gss=function(){ye(this,Z8)||(Kt(this,Z8,!0),typeof this.onSetModified=="function"&&this.onSetModified())};var pre;class Wss extends Iot{constructor(n){super();vs(this,pre);const{map:r,hash:a,transfer:i}=n.serializable,l=structuredClone(r,i?{transfer:i}:null);Kt(this,pre,{map:l,hash:a,transfer:i})}get print(){kp("Should not call PrintAnnotationStorage.print")}get serializable(){return ye(this,pre)}get modifiedIds(){return eh(this,"modifiedIds",{ids:new Set,hash:""})}}pre=new WeakMap;var bH;class oYn{constructor({ownerDocument:t=globalThis.document,styleElement:n=null}){vs(this,bH,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,bH).clear(),this.styleElement&&(this.styleElement.remove(),this.styleElement=null)}async loadSystemFont({systemFontInfo:t,_inspectFont:n}){if(!(!t||ye(this,bH).has(t.loadedName))){if(w0(!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,bH).add(r),n==null||n(t)}catch{su(`Cannot load system font: ${t.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(l)}return}kp("Not implemented: loadSystemFont without the Font Loading API.")}}async bind(t){if(t.attached||t.missingFile&&!t.systemFontInfo)return;if(t.attached=!0,t.systemFontInfo){await this.loadSystemFont(t);return}if(this.isFontLoadingAPISupported){const r=t.createNativeFontFace();if(r){this.addNativeFontFace(r);try{await r.loaded}catch(a){throw su(`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(p1||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(w0(!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){su("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 y=r(m,g);for(i=0,l=h.length-3;i{w.remove(),n.complete()})}}bH=new WeakMap;class lYn{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,${XKn(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){su(`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 lA.MOVE_TO:{const[o,c]=r.slice(i,i+2);a.push(d=>d.moveTo(o,c)),i+=2}break;case lA.LINE_TO:{const[o,c]=r.slice(i,i+2);a.push(d=>d.lineTo(o,c)),i+=2}break;case lA.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 lA.RESTORE:a.push(o=>o.restore());break;case lA.SAVE:a.push(o=>o.save());break;case lA.SCALE:w0(a.length===2,"Scale command is only valid at the third position.");break;case lA.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 lA.TRANSLATE:{const[o,c]=r.slice(i,i+2);a.push(d=>d.translate(o,c)),i+=2}break}return this.compiledGlyphs[n]=function(l,o){a[0](l),a[1](l),l.scale(o,-o);for(let c=2,d=a.length;c({cMapData:r,isCompressed:this.isCompressed})).catch(r=>{throw new Error(`Unable to load ${this.isCompressed?"binary ":""}CMap at: ${n}`)})}async _fetch(t){kp("Abstract method `_fetch` called.")}}class Zss extends Yss{async _fetch(t){const n=await FDe(t,this.isCompressed?"arraybuffer":"text");return n instanceof ArrayBuffer?new Uint8Array(n):DDe(n)}}class Xss{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 Q8,J8,H5,GA,r1,hIe,ez,jo,e1,jU,NU,$3e,kU,Qss,OZe,SU,AQ,EQ,zZe,TQ;class dYn extends Xss{constructor({docId:n,ownerDocument:r=globalThis.document}){super();vs(this,jo);vs(this,Q8);vs(this,J8);vs(this,H5);vs(this,GA);vs(this,r1);vs(this,hIe);vs(this,ez,0);Kt(this,GA,n),Kt(this,r1,r)}addFilter(n){if(!n)return"none";let r=ye(this,jo,e1).get(n);if(r)return r;const[a,i,l]=cs(this,jo,$3e).call(this,n),o=n.length===1?a:`${a}${i}${l}`;if(r=ye(this,jo,e1).get(o),r)return ye(this,jo,e1).set(n,r),r;const c=`g_${ye(this,GA)}_transfer_map_${X0(this,ez)._++}`,d=cs(this,jo,kU).call(this,c);ye(this,jo,e1).set(n,d),ye(this,jo,e1).set(o,d);const u=cs(this,jo,SU).call(this,c);return cs(this,jo,EQ).call(this,a,i,l,u),d}addHCMFilter(n,r){var g;const a=`${n}-${r}`,i="base";let l=ye(this,jo,jU).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,jU).set(i,l)),!n||!r))return l.url;const o=cs(this,jo,TQ).call(this,n);n=ol.makeHexColor(...o);const c=cs(this,jo,TQ).call(this,r);if(r=ol.makeHexColor(...c),ye(this,jo,NU).style.color="",n==="#000000"&&r==="#ffffff"||n===r)return l.url;const d=new Array(256);for(let x=0;x<=255;x++){const y=x/255;d[x]=y<=.03928?y/12.92:((y+.055)/1.055)**2.4}const u=d.join(","),h=`g_${ye(this,GA)}_hcm_filter`,m=l.filter=cs(this,jo,SU).call(this,h);cs(this,jo,EQ).call(this,u,u,u,m),cs(this,jo,OZe).call(this,m);const f=(x,y)=>{const v=o[x]/255,b=c[x]/255,w=new Array(y+1);for(let S=0;S<=y;S++)w[S]=v+S/y*(b-v);return w.join(",")};return cs(this,jo,EQ).call(this,f(0,5),f(1,5),f(2,5),m),l.url=cs(this,jo,kU).call(this,h),l.url}addAlphaFilter(n){let r=ye(this,jo,e1).get(n);if(r)return r;const[a]=cs(this,jo,$3e).call(this,[n]),i=`alpha_${a}`;if(r=ye(this,jo,e1).get(i),r)return ye(this,jo,e1).set(n,r),r;const l=`g_${ye(this,GA)}_alpha_map_${X0(this,ez)._++}`,o=cs(this,jo,kU).call(this,l);ye(this,jo,e1).set(n,o),ye(this,jo,e1).set(i,o);const c=cs(this,jo,SU).call(this,l);return cs(this,jo,zZe).call(this,a,c),o}addLuminosityFilter(n){let r=ye(this,jo,e1).get(n||"luminosity");if(r)return r;let a,i;if(n?([a]=cs(this,jo,$3e).call(this,[n]),i=`luminosity_${a}`):i="luminosity",r=ye(this,jo,e1).get(i),r)return ye(this,jo,e1).set(n,r),r;const l=`g_${ye(this,GA)}_luminosity_map_${X0(this,ez)._++}`,o=cs(this,jo,kU).call(this,l);ye(this,jo,e1).set(n,o),ye(this,jo,e1).set(i,o);const c=cs(this,jo,SU).call(this,l);return cs(this,jo,Qss).call(this,c),n&&cs(this,jo,zZe).call(this,a,c),o}addHighlightHCMFilter(n,r,a,i,l){var b;const o=`${r}-${a}-${i}-${l}`;let c=ye(this,jo,jU).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,jU).set(n,c)),!r||!a))return c.url;const[d,u]=[r,a].map(cs(this,jo,TQ).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(cs(this,jo,TQ).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(",")},y=`g_${ye(this,GA)}_hcm_${n}_filter`,v=c.filter=cs(this,jo,SU).call(this,y);return cs(this,jo,OZe).call(this,v),cs(this,jo,EQ).call(this,x(f[0],g[0],5),x(f[1],g[1],5),x(f[2],g[2],5),v),c.url=cs(this,jo,kU).call(this,y),c.url}destroy(n=!1){n&&ye(this,jo,jU).size!==0||(ye(this,H5)&&(ye(this,H5).parentNode.parentNode.remove(),Kt(this,H5,null)),ye(this,J8)&&(ye(this,J8).clear(),Kt(this,J8,null)),Kt(this,ez,0))}}Q8=new WeakMap,J8=new WeakMap,H5=new WeakMap,GA=new WeakMap,r1=new WeakMap,hIe=new WeakMap,ez=new WeakMap,jo=new WeakSet,e1=function(){return ye(this,J8)||Kt(this,J8,new Map)},jU=function(){return ye(this,hIe)||Kt(this,hIe,new Map)},NU=function(){if(!ye(this,H5)){const n=ye(this,r1).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,r1).createElementNS(_A,"svg");a.setAttribute("width",0),a.setAttribute("height",0),Kt(this,H5,ye(this,r1).createElementNS(_A,"defs")),n.append(a),a.append(ye(this,H5)),ye(this,r1).body.append(n)}return ye(this,H5)},$3e=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(",")]},kU=function(n){if(ye(this,Q8)===void 0){Kt(this,Q8,"");const r=ye(this,r1).URL;r!==ye(this,r1).baseURI&&(ODe(r)?su('#createUrl: ignore "data:"-URL for performance reasons.'):Kt(this,Q8,r.split("#",1)[0]))}return`url(${ye(this,Q8)}#${n})`},Qss=function(n){const r=ye(this,r1).createElementNS(_A,"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)},OZe=function(n){const r=ye(this,r1).createElementNS(_A,"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)},SU=function(n){const r=ye(this,r1).createElementNS(_A,"filter");return r.setAttribute("color-interpolation-filters","sRGB"),r.setAttribute("id",n),ye(this,jo,NU).append(r),r},AQ=function(n,r,a){const i=ye(this,r1).createElementNS(_A,r);i.setAttribute("type","discrete"),i.setAttribute("tableValues",a),n.append(i)},EQ=function(n,r,a,i){const l=ye(this,r1).createElementNS(_A,"feComponentTransfer");i.append(l),cs(this,jo,AQ).call(this,l,"feFuncR",n),cs(this,jo,AQ).call(this,l,"feFuncG",r),cs(this,jo,AQ).call(this,l,"feFuncB",a)},zZe=function(n,r){const a=ye(this,r1).createElementNS(_A,"feComponentTransfer");r.append(a),cs(this,jo,AQ).call(this,a,"feFuncA",n)},TQ=function(n){return ye(this,jo,NU).style.color=n,Pot(getComputedStyle(ye(this,jo,NU)).getPropertyValue("color"))};class Jss{constructor({baseUrl:t=null}){this.baseUrl=t}async fetch({filename:t}){if(!this.baseUrl)throw new Error("Ensure that the `standardFontDataUrl` API parameter is provided.");if(!t)throw new Error("Font filename must be specified.");const n=`${this.baseUrl}${t}`;return this._fetch(n).catch(r=>{throw new Error(`Unable to load font data at: ${n}`)})}async _fetch(t){kp("Abstract method `_fetch` called.")}}class ens extends Jss{async _fetch(t){const n=await FDe(t,"arraybuffer");return new Uint8Array(n)}}if(p1){var BZe=Promise.withResolvers(),ste=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=>{ste=t,BZe.resolve()},t=>{su(`loadPackages: ${t}`),ste=new Map,BZe.resolve()})}class UL{static get promise(){return BZe.promise}static get(t){return ste==null?void 0:ste.get(t)}}async function tns(s){const n=await UL.get("fs").promises.readFile(s);return new Uint8Array(n)}class uYn extends Xss{}class hYn extends Kss{_createCanvas(t,n){return UL.get("canvas").createCanvas(t,n)}}class mYn extends Yss{async _fetch(t){return tns(t)}}class fYn extends Jss{async _fetch(t){return tns(t)}}const d_={FILL:"Fill",STROKE:"Stroke",SHADING:"Shading"};function $Ze(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 Lot{getPattern(){kp("Abstract method `getPattern` called.")}}class pYn extends Lot{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===d_.STROKE||a===d_.FILL){const l=n.current.getClippedPathBoundingBox(a,wg(t))||[0,0,0,0],o=Math.ceil(l[2]-l[0])||1,c=Math.ceil(l[3]-l[1])||1,d=n.cachedCanvases.getCanvas("pattern",o,c),u=d.context;u.clearRect(0,0,u.canvas.width,u.canvas.height),u.beginPath(),u.rect(0,0,u.canvas.width,u.canvas.height),u.translate(-l[0],-l[1]),r=ol.transform(r,[1,0,0,1,l[0],l[1]]),u.transform(...n.baseTransform),this.matrix&&u.transform(...this.matrix),$Ze(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 $Ze(t,this._bbox),i=this._createGradient(t);return i}}function P$e(s,t,n,r,a,i,l,o){const c=t.coords,d=t.colors,u=s.data,h=s.width*4;let m;c[n+1]>c[r+1]&&(m=n,n=r,r=m,m=i,i=l,l=m),c[r+1]>c[a+1]&&(m=r,r=a,a=m,m=l,l=o,o=m),c[n+1]>c[r+1]&&(m=n,n=r,r=m,m=i,i=l,l=m);const f=(c[n]+t.offsetX)*t.scaleX,g=(c[n+1]+t.offsetY)*t.scaleY,x=(c[r]+t.offsetX)*t.scaleX,y=(c[r+1]+t.offsetY)*t.scaleY,v=(c[a]+t.offsetX)*t.scaleX,b=(c[a+1]+t.offsetY)*t.scaleY;if(g>=b)return;const w=d[i],S=d[i+1],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,Y,X,ae,le,ne,te;for(let J=U;J<=W;J++){if(Jb?ve=1:y===b?ve=0:ve=(y-J)/(y-b),V=x-(x-v)*ve,G=E-(E-R)*ve,Y=I-(I-D)*ve,X=P-(P-O)*ve}let ce;Jb?ce=1:ce=(g-J)/(g-b),ae=f-(f-v)*ce,le=w-(w-R)*ce,ne=S-(S-D)*ce,te=A-(A-O)*ce;const _e=Math.round(Math.min(V,ae)),he=Math.round(Math.max(V,ae));let ue=h*J+_e*4;for(let ve=_e;ve<=he;ve++)ce=(V-ve)/(V-ae),ce<0?ce=0:ce>1&&(ce=1),u[ue++]=G-(G-le)*ce|0,u[ue++]=Y-(Y-ne)*ce|0,u[ue++]=X-(X-te)*ce|0,u[ue++]=255}}function gYn(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,Y=o.createCanvasGraphics(G);if(Y.groupLevel=t.groupLevel,this.setFillAndStrokeStyleToContext(Y,a,l),G.translate(-U.scale*u,-W.scale*h),Y.transform(U.scale,0,0,W.scale,0,0),G.save(),this.clipBbox(Y,u,h,m,f),Y.baseTransform=wg(Y.ctx),Y.executeOperatorList(r),Y.endDrawing(),G.restore(),E||I){const X=V.canvas;E&&(S=c),I&&(A=d);const ae=this.getSizeAndScale(S,this.ctx.canvas.width,b),le=this.getSizeAndScale(A,this.ctx.canvas.height,w),ne=ae.size,te=le.size,J=t.cachedCanvases.getCanvas("pattern-workaround",ne,te),ce=J.context,_e=E?Math.floor(g/c):0,he=I?Math.floor(x/d):0;for(let ue=0;ue<=_e;ue++)for(let ve=0;ve<=he;ve++)ce.drawImage(X,ne*ue,te*ve,ne,te,0,0,ne,te);return{canvas:J.canvas,scaleX:ae.scale,scaleY: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(mIe.MAX_PATTERN_SIZE,n);let i=Math.ceil(t*r);return i>=a?i=a:r=i/t,{scale:r,size:i}}clipBbox(t,n,r,a,i){const l=a-n,o=i-r;t.ctx.rect(n,r,l,o),t.current.updateRectMinMax(wg(t.ctx),[n,r,a,i]),t.clip(),t.endPath()}setFillAndStrokeStyleToContext(t,n,r){const a=t.ctx,i=t.current;switch(n){case t3t.COLORED:const l=this.ctx;a.fillStyle=l.fillStyle,a.strokeStyle=l.strokeStyle,i.fillColor=l.fillStyle,i.strokeColor=l.strokeStyle;break;case t3t.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 VKn(`Unsupported paint type: ${n}`)}}getPattern(t,n,r,a){let i=r;a!==d_.SHADING&&(i=ol.transform(i,n.baseTransform),this.matrix&&(i=ol.transform(i,this.matrix)));const l=this.createPatternCanvas(n);let o=new DOMMatrix(i);o=o.translate(l.offsetX,l.offsetY),o=o.scale(1/l.scaleX,1/l.scaleY);const c=t.createPattern(l.canvas,"repeat");return c.setTransform(o),c}};Nr(mIe,"MAX_PATTERN_SIZE",3e3);let UZe=mIe;function bYn({src:s,srcPos:t=0,dest:n,width:r,height:a,nonBlackColor:i=4294967295,inverseDecode:l=!1}){const o=S_.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 jYn{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 Aue(s,t,n,r,a,i,l,o,c,d){const[u,h,m,f,g,x]=wg(s);if(h===0&&m===0){const b=l*u+g,w=Math.round(b),S=o*f+x,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 y=Math.hypot(u,h),v=Math.hypot(m,f);return[y*c,v*d]}function NYn(s){const{width:t,height:n}=s;if(t>a3t||n>a3t)return null;const r=1e3,a=new Uint8Array([0,2,4,0,1,0,5,4,8,10,0,8,0,2,1,0]),i=t+1;let l=new Uint8Array(i*(n+1)),o,c,d;const u=t+7&-8;let h=new Uint8Array(u*n),m=0;for(const v of s.data){let b=128;for(;b>0;)h[m++]=v&b?0:255,b>>=1}let f=0;for(m=0,h[m]!==0&&(l[0]=1,++f),c=1;c>2)+(h[m+1]?4:0)+(h[m-u+1]?8:0),a[v]&&(l[d+c]=a[v],++f),m++;if(h[m-u]!==h[m]&&(l[d+c]=h[m]?2:4,++f),f>r)return null}for(m=u*(n-1),d=o*i,h[m]!==0&&(l[d]=8,++f),c=1;cr)return null;const g=new Int32Array([0,i,-1,0,-i,0,0,0,1]),x=new Path2D;for(o=0;f&&o<=n;o++){let v=o*i;const b=v+t;for(;v>4,l[v]&=S>>2|S<<2),x.lineTo(v%i,v/i|0),l[v]||--f}while(w!==v);--o}return h=null,l=null,function(v){v.save(),v.scale(1/t,-1/n),v.translate(0,-n),v.fill(x),v.beginPath(),v.restore()}}class i3t{constructor(t,n){this.alphaIsShape=!1,this.fontSize=0,this.fontSizeScale=1,this.textMatrix=yss,this.textMatrixScale=1,this.fontMatrix=fZe,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=Jb.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=d_.FILL,n=null){const r=[this.minX,this.minY,this.maxX,this.maxY];if(t===d_.STROKE){n||kp("Stroke bounding box must include transform.");const a=ol.singularValueDecompose2dScale(n),i=a[0]*this.lineWidth/2,l=a[1]*this.lineWidth/2;r[0]-=i,r[1]-=l,r[2]+=i,r[3]+=l}return r}updateClipFromPath(){const t=ol.intersect(this.clipBox,this.getPathBoundingBox());this.startNewPathAndClipBox(t||[0,0,0,0])}isEmptyClip(){return this.minX===1/0}startNewPathAndClipBox(t){this.clipBox=t,this.minX=1/0,this.minY=1/0,this.maxX=0,this.maxY=0}getClippedPathBoundingBox(t=d_.FILL,n=null){return ol.intersect(this.clipBox,this.getPathBoundingBox(t,n))}}function o3t(s,t){if(typeof ImageData<"u"&&t instanceof ImageData){s.putImageData(t,0,0);return}const n=t.height,r=t.width,a=n%cw,i=(n-a)/cw,l=a===0?i:i+1,o=s.createImageData(r,cw);let c=0,d;const u=t.data,h=o.data;let m,f,g,x;if(t.kind===L3e.GRAYSCALE_1BPP){const y=u.byteLength,v=new Uint32Array(h.buffer,0,h.byteLength>>2),b=v.length,w=r+7>>3,S=4294967295,A=S_.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*cw)}else throw new Error(`bad image kind: ${t.kind}`)}function l3t(s,t){if(t.bitmap){s.drawImage(t.bitmap,0,0);return}const n=t.height,r=t.width,a=n%cw,i=(n-a)/cw,l=a===0?i:i+1,o=s.createImageData(r,cw);let c=0;const d=t.data,u=o.data;for(let h=0;hr3t&&typeof r=="function",u=d?Date.now()+_Yn: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!==pS.dependency)this[g].apply(this,i[o]);else for(const x of i[o]){const y=x.startsWith("g_")?m:f;if(!y.has(x))return y.get(x,r),o}if(o++,o===c)return o;if(d&&++h>r3t){if(Date.now()>u)return r(),o;h=0}}}endDrawing(){cs(this,YL,qZe).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(),cs(this,YL,VZe).call(this)}_scaleImage(t,n){const r=t.width??t.displayWidth,a=t.height??t.displayHeight;let i=Math.max(Math.hypot(n[0],n[1]),1),l=Math.max(Math.hypot(n[2],n[3]),1),o=r,c=a,d="prescale1",u,h;for(;i>2&&o>1||l>2&&c>1;){let m=o,f=c;i>2&&o>1&&(m=o>=16384?Math.floor(o/2)-1||1:Math.ceil(o/2),i/=o/m),l>2&&c>1&&(f=c>=16384?Math.floor(c/2)-1||1:Math.ceil(c)/2,l/=c/f),u=this.cachedCanvases.getCanvas(d,m,f),h=u.context,h.clearRect(0,0,m,f),h.drawImage(t,0,0,o,c,0,0,m,f),t=u.canvas,o=m,c=f,d=d==="prescale1"?"prescale2":"prescale1"}return{img:t,paintWidth:o,paintHeight:c}}_createMaskCanvas(t){const n=this.ctx,{width:r,height:a}=t,i=this.current.fillColor,l=this.current.patternFill,o=wg(n);let c,d,u,h;if((t.bitmap||t.data)&&t.count>1){const P=t.bitmap||t.data.buffer;d=JSON.stringify(l?o:[o.slice(0,4),i]),c=this._cachedBitmapsMap.get(P),c||(c=new Map,this._cachedBitmapsMap.set(P,c));const R=c.get(d);if(R&&!l){const D=Math.round(Math.min(o[0],o[2])+o[4]),O=Math.round(Math.min(o[1],o[3])+o[5]);return{canvas:R,offsetX:D,offsetY:O}}u=R}u||(h=this.cachedCanvases.getCanvas("maskCanvas",r,a),l3t(h.context,t));let m=ol.transform(o,[1/r,0,0,-1/a,0,0]);m=ol.transform(m,[1,0,0,1,0,-a]);const[f,g,x,y]=ol.getAxialAlignedBoundingBox([0,0,r,a],m),v=Math.round(x-f)||1,b=Math.round(y-g)||1,w=this.cachedCanvases.getCanvas("fillCanvas",v,b),S=w.context,A=f,E=g;S.translate(-A,-E),S.transform(...m),u||(u=this._scaleImage(h.canvas,cA(S)),u=u.img,c&&l&&c.set(d,u)),S.imageSmoothingEnabled=c3t(wg(S),t.interpolate),Aue(S,u,0,0,u.width,u.height,0,0,r,a),S.globalCompositeOperation="source-in";const I=ol.transform(cA(S),[1,0,0,1,-A,-E]);return S.fillStyle=l?i.getPattern(n,this,I,d_.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=kYn[t]}setLineJoin(t){this.ctx.lineJoin=SYn[t]}setMiterLimit(t){this.ctx.miterLimit=t}setDash(t,n){const r=this.ctx;r.setLineDash!==void 0&&(r.setLineDash(t),r.lineDashOffset=n)}setRenderingIntent(t){}setFlatness(t){}setGState(t){for(const[n,r]of t)switch(n){case"LW":this.setLineWidth(r);break;case"LC":this.setLineCap(r);break;case"LJ":this.setLineJoin(r);break;case"ML":this.setMiterLimit(r);break;case"D":this.setDash(r[0],r[1]);break;case"RI":this.setRenderingIntent(r);break;case"FL":this.setFlatness(r);break;case"Font":this.setFont(r[0],r[1]);break;case"CA":this.current.strokeAlpha=r;break;case"ca":this.current.fillAlpha=r,this.ctx.globalAlpha=r;break;case"BM":this.ctx.globalCompositeOperation=r;break;case"SMask":this.current.activeSMask=r?this.tempSMask:null,this.tempSMask=null,this.checkSMaskState();break;case"TR":this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(r);break}}get inSMaskMode(){return!!this.suspendedCtx}checkSMaskState(){const t=this.inSMaskMode;this.current.activeSMask&&!t?this.beginSMaskMode():!this.current.activeSMask&&t&&this.endSMaskMode()}beginSMaskMode(){if(this.inSMaskMode)throw new Error("beginSMaskMode called while already in smask mode");const t=this.ctx.canvas.width,n=this.ctx.canvas.height,r="smaskGroupAt"+this.groupLevel,a=this.cachedCanvases.getCanvas(r,t,n);this.suspendedCtx=this.ctx,this.ctx=a.context;const i=this.ctx;i.setTransform(...wg(this.suspendedCtx)),dX(this.suspendedCtx,i),wYn(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(),dX(this.ctx,this.suspendedCtx),this.ctx=this.suspendedCtx,this.suspendedCtx=null}compose(t){if(!this.current.activeSMask)return;t?(t[0]=Math.floor(t[0]),t[1]=Math.floor(t[1]),t[2]=Math.ceil(t[2]),t[3]=Math.ceil(t[3])):t=[0,0,this.ctx.canvas.width,this.ctx.canvas.height];const n=this.current.activeSMask,r=this.suspendedCtx;this.composeSMask(r,n,this.ctx,t),this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.clearRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height),this.ctx.restore()}composeSMask(t,n,r,a){const i=a[0],l=a[1],o=a[2]-i,c=a[3]-l;o===0||c===0||(this.genericComposeSMask(n.context,r,o,c,n.subtype,n.backdrop,n.transferMap,i,l,n.offsetX,n.offsetY),t.save(),t.globalAlpha=1,t.globalCompositeOperation="source-over",t.setTransform(1,0,0,1,0,0),t.drawImage(r.canvas,0,0),t.restore())}genericComposeSMask(t,n,r,a,i,l,o,c,d,u,h){let m=t.canvas,f=c-u,g=d-h;if(l){const y=ol.makeHexColor(...l);if(f<0||g<0||f+r>m.width||g+a>m.height){const v=this.cachedCanvases.getCanvas("maskExtension",r,a),b=v.context;b.drawImage(m,-f,-g),b.globalCompositeOperation="destination-atop",b.fillStyle=y,b.fillRect(0,0,r,a),b.globalCompositeOperation="source-over",m=v.canvas,f=g=0}else{t.save(),t.globalAlpha=1,t.setTransform(1,0,0,1,0,0);const v=new Path2D;v.rect(f,g,r,a),t.clip(v),t.globalCompositeOperation="destination-atop",t.fillStyle=y,t.fillRect(f,g,r,a),t.restore()}}n.save(),n.globalAlpha=1,n.setTransform(1,0,0,1,0,0),i==="Alpha"&&o?n.filter=this.filterFactory.addAlphaFilter(o):i==="Luminosity"&&(n.filter=this.filterFactory.addLuminosityFilter(o));const x=new Path2D;x.rect(c,d,r,a),n.clip(x),n.globalCompositeOperation="destination-in",n.drawImage(m,f,g,r,a,c,d,r,a),n.restore()}save(){this.inSMaskMode?(dX(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(),dX(this.suspendedCtx,this.ctx)):this.ctx.restore(),this.checkSMaskState(),this.pendingClip=null,this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null)}transform(t,n,r,a,i,l){this.ctx.transform(t,n,r,a,i,l),this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null}constructPath(t,n,r){const a=this.ctx,i=this.current;let l=i.x,o=i.y,c,d;const u=wg(a),h=u[0]===0&&u[3]===0||u[1]===0&&u[2]===0,m=h?r.slice(0):null;for(let f=0,g=0,x=t.length;fn3t&&(d=n3t),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&Jb.FILL_STROKE_MASK,h=!!(c&Jb.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===Jb.FILL||u===Jb.FILL_STROKE)&&i.fill(),(u===Jb.STROKE||u===Jb.FILL_STROKE)&&i.stroke(),i.restore()):((u===Jb.FILL||u===Jb.FILL_STROKE)&&i.fillText(t,n,r),(u===Jb.STROKE||u===Jb.FILL_STROKE)&&i.strokeText(t,n,r)),h&&(this.pendingTextPaths||(this.pendingTextPaths=[])).push({transform:wg(i),x:n,y:r,fontSize:d,addToPath:f})}get isFontSubpixelAAEnabled(){const{context:t}=this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled",10,10);t.scale(1.5,1),t.fillText("I",0,10);const n=t.getImageData(0,0,10,10).data;let r=!1;for(let a=3;a0&&n[a]<255){r=!0;break}return 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],y=n.textRenderingMode===Jb.FILL&&!r.disableFontFace&&!n.patternFill;i.save(),i.transform(...n.textMatrix),i.translate(n.x,n.y+n.textRise),d>0?i.scale(u,-1):i.scale(u,1);let v;if(n.patternFill){i.save();const E=n.fillColor.getPattern(i,this,cA(i),d_.FILL);v=wg(i),i.restore(),i.fillStyle=E}let b=n.lineWidth;const w=n.textMatrixScale;if(w===0||b===0){const E=n.textRenderingMode&Jb.FILL_STROKE_MASK;(E===Jb.STROKE||E===Jb.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 Jct(l,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack})};n=new UZe(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=vYn(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,cA(n),d_.SHADING);const a=cA(n);if(a){const{width:i,height:l}=n.canvas,[o,c,d,u]=ol.getAxialAlignedBoundingBox([0,0,i,l],a);this.ctx.fillRect(o,c,d-o,u-c)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.compose(this.current.getClippedPathBoundingBox()),this.restore()}beginInlineImage(){kp("Should not call beginInlineImage")}beginImageData(){kp("Should not call beginImageData")}paintFormXObjectBegin(t,n){if(this.contentVisible&&(this.save(),this.baseTransformStack.push(this.baseTransform),t&&this.transform(...t),this.baseTransform=wg(this.ctx),n)){const r=n[2]-n[0],a=n[3]-n[1];this.ctx.rect(n[0],n[1],r,a),this.current.updateRectMinMax(wg(this.ctx),n),this.clip(),this.endPath()}}paintFormXObjectEnd(){this.contentVisible&&(this.restore(),this.baseTransform=this.baseTransformStack.pop())}beginGroup(t){if(!this.contentVisible)return;this.save(),this.inSMaskMode&&(this.endSMaskMode(),this.current.activeSMask=null);const n=this.ctx;t.isolated||LDe("TODO: Support non-isolated groups."),t.knockout&&su("Knockout groups not supported.");const r=wg(n);if(t.matrix&&n.transform(...t.matrix),!t.bbox)throw new Error("Bounding box is required.");let a=ol.getAxialAlignedBoundingBox(t.bbox,wg(n));const i=[0,0,n.canvas.width,n.canvas.height];a=ol.intersect(a,i)||[0,0,0,0];const l=Math.floor(a[0]),o=Math.floor(a[1]),c=Math.max(Math.ceil(a[2])-l,1),d=Math.max(Math.ceil(a[3])-o,1);this.current.startNewPathAndClipBox([0,0,c,d]);let u="groupAt"+this.groupLevel;t.smask&&(u+="_smask_"+this.smaskCounter++%2);const h=this.cachedCanvases.getCanvas(u,c,d),m=h.context;m.translate(-l,-o),m.transform(...r),t.smask?this.smaskStack.push({canvas:h.canvas,context:m,offsetX:l,offsetY:o,subtype:t.smask.subtype,backdrop:t.smask.backdrop,transferMap:t.smask.transferMap||null,startTransformInverse:null}):(n.setTransform(1,0,0,1,0,0),n.translate(l,o),n.save()),dX(n,m),this.ctx=m,this.setGState([["BM","source-over"],["ca",1],["CA",1]]),this.groupStack.push(n),this.groupLevel++}endGroup(t){if(!this.contentVisible)return;this.groupLevel--;const n=this.ctx,r=this.groupStack.pop();if(this.ctx=r,this.ctx.imageSmoothingEnabled=!1,t.smask)this.tempSMask=this.smaskStack.pop(),this.restore();else{this.ctx.restore();const a=wg(this.ctx);this.restore(),this.ctx.save(),this.ctx.setTransform(...a);const i=ol.getAxialAlignedBoundingBox([0,0,n.canvas.width,n.canvas.height],a);this.ctx.drawImage(n.canvas,0,0),this.ctx.restore(),this.compose(i)}}beginAnnotation(t,n,r,a,i){if(cs(this,YL,qZe).call(this),Eue(this.ctx),this.ctx.save(),this.save(),this.baseTransform&&this.ctx.setTransform(...this.baseTransform),n){const l=n[2]-n[0],o=n[3]-n[1];if(i&&this.annotationCanvasMap){r=r.slice(),r[4]-=n[0],r[5]-=n[1],n=n.slice(),n[0]=n[1]=0,n[2]=l,n[3]=o;const[c,d]=ol.singularValueDecompose2dScale(wg(this.ctx)),{viewportScale:u}=this,h=Math.ceil(l*this.outputScaleX*u),m=Math.ceil(o*this.outputScaleY*u);this.annotationCanvas=this.canvasFactory.create(h,m);const{canvas:f,context:g}=this.annotationCanvas;this.annotationCanvasMap.set(t,f),this.annotationCanvas.savedCtx=this.ctx,this.ctx=g,this.ctx.save(),this.ctx.setTransform(c,0,0,-d,0,o*d),Eue(this.ctx)}else Eue(this.ctx),this.endPath(),this.ctx.rect(n[0],n[1],l,o),this.ctx.clip(),this.ctx.beginPath()}this.current=new i3t(this.ctx.canvas.width,this.ctx.canvas.height),this.transform(...r),this.transform(...a)}endAnnotation(){this.annotationCanvas&&(this.ctx.restore(),cs(this,YL,VZe).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=NYn(t)),a.compiled)){a.compiled(r);return}const i=this._createMaskCanvas(t),l=i.canvas;r.save(),r.setTransform(1,0,0,1,0,0),r.drawImage(l,i.offsetX,i.offsetY),r.restore(),this.compose()}paintImageMaskXObjectRepeat(t,n,r=0,a=0,i,l){if(!this.contentVisible)return;t=this.getObject(t.data,t);const o=this.ctx;o.save();const c=wg(o);o.transform(n,r,a,i,0,0);const d=this._createMaskCanvas(t);o.setTransform(1,0,0,1,d.offsetX-c[4],d.offsetY-c[5]);for(let u=0,h=l.length;uh?u/h:1,o=d>h?d/h:1}}this._cachedScaleForStroking[0]=l,this._cachedScaleForStroking[1]=o}return this._cachedScaleForStroking}rescaleAndStroke(t){const{ctx:n}=this,{lineWidth:r}=this.current,[a,i]=this.getScaleForStroking();if(n.lineWidth=r||1,a===1&&i===1){n.stroke();return}const l=n.getLineDash();if(t&&n.save(),n.scale(a,i),l.length>0){const o=Math.max(a,i);n.setLineDash(l.map(c=>c/o)),n.lineDashOffset/=o}n.stroke(),t&&n.restore()}isContentVisible(){for(let t=this.markedContentStack.length-1;t>=0;t--)if(!this.markedContentStack[t].visible)return!1;return!0}};YL=new WeakSet,qZe=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)},VZe=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 zV=Jct;for(const s in pS)zV.prototype[s]!==void 0&&(zV.prototype[pS[s]]=zV.prototype[s]);var xre,yre;class mE{static get workerPort(){return ye(this,xre)}static set workerPort(t){if(!(typeof Worker<"u"&&t instanceof Worker)&&t!==null)throw new Error("Invalid `workerPort` type.");Kt(this,xre,t)}static get workerSrc(){return ye(this,yre)}static set workerSrc(t){if(typeof t!="string")throw new Error("Invalid `workerSrc` type.");Kt(this,yre,t)}}xre=new WeakMap,yre=new WeakMap,vs(mE,xre,null),vs(mE,yre,"");const Tue={DATA:1,ERROR:2},Sy={CANCEL:1,CANCEL_COMPLETE:2,CLOSE:3,ENQUEUE:4,ERROR:5,PULL:6,PULL_COMPLETE:7,START_COMPLETE:8};function vj(s){switch(s instanceof Error||typeof s=="object"&&s!==null||kp('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),s.name){case"AbortException":return new h9(s.message);case"MissingPDFException":return new u9(s.message);case"PasswordException":return new pZe(s.message,s.code);case"UnexpectedResponseException":return new RDe(s.message,s.status);case"UnknownErrorException":return new gZe(s.message,s.details);default:return new gZe(s.message,s.toString())}}var _H,ok,sns,nns,rns,U3e;class MQ{constructor(t,n,r){vs(this,ok);vs(this,_H,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",cs(this,ok,sns).bind(this),{signal:ye(this,_H).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:Sy.PULL,streamId:i,desiredSize:d.desiredSize}),u.promise},cancel:d=>{w0(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:Sy.CANCEL,streamId:i,reason:vj(d)}),u.promise}},r)}destroy(){var t;(t=ye(this,_H))==null||t.abort(),Kt(this,_H,null)}}_H=new WeakMap,ok=new WeakSet,sns=function({data:t}){if(t.targetName!==this.sourceName)return;if(t.stream){cs(this,ok,rns).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===Tue.DATA)a.resolve(t.data);else if(t.callback===Tue.ERROR)a.reject(vj(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:Tue.DATA,callbackId:t.callbackId,data:l})},function(l){i.postMessage({sourceName:r,targetName:a,callback:Tue.ERROR,callbackId:t.callbackId,reason:vj(l)})});return}if(t.streamId){cs(this,ok,nns).call(this,t);return}n(t.data)},nns=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:Sy.ENQUEUE,streamId:n,chunk:d},h)},close(){this.isCancelled||(this.isCancelled=!0,i.postMessage({sourceName:r,targetName:a,stream:Sy.CLOSE,streamId:n}),delete l.streamSinks[n])},error(d){w0(d instanceof Error,"error must have a valid reason"),!this.isCancelled&&(this.isCancelled=!0,i.postMessage({sourceName:r,targetName:a,stream:Sy.ERROR,streamId:n,reason:vj(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:Sy.START_COMPLETE,streamId:n,success:!0})},function(d){i.postMessage({sourceName:r,targetName:a,stream:Sy.START_COMPLETE,streamId:n,reason:vj(d)})})},rns=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 Sy.START_COMPLETE:t.success?l.startCall.resolve():l.startCall.reject(vj(t.reason));break;case Sy.PULL_COMPLETE:t.success?l.pullCall.resolve():l.pullCall.reject(vj(t.reason));break;case Sy.PULL:if(!o){i.postMessage({sourceName:r,targetName:a,stream:Sy.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:Sy.PULL_COMPLETE,streamId:n,success:!0})},function(c){i.postMessage({sourceName:r,targetName:a,stream:Sy.PULL_COMPLETE,streamId:n,reason:vj(c)})});break;case Sy.ENQUEUE:if(w0(l,"enqueue should have stream controller"),l.isClosed)break;l.controller.enqueue(t.chunk);break;case Sy.CLOSE:if(w0(l,"close should have stream controller"),l.isClosed)break;l.isClosed=!0,l.controller.close(),cs(this,ok,U3e).call(this,l,n);break;case Sy.ERROR:w0(l,"error should have stream controller"),l.controller.error(vj(t.reason)),cs(this,ok,U3e).call(this,l,n);break;case Sy.CANCEL_COMPLETE:t.success?l.cancelCall.resolve():l.cancelCall.reject(vj(t.reason)),cs(this,ok,U3e).call(this,l,n);break;case Sy.CANCEL:if(!o)break;new Promise(function(c){var d;c((d=o.onCancel)==null?void 0:d.call(o,vj(t.reason)))}).then(function(){i.postMessage({sourceName:r,targetName:a,stream:Sy.CANCEL_COMPLETE,streamId:n,success:!0})},function(c){i.postMessage({sourceName:r,targetName:a,stream:Sy.CANCEL_COMPLETE,streamId:n,reason:vj(c)})}),o.sinkCapability.reject(vj(t.reason)),o.isCancelled=!0,delete this.streamSinks[n];break;default:throw new Error("Unexpected stream case")}},U3e=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 tz,vre;class AYn{constructor({parsedData:t,rawData:n}){vs(this,tz);vs(this,vre);Kt(this,tz,t),Kt(this,vre,n)}getRaw(){return ye(this,vre)}get(t){return ye(this,tz).get(t)??null}getAll(){return Cot(ye(this,tz))}has(t){return ye(this,tz).has(t)}}tz=new WeakMap,vre=new WeakMap;const CU=Symbol("INTERNAL");var bre,_re,wre,wH;class EYn{constructor(t,{name:n,intent:r,usage:a,rbGroups:i}){vs(this,bre,!1);vs(this,_re,!1);vs(this,wre,!1);vs(this,wH,!0);Kt(this,bre,!!(t&Oj.DISPLAY)),Kt(this,_re,!!(t&Oj.PRINT)),this.name=n,this.intent=r,this.usage=a,this.rbGroups=i}get visible(){if(ye(this,wre))return ye(this,wH);if(!ye(this,wH))return!1;const{print:t,view:n}=this.usage;return ye(this,bre)?(n==null?void 0:n.viewState)!=="OFF":ye(this,_re)?(t==null?void 0:t.printState)!=="OFF":!0}_setVisible(t,n,r=!1){t!==CU&&kp("Internal method `_setVisible` called."),Kt(this,wre,r),Kt(this,wH,n)}}bre=new WeakMap,_re=new WeakMap,wre=new WeakMap,wH=new WeakMap;var ZP,km,jH,NH,jre,HZe;class TYn{constructor(t,n=Oj.DISPLAY){vs(this,jre);vs(this,ZP,null);vs(this,km,new Map);vs(this,jH,null);vs(this,NH,null);if(this.renderingIntent=n,this.name=null,this.creator=null,t!==null){this.name=t.name,this.creator=t.creator,Kt(this,NH,t.order);for(const r of t.groups)ye(this,km).set(r.id,new EYn(n,r));if(t.baseState==="OFF")for(const r of ye(this,km).values())r._setVisible(CU,!1);for(const r of t.on)ye(this,km).get(r)._setVisible(CU,!0);for(const r of t.off)ye(this,km).get(r)._setVisible(CU,!1);Kt(this,jH,this.getHash())}}isVisible(t){if(ye(this,km).size===0)return!0;if(!t)return LDe("Optional content group not defined."),!0;if(t.type==="OCG")return ye(this,km).has(t.id)?ye(this,km).get(t.id).visible:(su(`Optional content group not found: ${t.id}`),!0);if(t.type==="OCMD"){if(t.expression)return cs(this,jre,HZe).call(this,t.expression);if(!t.policy||t.policy==="AnyOn"){for(const n of t.ids){if(!ye(this,km).has(n))return su(`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 su(`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 su(`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 su(`Optional content group not found: ${n}`),!0;if(ye(this,km).get(n).visible)return!1}return!0}return su(`Unknown optional content policy ${t.policy}.`),!0}return su(`Unknown group type ${t.type}.`),!0}setVisibility(t,n=!0,r=!0){var i;const a=ye(this,km).get(t);if(!a){su(`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(CU,!1,!0));a._setVisible(CU,!!n,!0),Kt(this,ZP,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}}Kt(this,ZP,null)}get hasInitialVisibility(){return ye(this,jH)===null||this.getHash()===ye(this,jH)}getOrder(){return ye(this,km).size?ye(this,NH)?ye(this,NH).slice():[...ye(this,km).keys()]:null}getGroups(){return ye(this,km).size>0?Cot(ye(this,km)):null}getGroup(t){return ye(this,km).get(t)||null}getHash(){if(ye(this,ZP)!==null)return ye(this,ZP);const t=new Hss;for(const[n,r]of ye(this,km))t.update(`${n}:${r.visible}`);return Kt(this,ZP,t.hexdigest())}}ZP=new WeakMap,km=new WeakMap,jH=new WeakMap,NH=new WeakMap,jre=new WeakSet,HZe=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)});w0(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(){w0(!this._fullRequestReader,"PDFDataTransportStream.getFullReader can only be called once.");const t=this._queuedChunks;return this._queuedChunks=null,new PYn(this,t,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(t,n){if(n<=this._progressiveDataLength)return null;const r=new IYn(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 PYn{constructor(t,n,r=!1,a=null){this._stream=t,this._done=r||!1,this._filename=Tot(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 IYn{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 LYn(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=DDe(h);h=m.decode(f),t=!1}catch{}}return h}function i(u){return t&&/[\x80-\xff]/.test(u)&&(u=a("utf-8",u),t&&(u=a("iso-8859-1",u))),u}function l(u){const h=[];let m;const f=r("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;(m=f.exec(u))!==null;){let[,x,y,v]=m;if(x=parseInt(x,10),x in h){if(x===0)break;continue}h[x]=[y,v]}const g=[];for(let x=0;x{if(!ans(i.status))throw zDe(i.status,a);this._reader=i.body.getReader(),this._headersCapability.resolve();const l=i.headers,{allowRangeRequests:o,suggestedLength:c}=Dot({responseHeaders:l,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=o,this._contentLength=c||this._contentLength,this._filename=Fot(l),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new h9("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:ons(t),done:!1})}cancel(t){var n;(n=this._reader)==null||n.cancel(t),this._abortController.abort()}}class DYn{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,ins(i,this._withCredentials,this._abortController)).then(o=>{if(!ans(o.status))throw zDe(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:ons(t),done:!1})}cancel(t){var n;(n=this._reader)==null||n.cancel(t),this._abortController.abort()}}const I$e=200,L$e=206;function FYn(s){const t=s.response;return typeof t!="string"?t:DDe(t).buffer}class OYn{constructor({url:t,httpHeaders:n,withCredentials:r}){this.url=t,this.isHttp=/^https?:/i.test(t),this.headers=Rot(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=L$e):a.expectedStatus=I$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||I$e;if(!(i===I$e&&r.expectedStatus===L$e)&&i!==r.expectedStatus){(d=r.onError)==null||d.call(r,a.status);return}const o=FYn(a);if(i===L$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 zYn{constructor(t){this._source=t,this._manager=new OYn(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 w0(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once."),this._fullRequestReader=new BYn(this._manager,this._source),this._fullRequestReader}getRangeReader(t,n){const r=new $Yn(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 BYn{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}=Dot({responseHeaders:r,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});a&&(this._isRangeSupported=!0),this._contentLength=i||this._contentLength,this._filename=Fot(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=zDe(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 $Yn{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=zDe(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 UYn=/^[a-z][a-z0-9\-+.]+:/i;function qYn(s){if(UYn.test(s))return new URL(s);const t=UL.get("url");return new URL(t.pathToFileURL(s))}function lns(s,t,n){return s.protocol==="http:"?UL.get("http").request(s,{headers:t},n):UL.get("https").request(s,{headers:t},n)}class VYn{constructor(t){this.source=t,this.url=qYn(t.url),this.isHttp=this.url.protocol==="http:"||this.url.protocol==="https:",this.isFsUrl=this.url.protocol==="file:",this.headers=Rot(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 w0(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once."),this._fullRequestReader=this.isFsUrl?new WYn(this):new HYn(this),this._fullRequestReader}getRangeReader(t,n){if(n<=this._progressiveDataLength)return null;const r=this.isFsUrl?new KYn(this,t,n):new GYn(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 cns{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 h9("streaming is disabled")),this._storedError&&this._readableStream.destroy(this._storedError)}}class dns{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 HYn extends cns{constructor(t){super(t);const n=Object.fromEntries(t.headers),r=a=>{if(a.statusCode===404){const c=new u9(`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}=Dot({responseHeaders:i,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=l,this._contentLength=o||this._contentLength,this._filename=Fot(i)};this._request=lns(this._url,n,r),this._request.on("error",a=>{this._storedError=a,this._headersCapability.reject(a)}),this._request.end()}}class GYn extends dns{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 u9(`Missing PDF "${this._url}".`);this._storedError=o;return}this._setReadableStream(l)};this._request=lns(this._url,a,i),this._request.on("error",l=>{this._storedError=l}),this._request.end()}}class WYn extends cns{constructor(t){super(t);const n=UL.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 u9(`Missing PDF "${this._url}".`)),this._storedError=r,this._headersCapability.reject(r)})}}class KYn extends dns{constructor(t,n,r){super(t);const a=UL.get("fs");this._setReadableStream(a.createReadStream(this._url,{start:n,end:r-1}))}}const YYn=1e5,ew=30,ZYn=.8;var SIt,XP,iw,Nre,kre,sz,WA,Sre,Cre,nz,kH,SH,QP,CH,Are,AH,rz,Ere,Tre,az,iz,Mre,JP,EH,wT,uns,hns,GZe,N2,q3e,WZe,mns,fns;const i0=class i0{constructor({textContentSource:t,container:n,viewport:r}){vs(this,wT);vs(this,XP,Promise.withResolvers());vs(this,iw,null);vs(this,Nre,!1);vs(this,kre,!!((SIt=globalThis.FontInspector)!=null&&SIt.enabled));vs(this,sz,null);vs(this,WA,null);vs(this,Sre,0);vs(this,Cre,0);vs(this,nz,null);vs(this,kH,null);vs(this,SH,0);vs(this,QP,0);vs(this,CH,Object.create(null));vs(this,Are,[]);vs(this,AH,null);vs(this,rz,[]);vs(this,Ere,new WeakMap);vs(this,Tre,null);var c;if(t instanceof ReadableStream)Kt(this,AH,t);else if(typeof t=="object")Kt(this,AH,new ReadableStream({start(d){d.enqueue(t),d.close()}}));else throw new Error('No "textContentSource" parameter specified.');Kt(this,iw,Kt(this,kH,n)),Kt(this,QP,r.scale*(globalThis.devicePixelRatio||1)),Kt(this,SH,r.rotation),Kt(this,WA,{div:null,properties:null,ctx:null});const{pageWidth:a,pageHeight:i,pageX:l,pageY:o}=r.rawDims;Kt(this,Tre,[1,0,0,-1,-l,o+i]),Kt(this,Cre,a),Kt(this,Sre,i),cs(c=i0,N2,mns).call(c),pB(n,r),ye(this,XP).promise.finally(()=>{ye(i0,EH).delete(this),Kt(this,WA,null),Kt(this,CH,null)}).catch(()=>{})}static get fontFamilyMap(){const{isWindows:t,isFirefox:n}=S_.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,nz).read().then(({value:n,done:r})=>{if(r){ye(this,XP).resolve();return}ye(this,sz)??Kt(this,sz,n.lang),Object.assign(ye(this,CH),n.styles),cs(this,wT,uns).call(this,n.items),t()},ye(this,XP).reject)};return Kt(this,nz,ye(this,AH).getReader()),ye(i0,EH).add(this),t(),ye(this,XP).promise}update({viewport:t,onBefore:n=null}){var i;const r=t.scale*(globalThis.devicePixelRatio||1),a=t.rotation;if(a!==ye(this,SH)&&(n==null||n(),Kt(this,SH,a),pB(ye(this,kH),{rotation:a})),r!==ye(this,QP)){n==null||n(),Kt(this,QP,r);const l={div:null,properties:null,ctx:cs(i=i0,N2,q3e).call(i,ye(this,sz))};for(const o of ye(this,rz))l.properties=ye(this,Ere).get(o),l.div=o,cs(this,wT,GZe).call(this,l)}}cancel(){var n;const t=new h9("TextLayer task cancelled.");(n=ye(this,nz))==null||n.cancel(t).catch(()=>{}),Kt(this,nz,null),ye(this,XP).reject(t)}get textDivs(){return ye(this,rz)}get textContentItemsStr(){return ye(this,Are)}static cleanup(){if(!(ye(this,EH).size>0)){ye(this,az).clear();for(const{canvas:t}of ye(this,iz).values())t.remove();ye(this,iz).clear()}}};XP=new WeakMap,iw=new WeakMap,Nre=new WeakMap,kre=new WeakMap,sz=new WeakMap,WA=new WeakMap,Sre=new WeakMap,Cre=new WeakMap,nz=new WeakMap,kH=new WeakMap,SH=new WeakMap,QP=new WeakMap,CH=new WeakMap,Are=new WeakMap,AH=new WeakMap,rz=new WeakMap,Ere=new WeakMap,Tre=new WeakMap,az=new WeakMap,iz=new WeakMap,Mre=new WeakMap,JP=new WeakMap,EH=new WeakMap,wT=new WeakSet,uns=function(t){var a,i;if(ye(this,Nre))return;(i=ye(this,WA)).ctx??(i.ctx=cs(a=i0,N2,q3e).call(a,ye(this,sz)));const n=ye(this,rz),r=ye(this,Are);for(const l of t){if(n.length>YYn){su("Ignoring additional textDivs for performance reasons."),Kt(this,Nre,!0);return}if(l.str===void 0){if(l.type==="beginMarkedContentProps"||l.type==="beginMarkedContent"){const o=ye(this,iw);Kt(this,iw,document.createElement("span")),ye(this,iw).classList.add("markedContent"),l.id!==null&&ye(this,iw).setAttribute("id",`${l.id}`),o.append(ye(this,iw))}else l.type==="endMarkedContent"&&Kt(this,iw,ye(this,iw).parentNode);continue}r.push(l.str),cs(this,wT,hns).call(this,l)}},hns=function(t){var x;const n=document.createElement("span"),r={angle:0,canvasWidth:0,hasText:t.str!=="",hasEOL:t.hasEOL,fontSize:0};ye(this,rz).push(n);const a=ol.transform(ye(this,Tre),t.transform);let i=Math.atan2(a[1],a[0]);const l=ye(this,CH)[t.fontName];l.vertical&&(i+=Math.PI/2);let o=ye(this,kre)&&l.fontSubstitution||l.fontFamily;o=i0.fontFamilyMap.get(o)||o;const c=Math.hypot(a[2],a[3]),d=c*cs(x=i0,N2,fns).call(x,o,ye(this,sz));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,iw)===ye(this,kH)?(f.left=`${(100*u/ye(this,Cre)).toFixed(2)}%`,f.top=`${(100*h/ye(this,Sre)).toFixed(2)}%`):(f.left=`${m}${u.toFixed(2)}px)`,f.top=`${m}${h.toFixed(2)}px)`),f.fontSize=`${m}${(ye(i0,JP)*c).toFixed(2)}px)`,f.fontFamily=o,r.fontSize=c,n.setAttribute("role","presentation"),n.textContent=t.str,n.dir=t.dir,ye(this,kre)&&(n.dataset.fontName=l.fontSubstitutionLoadedName||t.fontName),i!==0&&(r.angle=i*(180/Math.PI));let g=!1;if(t.str.length>1)g=!0;else if(t.str!==" "&&t.transform[0]!==t.transform[3]){const y=Math.abs(t.transform[0]),v=Math.abs(t.transform[3]);y!==v&&Math.max(y,v)/Math.min(y,v)>1.5&&(g=!0)}if(g&&(r.canvasWidth=l.vertical?t.height:t.width),ye(this,Ere).set(n,r),ye(this,WA).div=n,ye(this,WA).properties=r,cs(this,wT,GZe).call(this,ye(this,WA)),r.hasText&&ye(this,iw).append(n),r.hasEOL){const y=document.createElement("br");y.setAttribute("role","presentation"),ye(this,iw).append(y)}},GZe=function(t){var o;const{div:n,properties:r,ctx:a}=t,{style:i}=n;let l="";if(ye(i0,JP)>1&&(l=`scale(${1/ye(i0,JP)})`),r.canvasWidth!==0&&r.hasText){const{fontFamily:c}=i,{canvasWidth:d,fontSize:u}=r;cs(o=i0,N2,WZe).call(o,a,u*ye(this,QP),c);const{width:h}=a.measureText(n.textContent);h>0&&(l=`scaleX(${d*ye(this,QP)/h}) ${l}`)}r.angle!==0&&(l=`rotate(${r.angle}deg) ${l}`),l.length>0&&(i.transform=l)},N2=new WeakSet,q3e=function(t=null){let n=ye(this,iz).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,iz).set(t,n),ye(this,Mre).set(n,{size:0,family:""})}return n},WZe=function(t,n,r){const a=ye(this,Mre).get(t);n===a.size&&r===a.family||(t.font=`${n}px ${r}`,a.size=n,a.family=r)},mns=function(){if(ye(this,JP)!==null)return;const t=document.createElement("div");t.style.opacity=0,t.style.lineHeight=1,t.style.fontSize="1px",t.style.position="absolute",t.textContent="X",document.body.append(t),Kt(this,JP,t.getBoundingClientRect().height),t.remove()},fns=function(t,n){const r=ye(this,az).get(t);if(r)return r;const a=cs(this,N2,q3e).call(this,n);a.canvas.width=a.canvas.height=ew,cs(this,N2,WZe).call(this,a,ew,t);const i=a.measureText("");let l=i.fontBoundingBoxAscent,o=Math.abs(i.fontBoundingBoxDescent);if(l){const u=l/(l+o);return ye(this,az).set(t,u),a.canvas.width=a.canvas.height=0,u}a.strokeStyle="red",a.clearRect(0,0,ew,ew),a.strokeText("g",0,0);let c=a.getImageData(0,0,ew,ew).data;o=0;for(let u=c.length-1-3;u>=0;u-=4)if(c[u]>0){o=Math.ceil(u/4/ew);break}a.clearRect(0,0,ew,ew),a.strokeText("A",0,ew),c=a.getImageData(0,0,ew,ew).data,l=0;for(let u=0,h=c.length;u0){l=ew-Math.floor(u/4/ew);break}a.canvas.width=a.canvas.height=0;const d=l?l/(l+o):ZYn;return ye(this,az).set(t,d),d},vs(i0,N2),vs(i0,az,new Map),vs(i0,iz,new Map),vs(i0,Mre,new WeakMap),vs(i0,JP,null),vs(i0,EH,new Set);let xne=i0;class yne{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(yne.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 XYn=65536,QYn=100,JYn=5e3,eZn=p1?hYn:cYn,tZn=p1?mYn:Zss,sZn=p1?uYn:dYn,nZn=p1?fYn:ens;function rZn(s={}){typeof s=="string"||s instanceof URL?s={url:s}:(s instanceof ArrayBuffer||ArrayBuffer.isView(s))&&(s={data:s});const t=new KZe,{docId:n}=t,r=s.url?aZn(s.url):null,a=s.data?iZn(s.data):null,i=s.httpHeaders||null,l=s.withCredentials===!0,o=s.password??null,c=s.range instanceof pns?s.range:null,d=Number.isInteger(s.rangeChunkSize)&&s.rangeChunkSize>0?s.rangeChunkSize:XYn;let u=s.worker instanceof BV?s.worker:null;const h=s.verbosity,m=typeof s.docBaseUrl=="string"&&!ODe(s.docBaseUrl)?s.docBaseUrl:null,f=typeof s.cMapUrl=="string"?s.cMapUrl:null,g=s.cMapPacked!==!1,x=s.CMapReaderFactory||tZn,y=typeof s.standardFontDataUrl=="string"?s.standardFontDataUrl:null,v=s.StandardFontDataFactory||nZn,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:!p1,E=typeof s.isChrome=="boolean"?s.isChrome:!S_.platform.isFirefox&&typeof window<"u"&&!!(window!=null&&window.chrome),I=Number.isInteger(s.canvasMaxAreaInBytes)?s.canvasMaxAreaInBytes:-1,P=typeof s.disableFontFace=="boolean"?s.disableFontFace:p1,R=s.fontExtraProperties===!0,D=s.enableXfa===!0,O=s.ownerDocument||globalThis.document,U=s.disableRange===!0,W=s.disableStream===!0,V=s.disableAutoFetch===!0,G=s.pdfBug===!0,Y=s.CanvasFactory||eZn,X=s.FilterFactory||sZn,ae=s.enableHWA===!0,le=c?c.length:s.length??NaN,ne=typeof s.useSystemFonts=="boolean"?s.useSystemFonts:!p1&&!P,te=typeof s.useWorkerFetch=="boolean"?s.useWorkerFetch:x===Zss&&v===ens&&f&&y&&NQ(f,document.baseURI)&&NQ(y,document.baseURI);s.canvasFactory&&J4t("`canvasFactory`-instance option, please use `CanvasFactory` instead."),s.filterFactory&&J4t("`filterFactory`-instance option, please use `FilterFactory` instead.");const J=null;BKn(h);const ce={canvasFactory:new Y({ownerDocument:O,enableHWA:ae}),filterFactory:new X({docId:n,ownerDocument:O}),cMapReaderFactory:te?null:new x({baseUrl:f,isCompressed:g}),standardFontDataFactory:te?null:new v({baseUrl:y})};if(!u){const ue={verbosity:h,port:mE.workerPort};u=ue.port?BV.fromPort(ue):new BV(ue),t._worker=u}const _e={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:ne,cMapUrl:te?f:null,standardFontDataUrl:te?y:null}},he={disableFontFace:P,fontExtraProperties:R,ownerDocument:O,pdfBug:G,styleElement:J,loadingParams:{disableAutoFetch:V,enableXfa:D}};return u.promise.then(function(){if(t.destroyed)throw new Error("Loading aborted");if(u.destroyed)throw new Error("Worker was destroyed");const ue=u.messageHandler.sendWithPromise("GetDocRequest",_e,a?[a.buffer]:null);let ve;if(c)ve=new MYn(c,{disableRange:U,disableStream:W});else if(!a){if(!r)throw new Error("getDocument - no `url` parameter provided.");let Ee;p1?Ee=typeof fetch<"u"&&typeof Response<"u"&&"body"in Response.prototype&&NQ(r)?u3t:VYn:Ee=NQ(r)?u3t:zYn,ve=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 Se=new MQ(n,Ee,u.port),Le=new dZn(Se,t,ve,he,ce);t._transport=Le,Se.send("Ready",null)})}).catch(t._capability.reject),t}function aZn(s){if(s instanceof URL)return s.href;try{return new URL(s,window.location).href}catch{if(p1&&typeof s=="string")return s}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}function iZn(s){if(p1&&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 DDe(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 h3t(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 fIe;const pIe=class pIe{constructor(){this._capability=Promise.withResolvers(),this._transport=null,this._worker=null,this.docId=`d${X0(pIe,fIe)._++}`,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)}};fIe=new WeakMap,vs(pIe,fIe,0);let KZe=pIe;class pns{constructor(t,n,r=!1,a=null){this.length=t,this.initialData=n,this.progressiveDone=r,this.contentDispositionFilename=a,this._rangeListeners=[],this._progressListeners=[],this._progressiveReadListeners=[],this._progressiveDoneListeners=[],this._readyCapability=Promise.withResolvers()}addRangeListener(t){this._rangeListeners.push(t)}addProgressListener(t){this._progressListeners.push(t)}addProgressiveReadListener(t){this._progressiveReadListeners.push(t)}addProgressiveDoneListener(t){this._progressiveDoneListeners.push(t)}onDataRange(t,n){for(const r of this._rangeListeners)r(t,n)}onDataProgress(t,n){this._readyCapability.promise.then(()=>{for(const r of this._progressListeners)r(t,n)})}onDataProgressiveRead(t){this._readyCapability.promise.then(()=>{for(const n of this._progressiveReadListeners)n(t)})}onDataProgressiveDone(){this._readyCapability.promise.then(()=>{for(const t of this._progressiveDoneListeners)t()})}transportReady(){this._readyCapability.resolve()}requestDataRange(t,n){kp("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class oZn{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 eI,KA,zN,AU,V3e;class lZn{constructor(t,n,r,a=!1){vs(this,zN);vs(this,eI,null);vs(this,KA,!1);this._pageIndex=t,this._pageInfo=n,this._transport=r,this._stats=a?new Q4t:null,this._pdfBug=a,this.commonObjs=r.commonObjs,this.objs=new gns,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 Gie({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=EP.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;Kt(this,KA,!1),cs(this,zN,V3e).call(this),o||(o=this._transport.getOptionalContentConfig(f));let x=this._intentStates.get(g);x||(x=Object.create(null),this._intentStates.set(g,x)),x.streamReaderCancelTimeout&&(clearTimeout(x.streamReaderCancelTimeout),x.streamReaderCancelTimeout=null);const y=!!(f&Oj.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 v=E=>{var I;x.renderTasks.delete(b),(this._maybeCleanupAfterRender||y)&&Kt(this,KA,!0),cs(this,zN,AU).call(this,!y),E?(b.capability.reject(E),this._abortOperatorList({intentState:x,reason:E instanceof Error?E:new Error(E)})):b.capability.resolve(),this._stats&&(this._stats.timeEnd("Rendering"),this._stats.timeEnd("Overall"),(I=globalThis.Stats)!=null&&I.enabled&&globalThis.Stats.add(this.pageNumber,this._stats))},b=new ZZe({callback:v,params:{canvasContext:t,viewport:n,transform:i,background:l},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:c,operatorList:x.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!y,pdfBug:this._pdfBug,pageColors:d});(x.renderTasks||(x.renderTasks=new Set)).add(b);const w=b.task;return Promise.all([x.displayReadyCapability.promise,o]).then(([E,I])=>{var P;if(this.destroyed){v();return}if((P=this._stats)==null||P.time("Rendering"),!(I.renderingIntent&f))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");b.initializeGraphics({transparency:E,optionalContentConfig:I}),b.operatorListChanged()}).catch(v),w}getOperatorList({intent:t="display",annotationMode:n=EP.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=>yne.textContent(r));const n=this.streamTextContent(t);return new Promise(function(r,a){function i(){l.read().then(function({value:c,done:d}){if(d){r(o);return}o.lang??(o.lang=c.lang),Object.assign(o.styles,c.styles),o.items.push(...c.items),i()},a)}const l=n.getReader(),o={items:[],styles:Object.create(null),lang:null};i()})}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;const t=[];for(const n of this._intentStates.values())if(this._abortOperatorList({intentState:n,reason:new Error("Page was destroyed."),force:!0}),!n.opListReadCapability)for(const r of n.renderTasks)t.push(r.completed),r.cancel();return this.objs.clear(),Kt(this,KA,!1),cs(this,zN,V3e).call(this),Promise.all(t)}cleanup(t=!1){Kt(this,KA,!0);const n=cs(this,zN,AU).call(this,!1);return t&&n&&this._stats&&(this._stats=new Q4t),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();cs(this,zN,AU).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 Eot){let a=QYn;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 h9(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}}eI=new WeakMap,KA=new WeakMap,zN=new WeakSet,AU=function(t=!1){if(cs(this,zN,V3e).call(this),!ye(this,KA)||this.destroyed)return!1;if(t)return Kt(this,eI,setTimeout(()=>{Kt(this,eI,null),cs(this,zN,AU).call(this,!1)},JYn)),!1;for(const{renderTasks:n,operatorList:r}of this._intentStates.values())if(n.size>0||!r.lastChunk)return!1;return this._intentStates.clear(),this.objs.clear(),Kt(this,KA,!1),!0},V3e=function(){ye(this,eI)&&(clearTimeout(ye(this,eI)),Kt(this,eI,null))};var YA,gIe;class cZn{constructor(){vs(this,YA,new Map);vs(this,gIe,Promise.resolve())}postMessage(t,n){const r={data:structuredClone(t,n?{transfer:n}:null)};ye(this,gIe).then(()=>{for(const[a]of ye(this,YA))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){su("LoopbackPort - cannot use an `aborted` signal.");return}const l=()=>this.removeEventListener(t,n);a=()=>i.removeEventListener("abort",l),i.addEventListener("abort",l)}ye(this,YA).set(n,a)}removeEventListener(t,n){const r=ye(this,YA).get(n);r==null||r(),ye(this,YA).delete(n)}terminate(){for(const[,t]of ye(this,YA))t==null||t();ye(this,YA).clear()}}YA=new WeakMap,gIe=new WeakMap;var xIe,oz,lz,TH,H3e,MH,G3e;const Bp=class Bp{constructor({name:t=null,port:n=null,verbosity:r=$Kn()}={}){vs(this,TH);var a;if(this.name=t,this.destroyed=!1,this.verbosity=r,this._readyCapability=Promise.withResolvers(),this._port=null,this._webWorker=null,this._messageHandler=null,n){if((a=ye(Bp,lz))!=null&&a.has(n))throw new Error("Cannot use more than one PDFWorker per port.");(ye(Bp,lz)||Kt(Bp,lz,new WeakMap)).set(n,this),this._initializeFromPort(n);return}this._initialize()}get promise(){return p1?Promise.all([UL.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 MQ("main","worker",t),this._messageHandler.on("ready",function(){}),cs(this,TH,H3e).call(this)}_initialize(){if(ye(Bp,oz)||ye(Bp,MH,G3e)){this._setupFakeWorker();return}let{workerSrc:t}=Bp;try{Bp._isSameOrigin(window.location.href,t)||(t=Bp._createCDNWrapper(new URL(t,window.location).href));const n=new Worker(t,{type:"module"}),r=new MQ("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,cs(this,TH,H3e).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{LDe("The worker has been disabled.")}this._setupFakeWorker()}_setupFakeWorker(){ye(Bp,oz)||(su("Setting up fake worker."),Kt(Bp,oz,!0)),Bp._setupFakeWorkerGlobal.then(t=>{if(this.destroyed){this._readyCapability.reject(new Error("Worker was destroyed"));return}const n=new cZn;this._port=n;const r=`fake${X0(Bp,xIe)._++}`,a=new MQ(r+"_worker",r,n);t.setup(a,n),this._messageHandler=new MQ(r,r+"_worker",n),cs(this,TH,H3e).call(this)}).catch(t=>{this._readyCapability.reject(new Error(`Setting up fake worker failed: "${t.message}".`))})}destroy(){var t;this.destroyed=!0,this._webWorker&&(this._webWorker.terminate(),this._webWorker=null),(t=ye(Bp,lz))==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,lz))==null?void 0:r.get(t.port);if(n){if(n._pendingDestroy)throw new Error("PDFWorker.fromPort - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return n}return new Bp(t)}static get workerSrc(){if(mE.workerSrc)return mE.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get _setupFakeWorkerGlobal(){return eh(this,"_setupFakeWorkerGlobal",(async()=>ye(this,MH,G3e)?ye(this,MH,G3e):(await import(this.workerSrc)).WorkerMessageHandler)())}};xIe=new WeakMap,oz=new WeakMap,lz=new WeakMap,TH=new WeakSet,H3e=function(){this._readyCapability.resolve(),this._messageHandler.send("configure",{verbosity:this.verbosity})},MH=new WeakSet,G3e=function(){var t;try{return((t=globalThis.pdfjsWorker)==null?void 0:t.WorkerMessageHandler)||null}catch{return null}},vs(Bp,MH),vs(Bp,xIe,0),vs(Bp,oz,!1),vs(Bp,lz),p1&&(Kt(Bp,oz,!0),mE.workerSrc||(mE.workerSrc="./pdf.worker.mjs")),Bp._isSameOrigin=(t,n)=>{let r;try{if(r=new URL(t),!r.origin||r.origin==="null")return!1}catch{return!1}const a=new URL(n,r);return r.origin===a.origin},Bp._createCDNWrapper=t=>{const n=`await import("${t}");`;return URL.createObjectURL(new Blob([n],{type:"text/javascript"}))};let BV=Bp;var ZA,G5,PH,IH,W5,cz,PQ;class dZn{constructor(t,n,r,a,i){vs(this,cz);vs(this,ZA,new Map);vs(this,G5,new Map);vs(this,PH,new Map);vs(this,IH,new Map);vs(this,W5,null);this.messageHandler=t,this.loadingTask=n,this.commonObjs=new gns,this.fontLoader=new oYn({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 Iot)}getRenderingIntent(t,n=EP.ENABLE,r=null,a=!1,i=!1){let l=Oj.DISPLAY,o=FZe;switch(t){case"any":l=Oj.ANY;break;case"display":break;case"print":l=Oj.PRINT;break;default:su(`getRenderingIntent - invalid intent: ${t}`)}const c=l&Oj.PRINT&&r instanceof Wss?r:this.annotationStorage;switch(n){case EP.DISABLE:l+=Oj.ANNOTATIONS_DISABLE;break;case EP.ENABLE:break;case EP.ENABLE_FORMS:l+=Oj.ANNOTATIONS_FORMS;break;case EP.ENABLE_STORAGE:l+=Oj.ANNOTATIONS_STORAGE,o=c.serializable;break;default:su(`getRenderingIntent - invalid annotationMode: ${n}`)}a&&(l+=Oj.IS_EDITING),i&&(l+=Oj.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,W5))==null||r.reject(new Error("Worker was destroyed during onPassword callback"));const t=[];for(const a of ye(this,G5).values())t.push(a._destroy());ye(this,G5).clear(),ye(this,PH).clear(),ye(this,IH).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,ZA).clear(),this.filterFactory.destroy(),xne.cleanup(),(a=this._networkStream)==null||a.cancelAllRequests(new h9("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)=>{w0(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}w0(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)=>{w0(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}w0(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 oZn(r,this))}),t.on("DocException",function(r){let a;switch(r.name){case"PasswordException":a=new pZe(r.message,r.code);break;case"InvalidPDFException":a=new vss(r.message);break;case"MissingPDFException":a=new u9(r.message);break;case"UnexpectedResponseException":a=new RDe(r.message,r.status);break;case"UnknownErrorException":a=new gZe(r.message,r.details);break;default:kp("DocException - expected a valid Error.")}n._capability.reject(a)}),t.on("PasswordRequest",r=>{if(Kt(this,W5,Promise.withResolvers()),n.onPassword){const a=i=>{i instanceof Error?ye(this,W5).reject(i):ye(this,W5).resolve({password:i})};try{n.onPassword(a,r.code)}catch(i){ye(this,W5).reject(i)}}else ye(this,W5).reject(new pZe(r.message,r.code));return ye(this,W5).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,G5).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;su(`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 lYn(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;w0(m,"The imageRef must be defined.");for(const f of ye(this,G5).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,G5).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)>DKn&&(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&&su("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,PH).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,IH).set(i.refStr,t);const l=new lZn(n,i,this,this._params.pdfBug);return ye(this,G5).set(n,l),l});return ye(this,PH).set(n,a),a}getPageIndex(t){return h3t(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 cs(this,cz,PQ).call(this,"GetFieldObjects")}hasJSActions(){return cs(this,cz,PQ).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 cs(this,cz,PQ).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 cs(this,cz,PQ).call(this,"GetOptionalContentConfig").then(n=>new TYn(n,t))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const t="GetMetadata",n=ye(this,ZA).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 AYn(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,ZA).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,G5).values())if(!n.cleanup())throw new Error(`startCleanup: Page ${n.pageNumber} is currently rendering.`);this.commonObjs.clear(),t||this.fontLoader.clear(),ye(this,ZA).clear(),this.filterFactory.destroy(!0),xne.cleanup()}}cachedPageNumber(t){if(!h3t(t))return null;const n=t.gen===0?`${t.num}R`:`${t.num}R${t.gen}`;return ye(this,IH).get(n)??null}}ZA=new WeakMap,G5=new WeakMap,PH=new WeakMap,IH=new WeakMap,W5=new WeakMap,cz=new WeakSet,PQ=function(t,n=null){const r=ye(this,ZA).get(t);if(r)return r;const a=this.messageHandler.sendWithPromise(t,n);return ye(this,ZA).set(t,a),a};const Mue=Symbol("INITIAL_DATA");var jS,Pre,YZe;class gns{constructor(){vs(this,Pre);vs(this,jS,Object.create(null))}get(t,n=null){if(n){const a=cs(this,Pre,YZe).call(this,t);return a.promise.then(()=>n(a.data)),null}const r=ye(this,jS)[t];if(!r||r.data===Mue)throw new Error(`Requesting object that isn't resolved yet ${t}.`);return r.data}has(t){const n=ye(this,jS)[t];return!!n&&n.data!==Mue}resolve(t,n=null){const r=cs(this,Pre,YZe).call(this,t);r.data=n,r.resolve()}clear(){var t;for(const n in ye(this,jS)){const{data:r}=ye(this,jS)[n];(t=r==null?void 0:r.bitmap)==null||t.close()}Kt(this,jS,Object.create(null))}*[Symbol.iterator](){for(const t in ye(this,jS)){const{data:n}=ye(this,jS)[t];n!==Mue&&(yield[t,n])}}}jS=new WeakMap,Pre=new WeakSet,YZe=function(t){var n;return(n=ye(this,jS))[t]||(n[t]={...Promise.withResolvers(),data:Mue})};var tI;class uZn{constructor(t){vs(this,tI,null);Kt(this,tI,t),this.onContinue=null}get promise(){return ye(this,tI).capability.promise}cancel(t=0){ye(this,tI).cancel(null,t)}get separateAnnots(){const{separateAnnots:t}=ye(this,tI).operatorList;if(!t)return!1;const{annotationCanvasMap:n}=ye(this,tI);return t.form||t.canvas&&(n==null?void 0:n.size)>0}}tI=new WeakMap;var sI,dz;const e8=class e8{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}){vs(this,sI,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 uZn(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(e8,dz).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(e8,dz).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 zV(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,sI)&&(window.cancelAnimationFrame(ye(this,sI)),Kt(this,sI,null)),ye(e8,dz).delete(this._canvas),this.callback(t||new Eot(`Rendering cancelled, page ${this._pageIndex+1}`,n))}operatorListChanged(){var t;if(!this.graphicsReady){this.graphicsReadyCallback||(this.graphicsReadyCallback=this._continueBound);return}(t=this.stepper)==null||t.updateOperatorList(this.operatorList),!this.running&&this._continue()}_continue(){this.running=!0,!this.cancelled&&(this.task.onContinue?this.task.onContinue(this._scheduleNextBound):this._scheduleNext())}_scheduleNext(){this._useRequestAnimationFrame?Kt(this,sI,window.requestAnimationFrame(()=>{Kt(this,sI,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(e8,dz).delete(this._canvas),this.callback())))}};sI=new WeakMap,dz=new WeakMap,vs(e8,dz,new WeakSet);let ZZe=e8;const hZn="4.8.69",mZn="3634dab10";function m3t(s){return Math.floor(Math.max(0,Math.min(1,s))*255).toString(16).padStart(2,"0")}function uX(s){return Math.max(0,Math.min(255,255*s))}class f3t{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=uX(t),[t,t,t]}static G_HTML([t]){const n=m3t(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(uX)}static RGB_HTML(t){return`#${t.map(m3t).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[uX(1-Math.min(1,t+a)),uX(1-Math.min(1,r+a)),uX(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 fZn{create(t,n,r=!1){if(t<=0||n<=0)throw new Error("Invalid SVG dimensions");const a=this._createSVG("svg:svg");return a.setAttribute("version","1.1"),r||(a.setAttribute("width",`${t}px`),a.setAttribute("height",`${n}px`)),a.setAttribute("preserveAspectRatio","none"),a.setAttribute("viewBox",`0 0 ${t} ${n}`),a}createElement(t){if(typeof t!="string")throw new Error("Invalid SVG element type");return this._createSVG(t)}_createSVG(t){kp("Abstract method `_createSVG` called.")}}class Oot extends fZn{_createSVG(t){return document.createElementNS(_A,t)}}class xns{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&&yne.shouldBuildText(a.name)&&d.push(f)}return{textDivs:d}}const u=[[a,-1,l]];for(;u.length>0;){const[f,g,x]=u.at(-1);if(g+1===f.children.length){u.pop();continue}const y=f.children[++u.at(-1)[1]];if(y===null)continue;const{name:v}=y;if(v==="#text"){const w=document.createTextNode(y.value);d.push(w),x.append(w);continue}const b=(h=y==null?void 0:y.attributes)!=null&&h.xmlns?document.createElementNS(y.attributes.xmlns,v):document.createElement(v);if(x.append(b),y.attributes&&this.setAttributes({html:b,element:y,storage:n,intent:i,linkService:r}),((m=y.children)==null?void 0:m.length)>0)u.push([y,-1,b]);else if(y.value){const w=document.createTextNode(y.value);o&&yne.shouldBuildText(v)&&d.push(w),b.append(w)}}for(const f of c.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))f.setAttribute("readOnly",!0);return{textDivs:d}}static update(t){const n=`matrix(${t.viewport.transform.join(",")})`;t.div.style.transform=n,t.div.hidden=!1}}const Kie=1e3,pZn=9,xB=new WeakSet;function GE(s){return{width:s[2]-s[0],height:s[3]-s[1]}}class gZn{static create(t){switch(t.data.annotationType){case a0.LINK:return new yns(t);case a0.TEXT:return new xZn(t);case a0.WIDGET:switch(t.data.fieldType){case"Tx":return new yZn(t);case"Btn":return t.data.radioButton?new _ns(t):t.data.checkBox?new bZn(t):new _Zn(t);case"Ch":return new wZn(t);case"Sig":return new vZn(t)}return new m9(t);case a0.POPUP:return new QZe(t);case a0.FREETEXT:return new Sns(t);case a0.LINE:return new NZn(t);case a0.SQUARE:return new kZn(t);case a0.CIRCLE:return new SZn(t);case a0.POLYLINE:return new Cns(t);case a0.CARET:return new AZn(t);case a0.INK:return new zot(t);case a0.POLYGON:return new CZn(t);case a0.HIGHLIGHT:return new Ans(t);case a0.UNDERLINE:return new EZn(t);case a0.SQUIGGLY:return new TZn(t);case a0.STRIKEOUT:return new MZn(t);case a0.STAMP:return new Ens(t);case a0.FILEATTACHMENT:return new PZn(t);default:return new fy(t)}}}var uz,LH,RH,Ire,XZe;const edt=class edt{constructor(t,{isRenderable:n=!1,ignoreBorder:r=!1,createQuadrilaterals:a=!1}={}){vs(this,Ire);vs(this,uz,null);vs(this,LH,!1);vs(this,RH,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 edt._hasPopupData(this.data)}updateEdited(t){var r;if(!this.container)return;ye(this,uz)||Kt(this,uz,{rect:this.data.rect.slice(0)});const{rect:n}=t;n&&cs(this,Ire,XZe).call(this,n),(r=ye(this,RH))==null||r.popup.updateEdited(t)}resetEdited(){var t;ye(this,uz)&&(cs(this,Ire,XZe).call(this,ye(this,uz).rect),(t=ye(this,RH))==null||t.popup.resetEdited(),Kt(this,uz,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 m9||(i.tabIndex=Kie);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 QZe){const{rotation:x}=n;return!n.hasOwnCanvas&&x!==0&&this.setRotation(x,i),i}const{width:o,height:c}=GE(n.rect);if(!t&&n.borderStyle.width>0){l.borderWidth=`${n.borderStyle.width}px`;const x=n.borderStyle.horizontalCornerRadius,y=n.borderStyle.verticalCornerRadius;if(x>0||y>0){const b=`calc(${x}px * var(--scale-factor)) / calc(${y}px * var(--scale-factor))`;l.borderRadius=b}else if(this instanceof _ns){const b=`calc(${o}px * var(--scale-factor)) / calc(${c}px * var(--scale-factor))`;l.borderRadius=b}switch(n.borderStyle.style){case cX.SOLID:l.borderStyle="solid";break;case cX.DASHED:l.borderStyle="dashed";break;case cX.BEVELED:su("Unimplemented border style: beveled");break;case cX.INSET:su("Unimplemented border style: inset");break;case cX.UNDERLINE:l.borderBottomStyle="solid";break}const v=n.borderColor||null;v?(Kt(this,LH,!0),l.borderColor=ol.makeHexColor(v[0]|0,v[1]|0,v[2]|0)):l.borderWidth=0}const d=ol.normalizeRect([n.rect[0],r.view[3]-n.rect[1]+r.view[1],n.rect[2],r.view[3]-n.rect[3]+r.view[1]]),{pageWidth:u,pageHeight:h,pageX:m,pageY:f}=a.rawDims;l.left=`${100*(d[0]-m)/u}%`,l.top=`${100*(d[1]-f)/h}%`;const{rotation:g}=n;return n.hasOwnCanvas||g===0?(l.width=`${100*o/u}%`,l.height=`${100*c/h}%`):this.setRotation(g,i),i}setRotation(t,n=this.container){if(!this.data.rect)return;const{pageWidth:r,pageHeight:a}=this.parent.viewport.rawDims,{width:i,height:l}=GE(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]=f3t[`${l}_HTML`](o),this.annotationStorage.setValue(this.data.id,{[r]:f3t[`${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,y,v,b]=t.subarray(2,6);if(a===x&&i===y&&n===v&&r===b)return}const{style:l}=this.container;let o;if(ye(this,LH)){const{borderColor:x,borderWidth:y}=l;l.borderWidth=0,o=["url('data:image/svg+xml;utf8,",'',``],this.container.classList.add("hasBorder")}const c=a-n,d=i-r,{svgFactory:u}=this,h=u.createElement("svg");h.classList.add("quadrilateralsContainer"),h.setAttribute("width",0),h.setAttribute("height",0);const m=u.createElement("defs");h.append(m);const f=u.createElement("clipPath"),g=`clippath_${this.data.id}`;f.setAttribute("id",g),f.setAttribute("clipPathUnits","objectBoundingBox"),m.append(f);for(let x=2,y=t.length;x`)}ye(this,LH)&&(o.push("')"),l.backgroundImage=o.join("")),this.container.append(h),this.container.style.clipPath=`url(#${g})`}_createPopup(){const{data:t}=this,n=Kt(this,RH,new QZe({data:{color:t.color,titleObj:t.titleObj,modificationDate:t.modificationDate,contentsObj:t.contentsObj,richText:t.richText,parentRect:t.rect,borderStyle:0,id:`popup_${t.id}`,rotation:t.rotation},parent:this.parent,elements:[this]}));this.parent.div.append(n.render())}render(){kp("Abstract method `AnnotationElement.render` called")}_getElementsByName(t,n=null){const r=[];if(this._fieldObjects){const a=this._fieldObjects[t];if(a)for(const{page:i,id:l,exportValues:o}of a){if(i===-1||l===n)continue;const c=typeof o=="string"?o:null,d=document.querySelector(`[data-element-id="${l}"]`);if(d&&!xB.has(d)){su(`_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&&xB.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})})}};uz=new WeakMap,LH=new WeakMap,RH=new WeakMap,Ire=new WeakSet,XZe=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}=GE(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 fy=edt;var Hj,BO,vns,bns;class yns extends fy{constructor(n,r=null){super(n,{isRenderable:!0,ignoreBorder:!!(r!=null&&r.ignoreBorder),createQuadrilaterals:!0});vs(this,Hj);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?(cs(this,Hj,vns).call(this,a,n.attachment,n.attachmentDest),i=!0):n.setOCGState?(cs(this,Hj,bns).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==="")&&cs(this,Hj,BO).call(this)}_bindNamedAction(n,r){n.href=this.linkService.getAnchorUrl(""),n.onclick=()=>(this.linkService.executeNamedAction(r),!1),cs(this,Hj,BO).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),cs(this,Hj,BO).call(this)}_bindResetFormAction(n,r){const a=n.onclick;if(a||(n.href=this.linkService.getAnchorUrl("")),cs(this,Hj,BO).call(this),!this._fieldObjects){su('_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(!xB.has(g)){su(`_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}}}Hj=new WeakSet,BO=function(){this.container.setAttribute("data-internal-link","")},vns=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},cs(this,Hj,BO).call(this)},bns=function(n,r){n.href=this.linkService.getAnchorUrl(""),n.onclick=()=>(this.linkService.executeSetOCGState(r),!1),cs(this,Hj,BO).call(this)};class xZn extends fy{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 m9 extends fy{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 S_.platform.isMac?t.metaKey:t.ctrlKey}_setEventListener(t,n,r,a,i){r.includes("mouse")?t.addEventListener(r,l=>{var o;(o=this.linkService.eventBus)==null||o.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:a,value:i(l),shift:l.shiftKey,modifier:this._getKeyModifier(l)}})}):t.addEventListener(r,l=>{var o;if(r==="blur"){if(!n.focused||!l.relatedTarget)return;n.focused=!1}else if(r==="focus"){if(n.focused)return;n.focused=!0}i&&((o=this.linkService.eventBus)==null||o.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:a,value:i(l)}}))})}_setEventListeners(t,n,r,a){var i,l,o;for(const[c,d]of r)(d==="Action"||(i=this.data.actions)!=null&&i[d])&&((d==="Focus"||d==="Blur")&&(n||(n={focused:!1})),this._setEventListener(t,n,c,d,a),d==="Focus"&&!((l=this.data.actions)!=null&&l.Blur)?this._setEventListener(t,n,"blur","Blur",null):d==="Blur"&&!((o=this.data.actions)!=null&&o.Focus)&&this._setEventListener(t,n,"focus","Focus",null))}_setBackgroundColor(t){const n=this.data.backgroundColor||null;t.style.backgroundColor=n===null?"transparent":ol.makeHexColor(n[0],n[1],n[2])}_setTextStyle(t){const n=["left","center","right"],{fontColor:r}=this.data.defaultAppearanceData,a=this.data.defaultAppearanceData.fontSize||pZn,i=t.style;let l;const o=2,c=d=>Math.round(10*d)/10;if(this.data.multiLine){const d=Math.abs(this.data.rect[3]-this.data.rect[1]-o),u=Math.round(d/(E$e*a))||1,h=d/u;l=Math.min(a,c(h/E$e))}else{const d=Math.abs(this.data.rect[3]-this.data.rect[1]-o);l=Math.min(a,c(d/E$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 yZn extends m9{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),xB.add(r),r.setAttribute("data-element-id",n),r.disabled=this.data.readOnly,r.name=this.data.fieldName,r.tabIndex=Kie,this._setRequired(r,this.data.required),c&&(r.maxLength=c),r.addEventListener("input",m=>{t.setValue(n,{value:m.target.value}),this.setPropertyOnSiblings(r,"value",m.target.value,"value"),u.formattedValue=null}),r.addEventListener("resetform",m=>{const f=this.data.defaultFieldValue??"";r.value=u.userValue=f,u.formattedValue=null});let h=m=>{const{formattedValue:f}=u;f!=null&&(m.target.value=f),m.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){r.addEventListener("focus",f=>{var x;if(u.focused)return;const{target:g}=f;u.userValue&&(g.value=u.userValue),u.lastCommittedValue=g.value,u.commitKey=1,(x=this.data.actions)!=null&&x.Focus||(u.focused=!0)}),r.addEventListener("updatefromsandbox",f=>{this.showElementAndHideCanvas(f.target);const g={value(x){u.userValue=x.detail.value??"",t.setValue(n,{value:u.userValue.toString()}),x.target.value=u.userValue},formattedValue(x){const{formattedValue:y}=x.detail;u.formattedValue=y,y!=null&&x.target!==document.activeElement&&(x.target.value=y),t.setValue(n,{formattedValue:y})},selRange(x){x.target.setSelectionRange(...x.detail.selRange)},charLimit:x=>{var w;const{charLimit:y}=x.detail,{target:v}=x;if(y===0){v.removeAttribute("maxLength");return}v.setAttribute("maxLength",y);let b=u.userValue;!b||b.length<=y||(b=b.slice(0,y),v.value=u.userValue=b,t.setValue(n,{value:b}),(w=this.linkService.eventBus)==null||w.dispatch("dispatcheventinsandbox",{source:this,detail:{id:n,name:"Keystroke",value:b,willCommit:!0,commitKey:1,selStart:v.selectionStart,selEnd:v.selectionEnd}}))}};this._dispatchEventFromSandbox(g,f)}),r.addEventListener("keydown",f=>{var y;u.commitKey=1;let g=-1;if(f.key==="Escape"?g=0:f.key==="Enter"&&!this.data.multiLine?g=2:f.key==="Tab"&&(u.commitKey=3),g===-1)return;const{value:x}=f.target;u.lastCommittedValue!==x&&(u.lastCommittedValue=x,u.userValue=x,(y=this.linkService.eventBus)==null||y.dispatch("dispatcheventinsandbox",{source:this,detail:{id:n,name:"Keystroke",value:x,willCommit:!0,commitKey:g,selStart:f.target.selectionStart,selEnd:f.target.selectionEnd}}))});const m=h;h=null,r.addEventListener("blur",f=>{var x,y;if(!u.focused||!f.relatedTarget)return;(x=this.data.actions)!=null&&x.Blur||(u.focused=!1);const{value:g}=f.target;u.userValue=g,u.lastCommittedValue!==g&&((y=this.linkService.eventBus)==null||y.dispatch("dispatcheventinsandbox",{source:this,detail:{id:n,name:"Keystroke",value:g,willCommit:!0,commitKey:u.commitKey,selStart:f.target.selectionStart,selEnd:f.target.selectionEnd}})),m(f)}),(i=this.data.actions)!=null&&i.Keystroke&&r.addEventListener("beforeinput",f=>{var A;u.lastCommittedValue=null;const{data:g,target:x}=f,{value:y,selectionStart:v,selectionEnd:b}=x;let w=v,S=b;switch(f.inputType){case"deleteWordBackward":{const E=y.substring(0,v).match(/\w*[^\w]*$/);E&&(w-=E[0].length);break}case"deleteWordForward":{const E=y.substring(v).match(/^[^\w]*\w*/);E&&(S+=E[0].length);break}case"deleteContentBackward":v===b&&(w-=1);break;case"deleteContentForward":v===b&&(S+=1);break}f.preventDefault(),(A=this.linkService.eventBus)==null||A.dispatch("dispatcheventinsandbox",{source:this,detail:{id:n,name:"Keystroke",value:y,change:g||"",willCommit:!1,selStart:w,selEnd:S}})}),this._setEventListeners(r,u,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],f=>f.target.value)}if(h&&r.addEventListener("blur",h),this.data.comb){const f=(this.data.rect[2]-this.data.rect[0])/c;r.classList.add("comb"),r.style.letterSpacing=`calc(${f}px * var(--scale-factor) - 1ch)`}}else r=document.createElement("div"),r.textContent=this.data.fieldValue,r.style.verticalAlign="middle",r.style.display="table-cell",this.data.hasOwnCanvas&&(r.hidden=!0);return this._setTextStyle(r),this._setBackgroundColor(r),this._setDefaultPropertiesFromJS(r),this.container.append(r),this.container}}class vZn extends m9{constructor(t){super(t,{isRenderable:!!t.data.hasOwnCanvas})}}class bZn extends m9{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 xB.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=Kie,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 _ns extends m9{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(xB.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=Kie,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 _Zn extends yns{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 wZn extends m9{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");xB.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=Kie;let i=this.data.combo&&this.data.options.length>0;this.data.combo||(a.size=this.data.options.length,this.data.multiSelect&&(a.multiple=!0)),a.addEventListener("resetform",u=>{const h=this.data.defaultFieldValue;for(const m of a.options)m.selected=m.value===h});for(const u of this.data.options){const h=document.createElement("option");h.textContent=u.displayValue,h.value=u.exportValue,r.value.includes(u.exportValue)&&(h.setAttribute("selected",!0),i=!1),a.append(h)}let l=null;if(i){const u=document.createElement("option");u.value=" ",u.setAttribute("hidden",!0),u.setAttribute("selected",!0),a.prepend(u),l=()=>{u.remove(),a.removeEventListener("input",l),l=null},a.addEventListener("input",l)}const o=u=>{const h=u?"value":"textContent",{options:m,multiple:f}=a;return f?Array.prototype.filter.call(m,g=>g.selected).map(g=>g[h]):m.selectedIndex===-1?null:m[m.selectedIndex][h]};let c=o(!1);const d=u=>{const h=u.target.options;return Array.prototype.map.call(h,m=>({displayValue:m.textContent,exportValue:m.value}))};return this.enableScripting&&this.hasJSActions?(a.addEventListener("updatefromsandbox",u=>{const h={value(m){l==null||l();const f=m.detail.value,g=new Set(Array.isArray(f)?f:[f]);for(const x of a.options)x.selected=g.has(x.value);t.setValue(n,{value:o(!0)}),c=o(!1)},multipleSelection(m){a.multiple=!0},remove(m){const f=a.options,g=m.detail.remove;f[g].selected=!1,a.remove(g),f.length>0&&Array.prototype.findIndex.call(f,y=>y.selected)===-1&&(f[0].selected=!0),t.setValue(n,{value:o(!0),items:d(m)}),c=o(!1)},clear(m){for(;a.length!==0;)a.remove(0);t.setValue(n,{value:null,items:[]}),c=o(!1)},insert(m){const{index:f,displayValue:g,exportValue:x}=m.detail.insert,y=a.children[f],v=document.createElement("option");v.textContent=g,v.value=x,y?y.before(v):a.append(v),t.setValue(n,{value:o(!0),items:d(m)}),c=o(!1)},items(m){const{items:f}=m.detail;for(;a.length!==0;)a.remove(0);for(const g of f){const{displayValue:x,exportValue:y}=g,v=document.createElement("option");v.textContent=x,v.value=y,a.append(v)}a.options.length>0&&(a.options[0].selected=!0),t.setValue(n,{value:o(!0),items:d(m)}),c=o(!1)},indices(m){const f=new Set(m.detail.indices);for(const g of m.target.options)g.selected=f.has(g.index);t.setValue(n,{value:o(!0)}),c=o(!1)},editable(m){m.target.disabled=!m.detail.editable}};this._dispatchEventFromSandbox(h,u)}),a.addEventListener("input",u=>{var f;const h=o(!0),m=o(!1);t.setValue(n,{value:h}),u.preventDefault(),(f=this.linkService.eventBus)==null||f.dispatch("dispatcheventinsandbox",{source:this,detail:{id:n,name:"Keystroke",value:c,change:m,changeEx:h,willCommit:!1,commitKey:1,keyDown:!1}})}),this._setEventListeners(a,null,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"],["input","Action"],["input","Validate"]],u=>u.target.value)):a.addEventListener("input",function(u){t.setValue(n,{value:o(!0)})}),this.data.combo&&this._setTextStyle(a),this._setBackgroundColor(a),this._setDefaultPropertiesFromJS(a),this.container.append(a),this.container}}class QZe extends fy{constructor(t){const{data:n,elements:r}=t;super(t,{isRenderable:fy._hasPopupData(n)}),this.elements=r,this.popup=null}render(){this.container.classList.add("popupAnnotation");const t=this.popup=new jZn({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=>`${Aot}${r}`).join(",")),this.container}}var DH,yIe,vIe,FH,hz,hx,XA,OH,Lre,Rre,zH,QA,NS,JA,Dre,eE,Fre,mz,fz,of,W3e,JZe,wns,jns,Nns,kns,K3e,Y3e,eXe;class jZn{constructor({container:t,color:n,elements:r,titleObj:a,modificationDate:i,contentsObj:l,richText:o,parent:c,rect:d,parentRect:u,open:h}){vs(this,of);vs(this,DH,cs(this,of,Nns).bind(this));vs(this,yIe,cs(this,of,eXe).bind(this));vs(this,vIe,cs(this,of,Y3e).bind(this));vs(this,FH,cs(this,of,K3e).bind(this));vs(this,hz,null);vs(this,hx,null);vs(this,XA,null);vs(this,OH,null);vs(this,Lre,null);vs(this,Rre,null);vs(this,zH,null);vs(this,QA,!1);vs(this,NS,null);vs(this,JA,null);vs(this,Dre,null);vs(this,eE,null);vs(this,Fre,null);vs(this,mz,null);vs(this,fz,!1);var m;Kt(this,hx,t),Kt(this,Fre,a),Kt(this,XA,l),Kt(this,eE,o),Kt(this,Rre,c),Kt(this,hz,n),Kt(this,Dre,d),Kt(this,zH,u),Kt(this,Lre,r),Kt(this,OH,Mot.toDateObject(i)),this.trigger=r.flatMap(f=>f.getElementsToTriggerPopup());for(const f of this.trigger)f.addEventListener("click",ye(this,FH)),f.addEventListener("mouseenter",ye(this,vIe)),f.addEventListener("mouseleave",ye(this,yIe)),f.classList.add("popupTriggerArea");for(const f of r)(m=f.container)==null||m.addEventListener("keydown",ye(this,DH));ye(this,hx).hidden=!0,h&&cs(this,of,K3e).call(this)}render(){if(ye(this,NS))return;const t=Kt(this,NS,document.createElement("div"));if(t.className="popup",ye(this,hz)){const i=t.style.outlineColor=ol.makeHexColor(...ye(this,hz));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,hz).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,Fre),t.append(n),ye(this,OH)){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,OH).valueOf()})),n.append(i)}const a=ye(this,of,W3e);if(a)xns.render({xfaHtml:a,intent:"richText",div:t}),t.lastChild.classList.add("richText","popupContent");else{const i=this._formatContents(ye(this,XA));t.append(i)}ye(this,hx).append(t)}_formatContents({str:t,dir:n}){const r=document.createElement("p");r.classList.add("popupContent"),r.dir=n;const a=t.split(/(?:\r\n?|\n)/);for(let i=0,l=a.length;i{l.key==="Enter"&&(i?l.metaKey:l.ctrlKey)&&cs(this,Vre,tXe).call(this)}),!r.popupRef&&this.hasPopupData?this._createPopup():a.classList.add("popupTriggerArea"),n.append(a),n}getElementsToTriggerPopup(){return ye(this,qre)}addHighlightArea(){this.container.classList.add("highlightArea")}}qre=new WeakMap,Vre=new WeakSet,tXe=function(){var n;(n=this.downloadManager)==null||n.openOrDownloadData(this.content,this.filename)};var Hre,pz,gz,Gre,NB,Tns,sXe;class IZn{constructor({div:t,accessibilityManager:n,annotationCanvasMap:r,annotationEditorUIManager:a,page:i,viewport:l,structTreeLayer:o}){vs(this,NB);vs(this,Hre,null);vs(this,pz,null);vs(this,gz,new Map);vs(this,Gre,null);this.div=t,Kt(this,Hre,n),Kt(this,pz,r),Kt(this,Gre,o||null),this.page=i,this.viewport=l,this.zIndex=0,this._annotationEditorUIManager=a}hasEditableAnnotations(){return ye(this,gz).size>0}async render(t){var l;const{annotations:n}=t,r=this.div;pB(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 Oot,annotationStorage:t.annotationStorage||new Iot,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===a0.POPUP;if(c){const h=a.get(o.id);if(!h)continue;i.elements=h}else{const{width:h,height:m}=GE(o.rect);if(h<=0||m<=0)continue}i.data=o;const d=gZn.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 cs(this,NB,Tns).call(this,u,o.id),d._isEditable&&(ye(this,gz).set(d.data.id,d),(l=this._annotationEditorUIManager)==null||l.renderAnnotationElement(d))}cs(this,NB,sXe).call(this)}update({viewport:t}){const n=this.div;this.viewport=t,pB(n,{rotation:t.rotation}),cs(this,NB,sXe).call(this),n.hidden=!1}getEditableAnnotations(){return Array.from(ye(this,gz).values())}getEditableAnnotation(t){return ye(this,gz).get(t)}}Hre=new WeakMap,pz=new WeakMap,gz=new WeakMap,Gre=new WeakMap,NB=new WeakSet,Tns=async function(t,n){var l,o;const r=t.firstChild||t,a=r.id=`${Aot}${n}`,i=await((l=ye(this,Gre))==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,Hre))==null||o.moveElementInDOM(this.div,t,r,!1)},sXe=function(){if(!ye(this,pz))return;const t=this.div;for(const[n,r]of ye(this,pz)){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,pz).clear()};const Pue=/\r\n?|\n/g;var kS,Mj,Wre,xz,Pj,Hy,Mns,Pns,Ins,Z3e,sT,X3e,Q3e,Lns,rXe,Rns;const $f=class $f extends Cm{constructor(n){super({...n,name:"freeTextEditor"});vs(this,Hy);vs(this,kS);vs(this,Mj,"");vs(this,Wre,`${this.id}-editor`);vs(this,xz,null);vs(this,Pj);Kt(this,kS,n.color||$f._defaultColor||Cm._defaultLineColor),Kt(this,Pj,n.fontSize||$f._defaultFontSize)}static get _keyboardManager(){const n=$f.prototype,r=l=>l.isEmpty(),a=gB.TRANSLATE_SMALL,i=gB.TRANSLATE_BIG;return eh(this,"_keyboardManager",new Wie([[["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:cs(this,Hy,Mns).call(this,r);break;case td.FREETEXT_COLOR:cs(this,Hy,Pns).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,Pj)],[td.FREETEXT_COLOR,ye(this,kS)]]}_translateEmpty(n,r){this._uiManager.translateSelectedEditors(n,r,!0)}getInitialTranslation(){const n=this.parentScale;return[-$f._internalPadding*n,-($f._internalPadding+ye(this,Pj))*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(Dd.FREETEXT),super.enableEditMode(),this.overlayDiv.classList.remove("enabled"),this.editorDiv.contentEditable=!0,this._isDraggable=!1,this.div.removeAttribute("aria-activedescendant"),Kt(this,xz,new AbortController);const n=this._uiManager.combinedSignal(ye(this,xz));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,Wre)),this._isDraggable=!0,(n=ye(this,xz))==null||n.abort(),Kt(this,xz,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,Mj),r=Kt(this,Mj,cs(this,Hy,Ins).call(this).trimEnd());if(n===r)return;const a=i=>{if(Kt(this,Mj,i),!i){this.remove();return}cs(this,Hy,Q3e).call(this),this._uiManager.rebuild(this),cs(this,Hy,Z3e).call(this)};this.addCommands({cmd:()=>{a(r)},undo:()=>{a(n)},mustExec:!1}),cs(this,Hy,Z3e).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,Wre)),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,Pj)}px * var(--scale-factor))`,a.color=ye(this,kS),this.div.append(this.editorDiv),this.overlayDiv=document.createElement("div"),this.overlayDiv.classList.add("overlay","enabled"),this.div.append(this.overlayDiv),mPe(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);cs(this,Hy,Q3e).call(this),this._isDraggable=!0,this.editorDiv.contentEditable=!1}else this._isDraggable=!1,this.editorDiv.contentEditable=!0;return this.div}editorDivPaste(n){var g,x,y;const r=n.clipboardData||window.clipboardData,{types:a}=r;if(a.length===1&&a[0]==="text/plain")return;n.preventDefault();const i=cs(g=$f,sT,rXe).call(g,r.getData("text")||"").replaceAll(Pue,` `);if(!i)return;const l=window.getSelection();if(!l.rangeCount)return;this.editorDiv.normalize(),l.deleteFromDocument();const o=l.getRangeAt(0);if(!i.includes(` `)){o.insertNode(document.createTextNode(i)),this.editorDiv.normalize(),l.collapseToStart();return}const{startContainer:c,startOffset:d}=o,u=[],h=[];if(c.nodeType===Node.TEXT_NODE){const v=c.parentElement;if(h.push(c.nodeValue.slice(d).replaceAll(Pue,"")),v!==this.editorDiv){let b=u;for(const w of this.editorDiv.childNodes){if(w===v){b=h;continue}b.push(cs(x=$f,sT,X3e).call(x,w))}}u.push(c.nodeValue.slice(0,d).replaceAll(Pue,""))}else if(c===this.editorDiv){let v=u,b=0;for(const w of this.editorDiv.childNodes)b++===d&&(v=h),v.push(cs(y=$f,sT,X3e).call(y,w))}Kt(this,Mj,`${u.join(` `)}${i}${h.join(` `)}`),cs(this,Hy,Q3e).call(this);const m=new Range;let f=u.reduce((v,b)=>v+b.length,0);for(const{firstChild:v}of this.editorDiv.childNodes)if(v.nodeType===Node.TEXT_NODE){const b=v.nodeValue.length;if(f<=b){m.setStart(v,f),m.setEnd(v,f);break}f-=b}l.removeAllRanges(),l.addRange(m)}get contentDiv(){return this.editorDiv}static async deserialize(n,r,a){var o;let i=null;if(n instanceof Sns){const{data:{defaultAppearanceData:{fontSize:c,fontColor:d},rect:u,rotation:h,id:m,popupRef:f},textContent:g,textPosition:x,parent:{page:{pageNumber:y}}}=n;if(!g||g.length===0)return null;i=n={annotationType:Dd.FREETEXT,color:Array.from(d),fontSize:c,value:g.join(` `),position:x,pageIndex:y-1,rect:u.slice(0),rotation:h,id:m,deleted:!1,popupRef:f}}const l=await super.deserialize(n,r,a);return Kt(l,Pj,n.fontSize),Kt(l,kS,ol.makeHexColor(...n.color)),Kt(l,Mj,cs(o=$f,sT,rXe).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,kS)),l={annotationType:Dd.FREETEXT,color:i,fontSize:ye(this,Pj),value:cs(this,Hy,Lns).call(this),pageIndex:this.pageIndex,rect:a,rotation:this.rotation,structTreeParentId:this._structTreeParentId};return n?l:this.annotationElementId&&!cs(this,Hy,Rns).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,Pj)}px * var(--scale-factor))`,a.color=ye(this,kS),r.replaceChildren();for(const l of ye(this,Mj).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,Mj)}),r}resetAnnotationElement(n){super.resetAnnotationElement(n),n.resetEdited()}};kS=new WeakMap,Mj=new WeakMap,Wre=new WeakMap,xz=new WeakMap,Pj=new WeakMap,Hy=new WeakSet,Mns=function(n){const r=i=>{this.editorDiv.style.fontSize=`calc(${i}px * var(--scale-factor))`,this.translate(0,-(i-ye(this,Pj))*this.parentScale),Kt(this,Pj,i),cs(this,Hy,Z3e).call(this)},a=ye(this,Pj);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})},Pns=function(n){const r=i=>{Kt(this,kS,this.editorDiv.style.color=i)},a=ye(this,kS);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})},Ins=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(cs(a=$f,sT,X3e).call(a,i)),r=i);return n.join(` `)},Z3e=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()},sT=new WeakSet,X3e=function(n){return(n.nodeType===Node.TEXT_NODE?n.nodeValue:n.innerText).replaceAll(Pue,"")},Q3e=function(){if(this.editorDiv.replaceChildren(),!!ye(this,Mj))for(const n of ye(this,Mj).split(` `)){const r=document.createElement("div");r.append(n?document.createTextNode(n):document.createElement("br")),this.editorDiv.append(r)}},Lns=function(){return ye(this,Mj).replaceAll(" "," ")},rXe=function(n){return n.replaceAll(" "," ")},Rns=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},vs($f,sT),Nr($f,"_freeTextDefaultContent",""),Nr($f,"_internalPadding",0),Nr($f,"_defaultColor",null),Nr($f,"_defaultFontSize",10),Nr($f,"_type","freetext"),Nr($f,"_editorType",Dd.FREETEXT);let nXe=$f;class Dns{toSVGPath(){kp("Abstract method `toSVGPath` must be implemented.")}get box(){kp("Abstract getter `box` must be implemented.")}serialize(t,n){kp("Abstract method `serialize` must be implemented.")}get classNamesForDrawing(){kp("Abstract getter `classNamesForDrawing` must be implemented.")}get classNamesForOutlining(){kp("Abstract getter `classNamesForOutlining` must be implemented.")}get mustRemoveSelfIntersections(){return!1}}var Ij,SS,BH,$H,K5,uu,yz,vz,Kre,Yre,UH,qH,nI,Zre,bIe,_Ie,C0,IQ,Fns,Ons,zns,Bns,$ns,Uns;const MA=class MA{constructor({x:t,y:n},r,a,i,l,o=0){vs(this,C0);vs(this,Ij);vs(this,SS,[]);vs(this,BH);vs(this,$H);vs(this,K5,[]);vs(this,uu,new Float64Array(18));vs(this,yz);vs(this,vz);vs(this,Kre);vs(this,Yre);vs(this,UH);vs(this,qH);vs(this,nI,[]);Kt(this,Ij,r),Kt(this,qH,i*a),Kt(this,$H,l),ye(this,uu).set([NaN,NaN,NaN,NaN,t,n],6),Kt(this,BH,o),Kt(this,Yre,ye(MA,Zre)*a),Kt(this,Kre,ye(MA,_Ie)*a),Kt(this,UH,a),ye(this,nI).push(t,n)}isEmpty(){return isNaN(ye(this,uu)[8])}add({x:t,y:n}){var R;Kt(this,yz,t),Kt(this,vz,n);const[r,a,i,l]=ye(this,Ij);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 cs(this,C0,Ons).call(this,r),r.join(" ")}newFreeDrawOutline(t,n,r,a,i,l){return new qns(t,n,r,a,i,l)}getOutlines(){var h;const t=ye(this,K5),n=ye(this,SS),r=ye(this,uu),[a,i,l,o]=ye(this,Ij),c=new Float64Array((((h=ye(this,nI))==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 cs(this,C0,$ns).call(this,d,u),this.newFreeDrawOutline(d,c,ye(this,Ij),ye(this,UH),ye(this,BH),ye(this,$H))}};Ij=new WeakMap,SS=new WeakMap,BH=new WeakMap,$H=new WeakMap,K5=new WeakMap,uu=new WeakMap,yz=new WeakMap,vz=new WeakMap,Kre=new WeakMap,Yre=new WeakMap,UH=new WeakMap,qH=new WeakMap,nI=new WeakMap,Zre=new WeakMap,bIe=new WeakMap,_Ie=new WeakMap,C0=new WeakSet,IQ=function(){const t=ye(this,uu).subarray(4,6),n=ye(this,uu).subarray(16,18),[r,a,i,l]=ye(this,Ij);return[(ye(this,yz)+(t[0]-n[0])/2-r)/i,(ye(this,vz)+(t[1]-n[1])/2-a)/l,(ye(this,yz)+(n[0]-t[0])/2-r)/i,(ye(this,vz)+(n[1]-t[1])/2-a)/l]},Fns=function(){const[t,n,r,a]=ye(this,Ij),[i,l,o,c]=cs(this,C0,IQ).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`},Ons=function(t){const n=ye(this,SS);t.push(`L${n[4]} ${n[5]} Z`)},zns=function(t){const[n,r,a,i]=ye(this,Ij),l=ye(this,uu).subarray(4,6),o=ye(this,uu).subarray(16,18),[c,d,u,h]=cs(this,C0,IQ).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}`)},Bns=function(t){const n=ye(this,uu),[r,a,i,l]=ye(this,Ij),[o,c,d,u]=cs(this,C0,IQ).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,Ij),ye(this,UH),ye(this,BH),ye(this,$H))},$ns=function(t,n){const r=ye(this,SS);return t.set([NaN,NaN,NaN,NaN,r[4],r[5]],n),n+=6},Uns=function(t,n){const r=ye(this,uu).subarray(4,6),a=ye(this,uu).subarray(16,18),[i,l,o,c]=ye(this,Ij),[d,u,h,m]=cs(this,C0,IQ).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},vs(MA,Zre,8),vs(MA,bIe,2),vs(MA,_Ie,ye(MA,Zre)+ye(MA,bIe));let pPe=MA;var VH,bz,tE,Xre,Lj,Qre,Yx,ww,LQ,RQ,Vns;class qns extends Dns{constructor(n,r,a,i,l,o){super();vs(this,ww);vs(this,VH);vs(this,bz,null);vs(this,tE);vs(this,Xre);vs(this,Lj);vs(this,Qre);vs(this,Yx);Kt(this,Yx,n),Kt(this,Lj,r),Kt(this,VH,a),Kt(this,Qre,i),Kt(this,tE,l),Kt(this,Xre,o),cs(this,ww,Vns).call(this,o);const{x:c,y:d,width:u,height:h}=ye(this,bz);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,rI))n[3]?(t.push(...cs(this,T_,aXe).call(this,n)),cs(this,T_,Gns).call(this,n)):(cs(this,T_,Wns).call(this,n),t.push(...cs(this,T_,aXe).call(this,n)));return cs(this,T_,Hns).call(this,t)}}Jre=new WeakMap,rI=new WeakMap,CS=new WeakMap,T_=new WeakSet,Hns=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 LZn(a,ye(this,Jre))},J3e=function(t){const n=ye(this,CS);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,CS)[a];if(i!==t)break;if(i===t&&l===n){ye(this,CS).splice(a,1);return}}},aXe=function(t){const[n,r,a]=t,i=[[n,r,a]],l=cs(this,T_,J3e).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 eae,HH;class LZn extends Dns{constructor(n,r){super();vs(this,eae);vs(this,HH);Kt(this,HH,n),Kt(this,eae,r)}toSVGPath(){const n=[];for(const r of ye(this,HH)){let[a,i]=r;n.push(`M${a} ${i}`);for(let l=2;l-1?(Kt(this,ow,!0),cs(this,jd,eAe).call(this,n),cs(this,jd,UO).call(this)):ye(this,sE)&&(Kt(this,YH,n.anchorNode),Kt(this,aae,n.anchorOffset),Kt(this,iae,n.focusNode),Kt(this,oae,n.focusOffset),cs(this,jd,dXe).call(this),cs(this,jd,UO).call(this),this.rotate(this.rotation))}static get _keyboardManager(){const n=Xh.prototype;return eh(this,"_keyboardManager",new Wie([[["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,ow)?"free_highlight":"highlight",color:this._uiManager.highlightColorNames.get(this.color),thickness:ye(this,_N),methodOfCreation:ye(this,lae)}}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,XH)}updateParams(n,r){switch(n){case td.HIGHLIGHT_COLOR:cs(this,jd,Yns).call(this,r);break;case td.HIGHLIGHT_THICKNESS:cs(this,jd,Zns).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,_N)||Xh._defaultThickness],[td.HIGHLIGHT_FREE,ye(this,ow)]]}async addEditToolbar(){const n=await super.addEditToolbar();return n?(this._uiManager.highlightColors&&(Kt(this,ZH,new gPe({editor:this})),n.addColorPicker(ye(this,ZH))),n):null}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}fixAndSetPosition(){return super.fixAndSetPosition(cs(this,jd,DQ).call(this))}getBaseTranslation(){return[0,0]}getRect(n,r){return super.getRect(n,r,cs(this,jd,DQ).call(this))}onceAdded(){this.annotationElementId||this.parent.addUndoableEditor(this),this.div.focus()}remove(){cs(this,jd,uXe).call(this),this._reportTelemetry({action:"deleted"}),super.remove()}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(cs(this,jd,UO).call(this),this.isAttachedToDOM||this.parent.add(this)))}setParent(n){var a;let r=!1;this.parent&&!n?cs(this,jd,uXe).call(this):n&&(cs(this,jd,UO).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,ow)?(n=(n-this.rotation+360)%360,a=cs(i=Xh,BN,EU).call(i,ye(this,TS).box,n)):a=cs(l=Xh,BN,EU).call(l,this,n),r.rotate(ye(this,a1),n),r.rotate(ye(this,d0),n),r.updateBox(ye(this,a1),a),r.updateBox(ye(this,d0),cs(o=Xh,BN,EU).call(o,ye(this,bN).box,n))}render(){if(this.div)return this.div;const n=super.render();ye(this,QH)&&(n.setAttribute("aria-label",ye(this,QH)),n.setAttribute("role","mark")),ye(this,ow)?n.classList.add("free"):this.div.addEventListener("keydown",cs(this,jd,Qns).bind(this),{signal:this._uiManager._signal});const r=Kt(this,jz,document.createElement("div"));n.append(r),r.setAttribute("aria-hidden","true"),r.className="internal",r.style.clipPath=ye(this,wz);const[a,i]=this.parentDimensions;return this.setDims(this.width*a,this.height*i),mPe(this,ye(this,jz),["pointerover","pointerleave"]),this.enableEditing(),n}pointerover(){this.isSelected||this.parent.drawLayer.addClass(ye(this,d0),"hovered")}pointerleave(){this.isSelected||this.parent.drawLayer.removeClass(ye(this,d0),"hovered")}_moveCaret(n){switch(this.parent.unselect(this),n){case 0:case 2:cs(this,jd,tAe).call(this,!0);break;case 1:case 3:cs(this,jd,tAe).call(this,!1);break}}select(){var n,r;super.select(),ye(this,d0)&&((n=this.parent)==null||n.drawLayer.removeClass(ye(this,d0),"hovered"),(r=this.parent)==null||r.drawLayer.addClass(ye(this,d0),"selected"))}unselect(){var n;super.unselect(),ye(this,d0)&&((n=this.parent)==null||n.drawLayer.removeClass(ye(this,d0),"selected"),ye(this,ow)||cs(this,jd,tAe).call(this,!1))}get _mustFixPosition(){return!ye(this,ow)}show(n=this._isVisible){super.show(n),this.parent&&(this.parent.drawLayer.show(ye(this,a1),n),this.parent.drawLayer.show(ye(this,d0),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(),cs(this,BN,srs).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",pk,{signal:m}),a.addEventListener("pointermove",cs(this,BN,trs).bind(this,n),{signal:m}),this._freeHighlight=new iXe({x:i,y:l},[o,c,d,u],n.scale,this._defaultThickness/2,r,.001),{id:this._freeHighlightId,clipPathId:this._freeHighlightClipId}=n.drawLayer.draw(this._freeHighlight,this._defaultColor,this._defaultOpacity,!0)}static async deserialize(n,r,a){var x,y,v,b;let i=null;if(n instanceof Ans){const{data:{quadPoints:w,rect:S,rotation:A,id:E,color:I,opacity:P,popupRef:R},parent:{page:{pageNumber:D}}}=n;i=n={annotationType:Dd.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 zot){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:Dd.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),Kt(u,nE,d||1),c&&Kt(u,_N,n.thickness),u.annotationElementId=n.id||null,u._initialData=i;const[h,m]=u.pageDimensions,[f,g]=u.pageTranslation;if(o){const w=Kt(u,sE,[]);for(let S=0;S=0)Kt(this,a1,r),Kt(this,wz,a),this.parent.drawLayer.finalizeLine(r,n),Kt(this,d0,this.parent.drawLayer.drawOutline(ye(this,bN)));else if(this.parent){const f=this.parent.viewport.rotation;this.parent.drawLayer.updateLine(ye(this,a1),n),this.parent.drawLayer.updateBox(ye(this,a1),cs(h=Xh,BN,EU).call(h,ye(this,TS).box,(f-this.rotation+360)%360)),this.parent.drawLayer.updateLine(ye(this,d0),ye(this,bN)),this.parent.drawLayer.updateBox(ye(this,d0),cs(m=Xh,BN,EU).call(m,ye(this,bN).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,bN).box;Kt(this,XH,[(u[0]-l)/c,(u[1]-o)/d])},Yns=function(n){const r=(l,o)=>{var c,d,u;this.color=l,(c=this.parent)==null||c.drawLayer.changeColor(ye(this,a1),l),(d=ye(this,ZH))==null||d.updateColor(l),Kt(this,nE,o),(u=this.parent)==null||u.drawLayer.changeOpacity(ye(this,a1),o)},a=this.color,i=ye(this,nE);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)},Zns=function(n){const r=ye(this,_N),a=i=>{Kt(this,_N,i),cs(this,jd,Xns).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)},Xns=function(n){if(!ye(this,ow))return;cs(this,jd,eAe).call(this,{highlightOutlines:ye(this,TS).getNewOutline(n/2)}),this.fixAndSetPosition();const[r,a]=this.parentDimensions;this.setDims(this.width*r,this.height*a)},uXe=function(){ye(this,a1)===null||!this.parent||(this.parent.drawLayer.remove(ye(this,a1)),Kt(this,a1,null),this.parent.drawLayer.remove(ye(this,d0)),Kt(this,d0,null))},UO=function(n=this.parent){ye(this,a1)===null&&({id:X0(this,a1)._,clipPathId:X0(this,wz)._}=n.drawLayer.draw(ye(this,TS),this.color,ye(this,nE)),Kt(this,d0,n.drawLayer.drawOutline(ye(this,bN))),ye(this,jz)&&(ye(this,jz).style.clipPath=ye(this,wz)))},BN=new WeakSet,EU=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)},tAe=function(n){if(!ye(this,YH))return;const r=window.getSelection();n?r.setPosition(ye(this,YH),ye(this,aae)):r.setPosition(ye(this,iae),ye(this,oae))},DQ=function(){return ye(this,ow)?this.rotation:0},Jns=function(){if(ye(this,ow))return null;const[n,r]=this.pageDimensions,[a,i]=this.pageTranslation,l=ye(this,sE),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},ers=function(n){return ye(this,TS).serialize(n,cs(this,jd,DQ).call(this))},trs=function(n,r){this._freeHighlight.add(r)&&n.drawLayer.updatePath(this._freeHighlightId,this._freeHighlight)},srs=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=""},nrs=function(n){const{color:r}=this._initialData;return n.color.some((a,i)=>a!==r[i])},vs(Xh,BN),Nr(Xh,"_defaultColor",null),Nr(Xh,"_defaultOpacity",1),Nr(Xh,"_defaultThickness",12),Nr(Xh,"_type","highlight"),Nr(Xh,"_editorType",Dd.HIGHLIGHT),Nr(Xh,"_freeHighlightId",-1),Nr(Xh,"_freeHighlight",null),Nr(Xh,"_freeHighlightClipId","");let xPe=Xh;var Nz,kz,Y5,rE,wN,Sz,Cz,Az,aE,JH,Ez,Tz,iI,Gi,rrs,ars,irs,ors,mXe,lrs,fXe,crs,drs,urs,hrs,mrs,qO,pXe,gXe,xXe,sAe,nAe,TU,yXe,rAe,jT,frs,vXe,prs,grs,bXe,aAe,FQ;const xg=class xg extends Cm{constructor(n){super({...n,name:"inkEditor"});vs(this,Gi);vs(this,Nz,0);vs(this,kz,0);vs(this,Y5,null);vs(this,rE,new Path2D);vs(this,wN,!1);vs(this,Sz,null);vs(this,Cz,!1);vs(this,Az,!1);vs(this,aE,null);vs(this,JH,null);vs(this,Ez,0);vs(this,Tz,0);vs(this,iI,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:xg._defaultThickness=r;break;case td.INK_COLOR:xg._defaultColor=r;break;case td.INK_OPACITY:xg._defaultOpacity=r/100;break}}updateParams(n,r){switch(n){case td.INK_THICKNESS:cs(this,Gi,rrs).call(this,r);break;case td.INK_COLOR:cs(this,Gi,ars).call(this,r);break;case td.INK_OPACITY:cs(this,Gi,irs).call(this,r);break}}static get defaultPropertiesToUpdate(){return[[td.INK_THICKNESS,xg._defaultThickness],[td.INK_COLOR,xg._defaultColor||Cm._defaultLineColor],[td.INK_OPACITY,Math.round(xg._defaultOpacity*100)]]}get propertiesToUpdate(){return[[td.INK_THICKNESS,this.thickness||xg._defaultThickness],[td.INK_COLOR,this.color||xg._defaultColor||Cm._defaultLineColor],[td.INK_OPACITY,Math.round(100*(this.opacity??xg._defaultOpacity))]]}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.canvas||(cs(this,Gi,sAe).call(this),cs(this,Gi,nAe).call(this)),this.isAttachedToDOM||(this.parent.add(this),cs(this,Gi,TU).call(this)),cs(this,Gi,FQ).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,Y5)&&(clearTimeout(ye(this,Y5)),Kt(this,Y5,null)),(n=ye(this,aE))==null||n.disconnect(),Kt(this,aE,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,wN)||this.canvas===null||(super.enableEditMode(),this._isDraggable=!1,cs(this,Gi,pXe).call(this))}disableEditMode(){!this.isInEditMode()||this.canvas===null||(super.disableEditMode(),this._isDraggable=!this.isEmpty(),this.div.classList.remove("editing"),cs(this,Gi,gXe).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,wN)||(super.commit(),this.isEditing=!1,this.disableEditMode(),this.setInForeground(),Kt(this,wN,!0),this.div.classList.add("disabled"),cs(this,Gi,FQ).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,wN)||(this.setInForeground(),n.preventDefault(),this.div.contains(document.activeElement)||this.div.focus({preventScroll:!0}),cs(this,Gi,lrs).call(this,n.offsetX,n.offsetY))}canvasPointermove(n){n.preventDefault(),cs(this,Gi,fXe).call(this,n.offsetX,n.offsetY)}canvasPointerup(n){n.preventDefault(),cs(this,Gi,xXe).call(this,n)}canvasPointerleave(n){cs(this,Gi,xXe).call(this,n)}get isResizable(){return!this.isEmpty()&&ye(this,wN)}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]=cs(this,Gi,ors).call(this);if(this.setAt(a,i,0,0),this.setDims(l,o),cs(this,Gi,sAe).call(this),this.width){const[c,d]=this.parentDimensions;this.setAspectRatio(this.width*c,this.height*d),this.setAt(n*c,r*d,this.width*c,this.height*d),Kt(this,Az,!0),cs(this,Gi,TU).call(this),this.setDims(this.width*c,this.height*d),cs(this,Gi,qO).call(this),this.div.classList.add("disabled")}else this.div.classList.add("editing"),this.enableEditMode();return cs(this,Gi,nAe).call(this),this.div}setDimensions(n,r){const a=Math.round(n),i=Math.round(r);if(ye(this,Ez)===a&&ye(this,Tz)===i)return;Kt(this,Ez,a),Kt(this,Tz,i),this.canvas.style.visibility="hidden";const[l,o]=this.parentDimensions;this.width=n/l,this.height=r/o,this.fixAndSetPosition(),ye(this,wN)&&cs(this,Gi,yXe).call(this,n,r),cs(this,Gi,TU).call(this),cs(this,Gi,qO).call(this),this.canvas.style.visibility="visible",this.fixDims()}static async deserialize(n,r,a){var y,v,b;if(n instanceof zot)return null;const i=await super.deserialize(n,r,a);i.thickness=n.thickness,i.color=ol.makeHexColor(...n.color),i.opacity=n.opacity;const[l,o]=i.pageDimensions,c=i.width*l,d=i.height*o,u=i.parentScale,h=n.thickness/2;Kt(i,wN,!0),Kt(i,Ez,Math.round(c)),Kt(i,Tz,Math.round(d));const{paths:m,rect:f,rotation:g}=n;for(let{bezier:w}of m){w=cs(y=xg,jT,prs).call(y,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,cs(this,Gi,FQ).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})},ars=function(n){const r=i=>{this.color=i,cs(this,Gi,qO).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})},irs=function(n){const r=i=>{this.opacity=i,cs(this,Gi,qO).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})},ors=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]}},mXe=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}${nYn(a)}`},lrs=function(n,r){this.canvas.addEventListener("contextmenu",pk,{signal:this._uiManager._signal}),cs(this,Gi,gXe).call(this),Kt(this,Sz,new AbortController);const a=this._uiManager.combinedSignal(ye(this,Sz));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,Az)||(Kt(this,Az,!0),cs(this,Gi,TU).call(this),this.thickness||(this.thickness=xg._defaultThickness),this.color||(this.color=xg._defaultColor||Cm._defaultLineColor),this.opacity??(this.opacity=xg._defaultOpacity)),this.currentPath.push([n,r]),Kt(this,Cz,!1),cs(this,Gi,mXe).call(this),Kt(this,iI,()=>{cs(this,Gi,urs).call(this),ye(this,iI)&&window.requestAnimationFrame(ye(this,iI))}),window.requestAnimationFrame(ye(this,iI))},fXe=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,rE);if(l.push([n,r]),Kt(this,Cz,!0),l.length<=2){o.moveTo(...l[0]),o.lineTo(n,r);return}l.length===3&&(Kt(this,rE,o=new Path2D),o.moveTo(...l[0])),cs(this,Gi,hrs).call(this,o,...l.at(-3),...l.at(-2),n,r)},crs=function(){if(this.currentPath.length===0)return;const n=this.currentPath.at(-1);ye(this,rE).lineTo(...n)},drs=function(n,r){Kt(this,iI,null),n=Math.min(Math.max(n,0),this.canvas.width),r=Math.min(Math.max(r,0),this.canvas.height),cs(this,Gi,fXe).call(this,n,r),cs(this,Gi,crs).call(this);let a;if(this.currentPath.length!==1)a=cs(this,Gi,mrs).call(this);else{const d=[n,r];a=[[d,d.slice(),d.slice(),d]]}const i=ye(this,rE),l=this.currentPath;this.currentPath=[],Kt(this,rE,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||(cs(this,Gi,sAe).call(this),cs(this,Gi,nAe).call(this)),cs(this,Gi,FQ).call(this))};this.addCommands({cmd:o,undo:c,mustExec:!0})},urs=function(){if(!ye(this,Cz))return;Kt(this,Cz,!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,rE)),l.restore()},hrs=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)},mrs=function(){const n=this.currentPath;if(n.length<=2)return[[n[0],n[0],n.at(-1),n.at(-1)]];const r=[];let a,[i,l]=n[0];for(a=1;a{Kt(this,Y5,null),this.canvas.removeEventListener("contextmenu",pk)},10)),cs(this,Gi,drs).call(this,n.offsetX,n.offsetY),this.addToAnnotationStorage(),this.setInBackground()},sAe=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")},nAe=function(){Kt(this,aE,new ResizeObserver(n=>{const r=n[0].contentRect;r.width&&r.height&&this.setDimensions(r.width,r.height)})),ye(this,aE).observe(this.div),this._uiManager._signal.addEventListener("abort",()=>{var n;(n=ye(this,aE))==null||n.disconnect(),Kt(this,aE,null)},{once:!0})},TU=function(){if(!ye(this,Az))return;const[n,r]=this.parentDimensions;this.canvas.width=Math.ceil(this.width*n),this.canvas.height=Math.ceil(this.height*r),cs(this,Gi,rAe).call(this)},yXe=function(n,r){const a=cs(this,Gi,aAe).call(this),i=(n-a)/ye(this,kz),l=(r-a)/ye(this,Nz);this.scaleFactor=Math.min(i,l)},rAe=function(){const n=cs(this,Gi,aAe).call(this)/2;this.ctx.setTransform(this.scaleFactor,0,0,this.scaleFactor,this.translationX*this.scaleFactor+n,this.translationY*this.scaleFactor+n)},jT=new WeakSet,frs=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(Dd.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,Jv)&&(Kt(this,bg,null),this._uiManager.imageManager.deleteId(ye(this,Jv)),(n=ye(this,Z5))==null||n.remove(),Kt(this,Z5,null),(r=ye(this,oE))==null||r.disconnect(),Kt(this,oE,null),ye(this,X5)&&(clearTimeout(ye(this,X5)),Kt(this,X5,null))),super.remove()}rebuild(){if(!this.parent){ye(this,Jv)&&cs(this,Ou,iAe).call(this);return}super.rebuild(),this.div!==null&&(ye(this,Jv)&&ye(this,Z5)===null&&cs(this,Ou,iAe).call(this),this.isAttachedToDOM||this.parent.add(this))}onceAdded(){this._isDraggable=!0,this.div.focus()}isEmpty(){return!(ye(this,oI)||ye(this,bg)||ye(this,iE)||ye(this,lI)||ye(this,Jv))}get isResizable(){return!0}render(){if(this.div)return this.div;let n,r;if(this.width&&(n=this.x,r=this.y),super.render(),this.div.hidden=!0,this.div.setAttribute("role","figure"),this.addAltTextButton(),ye(this,bg)?cs(this,Ou,wXe).call(this):cs(this,Ou,iAe).call(this),this.width&&!this.annotationElementId){const[a,i]=this.parentDimensions;this.setAt(n*a,r*i,this.width*a,this.height*i)}return this.div}copyCanvas(n,r,a=!1){var f;n||(n=224);const{width:i,height:l}=ye(this,bg),o=new yZe;let c=ye(this,bg),d=i,u=l,h=null;if(r){if(i>r||l>r){const P=Math.min(r/i,r/l);d=Math.floor(i*P),u=Math.floor(l*P)}h=document.createElement("canvas");const g=h.width=Math.ceil(d*o.sx),x=h.height=Math.ceil(u*o.sy);ye(this,Rj)||(c=cs(this,Ou,oAe).call(this,g,x));const y=h.getContext("2d");y.filter=this._uiManager.hcmFilter;let v="white",b="#cfcfd8";this._uiManager.hcmFilter!=="none"?b="black":(f=window.matchMedia)!=null&&f.call(window,"(prefers-color-scheme: dark)").matches&&(v="#8f8f9d",b="#42414d");const w=15,S=w*o.sx,A=w*o.sy,E=new OffscreenCanvas(S*2,A*2),I=E.getContext("2d");I.fillStyle=v,I.fillRect(0,0,S*2,A*2),I.fillStyle=b,I.fillRect(0,0,S,A),I.fillRect(S,A,S,A),y.fillStyle=y.createPattern(E,"repeat"),y.fillRect(0,0,g,x),y.drawImage(c,0,0,c.width,c.height,0,0,g,x)}let m=null;if(a){let g,x;if(o.symmetric&&c.widthn||l>n){const b=Math.min(n/i,n/l);g=Math.floor(i*b),x=Math.floor(l*b),ye(this,Rj)||(c=cs(this,Ou,oAe).call(this,g,x))}const v=new OffscreenCanvas(g,x).getContext("2d",{willReadFrequently:!0});v.drawImage(c,0,0,c.width,c.height,0,0,g,x),m={width:g,height:x,data:v.getImageData(0,0,g,x).data}}return{canvas:h,width:d,height:u,imageData:m}}getImageForAltText(){return ye(this,Z5)}static async deserialize(n,r,a){var x;let i=null;if(n instanceof Ens){const{data:{rect:y,rotation:v,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(`${Aot}${b}`))==null?void 0:x.get("aria-label"))||"";i=n={annotationType:Dd.STAMP,bitmapId:P.id,bitmap:P.bitmap,pageIndex:E-1,rect:y.slice(0),rotation:v,id:b,deleted:!1,accessibilityData:{decorative:!1,altText:R},isSvg:!1,structParent:w,popupRef:S}}const l=await super.deserialize(n,r,a),{rect:o,bitmap:c,bitmapUrl:d,bitmapId:u,isSvg:h,accessibilityData:m}=n;u&&a.imageManager.isValidId(u)?(Kt(l,Jv,u),c&&Kt(l,bg,c)):Kt(l,iE,d),Kt(l,Rj,h);const[f,g]=l.pageDimensions;return l.width=(o[2]-o[0])/f,l.height=(o[3]-o[1])/g,l.annotationElementId=n.id||null,m&&(l.altTextData=m),l._initialData=i,Kt(l,tG,!!i),l}serialize(n=!1,r=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const a={annotationType:Dd.STAMP,bitmapId:ye(this,Jv),pageIndex:this.pageIndex,rect:this.getRect(0,0),rotation:this.rotation,isSvg:ye(this,Rj),structTreeParentId:this._structTreeParentId};if(n)return a.bitmapUrl=cs(this,Ou,lAe).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=cs(this,Ou,vrs).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,Rj)?(a.rect[2]-a.rect[0])*(a.rect[3]-a.rect[1]):null;if(!r.stamps.has(ye(this,Jv)))r.stamps.set(ye(this,Jv),{area:o,serialized:a}),a.bitmap=cs(this,Ou,lAe).call(this,!1);else if(ye(this,Rj)){const c=r.stamps.get(ye(this,Jv));o>c.area&&(c.area=o,c.serialized.bitmap.close(),c.serialized.bitmap=cs(this,Ou,lAe).call(this,!1))}return a}renderAnnotationElement(n){return n.updateEdited({rect:this.getRect(0,0)}),null}};bg=new WeakMap,Jv=new WeakMap,oI=new WeakMap,iE=new WeakMap,lI=new WeakMap,eG=new WeakMap,Z5=new WeakMap,oE=new WeakMap,X5=new WeakMap,Rj=new WeakMap,tG=new WeakMap,Ou=new WeakSet,OQ=function(n,r=!1){if(!n){this.remove();return}Kt(this,bg,n.bitmap),r||(Kt(this,Jv,n.id),Kt(this,Rj,n.isSvg)),n.file&&Kt(this,eG,n.file.name),cs(this,Ou,wXe).call(this)},zQ=function(){if(Kt(this,oI,null),this._uiManager.enableWaiting(!1),!!ye(this,Z5)){if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&ye(this,bg)){this._editToolbar.hide(),this._uiManager.editAltText(this,!0);return}if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&ye(this,bg)){this._reportTelemetry({action:"pdfjs.image.image_added",data:{alt_text_modal:!1,alt_text_type:"empty"}});try{this.mlGuessAltText()}catch{}}this.div.focus()}},iAe=function(){if(ye(this,Jv)){this._uiManager.enableWaiting(!0),this._uiManager.imageManager.getFromId(ye(this,Jv)).then(a=>cs(this,Ou,OQ).call(this,a,!0)).finally(()=>cs(this,Ou,zQ).call(this));return}if(ye(this,iE)){const a=ye(this,iE);Kt(this,iE,null),this._uiManager.enableWaiting(!0),Kt(this,oI,this._uiManager.imageManager.getFromUrl(a).then(i=>cs(this,Ou,OQ).call(this,i)).finally(()=>cs(this,Ou,zQ).call(this)));return}if(ye(this,lI)){const a=ye(this,lI);Kt(this,lI,null),this._uiManager.enableWaiting(!0),Kt(this,oI,this._uiManager.imageManager.getFromFile(a).then(i=>cs(this,Ou,OQ).call(this,i)).finally(()=>cs(this,Ou,zQ).call(this)));return}const n=document.createElement("input");n.type="file",n.accept=_te.supportedTypesStr;const r=this._uiManager._signal;Kt(this,oI,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}}),cs(this,Ou,OQ).call(this,i)}a()},{signal:r}),n.addEventListener("cancel",()=>{this.remove(),a()},{signal:r})}).finally(()=>cs(this,Ou,zQ).call(this))),n.click()},wXe=function(){const{div:n}=this;let{width:r,height:a}=ye(this,bg);const[i,l]=this.pageDimensions,o=.75;if(this.width)r=this.width*i,a=this.height*l;else if(r>o*i||a>o*l){const h=Math.min(o*i/r,o*l/a);r*=h,a*=h}const[c,d]=this.parentDimensions;this.setDims(r*c/i,a*d/l),this._uiManager.enableWaiting(!1);const u=Kt(this,Z5,document.createElement("canvas"));u.setAttribute("role","img"),this.addContainer(u),(!this._uiManager.useNewAltTextWhenAddingImage||!this._uiManager.useNewAltTextFlow||this.annotationElementId)&&(n.hidden=!1),cs(this,Ou,jXe).call(this,r,a),cs(this,Ou,yrs).call(this),ye(this,tG)||(this.parent.addUndoableEditor(this),Kt(this,tG,!0)),this._reportTelemetry({action:"inserted_image"}),ye(this,eG)&&u.setAttribute("aria-label",ye(this,eG))},xrs=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,X5)!==null&&clearTimeout(ye(this,X5)),Kt(this,X5,setTimeout(()=>{Kt(this,X5,null),cs(this,Ou,jXe).call(this,n,r)},200))},oAe=function(n,r){const{width:a,height:i}=ye(this,bg);let l=a,o=i,c=ye(this,bg);for(;l>2*n||o>2*r;){const d=l,u=o;l>2*n&&(l=l>=16384?Math.floor(l/2)-1:Math.ceil(l/2)),o>2*r&&(o=o>=16384?Math.floor(o/2)-1:Math.ceil(o/2));const h=new OffscreenCanvas(l,o);h.getContext("2d").drawImage(c,0,0,d,u,0,0,l,o),c=h.transferToImageBitmap()}return c},jXe=function(n,r){const a=new yZe,i=Math.ceil(n*a.sx),l=Math.ceil(r*a.sy),o=ye(this,Z5);if(!o||o.width===i&&o.height===l)return;o.width=i,o.height=l;const c=ye(this,Rj)?ye(this,bg):cs(this,Ou,oAe).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)},lAe=function(n){if(n){if(ye(this,Rj)){const i=this._uiManager.imageManager.getSvgUrl(ye(this,Jv));if(i)return i}const r=document.createElement("canvas");return{width:r.width,height:r.height}=ye(this,bg),r.getContext("2d").drawImage(ye(this,bg),0,0),r.toDataURL()}if(ye(this,Rj)){const[r,a]=this.pageDimensions,i=Math.round(this.width*r*$L.PDF_TO_CSS_UNITS),l=Math.round(this.height*a*$L.PDF_TO_CSS_UNITS),o=new OffscreenCanvas(i,l);return o.getContext("2d").drawImage(ye(this,bg),0,0,ye(this,bg).width,ye(this,bg).height,0,0,i,l),o.transferToImageBitmap()}return structuredClone(ye(this,bg))},yrs=function(){this._uiManager._signal&&(Kt(this,oE,new ResizeObserver(n=>{const r=n[0].contentRect;r.width&&r.height&&cs(this,Ou,xrs).call(this,r.width,r.height)})),ye(this,oE).observe(this.div),this._uiManager._signal.addEventListener("abort",()=>{var n;(n=ye(this,oE))==null||n.disconnect(),Kt(this,oE,null)},{once:!0}))},vrs=function(n){var d;const{rect:r,pageIndex:a,accessibilityData:{altText:i}}=this._initialData,l=n.rect.every((u,h)=>Math.abs(u-r[h])<1),o=n.pageIndex===a,c=(((d=n.accessibilityData)==null?void 0:d.alt)||"")===i;return{isSame:l&&o&&c,isSameAltText:c}},Nr(_te,"_type","stamp"),Nr(_te,"_editorType",Dd.STAMP);let _Xe=_te;var Mz,sG,Q5,cI,lE,Dj,dI,nG,rG,i1,cE,Ll,uI,Nb,brs,kXe,SXe,CXe,cAe;const mS=class mS{constructor({uiManager:t,pageIndex:n,div:r,structTreeLayer:a,accessibilityManager:i,annotationLayer:l,drawLayer:o,textLayer:c,viewport:d,l10n:u}){vs(this,Nb);vs(this,Mz);vs(this,sG,!1);vs(this,Q5,null);vs(this,cI,null);vs(this,lE,null);vs(this,Dj,new Map);vs(this,dI,!1);vs(this,nG,!1);vs(this,rG,!1);vs(this,i1,null);vs(this,cE,null);vs(this,Ll);const h=[...ye(mS,uI).values()];if(!mS._initialized){mS._initialized=!0;for(const m of h)m.initialize(u,t)}t.registerEditorTypes(h),Kt(this,Ll,t),this.pageIndex=n,this.div=r,Kt(this,Mz,i),Kt(this,Q5,l),this.viewport=d,Kt(this,i1,c),this.drawLayer=o,this._structTree=a,ye(this,Ll).addLayer(this)}get isEmpty(){return ye(this,Dj).size===0}get isInvisible(){return this.isEmpty&&ye(this,Ll).getMode()===Dd.NONE}updateToolbar(t){ye(this,Ll).updateToolbar(t)}updateMode(t=ye(this,Ll).getMode()){switch(cs(this,Nb,cAe).call(this),t){case Dd.NONE:this.disableTextSelection(),this.togglePointerEvents(!1),this.toggleAnnotationLayerPointerEvents(!0),this.disableClick();return;case Dd.INK:this.addInkEditorIfNeeded(!1),this.disableTextSelection(),this.togglePointerEvents(!0),this.disableClick();break;case Dd.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(mS,uI).values())n.toggle(`${r._type}Editing`,t===r._editorType);this.div.hidden=!1}hasTextLayer(t){var n;return t===((n=ye(this,i1))==null?void 0:n.div)}addInkEditorIfNeeded(t){if(ye(this,Ll).getMode()!==Dd.INK)return;if(!t){for(const r of ye(this,Dj).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,Q5))==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,Dj).values())r.enableEditing(),r.show(!0),r.annotationElementId&&(ye(this,Ll).removeChangedExistingAnnotation(r),t.add(r.annotationElementId));if(!ye(this,Q5))return;const n=ye(this,Q5).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;Kt(this,rG,!0),this.div.tabIndex=-1,this.togglePointerEvents(!1);const t=new Map,n=new Map;for(const i of ye(this,Dj).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,Q5)){const i=ye(this,Q5).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()}}cs(this,Nb,cAe).call(this),this.isEmpty&&(this.div.hidden=!0);const{classList:r}=this.div;for(const i of ye(mS,uI).values())r.remove(`${i._type}Editing`);this.disableTextSelection(),this.toggleAnnotationLayerPointerEvents(!0),Kt(this,rG,!1)}getEditableAnnotation(t){var n;return((n=ye(this,Q5))==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,i1))!=null&&t.div&&!ye(this,cE)){Kt(this,cE,new AbortController);const n=ye(this,Ll).combinedSignal(ye(this,cE));ye(this,i1).div.addEventListener("pointerdown",cs(this,Nb,brs).bind(this),{signal:n}),ye(this,i1).div.classList.add("highlighting")}}disableTextSelection(){var t;this.div.tabIndex=0,(t=ye(this,i1))!=null&&t.div&&ye(this,cE)&&(ye(this,cE).abort(),Kt(this,cE,null),ye(this,i1).div.classList.remove("highlighting"))}enableClick(){if(ye(this,cI))return;Kt(this,cI,new AbortController);const t=ye(this,Ll).combinedSignal(ye(this,cI));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,cI))==null||t.abort(),Kt(this,cI,null)}attach(t){ye(this,Dj).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,Dj).delete(t.id),(n=ye(this,Mz))==null||n.removePointerInTextLayer(t.contentDiv),!ye(this,rG)&&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,nG)||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,lE)&&(t._focusEventsAllowed=!1,Kt(this,lE,setTimeout(()=>{Kt(this,lE,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,Mz))==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,Nb,kXe))==null?void 0:t.canCreateNewEmptyEditor()}pasteEditor(t,n){ye(this,Ll).updateToolbar(t),ye(this,Ll).updateMode(t);const{offsetX:r,offsetY:a}=cs(this,Nb,CXe).call(this),i=this.getNextId(),l=cs(this,Nb,SXe).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(mS,uI).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=cs(this,Nb,SXe).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(cs(this,Nb,CXe).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}=S_.platform;if(!(t.button!==0||t.ctrlKey&&n)&&t.target===this.div&&ye(this,dI)){if(Kt(this,dI,!1),!ye(this,sG)){Kt(this,sG,!0);return}if(ye(this,Ll).getMode()===Dd.STAMP){ye(this,Ll).unselectAll();return}this.createAndAddNewEditor(t,!1)}}pointerdown(t){if(ye(this,Ll).getMode()===Dd.HIGHLIGHT&&this.enableTextSelection(),ye(this,dI)){Kt(this,dI,!1);return}const{isMac:n}=S_.platform;if(t.button!==0||t.ctrlKey&&n||t.target!==this.div)return;Kt(this,dI,!0);const r=ye(this,Ll).getActive();Kt(this,sG,!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,lE)&&(clearTimeout(ye(this,lE)),Kt(this,lE,null));for(const r of ye(this,Dj).values())(n=ye(this,Mz))==null||n.removePointerInTextLayer(r.contentDiv),r.setParent(null),r.isAttachedToDOM=!1,r.div.remove();this.div=null,ye(this,Dj).clear(),ye(this,Ll).removeLayer(this)}render({viewport:t}){this.viewport=t,pB(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(),cs(this,Nb,cAe).call(this);const n=this.viewport.rotation,r=t.rotation;if(this.viewport=t,pB(this.div,{rotation:r}),n!==r)for(const a of ye(this,Dj).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}};Mz=new WeakMap,sG=new WeakMap,Q5=new WeakMap,cI=new WeakMap,lE=new WeakMap,Dj=new WeakMap,dI=new WeakMap,nG=new WeakMap,rG=new WeakMap,i1=new WeakMap,cE=new WeakMap,Ll=new WeakMap,uI=new WeakMap,Nb=new WeakSet,brs=function(t){ye(this,Ll).unselectAll();const{target:n}=t;if(n===ye(this,i1).div||(n.getAttribute("role")==="img"||n.classList.contains("endOfContent"))&&ye(this,i1).div.contains(n)){const{isMac:r}=S_.platform;if(t.button!==0||t.ctrlKey&&r)return;ye(this,Ll).showAllEditors("highlight",!0,!0),ye(this,i1).div.classList.add("free"),this.toggleDrawing(),xPe.startHighlighting(this,ye(this,Ll).direction==="ltr",{target:ye(this,i1).div,x:t.x,y:t.y}),ye(this,i1).div.addEventListener("pointerup",()=>{ye(this,i1).div.classList.remove("free"),this.toggleDrawing(!0)},{once:!0,signal:ye(this,Ll)._signal}),t.preventDefault()}},kXe=function(){return ye(mS,uI).get(ye(this,Ll).getMode())},SXe=function(t){const n=ye(this,Nb,kXe);return n?new n.prototype.constructor(t):null},CXe=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}},cAe=function(){Kt(this,nG,!0);for(const t of ye(this,Dj).values())t.isEmpty()&&t.remove();Kt(this,nG,!1)},Nr(mS,"_initialized",!1),vs(mS,uI,new Map([nXe,hXe,_Xe,xPe].map(t=>[t._editorType,t])));let NXe=mS;var J5,cae,Ty,dE,dae,EXe,kB,TXe,_rs;const Zv=class Zv{constructor({pageIndex:t}){vs(this,kB);vs(this,J5,null);vs(this,cae,0);vs(this,Ty,new Map);vs(this,dE,new Map);this.pageIndex=t}setParent(t){if(!ye(this,J5)){Kt(this,J5,t);return}if(ye(this,J5)!==t){if(ye(this,Ty).size>0)for(const n of ye(this,Ty).values())n.remove(),t.append(n);Kt(this,J5,t)}}static get _svgFactory(){return eh(this,"_svgFactory",new Oot)}draw(t,n,r,a=!1){const i=X0(this,cae)._++,l=cs(this,kB,TXe).call(this,t.box);l.classList.add(...t.classNamesForDrawing);const o=Zv._svgFactory.createElement("defs");l.append(o);const c=Zv._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,dE).set(i,c);const u=cs(this,kB,_rs).call(this,o,d),h=Zv._svgFactory.createElement("use");return l.append(h),l.setAttribute("fill",n),l.setAttribute("fill-opacity",r),h.setAttribute("href",`#${d}`),ye(this,Ty).set(i,l),{id:i,clipPathId:`url(#${u})`}}drawOutline(t){const n=X0(this,cae)._++,r=cs(this,kB,TXe).call(this,t.box);r.classList.add(...t.classNamesForOutlining);const a=Zv._svgFactory.createElement("defs");r.append(a);const i=Zv._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=Zv._svgFactory.createElement("mask");a.append(u),o=`mask_p${this.pageIndex}_${n}`,u.setAttribute("id",o),u.setAttribute("maskUnits","objectBoundingBox");const h=Zv._svgFactory.createElement("rect");u.append(h),h.setAttribute("width","1"),h.setAttribute("height","1"),h.setAttribute("fill","white");const m=Zv._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=Zv._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,Ty).set(n,r),n}finalizeLine(t,n){const r=ye(this,dE).get(t);ye(this,dE).delete(t),this.updateBox(t,n.box),r.setAttribute("d",n.toSVGPath())}updateLine(t,n){ye(this,Ty).get(t).firstChild.firstChild.setAttribute("d",n.toSVGPath())}updatePath(t,n){ye(this,dE).get(t).setAttribute("d",n.toSVGPath())}updateBox(t,n){var r;cs(r=Zv,dae,EXe).call(r,ye(this,Ty).get(t),n)}show(t,n){ye(this,Ty).get(t).classList.toggle("hidden",!n)}rotate(t,n){ye(this,Ty).get(t).setAttribute("data-main-rotation",n)}changeColor(t,n){ye(this,Ty).get(t).setAttribute("fill",n)}changeOpacity(t,n){ye(this,Ty).get(t).setAttribute("fill-opacity",n)}addClass(t,n){ye(this,Ty).get(t).classList.add(n)}removeClass(t,n){ye(this,Ty).get(t).classList.remove(n)}getSVGRoot(t){return ye(this,Ty).get(t)}remove(t){ye(this,dE).delete(t),ye(this,J5)!==null&&(ye(this,Ty).get(t).remove(),ye(this,Ty).delete(t))}destroy(){Kt(this,J5,null);for(const t of ye(this,Ty).values())t.remove();ye(this,Ty).clear(),ye(this,dE).clear()}};J5=new WeakMap,cae=new WeakMap,Ty=new WeakMap,dE=new WeakMap,dae=new WeakSet,EXe=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}%`},kB=new WeakSet,TXe=function(t){var r;const n=Zv._svgFactory.create(1,1,!0);return ye(this,J5).append(n),n.setAttribute("aria-hidden",!0),cs(r=Zv,dae,EXe).call(r,n,t),n},_rs=function(t,n){const r=Zv._svgFactory.createElement("clipPath");t.append(r);const a=`clip_${n}`;r.setAttribute("id",a),r.setAttribute("clipPathUnits","objectBoundingBox");const i=Zv._svgFactory.createElement("use");return r.append(i),i.setAttribute("href",`#${n}`),i.classList.add("clip"),a},vs(Zv,dae);let AXe=Zv;cd.AbortException;cd.AnnotationEditorLayer;cd.AnnotationEditorParamsType;cd.AnnotationEditorType;cd.AnnotationEditorUIManager;cd.AnnotationLayer;cd.AnnotationMode;cd.ColorPicker;cd.DOMSVGFactory;cd.DrawLayer;cd.FeatureTest;var Bot=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 yPe=cd.getDocument;cd.getFilenameFromUrl;cd.getPdfFilenameFromUrl;cd.getXfaPageViewport;cd.isDataScheme;cd.isPdfFile;cd.noContextMenu;cd.normalizeUnicode;cd.setLayerDimensions;cd.shadow;cd.version;const $ot="/assets/pdf.worker.min-GB3t0DcA.mjs";Bot.workerSrc=$ot;const DZn=({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 yPe({data:u}).promise;if(o)return;c.innerHTML="";for(let m=1;m<=h.numPages;m+=1){const f=await h.getPage(m);if(o)return;const g=f.getViewport({scale:t}),x=document.createElement("canvas");x.width=Math.floor(g.width),x.height=Math.floor(g.height),x.className="mx-auto w-full max-w-[900px] rounded-md border border-border bg-white shadow-sm";const y=x.getContext("2d");y&&(c.appendChild(x),await f.render({canvasContext:y,viewport:g}).promise)}}catch(u){o||l((u==null?void 0:u.message)||"Could not render the preview")}finally{o||a(!1)}})(),()=>{o=!0})},[s,t]),e.jsxs("div",{className:"relative h-full overflow-y-auto bg-muted/40 p-4",children:[r&&e.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-background/70",children:e.jsx(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 f9({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}=bs(),d=j.useRef(null),[u,h]=j.useState(!1),m=async f=>{if(!(!f||!c)){if(!f.type.startsWith("image/")){re.error("Please choose an image file");return}if(f.size>20*1024*1024){re.error("That photo is larger than 20 MB");return}h(!0);try{const g=await IKn(c.id,f,r);n(g),re.success("Photo uploaded")}catch(g){re.error((g==null?void 0:g.message)||"Upload failed")}finally{h(!1),d.current&&(d.current.value="")}}};return e.jsxs("div",{className:Pt("space-y-2",o),children:[e.jsx(ee,{className:"text-xs",children:s}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:Pt("relative shrink-0 overflow-hidden border bg-muted",l?"h-16 w-16 rounded-full":"h-16 w-24 rounded-md"),children:t?e.jsx("img",{src:t,alt:s,className:"h-full w-full object-cover"}):e.jsx("div",{className:"flex h-full w-full items-center justify-center text-muted-foreground",children:e.jsx(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(Sv,{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(pr,{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 FZn({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(Sn,{checked:s.enabled,onCheckedChange:n=>t({enabled:n})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Adds a second agent to the cover, the About page, and the closing contact card."})]}),s.enabled&&e.jsxs(Ie,{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Name"}),e.jsx(pe,{value:s.name,onChange:n=>t({name:n.target.value}),placeholder:"Jordan Ellis"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Title"}),e.jsx(pe,{value:s.title||"",onChange:n=>t({title:n.target.value}),placeholder:"Co-listing agent"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Phone"}),e.jsx(pe,{value:s.phone||"",onChange:n=>t({phone:n.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Email"}),e.jsx(pe,{value:s.email||"",onChange:n=>t({email:n.target.value})})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Brokerage"}),e.jsx(pe,{value:s.brokerageName||"",onChange:n=>t({brokerageName:n.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"License #"}),e.jsx(pe,{value:s.licenseNumber||"",onChange:n=>t({licenseNumber:n.target.value})})]})]}),e.jsx(f9,{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(Ls,{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 OZn({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(Ie,{className:"grid gap-2 sm:grid-cols-2",children:mZe.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(ca,{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 zZn={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}]},BZn=["cover","welcome","agent","overview","closing"];function $Zn({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(Ie,{children:e.jsx(UB,{type:"multiple",className:"w-full",children:BZn.filter(i=>i==="cover"||!n.has(i)).map(i=>{const l=dts(s,i);return e.jsxs(h6,{value:i,children:[e.jsx(m6,{className:"text-sm",children:tHn[i]}),e.jsxs(f6,{className:"space-y-3 pt-1",children:[zZn[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(Ls,{rows:2,value:l[o.key]||"",placeholder:QYe[i][o.key],onChange:c=>r(i,o.key,c.target.value)}):e.jsx(pe,{value:l[o.key]||"",placeholder:QYe[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(Ax,{className:"h-3.5 w-3.5"})," Reset to default wording"]})]})]},i)})})})]})}function UZn({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,xot(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(c2,{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(Ie,{className:"space-y-4",children:[e.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:i$e.map(o=>e.jsxs("button",{type:"button",onClick:()=>a(o.layout),className:"rounded-lg border p-3 text-left transition-colors hover:border-primary hover:bg-muted/50",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-sm font-medium",children:o.name}),e.jsx(dn,{className:"h-3.5 w-3.5 text-muted-foreground"})]}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:o.description})]},o.layout))}),n.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(Vc,{}),e.jsx(UB,{type:"multiple",className:"w-full",children:n.map((o,c)=>{var d,u,h;return e.jsxs(h6,{value:o.id,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sn,{checked:o.enabled,onCheckedChange:m=>r(o.id,{enabled:m})}),e.jsx(m6,{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=i$e.find(m=>m.layout===o.layout))==null?void 0:u.name),e.jsx($e,{variant:"secondary",className:"text-[10px]",children:(h=i$e.find(m=>m.layout===o.layout))==null?void 0:h.name})]})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7",disabled:c===0,onClick:()=>l(o.id,-1),children:e.jsx(Zf,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7",disabled:c===n.length-1,onClick:()=>l(o.id,1),children:e.jsx(Dg,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7 text-destructive",onClick:()=>i(o.id),children:e.jsx(Hn,{className:"h-3.5 w-3.5"})})]}),e.jsxs(f6,{className:"space-y-3 pt-2",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Placement"}),e.jsxs(ms,{value:o.placement,onValueChange:m=>r(o.id,{placement:m}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"after-agent",children:'After "About your agent"'}),e.jsx(Ge,{value:"end",children:"Before the closing page"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Style"}),e.jsxs("div",{className:"flex h-10 items-center gap-2 rounded-md border px-3",children:[e.jsx(Sn,{checked:o.dark,onCheckedChange:m=>r(o.id,{dark:m})}),e.jsx("span",{className:"text-sm",children:"Dark background"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Eyebrow"}),e.jsx(pe,{value:o.kicker,onChange:m=>r(o.id,{kicker:m.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Headline"}),e.jsx(pe,{value:o.headline,onChange:m=>r(o.id,{headline:m.target.value})})]}),o.layout!=="statement"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Subhead"}),e.jsx(pe,{value:o.subhead,onChange:m=>r(o.id,{subhead:m.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Body copy"}),e.jsx(Ls,{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(f9,{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(Hn,{className:"h-3.5 w-3.5"})})]},f)),e.jsxs($,{variant:"outline",size:"sm",className:"gap-2",disabled:o.bullets.length>=7,onClick:()=>r(o.id,{bullets:[...o.bullets,""]}),children:[e.jsx(dn,{className:"h-3.5 w-3.5"})," Add item"]})]}),o.layout==="testimonials"&&e.jsxs("div",{className:"space-y-3 rounded-lg border bg-muted/30 p-3",children:[e.jsx(ee,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Testimonials (up to 4)"}),o.testimonials.map((m,f)=>e.jsxs("div",{className:"space-y-2 rounded-md border bg-background p-3",children:[e.jsx(Ls,{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(Hn,{className:"h-3.5 w-3.5"})," Remove"]})]},f)),e.jsxs($,{variant:"outline",size:"sm",className:"gap-2",disabled:o.testimonials.length>=4,onClick:()=>r(o.id,{testimonials:[...o.testimonials,{quote:"",name:"",detail:""}]}),children:[e.jsx(dn,{className:"h-3.5 w-3.5"})," Add testimonial"]})]}),o.layout==="stats"&&e.jsxs("div",{className:"space-y-2 rounded-lg border bg-muted/30 p-3",children:[e.jsx(ee,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Stats (up to 4)"}),o.stats.map((m,f)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pe,{className:"w-28",value:m.value,placeholder:"27",onChange:g=>{const x=[...o.stats];x[f]={...m,value:g.target.value},r(o.id,{stats:x})}}),e.jsx(pe,{value:m.label,placeholder:"Homes sold",onChange:g=>{const x=[...o.stats];x[f]={...m,label:g.target.value},r(o.id,{stats:x})}}),e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive",onClick:()=>r(o.id,{stats:o.stats.filter((g,x)=>x!==f)}),children:e.jsx(Hn,{className:"h-3.5 w-3.5"})})]},f)),e.jsxs($,{variant:"outline",size:"sm",className:"gap-2",disabled:o.stats.length>=4,onClick:()=>r(o.id,{stats:[...o.stats,{value:"",label:""}]}),children:[e.jsx(dn,{className:"h-3.5 w-3.5"})," Add stat"]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Only use numbers you can back up — leave a stat blank to hide it."})]})]})]},o.id)})})]})]})]})}function qZn({open:s,onOpenChange:t,defaultName:n,saving:r,onSave:a}){const[i,l]=j.useState(""),[o,c]=j.useState("");return j.useEffect(()=>{s&&(l((n==null?void 0:n.trim())||"My listing presentation"),c(""))},[s,n]),e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Save as a reusable template"}),e.jsx(Pr,{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(Ls,{rows:2,value:o,onChange:d=>c(d.target.value),placeholder:"Luxury version with co-listing agent and testimonials"})]})]}),e.jsxs(Sr,{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 g3t=["welcome","agent","overview","closing"],VZn=()=>{const{id:s}=Wi(),t=Xn(),{user:n}=bs(),{data:r}=N6e(),{data:a,isLoading:i,refetch:l}=JVn(s),{update:o}=cts(),{save:c}=lts(),[d,u]=j.useState(null),[h,m]=j.useState(null),[f,g]=j.useState(tZe(null)),[x,y]=j.useState(uts),[v,b]=j.useState([]),[w,S]=j.useState(JYe),[A,E]=j.useState(eZe),[I,P]=j.useState(null),[R,D]=j.useState(null),[O,U]=j.useState(!1),[W,V]=j.useState(!1),[G,Y]=j.useState(null),[X,ae]=j.useState(!1),[le,ne]=j.useState(!1),[te,J]=j.useState(!1),[ce,_e]=j.useState(!1),[he,ue]=j.useState(!0),[ve,Ee]=j.useState(!1),Se=j.useRef(null);j.useEffect(()=>{if(!a||d)return;u({title:a.title||"",addressLine1:a.property_address_line1||"",city:a.city||"",state:a.state||"",postalCode:a.postal_code||"",listPrice:a.list_price!=null?String(a.list_price):"",beds:a.beds!=null?String(a.beds):"",baths:a.baths!=null?String(a.baths):"",sqft:a.sqft!=null?String(a.sqft):""});const Xe=a.agent_snapshot;m({...r,...Xe||{}}),g(tZe(a.services)),y(hts(a.co_agent)),b(fts(a.custom_pages)),S(a.page_settings&&Object.keys(a.page_settings).length?a.page_settings:JYe),E(a.photo_focal||eZe),P(a.property_photo_path)},[a,r,d]),j.useEffect(()=>{let Xe=!1;return I?uPe(I).then(at=>{Xe||D(at)}):D(null),()=>{Xe=!0}},[I]);const Le=j.useMemo(()=>!a||!d?null:{...a,title:d.title,property_address_line1:d.addressLine1,city:d.city,state:d.state,postal_code:d.postalCode,list_price:d.listPrice?Number(d.listPrice):null,beds:d.beds?Number(d.beds):null,baths:d.baths?Number(d.baths):null,sqft:d.sqft?Number(d.sqft):null,agent_snapshot:h||{},co_agent:x,custom_pages:v,services:f,page_settings:w,photo_focal:A,property_photo_path:I},[a,d,h,x,v,f,w,A,I]),Fe=Xe=>u(at=>at&&{...at,...Xe}),ke=Xe=>m(at=>at&&{...at,...Xe}),Be=Xe=>(w.hidden||[]).includes(Xe),Ne=(Xe,at)=>S(rt=>{const Ke=new Set(rt.hidden||[]);return at?Ke.delete(Xe):Ke.add(Xe),{...rt,hidden:Array.from(Ke)}}),Ae=f.filter(Xe=>Xe.enabled),Ce=1+g3t.filter(Xe=>!Be(Xe)&&Xe!=="overview").length+(Be("overview")?0:1)+Ae.filter(Xe=>Xe.key!=="communication").length+v.filter(Xe=>Xe.enabled).length,Ve=async(Xe=!1)=>{if(Le){_e(!0);try{await o.mutateAsync({id:Le.id,title:Le.title||"Untitled Presentation",property_address_line1:Le.property_address_line1,city:Le.city,state:Le.state,postal_code:Le.postal_code,list_price:Le.list_price,beds:Le.beds,baths:Le.baths,sqft:Le.sqft,agent_snapshot:Le.agent_snapshot,co_agent:Le.co_agent,custom_pages:Le.custom_pages,services:Le.services,page_settings:Le.page_settings,photo_focal:Le.photo_focal,property_photo_path:Le.property_photo_path}),Xe||re.success("Presentation saved")}finally{_e(!1)}}},ze=async Xe=>{if(!(!n||!s)){if(!Xe.type.startsWith("image/")){re.error("Please choose a JPG or PNG photo");return}if(Xe.size>25*1024*1024){re.error("That photo is larger than 25 MB");return}U(!0);try{const at=await PKn(n.id,s,Xe);P(at);const rt=await uPe(at);D(rt?`${rt}${rt.includes("?")?"&":"?"}v=${Date.now()}`:null),await o.mutateAsync({id:s,property_photo_path:at}),re.success("Photo uploaded")}catch(at){re.error((at==null?void 0:at.message)||"Upload failed")}finally{U(!1)}}},qe=async()=>{if(Le){ae(!0);try{const Xe=await mss(hPe(Le,r,R),Le.template_id,I);Y(Xe)}catch(Xe){re.error((Xe==null?void 0:Xe.message)||"Could not build the preview")}finally{ae(!1)}}};j.useEffect(()=>{if(!he||!Le)return;const Xe=setTimeout(()=>{qe()},900);return()=>clearTimeout(Xe)},[he,Le]);const dt=async()=>{if(!(!Le||!n)){if(!Le.property_photo_path){re.error("Add the primary exterior photo before generating the PDF");return}ne(!0);try{await Ve(!0);const Xe=await fss(hPe(Le,r,R),Le.template_id,"print",I);await pss(n.id,Le.id,Xe),await l(),re.success("Presentation downloaded")}catch(Xe){re.error((Xe==null?void 0:Xe.message)||"Could not build the PDF")}finally{ne(!1)}}};return i||!d||!a?e.jsx(Vs,{children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(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:Xe=>Fe({title:Xe.target.value}),className:"h-9 border-none bg-transparent px-0 text-xl font-semibold shadow-none focus-visible:ring-0",placeholder:"Untitled Presentation"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Ae.length," services selected · ",Ce," pages"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{variant:"outline",onClick:()=>Ve(),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(BI,{className:"h-4 w-4"})," Save as template"]}),e.jsxs($,{variant:"outline",onClick:qe,disabled:X,className:"gap-2",children:[X?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Ca,{className:"h-4 w-4"})," Preview"]}),e.jsxs($,{variant:"outline",onClick:async()=>{await Ve(!0),J(!0)},className:"gap-2",children:[e.jsx(mn,{className:"h-4 w-4"})," Email"]}),e.jsxs($,{onClick:dt,disabled:le,className:"gap-2",children:[le?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(xi,{className:"h-4 w-4"}),"Generate PDF"]})]})]}),e.jsxs("div",{className:"grid gap-6 lg:grid-cols-[minmax(0,440px)_minmax(0,1fr)]",children:[e.jsxs(ha,{defaultValue:"property",className:"space-y-4",children:[e.jsxs(ma,{className:"grid w-full grid-cols-4",children:[e.jsx(Zt,{value:"property",children:"Property"}),e.jsx(Zt,{value:"branding",children:"Branding"}),e.jsx(Zt,{value:"plan",children:"Plan"}),e.jsx(Zt,{value:"pages",children:"Pages"})]}),e.jsxs(Xt,{value:"property",className:"space-y-4",children:[e.jsxs(je,{children:[e.jsx(St,{className:"pb-3",children:e.jsx(Et,{className:"text-base",children:"Property address"})}),e.jsxs(Ie,{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Street address"}),e.jsx(pe,{value:d.addressLine1,onChange:Xe=>Fe({addressLine1:Xe.target.value}),placeholder:"1408 Elmwood Drive"})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"col-span-2 space-y-1.5",children:[e.jsx(ee,{children:"City"}),e.jsx(pe,{value:d.city,onChange:Xe=>Fe({city:Xe.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"State"}),e.jsx(pe,{value:d.state,onChange:Xe=>Fe({state:Xe.target.value})})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"ZIP"}),e.jsx(pe,{value:d.postalCode,onChange:Xe=>Fe({postalCode:Xe.target.value})})]}),e.jsx(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:Xe=>Fe({listPrice:Xe.target.value.replace(/[^0-9.]/g,"")}),placeholder:"649000"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Square feet"}),e.jsx(pe,{inputMode:"numeric",value:d.sqft,onChange:Xe=>Fe({sqft:Xe.target.value.replace(/[^0-9]/g,"")})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Beds"}),e.jsx(pe,{inputMode:"numeric",value:d.beds,onChange:Xe=>Fe({beds:Xe.target.value.replace(/[^0-9.]/g,"")})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Baths"}),e.jsx(pe,{inputMode:"numeric",value:d.baths,onChange:Xe=>Fe({baths:Xe.target.value.replace(/[^0-9.]/g,"")})})]})]})]})]}),e.jsxs(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(Ie,{className:"space-y-3",children:[e.jsx("div",{role:"button",tabIndex:0,onClick:()=>{var Xe;return(Xe=Se.current)==null?void 0:Xe.click()},onKeyDown:Xe=>{var at;return Xe.key==="Enter"&&((at=Se.current)==null?void 0:at.click())},onDragOver:Xe=>{Xe.preventDefault(),V(!0)},onDragLeave:()=>V(!1),onDrop:Xe=>{var rt;Xe.preventDefault(),V(!1);const at=(rt=Xe.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(Sv,{className:"h-6 w-6"}),e.jsx("span",{className:"text-sm",children:"Drag & drop the front exterior photo"}),e.jsx("span",{className:"text-xs",children:"or click to browse · JPG or PNG · landscape works best"})]})}),e.jsx("input",{ref:Se,type:"file",accept:"image/*",className:"hidden",onChange:Xe=>{var rt;const at=(rt=Xe.target.files)==null?void 0:rt[0];at&&ze(at),Xe.target.value=""}}),R&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-3 rounded-lg border bg-muted/30 p-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium text-muted-foreground",children:[e.jsx(UJ,{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(Nx,{value:[A.x*100],min:0,max:100,step:1,onValueChange:([Xe])=>E(at=>({...at,x:Xe/100}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Vertical"}),e.jsx(Nx,{value:[A.y*100],min:0,max:100,step:1,onValueChange:([Xe])=>E(at=>({...at,y:Xe/100}))})]})]}),e.jsxs($,{variant:"outline",size:"sm",className:"w-full gap-2",onClick:()=>{var Xe;return(Xe=Se.current)==null?void 0:Xe.click()},disabled:O,children:[e.jsx(ro,{className:"h-4 w-4"})," Replace photo"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This photo anchors the cover and appears on a few key pages — photography, video, the property website, and the closing page."})]})]})]}),e.jsxs(Xt,{value:"branding",className:"space-y-4",children:[e.jsx(OZn,{value:w.theme||KWn,onChange:Xe=>S(at=>({...at,theme:Xe}))}),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(Ie,{className:"space-y-3",children:h&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Edits here apply to this presentation only — your LevelUp profile stays unchanged."}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Name"}),e.jsx(pe,{value:h.name,onChange:Xe=>ke({name:Xe.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Tagline"}),e.jsx(pe,{value:h.tagline||"",onChange:Xe=>ke({tagline:Xe.target.value}),placeholder:"Helping families move with confidence"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Phone"}),e.jsx(pe,{value:h.phone||"",onChange:Xe=>ke({phone:Xe.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Email"}),e.jsx(pe,{value:h.email||"",onChange:Xe=>ke({email:Xe.target.value})})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Website"}),e.jsx(pe,{value:h.website||"",onChange:Xe=>ke({website:Xe.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Brokerage"}),e.jsx(pe,{value:h.brokerageName||"",onChange:Xe=>ke({brokerageName:Xe.target.value})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"License #"}),e.jsx(pe,{value:h.licenseNumber||"",onChange:Xe=>ke({licenseNumber:Xe.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"License state"}),e.jsx(pe,{value:h.licenseState||"",onChange:Xe=>ke({licenseState:Xe.target.value})})]})]}),e.jsx(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:Xe=>ke({brandColor:Xe.target.value}),className:"h-9 w-12 cursor-pointer rounded border bg-transparent"}),e.jsx(pe,{value:h.brandColor,onChange:Xe=>ke({brandColor:Xe.target.value})})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Accent color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:h.accentColor,onChange:Xe=>ke({accentColor:Xe.target.value}),className:"h-9 w-12 cursor-pointer rounded border bg-transparent"}),e.jsx(pe,{value:h.accentColor,onChange:Xe=>ke({accentColor:Xe.target.value})})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Headshot URL"}),e.jsx(pe,{value:h.headshotUrl||"",onChange:Xe=>ke({headshotUrl:Xe.target.value}),placeholder:"Pulled from your profile photo"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Brokerage logo URL"}),e.jsx(pe,{value:h.brokerageLogoUrl||"",onChange:Xe=>ke({brokerageLogoUrl:Xe.target.value})})]}),r&&e.jsxs($,{variant:"outline",size:"sm",className:"w-full gap-2",onClick:()=>m({...r}),children:[e.jsx(ro,{className:"h-4 w-4"})," Reset to my LevelUp profile"]})]})})]}),e.jsx(FZn,{value:x,onChange:Xe=>y(at=>({...at,...Xe}))})]}),e.jsx(Xt,{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(Ie,{children:e.jsx(UB,{type:"multiple",className:"w-full",children:f.slice().sort((Xe,at)=>Xe.order-at.order).map(Xe=>{var at;return e.jsxs(h6,{value:Xe.key,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Sn,{checked:Xe.enabled,onCheckedChange:rt=>g(Ke=>Ke.map(Je=>Je.key===Xe.key?{...Je,enabled:rt}:Je))}),e.jsx(m6,{className:"flex-1 text-left text-sm",children:Xe.title})]}),e.jsxs(f6,{className:"space-y-3 pt-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Headline"}),e.jsx(pe,{value:Xe.title,onChange:rt=>g(Ke=>Ke.map(Je=>Je.key===Xe.key?{...Je,title:rt.target.value}:Je))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Description"}),e.jsx(Ls,{rows:4,value:Xe.body,onChange:rt=>g(Ke=>Ke.map(Je=>Je.key===Xe.key?{...Je,body:rt.target.value}:Je))})]}),!!((at=Xe.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"}),Xe.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(pt=>{var gt;return pt.key===Xe.key?{...pt,options:(gt=pt.options)==null?void 0:gt.map(ss=>ss.key===rt.key?{...ss,enabled:!!Ke}:ss)}:pt}))}),e.jsx("span",{className:"leading-snug",children:rt.label})]},rt.key))]})]})]},Xe.key)})})})]})}),e.jsxs(Xt,{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(Ie,{className:"space-y-3",children:[g3t.map(Xe=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsx("span",{className:"text-sm",children:nHn[Xe]}),e.jsx(Sn,{checked:!Be(Xe),onCheckedChange:at=>Ne(Xe,at)})]},Xe)),e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3 text-sm",children:[e.jsx("div",{className:"font-medium",children:"Page order"}),e.jsxs("ol",{className:"mt-2 space-y-1 text-xs text-muted-foreground",children:[e.jsx("li",{children:"01 · Cover"}),!Be("welcome")&&e.jsx("li",{children:"Marketing commitment"}),!Be("agent")&&e.jsx("li",{children:"About your agent"}),v.filter(Xe=>Xe.enabled&&Xe.placement!=="end").sort((Xe,at)=>Xe.order-at.order).map(Xe=>e.jsx("li",{children:Xe.headline||"Custom page"},Xe.id)),!Be("overview")&&e.jsx("li",{children:"Marketing plan overview"}),Ae.filter(Xe=>Xe.key!=="communication").map(Xe=>e.jsx("li",{children:Xe.title},Xe.key)),v.filter(Xe=>Xe.enabled&&Xe.placement==="end").sort((Xe,at)=>Xe.order-at.order).map(Xe=>e.jsx("li",{children:Xe.headline||"Custom page"},Xe.id)),!Be("closing")&&e.jsx("li",{children:"Communication & closing commitment"})]})]})]})]}),e.jsx($Zn,{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(Ie,{children:e.jsx($,{variant:"outline",size:"sm",className:"w-full",onClick:()=>b(Xe=>[...Xe,{...xot("testimonials",Xe.length),placement:"end"}]),children:`Add a "What they're saying" page`})})]}),e.jsx(UZn,{pages:v,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(Sn,{checked:he,onCheckedChange:ue}),"Auto-update"]})]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:qe,disabled:X,className:"gap-2",children:[X?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(ro,{className:"h-4 w-4"}),"Refresh"]})]}),e.jsx(Ie,{className:"h-[calc(70vh-60px)] p-0",children:G?e.jsx(DZn,{blob:G}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 bg-muted/30 text-center",children:[e.jsx(Ca,{className:"h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Fill in the address, upload the photo, then generate the preview."}),e.jsxs($,{onClick:qe,disabled:X,className:"gap-2",children:[X?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Ca,{className:"h-4 w-4"}),"Generate preview"]})]})})]})]})]}),e.jsx(qZn,{open:ve,onOpenChange:Ee,defaultName:d.title,saving:c.isPending,onSave:async(Xe,at)=>{await c.mutateAsync({name:Xe,description:at||null,template_id:a.template_id,agent_snapshot:h||{},co_agent:x,custom_pages:v,services:f,page_settings:w})}}),e.jsx(xss,{open:te,onOpenChange:J,row:Le,brand:r,photoUrl:R})]})};function HZn(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 wrs="popby_geocode_cache_v1";function GZn(){try{return JSON.parse(localStorage.getItem(wrs)||"{}")}catch{return{}}}function WZn(s){try{localStorage.setItem(wrs,JSON.stringify(s))}catch{}}function KZn({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=GZn(),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[Y,X]=G.features[0].center;w[U]={lat:X,lng:Y},S.set(D.id,{lat:X,lng:Y})}else w[U]=null}catch{}}};await Promise.all([I(),I(),I(),I()]),b||(WZn(w),h(new Map(S)),f(!1))})(),()=>{b=!0}},[c,n,g]);const y=j.useMemo(()=>{if(!n)return[];const b=[];return g.forEach(w=>{const S=u.get(w.id);if(!S)return;const A=HZn(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]),v=b=>{const S=/iPad|iPhone|iPod/.test(navigator.userAgent)?`https://maps.apple.com/?daddr=${b.lat},${b.lng}`:`https://www.google.com/maps/dir/?api=1&destination=${b.lat},${b.lng}`;window.open(S,"_blank","noopener")};return e.jsxs(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(Bq,{className:"h-5 w-5 text-primary"}),"Nearby Now"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Due contacts within driving distance — perfect for errand-day pop-bys."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(ms,{value:String(l),onValueChange:b=>o(Number(b)),children:[e.jsx(us,{className:"w-[110px] h-9",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"2",children:"2 miles"}),e.jsx(Ge,{value:"5",children:"5 miles"}),e.jsx(Ge,{value:"10",children:"10 miles"}),e.jsx(Ge,{value:"25",children:"25 miles"})]})]}),e.jsxs($,{size:"sm",variant:a==="ok"?"outline":"default",onClick:x,disabled:a==="loading",children:[a==="loading"?e.jsx(ro,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Bq,{className:"h-4 w-4 mr-1"}),a==="ok"?"Refresh":"Use my location"]})]})]})}),e.jsxs(Ie,{className:"space-y-3",children:[a==="idle"&&e.jsxs("div",{className:"text-center py-6 text-sm text-muted-foreground",children:[e.jsx(ci,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),"Tap ",e.jsx("span",{className:"font-medium text-foreground",children:'"Use my location"'})," to see who's close by right now."]}),a==="denied"&&e.jsxs("div",{className:"text-center py-6 text-sm text-destructive flex flex-col items-center gap-2",children:[e.jsx(ll,{className:"h-6 w-6"}),"Location access was blocked. Enable it in your browser to use Nearby Now."]}),a==="unavailable"&&e.jsx("div",{className:"text-center py-6 text-sm text-muted-foreground",children:"Geolocation isn't available on this device."}),a==="ok"&&!c&&e.jsx("div",{className:"text-center py-6 text-sm text-muted-foreground",children:"Mapping isn't configured yet — ask an admin to add the Mapbox token."}),a==="ok"&&c&&g.length===0&&e.jsx("div",{className:"text-center py-6 text-sm text-muted-foreground",children:"No due contacts have addresses yet. Add street addresses to your sphere to power this."}),a==="ok"&&c&&g.length>0&&m&&y.length===0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(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&&y.length===0&&g.length>0&&e.jsxs("div",{className:"text-center py-6 text-sm text-muted-foreground",children:["No due contacts within ",l," miles. Try widening the radius."]}),y.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs($e,{variant:"secondary",className:"font-medium",children:[y.length," nearby"]}),m&&e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(ro,{className:"h-3 w-3 animate-spin"})," still locating…"]})]}),e.jsx("div",{className:"space-y-2",children:y.map(b=>e.jsxs("div",{className:"flex items-center justify-between gap-3 p-3 rounded-lg bg-card border hover:border-primary/40 transition-colors",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("span",{className:"font-medium truncate",children:[b.first_name," ",b.last_name]}),e.jsx($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:()=>v(b),className:"h-9 w-9",title:"Directions",children:e.jsx(qJ,{className:"h-4 w-4"})}),e.jsxs($,{size:"sm",onClick:()=>t(b),children:[e.jsx(ul,{className:"h-4 w-4 mr-1"}),"Log"]})]})]},b.id))})]})]})]})}const YZn="0dde5abb-0005-4c8c-a471-30d0cbc9e280",ZZn=[{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 XZn(){const s=Xn(),t=SQt(),{data:n}=OBn(),{data:r}=qw(),{data:a}=fit(),{data:i}=rDe(90),{data:l}=R_(),o=qBn(),c=$Bn(),d=BBn(),u=UBn(),{data:h=[],isLoading:m}=st({queryKey:["popby-templates"],queryFn:async()=>{const{data:G,error:Y}=await q.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).eq("category_id",YZn).order("publish_date",{ascending:!1});if(Y)throw Y;const{data:X}=await q.from("template_likes").select("template_id"),{data:ae}=await q.from("template_comments").select("template_id"),le=new Map;X==null||X.forEach(te=>{le.set(te.template_id,(le.get(te.template_id)||0)+1)});const ne=new Map;return ae==null||ae.forEach(te=>{ne.set(te.template_id,(ne.get(te.template_id)||0)+1)}),(G||[]).map(te=>({...te,likesCount:le.get(te.id)||0,commentsCount:ne.get(te.id)||0}))}}),f=G=>{const Y=l==null?void 0:l.find(X=>X.id===G);return Y?`${Y.first_name} ${Y.last_name||""}`.trim():"Unknown"},g=G=>{if(!G)return null;const Y=n==null?void 0:n.find(X=>X.id===G);return(Y==null?void 0:Y.name)||null},[x,y]=j.useState(null),[v,b]=j.useState(!1),[w,S]=j.useState(!1),[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),y(null),P({popby_item_id:"",notes:""}))},U=async()=>{R.name.trim()&&(await d.mutateAsync({name:R.name.trim(),description:R.description.trim()||void 0}),E(!1),D({name:"",description:""}))},W=async(G,Y)=>{await u.mutateAsync({relationship_type_id:G,frequency_days:parseInt(Y)})},V=G=>{var X;const Y=a==null?void 0:a.find(ae=>ae.relationship_type_id===G);return((X=Y==null?void 0:Y.frequency_days)==null?void 0:X.toString())||"90"};return e.jsx(Vs,{title:"Popbys",description:"Drop off gifts to stay top of mind",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Popbys"}),e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded border border-amber-500 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"Beta"})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsx(je,{children:e.jsxs(Ie,{className:"p-4 text-center",children:[e.jsx("div",{className:"text-3xl font-bold text-primary",children:o.thisWeekCount}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"This Week"})]})}),e.jsx(je,{children:e.jsxs(Ie,{className:"p-4 text-center",children:[e.jsx("div",{className:"text-3xl font-bold text-emerald-500",children:o.thisMonthCount}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"This Month"})]})}),e.jsx(je,{children:e.jsxs(Ie,{className:"p-4 text-center",children:[e.jsx("div",{className:"text-3xl font-bold text-amber-500",children:o.dueCount}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Due Now"})]})})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs($,{onClick:()=>s("/mission-control/popbys/map"),children:[e.jsx(ci,{className:"h-4 w-4 mr-2"}),"View Map"]}),e.jsxs($,{variant:"outline",onClick:()=>S(!0),children:[e.jsx(Nd,{className:"h-4 w-4 mr-2"}),"Frequency Settings"]}),e.jsxs($,{variant:"outline",onClick:()=>E(!0),children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Add Popby Idea"]})]}),e.jsxs(ha,{defaultValue:"due",children:[e.jsxs(ma,{children:[e.jsx(Zt,{value:"due",children:"Due for Popby"}),e.jsx(Zt,{value:"activity",children:"Recent Activity"}),e.jsx(Zt,{value:"library",children:"Popby Library"}),e.jsx(Zt,{value:"templates",children:"Popby Templates"})]}),e.jsxs(Xt,{value:"due",className:"space-y-4 mt-4",children:[e.jsx(KZn,{contacts:t||[],onLogPopby:G=>{y(G),b(!0)}}),!t||t.length===0?e.jsx(je,{children:e.jsxs(Ie,{className:"p-8 text-center text-muted-foreground",children:[e.jsx(ul,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No contacts due for a popby right now!"}),e.jsx("p",{className:"text-sm mt-1",children:"Great job staying connected."})]})}):e.jsx("div",{className:"space-y-3",children:t.map(G=>e.jsx(je,{className:"hover:shadow-md transition-shadow",children:e.jsx(Ie,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"font-medium",children:[G.first_name," ",G.last_name]}),G.daysOverdue>0&&e.jsxs($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:[nX(G).hasAddress&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ci,{className:"h-3 w-3"}),nX(G).city||nX(G).line,nX(G).isSecondary&&e.jsxs("span",{className:"text-xs",children:["(",nX(G).label,")"]})]}),G.tags&&G.tags.length>0&&e.jsx("span",{children:G.tags.map(Y=>{var X;return(X=Y.relationship_type)==null?void 0:X.name}).join(", ")})]}),G.lastPopby&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Last popby: ",en(new Date(G.lastPopby),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[G.phone&&e.jsx($,{size:"sm",variant:"ghost",asChild:!0,children:e.jsx("a",{href:`tel:${G.phone}`,children:e.jsx(Da,{className:"h-4 w-4"})})}),e.jsxs($,{size:"sm",onClick:()=>{y(G),b(!0)},children:[e.jsx(Wl,{className:"h-4 w-4 mr-1"}),"Log Popby"]})]})]})})},G.id))})]}),e.jsx(Xt,{value:"activity",className:"space-y-4 mt-4",children:!i||i.length===0?e.jsx(je,{children:e.jsxs(Ie,{className:"p-8 text-center text-muted-foreground",children:[e.jsx(da,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No popby activity yet!"}),e.jsx("p",{className:"text-sm mt-1",children:"Start logging popbys to see your history here."})]})}):e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-lg",children:"Recent Popby Log"})}),e.jsx(Ie,{className:"space-y-3",children:i.map(G=>e.jsxs("div",{className:"flex items-start gap-3 pb-3 border-b last:border-0 last:pb-0",children:[e.jsx("div",{className:"h-10 w-10 rounded-full bg-orange-500/10 flex items-center justify-center",children:e.jsx(ul,{className:"h-5 w-5 text-orange-500"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-medium",children:f(G.contact_id)}),g(G.popby_item_id)&&e.jsx($e,{variant:"secondary",className:"text-xs",children:g(G.popby_item_id)})]}),e.jsx("div",{className:"text-sm text-muted-foreground",children:en(new Date(G.completed_at),"MMM d, yyyy h:mm a")}),G.notes&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:G.notes})]})]},G.id))})]})}),e.jsx(Xt,{value:"library",className:"space-y-4 mt-4",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[n==null?void 0:n.map(G=>e.jsx(je,{children:e.jsx(Ie,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(ul,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-medium",children:G.name}),G.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:G.description}),!G.owner_user_id&&e.jsx($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(Ie,{className:"p-4 flex items-center justify-center h-full min-h-[100px]",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(dn,{className:"h-8 w-8 mx-auto mb-2"}),e.jsx("p",{children:"Add New Popby Idea"})]})})})]})}),e.jsxs(Xt,{value:"templates",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:[h.length," template",h.length!==1?"s":""," found"]}),m&&e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6",children:[...Array(4)].map((G,Y)=>e.jsx(je,{children:e.jsxs(Ie,{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"})]})]})},Y))}),!m&&h.length===0&&e.jsx(je,{children:e.jsxs(Ie,{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(Ie,{className:"p-4 flex flex-col",children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 mb-1",children:G.name}),G.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3 flex-1",children:zte(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(qy,{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:Y=>{Y.stopPropagation(),s(`/templates/${G.id}`)},children:[e.jsx(Fr,{className:"h-4 w-4"}),"View Template"]})]})]},G.id))})]})]}),e.jsx(zs,{open:v,onOpenChange:b,children:e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsxs(Bs,{children:["Log Popby for ",x==null?void 0:x.first_name," ",x==null?void 0:x.last_name]})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Popby Item (optional)"}),e.jsxs(ms,{value:I.popby_item_id,onValueChange:G=>P(Y=>({...Y,popby_item_id:G})),children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Select a popby item..."})}),e.jsx(hs,{children:n==null?void 0:n.map(G=>e.jsx(Ge,{value:G.id,children:G.name},G.id))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Notes (optional)"}),e.jsx(Ls,{placeholder:"Any notes about this popby...",value:I.notes,onChange:G=>P(Y=>({...Y,notes:G.target.value}))})]})]}),e.jsxs(Sr,{children:[e.jsx($,{variant:"outline",onClick:()=>b(!1),children:"Cancel"}),e.jsx($,{onClick:O,disabled:c.isPending,children:"Log Popby"})]})]})}),e.jsx(zs,{open:w,onOpenChange:S,children:e.jsxs(Os,{className:"max-w-md",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Popby Frequency Settings"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set default popby frequency for each relationship type. You can override these per-contact."}),r==null?void 0:r.map(G=>e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsx(ee,{className:"font-medium",children:G.name}),e.jsxs(ms,{value:V(G.id),onValueChange:Y=>W(G.id,Y),children:[e.jsx(us,{className:"w-[180px]",children:e.jsx(fs,{})}),e.jsx(hs,{children:ZZn.map(Y=>e.jsx(Ge,{value:Y.value,children:Y.label},Y.value))})]})]},G.id))]}),e.jsx(Sr,{children:e.jsx($,{onClick:()=>S(!1),children:"Done"})})]})}),e.jsx(zs,{open:A,onOpenChange:E,children:e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Add Popby Idea"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Name *"}),e.jsx(pe,{placeholder:"e.g., Homemade cookies",value:R.name,onChange:G=>D(Y=>({...Y,name:G.target.value}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Description"}),e.jsx(Ls,{placeholder:"Optional description...",value:R.description,onChange:G=>D(Y=>({...Y,description:G.target.value}))})]})]}),e.jsxs(Sr,{children:[e.jsx($,{variant:"outline",onClick:()=>E(!1),children:"Cancel"}),e.jsx($,{onClick:U,disabled:!R.name.trim()||d.isPending,children:"Add Item"})]})]})})]})})}const QZn=z2({property_address:vl().min(1,"Property address is required"),city:vl().optional(),state:vl().optional(),zip:vl().optional(),transaction_type:mtt(["buyer","seller"]),close_date:vl().min(1,"Close date is required"),sale_price:fee().min(0,"Sale price must be positive"),commission_amount:fee().optional(),lead_source_id:vl().optional(),client_type_id:vl().optional(),contact_id:vl().optional(),notes:vl().optional(),is_win:MTs()});function jrs({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=S6e(),m=PWs(),{data:f}=BB(),{data:g}=qw(),{data:x}=R_(),y=v6e(),v=ont(),{data:b}=C6e(),w=(b==null?void 0:b.show_commission)??!0,S=bLe({resolver:_Le(QZn),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 y.mutateAsync({first_name:R,last_name:O,tagIds:[]});U&&(S.setValue("contact_id",U.id),l(""),c(!1),a(!1))},I=async()=>{if(!d.trim())return;const R=await v.mutateAsync(d.trim());R&&(S.setValue("lead_source_id",R.id),u(""))},P=x==null?void 0:x.find(R=>R.id===S.watch("contact_id"));return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-lg max-h-[90vh]",children:[e.jsx(Us,{children:e.jsx(Bs,{children:n?"Edit Transaction":"Add Transaction"})}),e.jsx(uo,{className:"max-h-[70vh] pr-4",children:e.jsx(kLe,{...S,children:e.jsxs("form",{onSubmit:S.handleSubmit(A),className:"space-y-4",children:[e.jsx(jg,{control:S.control,name:"property_address",render:({field:R})=>e.jsxs(Up,{children:[e.jsx(qp,{children:"Property Address *"}),e.jsx(Vp,{children:e.jsx(pe,{placeholder:"123 Main St",...R})}),e.jsx(f_,{})]})}),e.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[e.jsx(jg,{control:S.control,name:"city",render:({field:R})=>e.jsxs(Up,{children:[e.jsx(qp,{children:"City"}),e.jsx(Vp,{children:e.jsx(pe,{placeholder:"City",...R})})]})}),e.jsx(jg,{control:S.control,name:"state",render:({field:R})=>e.jsxs(Up,{children:[e.jsx(qp,{children:"State"}),e.jsx(Vp,{children:e.jsx(pe,{placeholder:"TX",...R})})]})}),e.jsx(jg,{control:S.control,name:"zip",render:({field:R})=>e.jsxs(Up,{children:[e.jsx(qp,{children:"Zip"}),e.jsx(Vp,{children:e.jsx(pe,{placeholder:"75001",...R})})]})})]}),e.jsx(jg,{control:S.control,name:"transaction_type",render:({field:R})=>e.jsxs(Up,{children:[e.jsx(qp,{children:"Transaction Type *"}),e.jsxs(ms,{onValueChange:R.onChange,value:R.value,children:[e.jsx(Vp,{children:e.jsx(us,{children:e.jsx(fs,{placeholder:"Select type"})})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"buyer",children:"Buyer"}),e.jsx(Ge,{value:"seller",children:"Seller"})]})]}),e.jsx(f_,{})]})}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx(jg,{control:S.control,name:"close_date",render:({field:R})=>e.jsxs(Up,{children:[e.jsx(qp,{children:"Close Date *"}),e.jsx(Vp,{children:e.jsx(pe,{type:"date",...R})}),e.jsx(f_,{})]})}),e.jsx(jg,{control:S.control,name:"sale_price",render:({field:R})=>e.jsxs(Up,{children:[e.jsx(qp,{children:"Sale Price *"}),e.jsx(Vp,{children:e.jsx(pe,{type:"number",placeholder:"0",...R,onChange:D=>R.onChange(Number(D.target.value))})}),e.jsx(f_,{})]})})]}),w&&e.jsx(jg,{control:S.control,name:"commission_amount",render:({field:R})=>e.jsxs(Up,{children:[e.jsx(qp,{children:"Commission"}),e.jsx(Vp,{children:e.jsx(pe,{type:"number",placeholder:"0",...R,value:R.value??"",onChange:D=>R.onChange(D.target.value?Number(D.target.value):void 0)})})]})}),e.jsx(jg,{control:S.control,name:"lead_source_id",render:({field:R})=>e.jsxs(Up,{children:[e.jsx(qp,{children:"Lead Source"}),e.jsxs(ms,{onValueChange:R.onChange,value:R.value||"",children:[e.jsx(Vp,{children:e.jsx(us,{children:e.jsx(fs,{placeholder:"Select source"})})}),e.jsx(hs,{children:f==null?void 0:f.map(D=>e.jsx(Ge,{value:D.id,children:D.name},D.id))})]})]})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{placeholder:"Add custom source...",value:d,onChange:R=>u(R.target.value),className:"flex-1"}),e.jsx($,{type:"button",variant:"outline",size:"icon",onClick:I,disabled:!d.trim(),children:e.jsx(dn,{className:"h-4 w-4"})})]}),e.jsx(jg,{control:S.control,name:"client_type_id",render:({field:R})=>e.jsxs(Up,{children:[e.jsx(qp,{children:"Client Type"}),e.jsxs(ms,{onValueChange:R.onChange,value:R.value||"",children:[e.jsx(Vp,{children:e.jsx(us,{children:e.jsx(fs,{placeholder:"Select client type"})})}),e.jsx(hs,{children:g==null?void 0:g.map(D=>e.jsx(Ge,{value:D.id,children:D.name},D.id))})]})]})}),e.jsx(jg,{control:S.control,name:"contact_id",render:({field:R})=>e.jsxs(Up,{children:[e.jsx(qp,{children:"Client Contact"}),e.jsxs(Kd,{open:r,onOpenChange:a,children:[e.jsx(Yd,{asChild:!0,children:e.jsx(Vp,{children:e.jsxs($,{variant:"outline",role:"combobox",className:Pt("w-full justify-between",!R.value&&"text-muted-foreground"),children:[P?`${P.first_name} ${P.last_name||""}`.trim():"Select contact",e.jsx(Sw,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})})}),e.jsxs(Od,{className:"w-full p-0",align:"start",children:[e.jsxs(S2,{children:[e.jsx(C2,{placeholder:"Search contacts..."}),e.jsxs(A2,{children:[e.jsx(E2,{children:e.jsxs("div",{className:"p-2 space-y-2",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"No contact found."}),!o&&e.jsxs($,{variant:"outline",size:"sm",className:"w-full",onClick:()=>c(!0),children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Add New Contact"]})]})}),e.jsx(Dw,{children:x==null?void 0:x.map(D=>e.jsxs(m1,{value:`${D.first_name} ${D.last_name||""}`,onSelect:()=>{R.onChange(D.id),a(!1)},children:[e.jsx(ca,{className:Pt("mr-2 h-4 w-4",D.id===R.value?"opacity-100":"opacity-0")}),D.first_name," ",D.last_name||""]},D.id))})]})]}),o&&e.jsxs("div",{className:"p-2 border-t space-y-2",children:[e.jsx(pe,{placeholder:"Enter contact name...",value:i,onChange:D=>l(D.target.value)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{size:"sm",onClick:E,disabled:!i.trim()||y.isPending,children:"Add Contact"}),e.jsx($,{size:"sm",variant:"outline",onClick:()=>{c(!1),l("")},children:"Cancel"})]})]})]})]})]})}),e.jsx(jg,{control:S.control,name:"notes",render:({field:R})=>e.jsxs(Up,{children:[e.jsx(qp,{children:"Notes"}),e.jsx(Vp,{children:e.jsx(Ls,{placeholder:"Any notes about this transaction...",...R})})]})}),e.jsx(jg,{control:S.control,name:"is_win",render:({field:R})=>e.jsxs(Up,{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(qp,{children:"Mark as Win 🏆"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Highlight this as a notable success"})]}),e.jsx(Vp,{children:e.jsx(Sn,{checked:R.value,onCheckedChange:R.onChange})})]})}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{type:"submit",disabled:h.isPending||m.isPending,children:[n?"Update":"Add"," Transaction"]})]})]})})})]})})}function Uot({transactions:s,showCommission:t,isLoading:n,agentNameMap:r,readOnly:a}){const[i,l]=j.useState(null),[o,c]=j.useState(null),[d,u]=j.useState(""),[h,m]=j.useState("all"),[f,g]=j.useState("all"),[x,y]=j.useState("all"),[v,b]=j.useState(!1),w=IWs(),S=S6e(),{data:A}=BB(),{data:E}=qw(),I=FK(),P=O=>{const{id:U,created_at:W,updated_at:V,lead_source:G,client_type:Y,contact:X,...ae}=O;S.mutate(ae)},R=()=>{o&&(w.mutate(o),c(null))},D=s.filter(O=>{var X,ae,le,ne;const U=d===""||O.property_address.toLowerCase().includes(d.toLowerCase())||((ae=(X=O.contact)==null?void 0:X.first_name)==null?void 0:ae.toLowerCase().includes(d.toLowerCase()))||((ne=(le=O.contact)==null?void 0:le.last_name)==null?void 0:ne.toLowerCase().includes(d.toLowerCase())),W=h==="all"||O.transaction_type===h,V=f==="all"||O.lead_source_id===f,G=x==="all"||O.client_type_id===x,Y=!v||O.is_win;return U&&W&&V&&G&&Y});return n?e.jsx(je,{children:e.jsx(Ie,{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(Zr,{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:v?"default":"outline",size:"sm",onClick:()=>b(!v),children:[e.jsx(Im,{className:"h-4 w-4 mr-1"}),"Wins"]})]})]})}),e.jsx(Ie,{children:D.length===0?e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No transactions found"}):I?e.jsx("div",{className:"space-y-3",children:D.map(O=>e.jsxs(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: "}),ggt(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(_p,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>P(O),children:e.jsx(Ha,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>c(O.id),children:e.jsx(Hn,{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(En,{children:[r&&e.jsx(Dt,{children:"Agent"}),e.jsx(Dt,{children:"Property"}),e.jsx(Dt,{children:"Type"}),e.jsx(Dt,{children:"Close Date"}),e.jsx(Dt,{children:"Sale Price"}),t&&e.jsx(Dt,{children:"Commission"}),e.jsx(Dt,{children:"Lead Source"}),e.jsx(Dt,{children:"Client"}),!a&&e.jsx(Dt,{className:"w-[50px]"})]})}),e.jsx(fi,{children:D.map(O=>{var U;return e.jsxs(En,{children:[r&&e.jsx(_t,{className:"font-medium text-sm",children:r[O.owner_user_id]||"Unknown"}),e.jsx(_t,{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(_t,{children:e.jsx($e,{variant:O.transaction_type==="buyer"?"default":"secondary",children:O.transaction_type})}),e.jsx(_t,{children:ggt(O.close_date)}),e.jsx(_t,{children:Xm(O.sale_price)}),t&&e.jsx(_t,{children:O.commission_amount?Xm(O.commission_amount):"-"}),e.jsx(_t,{children:((U=O.lead_source)==null?void 0:U.name)||"-"}),e.jsx(_t,{children:O.contact?`${O.contact.first_name} ${O.contact.last_name||""}`.trim():"-"}),!a&&e.jsx(_t,{children:e.jsxs($u,{children:[e.jsx(Uu,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",children:e.jsx(Jx,{className:"h-4 w-4"})})}),e.jsxs(Au,{align:"end",children:[e.jsxs(ja,{onClick:()=>l(O),children:[e.jsx(_p,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsxs(ja,{onClick:()=>P(O),children:[e.jsx(Ha,{className:"h-4 w-4 mr-2"}),"Duplicate"]}),e.jsxs(ja,{onClick:()=>c(O.id),className:"text-destructive",children:[e.jsx(Hn,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})})]},O.id)})})]})})})]}),e.jsx(jrs,{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 Nrs({goals:s,stats:t,year:n,showCommission:r}){const a=new Date().getMonth()+1,i=new Date().getFullYear()===n?a:12,l=12-i,o=(m,f)=>{if(!f||f===0)return null;const g=Math.min(m/f*100,100),x=Math.max(f-m,0),y=l>0?x/l:0,v=i/12*100,b=g>=v?"ahead":g>=v*.8?"on-track":"behind";return{percent:g,remaining:x,pace:y,status:b}},c=o(t.totalTransactions,s.transactions_goal),d=o(t.totalVolume,s.volume_goal),u=r?o(t.totalCommission,s.gci_goal):null,h=m=>{switch(m){case"ahead":return e.jsxs($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(ZN,{className:"h-3 w-3 mr-1"}),"On Track"]});case"behind":return e.jsxs($e,{variant:"destructive",children:[e.jsx(sC,{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(nh,{className:"h-5 w-5 text-primary"}),e.jsxs(Et,{children:[n," Goals Progress"]})]})}),e.jsx(Ie,{children:e.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[s.transactions_goal&&c&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-medium",children:"Transactions"}),h(c.status)]}),e.jsx(Yi,{value:c.percent,className:"h-2"}),e.jsxs("div",{className:"flex justify-between text-sm text-muted-foreground",children:[e.jsxs("span",{children:[t.totalTransactions," of ",s.transactions_goal]}),e.jsxs("span",{children:[Math.round(c.percent),"%"]})]}),c.remaining>0&&l>0&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Need ",Math.ceil(c.pace),"/month to hit goal"]})]}),s.volume_goal&&d&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-medium",children:"Volume"}),h(d.status)]}),e.jsx(Yi,{value:d.percent,className:"h-2"}),e.jsxs("div",{className:"flex justify-between text-sm text-muted-foreground",children:[e.jsxs("span",{children:[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 JZn={light:"",dark:".dark"},krs=j.createContext(null);function Srs(){const s=j.useContext(krs);if(!s)throw new Error("useChart must be used within a ");return s}const Crs=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(krs.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(eXn,{id:o,config:r}),e.jsx(N_,{children:n})]})})});Crs.displayName="Chart";const eXn=({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(JZn).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},Ars=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}=Srs(),x=j.useMemo(()=>{var A;if(a||!(t!=null&&t.length))return null;const[v]=t,b=`${m||v.dataKey||v.name||"value"}`,w=MXe(g,v,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 y=t.length===1&&r!=="dot";return e.jsxs("div",{ref:f,className:Pt("grid min-w-[8rem] items-start gap-1.5 rounded-lg border border-border/50 bg-background px-2.5 py-1.5 text-xs shadow-xl",n),children:[y?null:x,e.jsx("div",{className:"grid gap-1.5",children:t.map((v,b)=>{const w=`${h||v.name||v.dataKey||"value"}`,S=MXe(g,v,w),A=u||v.payload.fill||v.color;return e.jsx("div",{className:Pt("flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground",r==="dot"&&"items-center"),children:d&&(v==null?void 0:v.value)!==void 0&&v.name?d(v.value,v.name,v,b,v.payload):e.jsxs(e.Fragment,{children:[S!=null&&S.icon?e.jsx(S.icon,{}):!i&&e.jsx("div",{className:Pt("shrink-0 rounded-[2px] border-[--color-border] bg-[--color-bg]",{"h-2.5 w-2.5":r==="dot","w-1":r==="line","w-0 border-[1.5px] border-dashed bg-transparent":r==="dashed","my-0.5":y&&r==="dashed"}),style:{"--color-bg":A,"--color-border":A}}),e.jsxs("div",{className:Pt("flex flex-1 justify-between leading-none",y?"items-end":"items-center"),children:[e.jsxs("div",{className:"grid gap-1.5",children:[y?x:null,e.jsx("span",{className:"text-muted-foreground",children:(S==null?void 0:S.label)||v.name})]}),v.value&&e.jsx("span",{className:"font-mono font-medium tabular-nums text-foreground",children:v.value.toLocaleString()})]})]})},v.dataKey)})})]})});Ars.displayName="ChartTooltip";const tXn=j.forwardRef(({className:s,hideIcon:t=!1,payload:n,verticalAlign:r="bottom",nameKey:a},i)=>{const{config:l}=Srs();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=MXe(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});tXn.displayName="ChartLegend";function MXe(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 Iue=["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 qot({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(Ie,{className:"py-12 text-center text-muted-foreground",children:"Add transactions to see your performance charts"})}):e.jsxs("div",{className:"grid gap-6",children:[n&&e.jsxs(je,{className:"overflow-hidden",children:[e.jsx(St,{children:e.jsx(Et,{className:"text-base",children:"Transactions by Month"})}),e.jsx(Ie,{className:"overflow-hidden",children:e.jsx(Crs,{config:{count:{label:"Transactions",color:"hsl(var(--primary))"}},className:"h-[250px]",children:e.jsx(N_,{width:"100%",height:"100%",children:e.jsxs(LK,{data:s.transactionsByMonth,margin:{top:5,right:10,left:0,bottom:5},children:[e.jsx(gT,{strokeDasharray:"3 3",className:"stroke-muted"}),e.jsx(Ab,{dataKey:"month",tick:{fontSize:11},className:"fill-muted-foreground",interval:0}),e.jsx(Eb,{allowDecimals:!1,tick:{fontSize:12},className:"fill-muted-foreground",width:30}),e.jsx(Cg,{content:e.jsx(Ars,{})}),e.jsx(Fw,{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(Ie,{children:[e.jsx("div",{className:"h-[250px]",children:e.jsx(N_,{width:"100%",height:"100%",children:e.jsxs(CXt,{children:[e.jsx(f3,{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(ZB,{fill:Iue[i%Iue.length]},`cell-${i}`))}),e.jsx(Cg,{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:Iue[i%Iue.length]}}),e.jsx("span",{className:"text-muted-foreground",children:a.name})]},a.name))})]})]})]})}function sXn(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=Ctt(t,r,new Date);if(HHe(a))return en(a,"yyyy-MM-dd")}catch{}try{const r=new Date(t);if(HHe(r))return en(r,"yyyy-MM-dd")}catch{}return null}const nXn=["property_address","city","state","zip","transaction_type","close_date","sale_price","commission_amount","lead_source","client_type","is_win","notes"];function rXn({open:s,onOpenChange:t}){const[n,r]=j.useState([]),[a,i]=j.useState(!1),[l,o]=j.useState(0),{data:c}=BB(),{data:d}=qw(),u=S6e(),h=()=>{const v=nXn.join(","),b=["123 Main St","Dallas","TX","75001","buyer","2024-06-15","450000","13500","Referral","Past Client","yes","Great transaction!"].join(","),w=`${v} ${b}`,S=new Blob([w],{type:"text/csv"}),A=URL.createObjectURL(S),E=document.createElement("a");E.href=A,E.download="transaction-import-template.csv",E.click(),URL.revokeObjectURL(A)},m=v=>{const b=v.split(` `).filter(S=>S.trim());if(b.length<2)return[];const w=b[0].split(",").map(S=>S.trim().toLowerCase().replace(/['"]/g,""));return b.slice(1).map((S,A)=>{var X,ae,le,ne;const E=[];let I="",P=!1;for(const te of S)te==='"'?P=!P:te===","&&!P?(E.push(I.trim()),I=""):I+=te;E.push(I.trim());const R=te=>{var ce;const J=w.indexOf(te);return J>=0?(ce=E[J])==null?void 0:ce.replace(/^["']|["']$/g,"").trim():""},D=(X=R("transaction_type"))==null?void 0:X.toLowerCase(),O=(ae=R("sale_price"))==null?void 0:ae.replace(/[$,]/g,""),U=(le=R("commission_amount"))==null?void 0:le.replace(/[$,]/g,""),W=(ne=R("is_win"))==null?void 0:ne.toLowerCase(),V=R("close_date"),G=sXn(V);let Y;return R("property_address")?["buyer","seller"].includes(D)?G?(!O||isNaN(Number(O)))&&(Y="Invalid sale price"):Y=`Invalid date format: "${V}" - use MM/DD/YYYY or YYYY-MM-DD`:Y='Transaction type must be "buyer" or "seller"':Y="Missing property address",{property_address:R("property_address"),city:R("city"),state:R("state"),zip:R("zip"),transaction_type:D==="seller"?"seller":"buyer",close_date:G||"",sale_price:Number(O)||0,commission_amount:U?Number(U):null,lead_source_name:R("lead_source"),client_type_name:R("client_type"),is_win:["yes","true","1"].includes(W),notes:R("notes"),error:Y}})},f=v=>{var S;const b=(S=v.target.files)==null?void 0:S[0];if(!b)return;const w=new FileReader;w.onload=A=>{var P;const E=(P=A.target)==null?void 0:P.result,I=m(E);r(I)},w.readAsText(b)},g=async()=>{const v=n.filter(S=>!S.error);if(v.length===0){re.error("No valid transactions to import");return}i(!0),o(0);let b=0,w=0;for(let S=0;SP.name.toLowerCase()===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)/v.length*100))}i(!1),b>0&&re.success(`Imported ${b} transaction${b>1?"s":""}`),w>0&&re.error(`Failed to import ${w} transaction${w>1?"s":""}`),r([]),t(!1)},x=n.filter(v=>!v.error).length,y=n.filter(v=>v.error).length;return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-2xl max-h-[90vh]",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Import Transactions"}),e.jsx(Pr,{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(xi,{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(ca,{className:"h-3 w-3 mr-1"}),x," valid"]}),y>0&&e.jsxs($e,{variant:"destructive",children:[e.jsx(ll,{className:"h-3 w-3 mr-1"}),y," errors"]})]}),e.jsx(uo,{className:"h-[200px] border rounded-lg",children:e.jsxs("div",{className:"p-2 space-y-2",children:[n.slice(0,10).map((v,b)=>e.jsxs("div",{className:`p-2 rounded text-sm ${v.error?"bg-destructive/10":"bg-muted/50"}`,children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"font-medium",children:v.property_address||"(no address)"}),e.jsx($e,{variant:v.transaction_type==="buyer"?"default":"secondary",children:v.transaction_type})]}),e.jsxs("div",{className:"text-muted-foreground",children:[v.close_date," • $",v.sale_price.toLocaleString()]}),v.error&&e.jsx(Sse,{variant:"destructive",className:"mt-1 py-1",children:e.jsx(Cse,{className:"text-xs",children:v.error})})]},b)),n.length>10&&e.jsxs("p",{className:"text-center text-sm text-muted-foreground",children:["...and ",n.length-10," more"]})]})}),a&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"w-full bg-muted rounded-full h-2",children:e.jsx("div",{className:"bg-primary h-2 rounded-full transition-all",style:{width:`${l}%`}})}),e.jsxs("p",{className:"text-sm text-center text-muted-foreground",children:["Importing... ",l,"%"]})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{onClick:g,disabled:x===0||a,children:[e.jsx(ni,{className:"h-4 w-4 mr-2"}),"Import ",x," Transaction",x!==1?"s":""]})]})]})]})})}const aXn=z2({transactions_goal:fee().min(0).optional(),volume_goal:fee().min(0).optional(),gci_goal:fee().min(0).optional()});function iXn({open:s,onOpenChange:t,year:n,existingGoals:r}){const a=LWs(),{data:i}=C6e(),l=(i==null?void 0:i.show_commission)??!0,o=bLe({resolver:_Le(aXn),defaultValues:{transactions_goal:void 0,volume_goal:void 0,gci_goal:void 0}});j.useEffect(()=>{r?o.reset({transactions_goal:r.transactions_goal??void 0,volume_goal:r.volume_goal?Number(r.volume_goal):void 0,gci_goal:r.gci_goal?Number(r.gci_goal):void 0}):o.reset({transactions_goal:void 0,volume_goal:void 0,gci_goal:void 0})},[r,o,s]);const c=async d=>{await a.mutateAsync({year:n,transactions_goal:d.transactions_goal??null,volume_goal:d.volume_goal??null,gci_goal:l?d.gci_goal??null:null}),t(!1)};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-md",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{children:[n," Goals"]}),e.jsx(Pr,{children:"Set your annual targets to track your progress throughout the year."})]}),e.jsx(kLe,{...o,children:e.jsxs("form",{onSubmit:o.handleSubmit(c),className:"space-y-4",children:[e.jsx(jg,{control:o.control,name:"transactions_goal",render:({field:d})=>e.jsxs(Up,{children:[e.jsx(qp,{children:"Transactions Goal"}),e.jsx(Vp,{children:e.jsx(pe,{type:"number",placeholder:"e.g., 24",...d,value:d.value??"",onChange:u=>d.onChange(u.target.value?Number(u.target.value):void 0)})}),e.jsx(W4e,{children:"Total number of deals you want to close"}),e.jsx(f_,{})]})}),e.jsx(jg,{control:o.control,name:"volume_goal",render:({field:d})=>e.jsxs(Up,{children:[e.jsx(qp,{children:"Volume Goal ($)"}),e.jsx(Vp,{children:e.jsx(pe,{type:"number",placeholder:"e.g., 5000000",...d,value:d.value??"",onChange:u=>d.onChange(u.target.value?Number(u.target.value):void 0)})}),e.jsx(W4e,{children:"Total sales volume you want to achieve"}),e.jsx(f_,{})]})}),l&&e.jsx(jg,{control:o.control,name:"gci_goal",render:({field:d})=>e.jsxs(Up,{children:[e.jsx(qp,{children:"GCI Goal ($)"}),e.jsx(Vp,{children:e.jsx(pe,{type:"number",placeholder:"e.g., 150000",...d,value:d.value??"",onChange:u=>d.onChange(u.target.value?Number(u.target.value):void 0)})}),e.jsx(W4e,{children:"Gross commission income target"}),e.jsx(f_,{})]})}),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 Vot({transactions:s,isLoading:t}){const n=j.useRef(null),r=j.useRef(null),a=j.useRef([]),i=j.useRef(null),{isAdmin:l}=bs(),[o,c]=j.useState(""),[d,u]=j.useState(!0),[h,m]=j.useState(0),[f,g]=j.useState(!1),x=s.filter(v=>v.latitude!=null&&v.longitude!=null),y=s.filter(v=>v.latitude==null||v.longitude==null);return j.useEffect(()=>{(async()=>{u(!0);try{const{data:b}=await q.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();b!=null&&b.value&&c(b.value)}catch(b){console.error("Error fetching mapbox token:",b)}u(!1)})()},[]),j.useEffect(()=>{if(!o||y.length===0||f)return;(async()=>{var w;g(!0);let b=0;for(const S of y){const 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;wu.accessToken=o;const v=s.filter(S=>S.latitude!=null&&S.longitude!=null);let b=[-98.5795,39.8283],w=4;if(v.length>0){const S=v.reduce((E,I)=>E+I.longitude,0)/v.length,A=v.reduce((E,I)=>E+I.latitude,0)/v.length;b=[S,A],w=v.length===1?12:10}return r.current=new wu.Map({container:n.current,style:"mapbox://styles/mapbox/light-v11",zoom:w,center:b}),r.current.addControl(new wu.NavigationControl,"top-right"),()=>{var S;(S=r.current)==null||S.remove(),r.current=null}},[o]),j.useEffect(()=>{var b;if(!r.current||!o)return;a.current.forEach(w=>w.remove()),a.current=[],(b=i.current)==null||b.remove();const v=s.filter(w=>w.latitude!=null&&w.longitude!=null);if(v.forEach(w=>{var R;const S=w.transaction_type==="buyer",A=S?"#3B82F6":"#10B981",E=document.createElement("div");E.className="cursor-pointer",E.innerHTML=`
${S?'':''}
`;const I=new wu.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 wu.Marker(E).setLngLat([w.longitude,w.latitude]).setPopup(I).addTo(r.current);a.current.push(P)}),v.length>1){const w=new wu.LngLatBounds;v.forEach(S=>w.extend([S.longitude,S.latitude])),r.current.fitBounds(w,{padding:60,maxZoom:13})}else v.length===1&&r.current.flyTo({center:[v[0].longitude,v[0].latitude],zoom:12})},[s,o,f]),d||t?e.jsx(je,{children:e.jsx(Ie,{className:"flex items-center justify-center h-[50vh]",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary"})})}):o?s.length===0?e.jsx(je,{children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center h-[50vh] text-center gap-3",children:[e.jsx(ci,{className:"h-12 w-12 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:"No Transactions Yet"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Add transactions to see them plotted on the map."})]})]})}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-4 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-4 h-4 rounded-full border-2 border-white shadow",style:{background:"#3B82F6"}}),e.jsx("span",{children:"Buyer"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-4 h-4 rounded-full border-2 border-white shadow",style:{background:"#10B981"}}),e.jsx("span",{children:"Seller"})]}),e.jsxs("span",{className:"text-muted-foreground ml-auto text-xs",children:[x.length," of ",s.length," mapped",f&&" · Geocoding..."]})]}),e.jsx("div",{ref:n,className:"w-full h-[55vh] rounded-lg shadow-lg border"})]}):e.jsx(je,{children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center h-[50vh] text-center gap-3",children:[e.jsx(ll,{className:"h-12 w-12 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:"Map Not Configured"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:l?"Set up your Mapbox token in the Popby Map to enable maps across the platform.":"The map feature has not been configured yet. Please contact your administrator."})]})]})})}const Ers=()=>{const{data:s}=zw();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"})},oXn=s=>{const{data:t}=zw(),{data:n}=Ers();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 lXn(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 cXn(s,t){return s?s.split(" ").map(n=>n[0]).join("").toUpperCase().slice(0,2):t[0].toUpperCase()}function dXn({year:s}){var m;const{data:t,isLoading:n}=Ers(),{data:r,isLoading:a}=oXn(s),i=Xn(),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=>lXn(D,r));f.sort((D,O)=>O.totalVolume-D.totalVolume);const g={};t.forEach(D=>{g[D.id]=D.name||D.email});const x=r.length,y=r.reduce((D,O)=>D+Number(O.sale_price),0),v=r.reduce((D,O)=>D+(Number(O.commission_amount)||0),0),b=r.filter(D=>D.transaction_type==="buyer").length,w=r.filter(D=>D.transaction_type==="seller").length,S={};r.forEach(D=>{var U;const O=((U=D.lead_source)==null?void 0:U.name)||"Unknown";S[O]=(S[O]||0)+1});const 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:y,avgPrice:x>0?y/x:0,totalGCI:v,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(Ie,{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(Ie,{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(Ie,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(va,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Team Transactions"})]}),e.jsx("p",{className:"text-2xl font-bold",children:o.totalTxns}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[o.buyerCount,"B / ",o.sellerCount,"S"]})]})}),e.jsx(je,{children:e.jsxs(Ie,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(nu,{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(Ie,{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(Ie,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(nu,{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(Ie,{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(Ie,{className:"pt-4 flex items-center gap-4",children:[e.jsx("div",{className:"flex items-center justify-center h-10 w-10 rounded-full bg-primary/10",children:e.jsx(Kl,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("p",{className:"text-sm font-medium text-muted-foreground",children:["Top Performer — ",s]}),e.jsx("p",{className:"text-lg font-bold",children:d.member.name||d.member.email})]}),e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:[d.totalTransactions," deals"]}),e.jsx("p",{className:"font-semibold",children:Xm(d.totalVolume,!0)})]})]})}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-lg",children:"Member Performance"})}),e.jsx(Ie,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Agent"}),e.jsx(Dt,{className:"text-center",children:"Transactions"}),e.jsx(Dt,{className:"text-center",children:"B / S"}),e.jsx(Dt,{className:"text-right",children:"Volume"}),e.jsx(Dt,{className:"text-right",children:"Avg Price"}),e.jsx(Dt,{className:"text-right",children:"GCI"}),e.jsx(Dt,{className:"text-right"})]})}),e.jsx(fi,{children:c.map((f,g)=>e.jsxs(En,{children:[e.jsx(_t,{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:cXn(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(_t,{className:"text-center font-semibold",children:f.totalTransactions}),e.jsxs(_t,{className:"text-center text-sm",children:[f.buyerCount," / ",f.sellerCount]}),e.jsx(_t,{className:"text-right font-medium",children:Xm(f.totalVolume,!0)}),e.jsx(_t,{className:"text-right text-sm",children:Xm(f.averagePrice,!0)}),e.jsx(_t,{className:"text-right font-medium",children:Xm(f.totalGCI,!0)}),e.jsx(_t,{className:"text-right",children:e.jsx($,{variant:"ghost",size:"sm",onClick:()=>i(`/mission-control/scorecard/${f.member.id}`),children:e.jsx(Ca,{className:"h-4 w-4"})})})]},f.member.id))})]})})})]}),e.jsxs(ha,{defaultValue:"transactions",className:"space-y-4",children:[e.jsxs(ma,{children:[e.jsxs(Zt,{value:"transactions",children:[e.jsx(T0,{className:"h-4 w-4 mr-1"}),"All Transactions"]}),e.jsxs(Zt,{value:"charts",children:[e.jsx(Gl,{className:"h-4 w-4 mr-1"}),"Charts"]}),e.jsxs(Zt,{value:"map",children:[e.jsx(ci,{className:"h-4 w-4 mr-1"}),"Map"]})]}),e.jsx(Xt,{value:"transactions",children:e.jsx(Uot,{transactions:r||[],showCommission:!0,isLoading:a,agentNameMap:u,readOnly:!0})}),e.jsx(Xt,{value:"charts",children:h&&e.jsx(qot,{stats:h,year:s})}),e.jsx(Xt,{value:"map",children:e.jsx(Vot,{transactions:r||[],isLoading:a})})]})]})}const dAe=new Date().getFullYear(),x3t=Array.from({length:10},(s,t)=>dAe-t),Lue="all";function uXn(){var O;const[s,t]=j.useState(dAe),n=s===null?Lue:String(s),r=U=>t(U===Lue?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}=zw(),x=(g==null?void 0:g.role)==="team_leader",{data:y,isLoading:v}=lnt(s??void 0),{yearStats:b,lifetimeStats:w,showCommission:S}=XUt(s??void 0),{data:A,isLoading:E}=ZUt(s??dAe),{data:I}=C6e(),P=RWs(),R=()=>{if(!y||y.length===0)return;const U=["Property Address","City","State","Zip","Transaction Type","Close Date","Sale Price",...S?["Commission"]:[],"Lead Source","Client Type","Contact Name","Is Win","Notes"],W=y.map(ae=>{var le,ne;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)||"",((ne=ae.client_type)==null?void 0:ne.name)||"",ae.contact?`${ae.contact.first_name} ${ae.contact.last_name||""}`.trim():"",ae.is_win?"Yes":"No",ae.notes||""]}),V=[U,...W].map(ae=>ae.map(le=>`"${String(le).replace(/"/g,'""')}"`).join(",")).join(` `),G=new Blob([V],{type:"text/csv"}),Y=URL.createObjectURL(G),X=document.createElement("a");X.href=Y,X.download=s===null?"transactions-all.csv":`transactions-${s}.csv`,X.click(),URL.revokeObjectURL(Y)},D=!y||y.length===0;return e.jsxs(Vs,{title:"Scorecard",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Scorecard"}),e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded border border-amber-500/50 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"Beta"})]}),x&&e.jsxs("div",{className:"flex items-center gap-1 bg-muted rounded-lg p-1 w-fit",children:[e.jsx($,{variant:m==="my"?"default":"ghost",size:"sm",onClick:()=>f("my"),className:"h-8",children:"My Scorecard"}),e.jsxs($,{variant:m==="team"?"default":"ghost",size:"sm",onClick:()=>f("team"),className:"h-8",children:[e.jsx(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:Lue,children:"All Years"}),x3t.map(U=>e.jsx(Ge,{value:String(U),children:U},U))]})]})]}),e.jsx(dXn,{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:Lue,children:"All Years"}),x3t.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(Ie,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(ee,{children:"Show Commission"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Display commission fields and include in stats"})]}),e.jsx(Sn,{checked:(I==null?void 0:I.show_commission)??!0,onCheckedChange:U=>P.mutate({show_commission:U})})]})})]}),D&&!v?e.jsx(je,{className:"py-12",children:e.jsxs(Ie,{className:"text-center space-y-4",children:[e.jsx("div",{className:"w-16 h-16 mx-auto rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx(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(dn,{className:"h-4 w-4 mr-2"}),"Add Your First Transaction"]}),e.jsxs($,{variant:"outline",onClick:()=>o(!0),children:[e.jsx(ni,{className:"h-4 w-4 mr-2"}),"Import CSV"]})]}),e.jsxs("div",{className:"pt-4 border-t mt-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:"Need help formatting your data?"}),e.jsx($,{variant:"link",className:"h-auto p-0",asChild:!0,children:e.jsxs("a",{href:"/templates/transaction-import-template.csv",download:!0,children:[e.jsx(xi,{className:"h-4 w-4 mr-2"}),"Download CSV Template"]})})]})]})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs($,{onClick:()=>i(!0),children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Add Transaction"]}),e.jsxs($,{variant:"outline",onClick:()=>d(!0),children:[e.jsx(nh,{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(xi,{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(xi,{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(Ie,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(va,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Transactions"})]}),e.jsx("p",{className:"text-2xl font-bold",children:b.totalTransactions}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[w.totalTransactions," lifetime"]})]})}),e.jsx(je,{children:e.jsxs(Ie,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(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(Ie,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(nu,{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(Ie,{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(Ie,{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(Ie,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(nu,{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(Ie,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-teal-600 dark:text-teal-400 mb-1",children:[e.jsx(nu,{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(Nrs,{goals:A,stats:b,year:s,showCommission:S}),e.jsxs(ha,{defaultValue:"transactions",className:"space-y-4",children:[e.jsxs(ma,{children:[e.jsx(Zt,{value:"transactions",children:"Transactions"}),e.jsx(Zt,{value:"charts",children:"Charts"}),e.jsxs(Zt,{value:"map",children:[e.jsx(ci,{className:"h-4 w-4 mr-1"}),"Map"]})]}),e.jsx(Xt,{value:"transactions",children:e.jsx(Uot,{transactions:y||[],showCommission:S,isLoading:v})}),e.jsx(Xt,{value:"charts",children:e.jsx(qot,{stats:b,year:s??void 0})}),e.jsx(Xt,{value:"map",children:e.jsx(Vot,{transactions:y||[],isLoading:v})})]})]})]})]}),e.jsx(jrs,{open:a,onOpenChange:i}),e.jsx(rXn,{open:l,onOpenChange:o}),e.jsx(iXn,{open:c,onOpenChange:d,year:s??dAe,existingGoals:A})]})}const hXn=s=>st({queryKey:["listing-launch-kit",s],enabled:!!s,queryFn:async()=>{const[t,n]=await Promise.all([q.from("listing_launch_kits").select("*").eq("listing_id",s).maybeSingle(),q.from("listing_community_guides").select("*").eq("listing_id",s).maybeSingle()]);return{kit:t.data??null,guide:n.data??null}}}),mXn=()=>{const s=Wt();return mt({mutationFn:async({listingId:t,regenerate:n})=>{const{data:r,error:a}=await q.functions.invoke("listing-launch-kit",{body:{listingId:t,regenerate:!!n}});if(a){const i=r==null?void 0:r.error;throw new Error(i||a.message||"Could not build the launch kit.")}if(r!=null&&r.error)throw new Error(r.error);return r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["listing-launch-kit",n.listingId]})}})},fXn=()=>{const s=Wt();return mt({mutationFn:async({guideId:t,enabled:n})=>{const{error:r}=await q.from("listing_community_guides").update({is_enabled:n}).eq("id",t);if(r)throw r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["listing-launch-kit",n.listingId]})}})};function EM({label:s,value:t,multiline:n=!0}){const[r,a]=j.useState(!1);if(!t)return null;const i=async()=>{await navigator.clipboard.writeText(t),a(!0),re.success(`${s} copied`),setTimeout(()=>a(!1),1800)};return e.jsxs("div",{className:"rounded-xl border border-border bg-card/60 overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 px-4 py-2.5 border-b border-border bg-muted/40",children:[e.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:s}),e.jsxs($,{size:"sm",variant:"ghost",className:"h-7 px-2 text-xs",onClick:i,children:[r?e.jsx(ca,{className:"h-3.5 w-3.5 mr-1 text-primary"}):e.jsx(Ha,{className:"h-3.5 w-3.5 mr-1"}),r?"Copied":"Copy"]})]}),e.jsx("p",{className:`px-4 py-3 text-sm leading-relaxed text-foreground ${n?"whitespace-pre-wrap":""}`,children:t})]})}function Trs({listingId:s,open:t,onOpenChange:n,listingAddress:r,listingSlug:a,autoGenerate:i}){var S,A,E,I,P,R,D,O,U,W,V,G,Y,X,ae,le;const l=Xn(),{data:o,isLoading:c}=hXn(t?s:null),d=mXn(),u=fXn(),[h,m]=j.useState(!1),f=(o==null?void 0:o.kit)??null,g=(o==null?void 0:o.guide)??null,x=d.isPending;j.useEffect(()=>{if(!t){m(!1);return}c||h||f||!s||(i||!f)&&(m(!0),d.mutate({listingId:s},{onError:ne=>re.error((ne==null?void 0:ne.message)||"Could not build the launch kit.")}))},[t,c,f,s,i,h]);const y=j.useMemo(()=>{const ne=a||s;return ne?`${window.location.origin}/public/listing/${ne}`:null},[a,s]),v=ne=>{ne&&(sessionStorage.setItem("social-studio-seed",JSON.stringify({caption:ne,source:"listing-launch-kit",sourceRef:s})),n(!1),l("/social-studio"),re.success("Draft ready in Social Studio"))},b=()=>{s&&d.mutate({listingId:s,regenerate:!0},{onSuccess:()=>re.success("Fresh launch kit ready"),onError:ne=>re.error((ne==null?void 0:ne.message)||"Could not rebuild the launch kit.")})},w=((S=f==null?void 0:f.social)==null?void 0:S.hashtags)??[];return e.jsx(zs,{open:t,onOpenChange:n,children:e.jsxs(Os,{className:"max-w-4xl p-0 gap-0 overflow-hidden border-border flex flex-col max-h-[92vh]",children:[e.jsxs("div",{className:"relative bg-gradient-to-br from-slate-900 via-slate-900 to-primary/30 px-6 pt-6 pb-5",children:[e.jsx("div",{className:"absolute inset-0 opacity-30 bg-[radial-gradient(circle_at_top_right,hsl(var(--primary)/0.5),transparent_60%)]"}),e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[11px] uppercase tracking-[0.22em] text-white/60 mb-2",children:[e.jsx(qg,{className:"h-3.5 w-3.5"}),"Listing Launch Kit"]}),e.jsx("h2",{className:"font-display text-2xl sm:text-[28px] font-semibold text-white leading-tight",children:((A=f==null?void 0:f.angle)==null?void 0:A.headline)||r||"Your listing, ready to launch"}),((E=f==null?void 0:f.angle)==null?void 0:E.target_buyer)&&e.jsxs("p",{className:"mt-2 text-sm text-white/70 flex items-start gap-2 max-w-2xl",children:[e.jsx(nh,{className:"h-4 w-4 mt-0.5 shrink-0 text-primary-foreground/80"}),f.angle.target_buyer]}),e.jsxs("div",{className:"mt-4 flex flex-wrap items-center gap-2",children:[(((I=f==null?void 0:f.angle)==null?void 0:I.pillars)??[]).map((ne,te)=>e.jsxs($e,{variant:"outline",className:"border-white/20 bg-white/10 text-white/90 font-normal backdrop-blur-sm",children:[e.jsx(Nn,{className:"h-3 w-3 mr-1"}),ne]},te)),e.jsx("div",{className:"ml-auto",children:e.jsxs($,{size:"sm",variant:"outline",className:"h-8 border-white/25 bg-white/10 text-white hover:bg-white/20 hover:text-white",onClick:b,disabled:x||!s,children:[e.jsx(ro,{className:`h-3.5 w-3.5 mr-1.5 ${x?"animate-spin":""}`}),x?"Building…":"Regenerate"]})})]})]})]}),x&&!f?e.jsxs("div",{className:"p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Ct,{className:"h-4 w-4 animate-spin text-primary"}),"Writing your scripts, captions, sphere emails and community guide…"]}),e.jsx(xn,{className:"h-24 w-full"}),e.jsx(xn,{className:"h-24 w-full"}),e.jsx(xn,{className:"h-24 w-full"})]}):f?e.jsxs(ha,{defaultValue:"video",className:"w-full flex-1 min-h-0 flex flex-col",children:[e.jsx("div",{className:"px-4 pt-4 border-b border-border",children:e.jsx(ma,{className:"w-full justify-start gap-1 bg-transparent p-0 h-auto flex-wrap",children:[{v:"video",label:"Video & Reels",icon:ua},{v:"social",label:"Social",icon:Fd},{v:"sphere",label:"Sphere Blast",icon:Kr},{v:"openhouse",label:"Open House",icon:i2},{v:"guide",label:"Community Guide",icon:Xf}].map(({v:ne,label:te,icon:J})=>e.jsxs(Zt,{value:ne,className:"rounded-t-lg rounded-b-none border-b-2 border-transparent px-3 py-2 text-sm data-[state=active]:border-primary data-[state=active]:bg-primary/5 data-[state=active]:text-primary data-[state=active]:shadow-none",children:[e.jsx(J,{className:"h-4 w-4 mr-1.5"}),te]},ne))})}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto overscroll-contain",children:e.jsxs("div",{className:"p-5 space-y-4",children:[e.jsxs(Xt,{value:"video",className:"m-0 space-y-4",children:[e.jsx(EM,{label:"3-second hook",value:(R=(P=f.video)==null?void 0:P.reel_script)==null?void 0:R.hook}),e.jsx(EM,{label:"Walkthrough script",value:(O=(D=f.video)==null?void 0:D.reel_script)==null?void 0:O.walkthrough}),e.jsx(EM,{label:"Call to action",value:(W=(U=f.video)==null?void 0:U.reel_script)==null?void 0:W.cta}),(((V=f.video)==null?void 0:V.hooks)??[]).length>0&&e.jsxs("div",{className:"rounded-xl border border-border bg-card/60 overflow-hidden",children:[e.jsx("div",{className:"px-4 py-2.5 border-b border-border bg-muted/40 text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:"Story & Reel text overlays"}),e.jsx("ul",{className:"divide-y divide-border",children:f.video.hooks.map((ne,te)=>e.jsxs("li",{className:"flex items-center justify-between gap-3 px-4 py-2.5",children:[e.jsx("span",{className:"text-sm",children:ne}),e.jsx($,{size:"sm",variant:"ghost",className:"h-7 px-2 text-xs shrink-0",onClick:()=>{navigator.clipboard.writeText(ne),re.success("Copied")},children:e.jsx(Ha,{className:"h-3.5 w-3.5"})})]},te))})]})]}),e.jsxs(Xt,{value:"social",className:"m-0 space-y-4",children:[["instagram","facebook","linkedin"].map(ne=>{var ce;const te=(ce=f.social)==null?void 0:ce[ne];if(!te)return null;const J=ne==="linkedin"?"LinkedIn":ne==="instagram"?"Instagram":"Facebook";return e.jsxs("div",{className:"space-y-2",children:[e.jsx(EM,{label:`${J} caption`,value:te}),e.jsxs($,{size:"sm",variant:"secondary",onClick:()=>v(te),children:[e.jsx(Kr,{className:"h-3.5 w-3.5 mr-1.5"}),"Send to Social Studio"]})]},ne)}),w.length>0&&e.jsxs("div",{className:"rounded-xl border border-border bg-card/60 p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:"Hashtags"}),e.jsxs($,{size:"sm",variant:"ghost",className:"h-7 px-2 text-xs",onClick:()=>{navigator.clipboard.writeText(w.join(" ")),re.success("Hashtags copied")},children:[e.jsx(Ha,{className:"h-3.5 w-3.5 mr-1"}),"Copy all"]})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:w.map((ne,te)=>e.jsx($e,{variant:"secondary",className:"font-normal",children:ne},te))})]})]}),e.jsxs(Xt,{value:"sphere",className:"m-0 space-y-4",children:[e.jsx(EM,{label:"Email subject",value:(G=f.outreach)==null?void 0:G.email_subject,multiline:!1}),e.jsx(EM,{label:"Email to your sphere",value:(Y=f.outreach)==null?void 0:Y.email_body}),e.jsx(EM,{label:"VIP text message",value:(X=f.outreach)==null?void 0:X.sms})]}),e.jsxs(Xt,{value:"openhouse",className:"m-0 space-y-4",children:[e.jsx(EM,{label:"60-second door pitch",value:(ae=f.open_house)==null?void 0:ae.pitch}),(((le=f.open_house)==null?void 0:le.neighborhood_points)??[]).length>0&&e.jsxs("div",{className:"rounded-xl border border-border bg-card/60 overflow-hidden",children:[e.jsx("div",{className:"px-4 py-2.5 border-b border-border bg-muted/40 text-[11px] font-semibold uppercase tracking-[0.16em] text-muted-foreground",children:"Neighborhood talking points"}),e.jsx("ul",{className:"divide-y divide-border",children:f.open_house.neighborhood_points.map((ne,te)=>e.jsxs("li",{className:"px-4 py-2.5 text-sm flex gap-2",children:[e.jsx("span",{className:"text-primary",children:"•"}),ne]},te))})]})]}),e.jsx(Xt,{value:"guide",className:"m-0 space-y-4",children:g?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"rounded-xl border border-primary/25 bg-primary/5 p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"font-medium text-sm flex items-center gap-2",children:[e.jsx(Yn,{className:"h-4 w-4 text-primary"}),"Show the free guide download on your public listing page"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Visitors trade their name, email and cell for the guide — each one lands in your CRM as a new lead."})]}),e.jsx(Sn,{checked:g.is_enabled,disabled:u.isPending,onCheckedChange:ne=>u.mutate({guideId:g.id,enabled:ne,listingId:s},{onSuccess:()=>re.success(ne?"Guide download is live":"Guide download hidden"),onError:()=>re.error("Could not update the guide")})})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 mt-4",children:[e.jsxs($e,{variant:"secondary",className:"font-normal",children:[g.download_count," download",g.download_count===1?"":"s"]}),y&&e.jsxs($,{size:"sm",variant:"outline",onClick:()=>{navigator.clipboard.writeText(y),re.success("Share link copied — great for neighborhood groups")},children:[e.jsx(Wd,{className:"h-3.5 w-3.5 mr-1.5"}),"Copy share link"]})]})]}),e.jsx("div",{className:"rounded-xl border border-border bg-card/60 p-5",children:e.jsx(T7t,{title:g.title,subtitle:g.subtitle,areaLabel:g.area_label,sections:g.sections??[]})})]}):e.jsx("p",{className:"text-sm text-muted-foreground py-8 text-center",children:"No community guide was generated for this listing yet. Try Regenerate."})})]})})]}):e.jsxs("div",{className:"p-10 text-center",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"No launch kit yet for this listing."}),e.jsxs($,{onClick:b,disabled:!s,children:[e.jsx(Nn,{className:"h-4 w-4 mr-2"}),"Build my launch kit"]})]})]})})}const pXn={active:"bg-emerald-500",coming_soon:"bg-sky-500",office_exclusive:"bg-indigo-500",pre_market:"bg-cyan-500",price_improvement:"bg-orange-500",under_contract:"bg-purple-500",sold:"bg-gray-500"},gXn={active:"Active",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},xXn={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"};function yXn({listing:s,onClick:t,onEdit:n,onDelete:r,onCreateMusicVideo:a,onLaunchKit:i,showActions:l}){var A,E;const{user:o}=bs(),{data:c}=z$t(s.id),d=O$t(),[u,h]=j.useState(!1),m=I=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(I),f=((A=s.photos)==null?void 0:A.find(I=>I.is_primary))||((E=s.photos)==null?void 0:E[0]),g=A$t(s.agent_id)||(o==null?void 0:o.id)===s.agent_id,x=s.listing_class==="commercial",y=s.commercial??null,v=s.lifecycle_stage==="pitch",b=x?[yE(y==null?void 0:y.building_sf)?`${yE(y==null?void 0:y.building_sf)} building`:null,yE(y==null?void 0:y.available_sf)?`${yE(y==null?void 0:y.available_sf)} available`:null,TEe(y==null?void 0:y.cap_rate)?`${TEe(y==null?void 0:y.cap_rate)} cap`:null,(y==null?void 0:y.price_per_sf)!=null?`${LN(y.price_per_sf,2)}/SF`:null,(y==null?void 0:y.units)!=null?`${y.units} units`:null].filter(Boolean).slice(0,3):[],w=async I=>{I.stopPropagation();try{const P=await d.mutateAsync(s.id);re.success(P.saved?"Listing saved!":"Listing removed from saved")}catch{re.error("Failed to save listing")}},S=I=>{if(I.stopPropagation(),o)h(!0);else{const P=`${s.listing_class==="commercial"?"https://commercial.relevelup.com":"https://listings.relevelup.com"}/${s.slug||s.id}`;navigator.clipboard.writeText(P),re.success("Link copied to clipboard!")}};return e.jsxs(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:[f?e.jsx("img",{src:f.photo_url,alt:s.property_address||s.city,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:e.jsx(j_,{className:"h-12 w-12"})}),e.jsxs("div",{className:"absolute top-2 left-2 flex flex-wrap gap-1",children:[e.jsx($e,{className:`${pXn[s.status]} text-white border-0`,children:x&&v?"Pitch":gXn[s.status]}),x&&e.jsx($e,{className:"border-0 bg-[#0b0f14]/90 text-white",children:y!=null&&y.deal_type?AL[y.deal_type]:"Commercial"})]}),s.is_featured&&e.jsx("div",{className:"absolute top-2 right-2 p-1.5 bg-amber-500 rounded-full",children:e.jsx(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:w,children:e.jsx(Jo,{className:`h-4 w-4 ${c?"fill-pink-500 text-pink-500":""}`})}),e.jsx($,{size:"icon",variant:"secondary",className:"h-8 w-8",onClick:S,title:g?"Copy link":"Share & earn leads",children:g?e.jsx(Fd,{className:"h-4 w-4"}):e.jsx(Nn,{className:"h-4 w-4 text-amber-500"})})]})]}),e.jsx(y6e,{open:u,onOpenChange:h,listingId:s.id,listingSlug:s.slug||null,listingTitle:s.property_address||`${s.city}, ${s.state}`,isCommercial:s.listing_class==="commercial"}),e.jsxs(Ie,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xl font-bold text-primary",children:x?kG(y,s.price):m(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:[x?e.jsx("p",{className:"font-medium truncate",children:rL(s,y)}):s.property_address&&e.jsx("p",{className:"font-medium truncate",children:s.property_address}),e.jsxs("p",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[e.jsx(ci,{className:"h-3 w-3"}),x?qae(s,y):`${s.city}, ${s.state}${s.neighborhood?` • ${s.neighborhood}`:""}`]})]}),e.jsx("div",{className:"flex items-center gap-4 text-sm text-muted-foreground",children:x?b.map(I=>e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(j_,{className:"h-4 w-4"}),I]},I)):e.jsxs(e.Fragment,{children:[s.bedrooms&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(r2,{className:"h-4 w-4"}),s.bedrooms," bd"]}),s.bathrooms&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(A0,{className:"h-4 w-4"}),s.bathrooms," ba"]}),s.square_footage&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(j_,{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:x?y!=null&&y.commercial_type?i6[y.commercial_type]:"Commercial":xXn[s.property_type]}),s.agent&&e.jsx("p",{className:"text-xs text-muted-foreground truncate max-w-[120px]",children:s.agent.name})]}),e.jsxs("div",{className:"flex items-center gap-3 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ca,{className:"h-3 w-3"}),s.view_count]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Fd,{className:"h-3 w-3"}),s.share_count]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Jo,{className:"h-3 w-3"}),s.save_count]})]}),l&&(n||r||a||i)&&e.jsxs("div",{className:"flex flex-wrap gap-2",children:[i&&e.jsxs($,{variant:"outline",size:"sm",className:"flex-1 min-w-[140px] gap-1.5 border-primary/50 text-primary hover:bg-primary/10",onClick:I=>{I.stopPropagation(),i()},children:[e.jsx(qg,{className:"h-4 w-4"}),"Launch Kit"]}),a&&e.jsxs($,{variant:"outline",size:"sm",className:"flex-1 min-w-[140px] gap-1.5 border-violet-500/60 text-violet-600 hover:bg-violet-50",onClick:I=>{I.stopPropagation(),a()},children:[e.jsx(Hq,{className:"h-4 w-4"}),"Music Video"]}),n&&e.jsxs($,{variant:"outline",size:"sm",className:"flex-1",onClick:I=>{I.stopPropagation(),n()},children:[e.jsx(_p,{className:"h-4 w-4 mr-2"}),"Edit"]}),r&&e.jsx($,{variant:"destructive",size:"sm",onClick:I=>{I.stopPropagation(),r()},children:e.jsx(Hn,{className:"h-4 w-4"})})]})]})]})}const Hot="lu_listing_selection_v1",vPe=24,bPe=new Set;function Mrs(){try{return JSON.parse(sessionStorage.getItem(Hot)||"{}")}catch{return{}}}function R$e(s){try{sessionStorage.setItem(Hot,JSON.stringify(s))}catch{}bPe.forEach(t=>t())}let wA=Mrs();function vXn(){wA=Mrs(),bPe.forEach(s=>s())}typeof window<"u"&&window.addEventListener("storage",s=>{s.key===Hot&&vXn()});const yP={getSnapshot:()=>wA,subscribe(s){return bPe.add(s),()=>bPe.delete(s)},toggle(s){const t={...wA};if(t[s.mlsNumber])delete t[s.mlsNumber];else{if(Object.keys(t).length>=vPe)return!1;t[s.mlsNumber]=s}return wA=t,R$e(t),!0},remove(s){const t={...wA};delete t[s],wA=t,R$e(t)},clear(){wA={},R$e({})},has(s){return!!wA[s]},all(){return Object.values(wA)}};function Prs(){const s=j.useSyncExternalStore(yP.subscribe,yP.getSnapshot,yP.getSnapshot);return{selected:Object.values(s),selectedIds:new Set(Object.keys(s)),count:Object.keys(s).length,has:t=>!!s[t],toggle:yP.toggle,remove:yP.remove,clear:yP.clear}}const bXn=new Set(["office_exclusive","coming_soon","pre_market"]);function _Xn(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=bXn.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 hX(s){const{has:t}=Prs(),n=`lx-${s.listing.id}`,r=t(n);return e.jsxs("div",{className:"relative",children:[e.jsx(yXn,{...s}),e.jsx("button",{type:"button",onClick:a=>{a.stopPropagation(),yP.toggle(_Xn(s.listing))||re.error(`You can select up to ${vPe} 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(ca,{className:"h-4 w-4"}):e.jsx(mn,{className:"h-4 w-4"})})]})}function wXn({open:s,onOpenChange:t,listings:n}){const{user:r}=bs(),{leadSite:a}=ng(),[i,l]=j.useState("grid"),[o,c]=j.useState(""),[d,u]=j.useState(""),[h,m]=j.useState(""),[f,g]=j.useState(new Set),[x,y]=j.useState(!1),[v,b]=j.useState(!1),{data:w}=sie(),[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))),Y=G.length===1?` in ${G[0]}`:"";c(n.length===1?`New listing for you${Y}`:`${n.length} hand-picked listings${Y}`)}d||u(`Hi {{first_name}}, Thought of you — I just picked a few properties I think you'll love. Take a look and let me know if anything catches your eye. Happy to set up a private showing whenever works.`)}},[s]);const{data:E=[],isLoading:I}=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:Y}=await q.functions.invoke("listing-email-suggestions",{body:{listings:n.map(X=>({mlsNumber:X.mlsNumber,city:X.city,state:X.state,price:X.price,bedrooms:X.bedrooms,bathrooms:X.bathrooms}))}});if(Y)throw Y;return G},enabled:s&&n.length>0}),R=(P==null?void 0:P.suggestions)||[],D=j.useMemo(()=>{const G=h.trim().toLowerCase();return G?E.filter(Y=>`${Y.first_name??""} ${Y.last_name??""} ${Y.email} ${Y.city??""}`.toLowerCase().includes(G)):E},[E,h]),O=G=>{g(Y=>{const X=new Set(Y);return X.has(G)?X.delete(G):X.add(G),X})},U=()=>{g(G=>{const Y=new Set(G);return R.forEach(X=>Y.add(X.contact_id)),Y})},W=n.length>0&&n.every(G=>G.mlsNumber.startsWith("lx-")),V=async()=>{if(!W&&!(a!=null&&a.id)){re.error("You need an active lead site to send listings.");return}if(!o.trim())return re.error("Subject is required");if(f.size===0)return re.error("Pick at least one recipient");if(!v&&w&&!w.hasVerifiedSes){A(!0);return}const G=E.filter(Y=>f.has(Y.id)).map(Y=>({contact_id:Y.id,email:Y.email,first_name:Y.first_name,last_name:Y.last_name}));y(!0);try{const{data:Y,error:X}=await q.functions.invoke("listing-email-send",{body:{lead_site_id:(a==null?void 0:a.id)||null,layout:i,subject:o.trim(),intro_message:d.trim()||null,listings:n.map(ae=>({mlsNumber:ae.mlsNumber,address:ae.address,city:ae.city,state:ae.state,zip:ae.zip,price:ae.price,bedrooms:ae.bedrooms,bathrooms:ae.bathrooms,sqft:ae.sqft,status:ae.status,photos:(ae.photos||[]).slice(0,1),description:ae.description||"",external_url:ae.externalUrl||null,is_private:ae.is_private===!0})),recipients:G}});if(X)throw X;if(!(Y!=null&&Y.success))throw new Error((Y==null?void 0:Y.error)||"Send failed");re.success(`Sent ${Y.sent}/${G.length} via ${v?"Gmail":"Amazon SES"}${Y.failed?` · ${Y.failed} failed`:""}`),yP.clear(),g(new Set),t(!1)}catch(Y){re.error((Y==null?void 0:Y.message)||"Failed to send")}finally{y(!1)}};return e.jsxs(zs,{open:s,onOpenChange:t,children:[e.jsxs(Os,{className:"max-w-5xl max-h-[92vh] overflow-hidden p-0 flex flex-col",children:[e.jsxs(Us,{className:"px-6 pt-6 pb-2",children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(mn,{className:"h-5 w-5 text-primary"}),"Email ",n.length," ",n.length===1?"Listing":"Listings"]}),e.jsx(Pr,{children:W?"Send your Listing Exchange properties. Recipients land on listings.relevelup.com and clicks track back to the contact.":"Drive traffic to your site. Recipients land on your lead site and clicks show up on Mission Control."})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-0 flex-1 overflow-hidden",children:[e.jsxs("div",{className:"overflow-y-auto px-6 pb-4 space-y-4 border-r",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Selected listings"}),e.jsx("div",{className:"mt-2 flex gap-2 overflow-x-auto pb-1",children:n.map(G=>{var Y;return e.jsxs("div",{className:"shrink-0 w-32 rounded-lg overflow-hidden border bg-muted",children:[e.jsx("div",{className:"h-20 w-full bg-muted",children:((Y=G.photos)==null?void 0:Y[0])&&e.jsx("img",{src:G.photos[0],alt:"",className:"h-full w-full object-cover"})}),e.jsxs("div",{className:"p-1.5",children:[e.jsxs("div",{className:"text-[11px] font-semibold truncate",children:["$",(G.price/1e3).toFixed(0),"k"]}),e.jsxs("div",{className:"text-[10px] text-muted-foreground truncate",children:[G.city,", ",G.state]})]})]},G.mlsNumber)})})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Layout"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-2",children:[e.jsxs("button",{type:"button",onClick:()=>l("grid"),className:`rounded-lg border p-3 text-left transition ${i==="grid"?"border-primary bg-primary/5":"hover:bg-muted/50"}`,children:[e.jsx(Qf,{className:"h-4 w-4 mb-1.5"}),e.jsx("div",{className:"text-sm font-medium",children:"Magazine grid"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Clean card stack"})]}),e.jsxs("button",{type:"button",onClick:()=>l("hero"),className:`rounded-lg border p-3 text-left transition ${i==="hero"?"border-primary bg-primary/5":"hover:bg-muted/50"}`,children:[e.jsx(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(Ls,{id:"intro",value:d,onChange:G=>u(G.target.value),placeholder:"Optional intro shown above the listings…",className:"mt-1 min-h-[120px]"}),e.jsxs("p",{className:"text-[11px] text-muted-foreground mt-1",children:["Use ",e.jsx("code",{className:"px-1 rounded bg-muted",children:"{{first_name}}"})," to personalize."]})]}),e.jsxs("div",{className:"rounded-lg border bg-muted/40 p-3 text-xs text-muted-foreground",children:["Sending via"," ",e.jsx("span",{className:"font-medium text-foreground",children:v?"your connected Gmail":"Amazon SES"}),". Every click tracks back to the contact and triggers a buyer signal."]})]}),e.jsxs("div",{className:"flex flex-col overflow-hidden",children:[e.jsxs("div",{className:"px-6 pt-4 pb-2 space-y-3",children:[R.length>0&&e.jsxs(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(Nn,{className:"h-4 w-4 text-amber-600"}),e.jsxs("div",{className:"text-sm font-medium",children:[R.length," smart ",R.length===1?"match":"matches"]})]}),e.jsx($,{size:"sm",variant:"outline",onClick:U,children:"Add all"})]}),e.jsx(uo,{className:"max-h-32 mt-2",children:e.jsx("div",{className:"space-y-1",children:R.slice(0,12).map(G=>{const Y=f.has(G.contact_id);return e.jsxs("label",{className:"flex items-start gap-2 text-xs py-1 cursor-pointer",children:[e.jsx(ai,{checked:Y,onCheckedChange:()=>O(G.contact_id),className:"mt-0.5"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium truncate",children:[G.first_name," ",G.last_name??""," ",e.jsxs("span",{className:"text-muted-foreground font-normal",children:["· ",G.email]})]}),e.jsx("div",{className:"text-muted-foreground truncate",children:G.reason})]})]},G.contact_id)})})})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs(ee,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:["All contacts (",D.length,")"]}),f.size>0&&e.jsxs($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(uo,{className:"h-full",children:I?e.jsx("div",{className:"p-4 text-sm text-muted-foreground",children:"Loading…"}):D.length===0?e.jsx("div",{className:"p-4 text-sm text-muted-foreground text-center",children:"No contacts found"}):e.jsx("div",{className:"divide-y",children:D.map(G=>{const Y=f.has(G.id);return e.jsxs("label",{className:"flex items-center gap-2 px-3 py-2 cursor-pointer hover:bg-muted/40",children:[e.jsx(ai,{checked:Y,onCheckedChange:()=>O(G.id)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"text-sm font-medium truncate",children:[G.first_name," ",G.last_name??""]}),e.jsxs("div",{className:"text-xs text-muted-foreground truncate",children:[G.email,G.city&&e.jsxs(e.Fragment,{children:[" · ",G.city]})]})]})]},G.id)})})})})}),e.jsxs("div",{className:"px-6 py-2 text-xs text-muted-foreground border-t flex items-center justify-between",children:[e.jsxs("span",{children:[e.jsx("strong",{className:"text-foreground",children:f.size})," recipients"]}),f.size>0&&e.jsxs($,{variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>g(new Set),children:[e.jsx(pr,{className:"h-3 w-3 mr-1"}),"Clear"]})]})]})]}),e.jsxs(Sr,{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(Kr,{className:"h-4 w-4 mr-2"}),"Send to ",f.size," ",f.size===1?"contact":"contacts"]})})]})]}),e.jsx(w6e,{open:S,onOpenChange:A,hasPending:!!(w!=null&&w.hasPendingSes),pendingEmails:w==null?void 0:w.pendingEmails})]})}function jXn(){const{selected:s,count:t,remove:n,clear:r}=Prs(),[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>=vPe?"Max reached":`Pick up to ${vPe}`})]})]}),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(pr,{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(Hn,{className:"h-4 w-4"})," Clear"]}),e.jsxs($,{size:"sm",className:"gap-1.5",onClick:()=>i(!0),children:[e.jsx(Kr,{className:"h-4 w-4"}),"Email these ",t===1?"listing":"listings"]})]})]})}),e.jsx(wXn,{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"}],kXn=[{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 SXn({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(pr,{className:"h-4 w-4"})})]})]}),e.jsxs(Ie,{children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Status"}),e.jsxs(ms,{value:s.status||"all",onValueChange:o=>t({...s,status:o==="all"?void 0:o}),children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"All statuses"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Statuses"}),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"}),kXn.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(AL).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(i6).map(([o,c])=>e.jsx(Ge,{value:o,children:c},o))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Min Building SF"}),e.jsx(pe,{type:"number",placeholder:"Any size",value:a.minBuildingSf??"",onChange:o=>i({minBuildingSf:o.target.value?Number(o.target.value):void 0})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Min Cap Rate (%)"}),e.jsx(pe,{type:"number",step:"0.1",placeholder:"Any",value:a.minCapRate??"",onChange:o=>i({minCapRate:o.target.value?Number(o.target.value):void 0})})]})]}),e.jsxs("div",{className:"flex items-center justify-between mt-4 pt-4 border-t",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Open to Referrals Only"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show only listings accepting buyer referrals"})]}),e.jsx(Sn,{checked:s.openToReferrals||!1,onCheckedChange:o=>t({...s,openToReferrals:o||void 0})})]})]})]})}function CXn({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(TE,{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(Ie,{children:e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs("div",{className:"text-center p-4 rounded-lg bg-gradient-to-br from-emerald-500/10 to-emerald-500/5 border border-emerald-500/20",children:[e.jsx("div",{className:"w-12 h-12 mx-auto mb-2 rounded-full bg-emerald-500/20 flex items-center justify-center",children:e.jsx(Fd,{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(TE,{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(Ie,{children:e.jsxs(ha,{defaultValue:"sharers",children:[e.jsxs(ma,{className:"w-full",children:[e.jsxs(Zt,{value:"sharers",className:"flex-1",children:[e.jsx(Fd,{className:"h-4 w-4 mr-2"}),"Top Sharers"]}),e.jsxs(Zt,{value:"listers",className:"flex-1",children:[e.jsx(va,{className:"h-4 w-4 mr-2"}),"Top Contributors"]})]}),e.jsx(Xt,{value:"sharers",className:"mt-4",children:n(s==null?void 0:s.topSharers,"shares")}),e.jsx(Xt,{value:"listers",className:"mt-4",children:n(s==null?void 0:s.topListers,"listings")})]})})]})]})}const y3t={coming_soon:"#F59E0B",office_exclusive:"#6366F1",pre_market:"#06B6D4",active:"#10B981",price_improvement:"#8B5CF6",under_contract:"#3B82F6",sold:"#A855F7"},v3t={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 AXn(s){return s>=1e6?`$${(s/1e6).toFixed(1)}M`:`$${(s/1e3).toFixed(0)}K`}function EXn({listings:s,isLoading:t}){const n=Xn(),r=j.useRef(null),a=j.useRef(null),i=j.useRef([]),{isAdmin:l}=bs(),[o,c]=j.useState(""),[d,u]=j.useState(!0),[h,m]=j.useState(!1),f=s.filter(x=>x.latitude!=null&&x.longitude!=null),g=s.filter(x=>(x.latitude==null||x.longitude==null)&&(x.property_address||x.city));return j.useEffect(()=>{(async()=>{u(!0);try{const{data:y}=await q.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();y!=null&&y.value&&c(y.value)}catch(y){console.error("Error fetching mapbox token:",y)}u(!1)})()},[]),j.useEffect(()=>{if(!o||g.length===0||h)return;(async()=>{var y;m(!0);for(const v of g){const b=[v.property_address,v.city,v.state].filter(Boolean).join(", ");if(b)try{const S=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(b)}.json?access_token=${o}&limit=1`)).json();if((y=S.features)!=null&&y[0]){const[A,E]=S.features[0].center;await q.from("listings").update({latitude:E,longitude:A}).eq("id",v.id),v.latitude=E,v.longitude=A}}catch(w){console.error("Geocode error:",w)}}m(!1)})()},[o,s]),j.useEffect(()=>{if(!r.current||!o||a.current)return;wu.accessToken=o;const x=s.filter(b=>b.latitude!=null&&b.longitude!=null);let y=[-98.5795,39.8283],v=4;if(x.length>0){const b=x.reduce((S,A)=>S+A.longitude,0)/x.length,w=x.reduce((S,A)=>S+A.latitude,0)/x.length;y=[b,w],v=x.length===1?12:10}return a.current=new wu.Map({container:r.current,style:"mapbox://styles/mapbox/light-v11",zoom:v,center:y}),a.current.addControl(new wu.NavigationControl,"top-right"),()=>{var b;(b=a.current)==null||b.remove(),a.current=null}},[o]),j.useEffect(()=>{if(!a.current||!o)return;i.current.forEach(y=>y.remove()),i.current=[];const x=s.filter(y=>y.latitude!=null&&y.longitude!=null);if(x.forEach(y=>{var E,I,P;const v=y3t[y.status]||"#10B981",b=((E=y.photos)==null?void 0:E.find(R=>R.is_primary))||((I=y.photos)==null?void 0:I[0]),w=document.createElement("div");w.className="cursor-pointer",w.innerHTML=`
`;const S=new wu.Popup({offset:25,closeButton:!0,maxWidth:"280px"}).setHTML(`
${b!=null&&b.photo_url?``:""}
${AXn(y.price)}
${y.property_address||""}
${y.city}, ${y.state}
${v3t[y.status]||y.status} ${y.bedrooms?`${y.bedrooms} bed`:""} ${y.bathrooms?`${y.bathrooms} bath`:""}
${(P=y.agent)!=null&&P.name?`
Listed by ${y.agent.name}
`:""}
Click to view details →
`),A=new wu.Marker(w).setLngLat([y.longitude,y.latitude]).setPopup(S).addTo(a.current);i.current.push(A)}),x.length>1){const y=new wu.LngLatBounds;x.forEach(v=>y.extend([v.longitude,v.latitude])),a.current.fitBounds(y,{padding:60,maxZoom:13})}else x.length===1&&a.current.flyTo({center:[x[0].longitude,x[0].latitude],zoom:12})},[s,o,h]),j.useEffect(()=>(window.__navigateToListing__=x=>{n(`/mission-control/listings/${x}`)},()=>{delete window.__navigateToListing__}),[n]),d||t?e.jsx(je,{children:e.jsx(Ie,{className:"flex items-center justify-center h-[60vh]",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary"})})}):o?s.length===0?e.jsx(je,{children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center h-[60vh] text-center gap-3",children:[e.jsx(ci,{className:"h-12 w-12 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:"No Listings Yet"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Add listings to see them on the map."})]})]})}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-sm",children:[Object.entries(y3t).map(([x,y])=>e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:"w-3 h-3 rounded-full border-2 border-white shadow",style:{background:y}}),e.jsx("span",{className:"text-xs",children:v3t[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(Ie,{className:"flex flex-col items-center justify-center h-[60vh] text-center gap-3",children:[e.jsx(ll,{className:"h-12 w-12 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:"Map Not Configured"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:l?"Set up your Mapbox token in Settings to enable maps.":"The map feature has not been configured yet. Please contact your administrator."})]})]})})}const PXe="homereel_mv_prefill",IXe="homereel_mv_badge_default";function Irs(s){try{sessionStorage.setItem(PXe,JSON.stringify(s)),s.badge&&s.badge.type!=="none"&&sessionStorage.setItem(IXe,JSON.stringify(s.badge))}catch{}}function hCr(){try{const s=sessionStorage.getItem(PXe);return s?(sessionStorage.removeItem(PXe),JSON.parse(s)):null}catch{return null}}function mCr(){try{const s=sessionStorage.getItem(IXe);return s?(sessionStorage.removeItem(IXe),JSON.parse(s)):null}catch{return null}}function Lrs(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 TXn(){var X,ae,le,ne,te,J,ce,_e;const s=Xn(),{brokerageId:t}=bs(),{data:n,isLoading:r}=E$t(),[a,i]=j.useState("feed"),[l,o]=j.useState(!1),[c,d]=j.useState(null),[u,h]=j.useState(""),[m,f]=j.useState("all"),[g,x]=j.useState({sortBy:"newest"}),{data:y,isLoading:v}=T$t({...g,listingClass:m==="all"?void 0:m,city:u||g.city}),{data:b,isLoading:w}=yqs(),{data:S,isLoading:A}=Hst(),{data:E,isLoading:I}=wqs(),{data:P,isLoading:R}=kqs(),{data:D}=Nqs(),O=I$t(),U=g.commercial,W=(y??[]).filter(he=>{if(!U||he.listing_class!=="commercial")return!U||Object.values(U).every(ve=>ve===void 0)||he.listing_class!=="commercial";const ue=he.commercial??{};return!(U.dealType&&ue.deal_type!==U.dealType||U.commercialType&&ue.commercial_type!==U.commercialType||U.minBuildingSf&&Number(ue.building_sf??0)he.lifecycle_stage==="pitch"),G=he=>s(he.listing_class==="commercial"?`/mission-control/listings/${he.id}/commercial`:`/mission-control/listings/${he.id}`),Y=async he=>{if(await fo("Are you sure you want to delete this listing? This action cannot be undone."))try{await O.mutateAsync(he),re.success("Listing deleted successfully")}catch{re.error("Failed to delete listing")}};return r?e.jsx(Vs,{title:"Listing Exchange",description:"Community-powered listing collaboration",children:e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full"})})}):n?e.jsxs(Vs,{title:"Listing Exchange",description:"Community-powered listing collaboration",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Listing Exchange"}),e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded border border-amber-500 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"Beta"})]}),e.jsxs($,{onClick:()=>s("/mission-control/listings/new"),children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Add Listing"]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(je,{children:e.jsxs(Ie,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(va,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(y==null?void 0:y.length)||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Active Listings"})]})]})}),e.jsx(je,{children:e.jsxs(Ie,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-pink-500/10 rounded-lg",children:e.jsx(Jo,{className:"h-5 w-5 text-pink-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(b==null?void 0:b.length)||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Saved"})]})]})}),e.jsx(je,{children:e.jsxs(Ie,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-emerald-500/10 rounded-lg",children:e.jsx($I,{className:"h-5 w-5 text-emerald-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(S==null?void 0:S.length)||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"My Listings"})]})]})}),e.jsx(je,{children:e.jsxs(Ie,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-sky-500/10 rounded-lg",children:e.jsx(Yn,{className:"h-5 w-5 text-sky-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(((X=E==null?void 0:E.sent)==null?void 0:X.length)||0)+(((ae=E==null?void 0:E.received)==null?void 0:ae.length)||0)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Referrals"})]})]})})]}),e.jsxs(ha,{value:a,onValueChange:i,children:[e.jsxs(ma,{className:"w-full justify-start overflow-x-auto",children:[e.jsx(Zt,{value:"feed",children:"Community Feed"}),t&&e.jsx(Zt,{value:"brokerage",children:"Brokerage"}),e.jsx(Zt,{value:"my-listings",children:"My Listings"}),V.length>0&&e.jsxs(Zt,{value:"pitches",children:["Pitches (",V.length,")"]}),e.jsx(Zt,{value:"saved",children:"Saved"}),e.jsx(Zt,{value:"referrals",children:"Referrals"}),e.jsx(Zt,{value:"map",children:"Map"}),e.jsx(Zt,{value:"leaderboard",children:"Leaderboard"})]}),e.jsxs(Xt,{value:"feed",className:"space-y-4",children:[e.jsx("div",{className:"inline-flex rounded-lg border bg-muted/40 p-1",children:["all","residential","commercial"].map(he=>e.jsx("button",{type:"button",onClick:()=>f(he),className:`rounded-md px-4 py-1.5 text-sm font-medium capitalize transition ${m===he?"bg-background shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:he==="all"?"All listings":he},he))}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Zr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search by city or neighborhood...",value:u,onChange:he=>h(he.target.value),className:"pl-9"})]}),e.jsxs(ms,{value:g.sortBy,onValueChange:he=>x({...g,sortBy:he}),children:[e.jsx(us,{className:"w-[180px]",children:e.jsx(fs,{placeholder:"Sort by"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"newest",children:"Newest First"}),e.jsx(Ge,{value:"updated",children:"Recently Updated"}),e.jsx(Ge,{value:"price_asc",children:"Price: Low to High"}),e.jsx(Ge,{value:"price_desc",children:"Price: High to Low"})]})]}),e.jsxs($,{variant:"outline",onClick:()=>o(!l),children:[e.jsx(Cw,{className:"h-4 w-4 mr-2"}),"Filters"]})]}),l&&e.jsx(SXn,{filters:g,onFiltersChange:x,onClose:()=>o(!1),showCommercial:m!=="residential"}),v?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(6)].map((he,ue)=>e.jsxs(je,{children:[e.jsx(xn,{className:"h-48 w-full"}),e.jsxs(Ie,{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"})]})]},ue))}):(y==null?void 0:y.length)===0?e.jsx(je,{children:e.jsxs(Ie,{className:"py-12 text-center",children:[e.jsx(va,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No listings found"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Be the first to share a listing with the community!"}),e.jsxs($,{onClick:()=>s("/mission-control/listings/new"),children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Add Listing"]})]})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:W.map(he=>e.jsx(hX,{listing:he,onClick:()=>G(he)},he.id))})]}),e.jsx(Xt,{value:"my-listings",className:"space-y-4",children:A?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(3)].map((he,ue)=>e.jsxs(je,{children:[e.jsx(xn,{className:"h-48 w-full"}),e.jsxs(Ie,{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"})]})]},ue))}):(S==null?void 0:S.length)===0?e.jsx(je,{children:e.jsxs(Ie,{className:"py-12 text-center",children:[e.jsx($I,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No listings yet"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Share your listings with the LevelUp community!"}),e.jsxs($,{onClick:()=>s("/mission-control/listings/new"),children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Add Your First Listing"]})]})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:S==null?void 0:S.map(he=>e.jsx(hX,{listing:he,showActions:!0,onClick:()=>G(he),onEdit:()=>s(he.listing_class==="commercial"?`/mission-control/listings/${he.id}/commercial`:`/mission-control/listings/${he.id}/edit`),onDelete:()=>Y(he.id),onLaunchKit:()=>d(he),onCreateMusicVideo:()=>{const ue=(he.photos??[]).slice().sort((ve,Ee)=>(Ee.is_primary?1:0)-(ve.is_primary?1:0)||(ve.sort_order??0)-(Ee.sort_order??0)).map(ve=>ve.photo_url).filter(Boolean);if(ue.length===0){re.error("Add photos to this listing first.");return}Irs({photos:ue,details:{address:he.property_address||`${he.city??""} ${he.state??""}`.trim(),beds:he.bedrooms?String(he.bedrooms):"",baths:he.bathrooms?String(he.bathrooms):"",sqft:he.square_footage?String(he.square_footage):"",price:he.price?String(he.price):"",highlights:he.description||""},sourceLabel:"My Listings",badge:Lrs(he.status,he.price)}),s("/admin/beta/homereel?tab=music-video")}},he.id))})}),e.jsxs(Xt,{value:"pitches",className:"space-y-4",children:[e.jsx(je,{className:"border-dashed",children:e.jsx(Ie,{className:"py-4 text-sm text-muted-foreground",children:"Pitches are private to you. They never appear in the Exchange, public search, or sitemaps until you mark the assignment as won."})}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:V.map(he=>e.jsx(hX,{listing:he,showActions:!0,onClick:()=>s(`/mission-control/listings/${he.id}/commercial`),onEdit:()=>s(`/mission-control/listings/${he.id}/commercial`),onDelete:()=>Y(he.id)},he.id))})]}),e.jsx(Xt,{value:"saved",className:"space-y-4",children:w?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(3)].map((he,ue)=>e.jsxs(je,{children:[e.jsx(xn,{className:"h-48 w-full"}),e.jsxs(Ie,{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"})]})]},ue))}):(b==null?void 0:b.length)===0?e.jsx(je,{children:e.jsxs(Ie,{className:"py-12 text-center",children:[e.jsx(Jo,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No saved listings"}),e.jsx("p",{className:"text-muted-foreground",children:"Save listings to quickly access them later"})]})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:b==null?void 0:b.map(he=>e.jsx(hX,{listing:he.listing,onClick:()=>G(he.listing)},he.id))})}),e.jsx(Xt,{value:"referrals",className:"space-y-6",children:e.jsxs("div",{className:"grid md:grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"font-semibold mb-3 flex items-center gap-2",children:[e.jsx(Fd,{className:"h-4 w-4"}),"Referrals Sent (",((le=E==null?void 0:E.sent)==null?void 0:le.length)||0,")"]}),((ne=E==null?void 0:E.sent)==null?void 0:ne.length)===0?e.jsx(je,{children:e.jsx(Ie,{className:"py-8 text-center text-muted-foreground",children:"No referrals sent yet"})}):e.jsx("div",{className:"space-y-3",children:(te=E==null?void 0:E.sent)==null?void 0:te.map(he=>{var ue,ve;return e.jsx(je,{children:e.jsx(Ie,{className:"p-4",children:e.jsxs("div",{className:"flex justify-between items-start mb-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:he.buyer_name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:((ue=he.listing)==null?void 0:ue.property_address)||((ve=he.listing)==null?void 0:ve.city)})]}),e.jsx($e,{variant:he.status==="closed"?"default":"secondary",children:he.status.replace("_"," ")})]})})},he.id)})})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"font-semibold mb-3 flex items-center gap-2",children:[e.jsx(Yn,{className:"h-4 w-4"}),"Referrals Received (",((J=E==null?void 0:E.received)==null?void 0:J.length)||0,")"]}),((ce=E==null?void 0:E.received)==null?void 0:ce.length)===0?e.jsx(je,{children:e.jsx(Ie,{className:"py-8 text-center text-muted-foreground",children:"No referrals received yet"})}):e.jsx("div",{className:"space-y-3",children:(_e=E==null?void 0:E.received)==null?void 0:_e.map(he=>{var ue;return e.jsx(je,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsxs("div",{className:"flex justify-between items-start mb-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:he.buyer_name}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["From: ",(ue=he.sender)==null?void 0:ue.name]})]}),e.jsx($e,{variant:he.status==="closed"?"default":"secondary",children:he.status.replace("_"," ")})]}),e.jsx($,{size:"sm",variant:"outline",className:"w-full mt-2",onClick:()=>s(`/mission-control/listings/${he.listing_id}`),children:"View Listing"})]})},he.id)})})]})]})}),t&&e.jsx(Xt,{value:"brokerage",className:"space-y-4",children:R?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(3)].map((he,ue)=>e.jsxs(je,{children:[e.jsx(xn,{className:"h-48 w-full"}),e.jsxs(Ie,{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"})]})]},ue))}):(P==null?void 0:P.length)===0?e.jsx(je,{children:e.jsxs(Ie,{className:"py-12 text-center",children:[e.jsx($I,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No brokerage listings yet"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"No agents in your brokerage have added listings yet."}),e.jsxs($,{onClick:()=>s("/mission-control/listings/new"),children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Add a Listing"]})]})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:P==null?void 0:P.map(he=>e.jsx(hX,{listing:he,onClick:()=>G(he)},he.id))})}),e.jsx(Xt,{value:"map",children:e.jsx(EXn,{listings:y||[],isLoading:v})}),e.jsx(Xt,{value:"leaderboard",children:e.jsx(CXn,{leaderboard:D})})]})]}),e.jsx(jXn,{}),e.jsx(Trs,{listingId:(c==null?void 0:c.id)??null,open:!!c,onOpenChange:he=>!he&&d(null),listingAddress:c==null?void 0:c.property_address,listingSlug:(c==null?void 0:c.slug)??null})]}):e.jsx(Vs,{title:"Listing Exchange",description:"Community-powered listing collaboration",children:e.jsx(je,{children:e.jsxs(Ie,{className:"py-12 text-center",children:[e.jsx(va,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"Coming Soon"}),e.jsx("p",{className:"text-muted-foreground",children:"Listing Exchange is currently in development. Check back soon!"})]})})})}const MXn=s=>s<1024?`${s} B`:s<1024*1024?`${(s/1024).toFixed(0)} KB`:`${(s/(1024*1024)).toFixed(1)} MB`;function PXn({listingId:s,ownerOnly:t=!1}){const{data:n=[]}=i6e(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 Gst(i);window.open(l,"_blank")}catch{re.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(Jr,{className:"h-5 w-5"}),"Documents & Disclosures (",r.length,")"]})}),e.jsx(Ie,{children:e.jsx("div",{className:"space-y-2",children:r.map(i=>e.jsxs("button",{onClick:()=>a(i.storage_path),className:"w-full flex items-center gap-3 p-3 rounded-lg border hover:bg-muted transition-colors text-left group",children:[e.jsx("div",{className:"p-2 rounded-md bg-primary/10 flex-shrink-0",children:e.jsx(Jr,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-sm font-medium truncate",children:i.file_name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:MXn(i.file_size)})]}),e.jsx(xi,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary"})]},i.id))})})]})}function xw(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 Yie(){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 Rrs(){const s=Sa(),t=Wt();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 eY(){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 Drs(){const s=Sa(),t=Wt();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 Frs(){const s=Wt();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 IXn(){const s=Wt();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 LXn(){const s=Wt();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 RXn(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 DXn(){const s=Wt();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 FXn(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 OXn(){const s=Wt();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 zXn(){const s=Wt();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 BXn(){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+(xw(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+(xw(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+(xw(c)||0),0),projectedAnnualNet:l.reduce((o,c)=>o+(xw(c)||0),0)+r.reduce((o,c)=>{const d=(c.probability??50)/100;return o+(xw(c)||0)*d},0)}},enabled:!!s})}function $Xn(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 UXn(){const s=Wt();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 qXn(){const s=Wt();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 VXn({listing:s}){const t=Xn(),[n,r]=j.useState(""),[a,i]=j.useState(!1),{data:l,isLoading:o}=$Xn(s.id),{data:c,isLoading:d}=Yie(),{data:u,isLoading:h}=eY(),m=Rrs(),f=UXn(),g=qXn(),x=Drs(),y=(u==null?void 0:u.filter(A=>!A.listing_id))||[],v=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=v(s.status);await x.mutateAsync({deal_name:s.property_address?`${s.property_address}, ${s.city}`:`${s.city}, ${s.state}`,deal_type:"seller",stage_id:(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}),re.success("Deal created and linked to listing!")}catch(A){console.error("Failed to create deal:",A),re.error("Failed to create deal")}finally{i(!1)}},w=async()=>{if(!n){re.error("Please select a deal");return}try{await f.mutateAsync({dealId:n,listingId:s.id}),re.success("Listing linked to deal!"),r("")}catch{re.error("Failed to link listing")}},S=async()=>{if(l)try{await g.mutateAsync({dealId:l.id,listingId:s.id}),re.success("Listing unlinked from deal")}catch{re.error("Failed to unlink listing")}};return o||d?e.jsxs(je,{children:[e.jsx(St,{children:e.jsxs(Et,{className:"flex items-center gap-2 text-base",children:[e.jsx(l2,{className:"h-4 w-4"}),"Deal Pipeline"]})}),e.jsx(Ie,{children:e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(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(Wd,{className:"h-4 w-4 text-primary"}),"Linked to Pipeline"]})}),e.jsxs(Ie,{className:"space-y-3",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:l.deal_name}),e.jsx("div",{className:"flex items-center gap-2 mt-1",children:l.deal_pipeline_stages&&e.jsx($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(n7,{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(l2,{className:"h-4 w-4"}),"Deal Pipeline"]})}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Link this listing to your pipeline to track the deal and sync status changes."}),e.jsxs($,{onClick:b,disabled:a||x.isPending,className:"w-full",size:"sm",children:[a||x.isPending?e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Create New Deal"]}),y.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-0 flex items-center",children:e.jsx("span",{className:"w-full border-t"})}),e.jsx("div",{className:"relative flex justify-center text-xs uppercase",children:e.jsx("span",{className:"bg-card px-2 text-muted-foreground",children:"or"})})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(ms,{value:n,onValueChange:r,children:[e.jsx(us,{className:"flex-1 text-sm",children:e.jsx(fs,{placeholder:"Link to existing deal..."})}),e.jsx(hs,{children:y.map(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(Wd,{className:"h-4 w-4"})})]})]})]})]})}const HXn={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"},GXn={active:"Active",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},b3t={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"};function WXn(){var he,ue,ve,Ee,Se,Le,Fe,ke,Be;const{listingId:s}=Wi(),t=Xn(),{user:n,isAdmin:r}=bs(),{data:a,isLoading:i}=Zae(s||""),{data:l}=z$t(s||""),{data:o}=bqs(s||""),c=O$t(),d=vqs(),u=_qs(),h=I$t(),m=jqs(),[f,g]=j.useState(!1),[x,y]=j.useState(!1),[v,b]=j.useState(!1),[w,S]=j.useState(!1),[A,E]=gc();j.useEffect(()=>{A.get("launchkit")==="1"&&(S(!0),A.delete("launchkit"),E(A,{replace:!0}))},[A,E]);const[I,P]=j.useState(!1),[R,D]=j.useState(!1),[O,U]=j.useState(!1),[W,V]=j.useState(null),[G,Y]=j.useState({buyerName:"",buyerType:"",notes:""}),X=A$t(a==null?void 0:a.agent_id),ae=(n==null?void 0:n.id)===(a==null?void 0:a.agent_id)||X,le=Ne=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(Ne),ne=async Ne=>{const Ae=`https://listings.relevelup.com/${(a==null?void 0:a.slug)||(a==null?void 0:a.id)}`,Ce=`Check out this listing: ${(a==null?void 0:a.property_address)||(a==null?void 0:a.city)}`;u.mutate({listingId:a.id,shareType:Ne});try{switch(Ne){case"facebook":window.open(`https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(Ae)}`,"_blank");break;case"copy":await navigator.clipboard.writeText(Ae),re.success("Link copied to clipboard!");break;case"text":window.open(`sms:?body=${encodeURIComponent(`${Ce} ${Ae}`)}`);break;case"email":window.open(`mailto:?subject=${encodeURIComponent(Ce)}&body=${encodeURIComponent(`Check out this listing: ${Ae}`)}`);break}}catch(Ve){console.error("Share error:",Ve),re.error("Failed to share")}},te=async()=>{try{await h.mutateAsync(a.id),re.success("Listing deleted"),t("/mission-control/listings")}catch{re.error("Failed to delete listing")}},J=async()=>{if(!G.buyerName.trim()){re.error("Please enter buyer name");return}try{await m.mutateAsync({listingId:a.id,listingAgentId:a.agent_id,buyerName:G.buyerName,buyerType:G.buyerType||void 0,notes:G.notes||void 0}),re.success("Referral sent successfully!"),y(!1),Y({buyerName:"",buyerType:"",notes:""})}catch{re.error("Failed to send referral")}},ce=Ne=>{var Xe,at;const Ae=(a==null?void 0:a.property_address)||`${a==null?void 0:a.city}, ${a==null?void 0:a.state}`,Ce=le((a==null?void 0:a.price)||0),Ve=a!=null&&a.bedrooms?`${a.bedrooms}BD`:"",ze=a!=null&&a.bathrooms?`${a.bathrooms}BA`:"",qe=a!=null&&a.square_footage?`${a.square_footage.toLocaleString()}SF`:"",dt=[Ve,ze,qe].filter(Boolean).join(" | ");switch(Ne){case"just_listed":return`🏡 JUST LISTED! ${Ae} ${Ce} ${dt} ${(a==null?void 0:a.description)||"Schedule your showing today!"} #JustListed #RealEstate #HomeForSale #${(Xe=a==null?void 0:a.city)==null?void 0:Xe.replace(/\s/g,"")}`;case"price_improvement":return`📣 PRICE IMPROVEMENT! ${Ae} Now ${Ce}! ${dt} Don't miss this opportunity! #PriceReduced #RealEstate #HomeForSale`;case"teaser":return`Looking for a ${b3t[(a==null?void 0:a.property_type)||"single_family"].toLowerCase()} in ${a==null?void 0:a.city}? 👀 I've got just the one for you! ${dt} DM me for details! 📩 #ComingSoon #RealEstate #${(at=a==null?void 0:a.city)==null?void 0:at.replace(/\s/g,"")}`;default:return""}};if(a&&a.listing_class==="commercial")return e.jsx(Rd,{to:`/mission-control/listings/${a.id}/commercial`,replace:!0});if(i)return e.jsx(Vs,{title:"Listing",description:"",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(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(!a)return e.jsx(Vs,{title:"Listing Not Found",description:"",children:e.jsx(je,{children:e.jsxs(Ie,{className:"py-12 text-center",children:[e.jsx("p",{className:"text-muted-foreground mb-4",children:"This listing could not be found."}),e.jsx($,{onClick:()=>t("/mission-control/listings"),children:"Back to Listings"})]})})});const _e=((he=a.photos)==null?void 0:he.find(Ne=>Ne.is_primary))||((ue=a.photos)==null?void 0:ue[0]);return e.jsxs(Vs,{title:"",description:"",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs($,{variant:"ghost",onClick:()=>t("/mission-control/listings"),children:[e.jsx(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:()=>_e&&V(_e.photo_url),children:_e?e.jsx("img",{src:_e.photo_url,alt:"Primary",className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:"No photos"})})}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:(ve=a.photos)==null?void 0:ve.slice(1,5).map((Ne,Ae)=>e.jsx("div",{className:"aspect-square rounded-lg overflow-hidden bg-muted cursor-pointer",onClick:()=>V(Ne.photo_url),children:e.jsx("img",{src:Ne.photo_url,alt:`Photo ${Ae+2}`,className:"w-full h-full object-cover"})},Ne.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(Ie,{className:"p-6",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-4 mb-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx($e,{className:`${HXn[a.status]} text-white border-0`,children:GXn[a.status]}),a.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"]}),a.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:le(a.price)}),a.property_address&&e.jsx("p",{className:"text-xl font-medium",children:a.property_address}),e.jsxs("p",{className:"text-muted-foreground flex items-center gap-1",children:[e.jsx(ci,{className:"h-4 w-4"}),a.city,", ",a.state,a.neighborhood&&` • ${a.neighborhood}`]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx($,{variant:"outline",size:"icon",onClick:()=>c.mutate(a.id),children:e.jsx(Jo,{className:`h-4 w-4 ${l?"fill-pink-500 text-pink-500":""}`})}),e.jsx($,{variant:"outline",size:"icon",onClick:()=>d.mutate(a.id),children:o?e.jsx(YS,{className:"h-4 w-4"}):e.jsx(Uy,{className:"h-4 w-4"})}),!ae&&e.jsxs($,{variant:"outline",className:"border-amber-500 text-amber-600 hover:bg-amber-50",onClick:()=>b(!0),children:[e.jsx(Nn,{className:"h-4 w-4 mr-2"}),"Share & Earn Leads"]}),e.jsxs($u,{children:[e.jsx(Uu,{asChild:!0,children:e.jsxs($,{variant:"outline",children:[e.jsx(Fd,{className:"h-4 w-4 mr-2"}),"Share"]})}),e.jsxs(Au,{children:[e.jsxs(ja,{onClick:()=>ne("copy"),children:[e.jsx(Ha,{className:"h-4 w-4 mr-2"}),"Copy Link"]}),e.jsxs(ja,{onClick:()=>ne("facebook"),children:[e.jsx(Qp,{className:"h-4 w-4 mr-2"}),"Facebook"]}),e.jsxs(ja,{onClick:()=>ne("text"),children:[e.jsx(eo,{className:"h-4 w-4 mr-2"}),"Text"]}),e.jsxs(ja,{onClick:()=>ne("email"),children:[e.jsx(mn,{className:"h-4 w-4 mr-2"}),"Email"]})]})]}),ae&&e.jsxs(e.Fragment,{children:[e.jsxs($,{variant:"outline",onClick:()=>{const Ne=(a.photos??[]).slice().sort((Ae,Ce)=>(Ce.is_primary?1:0)-(Ae.is_primary?1:0)||(Ae.sort_order??0)-(Ce.sort_order??0)).map(Ae=>Ae.photo_url).filter(Boolean);if(Ne.length===0){re.error("Add photos to this listing first.");return}Irs({photos:Ne,details:{address:a.property_address||`${a.city??""} ${a.state??""}`.trim(),beds:a.bedrooms?String(a.bedrooms):"",baths:a.bathrooms?String(a.bathrooms):"",sqft:a.square_footage?String(a.square_footage):"",price:a.price?String(a.price):"",highlights:a.description||""},sourceLabel:"Listing Exchange",badge:Lrs(a.status,a.price)}),t("/admin/beta/homereel?tab=music-video")},className:"gap-2 border-violet-500/60 text-violet-600 hover:bg-violet-50",children:[e.jsx(Hq,{className:"h-4 w-4"}),"Create Music Video"]}),e.jsxs($,{onClick:()=>S(!0),className:"gap-2 bg-gradient-to-r from-slate-900 to-primary text-white shadow-md hover:opacity-95",children:[e.jsx(qg,{className:"h-4 w-4"}),"Launch Kit"]}),r&&e.jsxs($,{variant:"outline",className:"gap-2",onClick:()=>t(`/mission-control/direct-mail?listing=${s}`),children:[e.jsx(mn,{className:"h-4 w-4"}),"Mail Studio"]}),e.jsxs($,{variant:"outline",onClick:()=>D(!0),className:"gap-2 border-amber-500/60 text-amber-600 hover:bg-amber-50",children:[e.jsx(Nn,{className:"h-4 w-4"}),"Just Listed Graphic"]}),e.jsxs($,{variant:"outline",onClick:()=>U(!0),className:"gap-2",children:[e.jsx(Jp,{className:"h-4 w-4"}),"QR Code"]}),e.jsxs($,{variant:"outline",onClick:()=>P(!0),className:"gap-2",children:[e.jsx(mn,{className:"h-4 w-4"}),"Email My Sphere"]}),e.jsxs($,{onClick:()=>t(`/mission-control/listings/${a.id}/customize`),className:"gap-2 bg-gradient-to-r from-primary to-primary/80 hover:opacity-95 text-primary-foreground shadow-md",children:[e.jsx(Nn,{className:"h-4 w-4"}),"Customize Public Page"]}),e.jsxs($,{variant:"outline",onClick:()=>t(`/mission-control/listings/${a.id}/edit`),children:[e.jsx(_p,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsx($,{variant:"destructive",size:"icon",onClick:()=>g(!0),children:e.jsx(Hn,{className:"h-4 w-4"})})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-4 py-4 border-y",children:[a.bedrooms&&e.jsxs("div",{className:"text-center",children:[e.jsx(r2,{className:"h-5 w-5 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"font-semibold",children:a.bedrooms}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Beds"})]}),a.bathrooms&&e.jsxs("div",{className:"text-center",children:[e.jsx(A0,{className:"h-5 w-5 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"font-semibold",children:a.bathrooms}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Baths"})]}),a.square_footage&&e.jsxs("div",{className:"text-center",children:[e.jsx(j_,{className:"h-5 w-5 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"font-semibold",children:a.square_footage.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Sq Ft"})]}),a.year_built&&e.jsxs("div",{className:"text-center",children:[e.jsx(Ta,{className:"h-5 w-5 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"font-semibold",children:a.year_built}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Built"})]})]}),e.jsxs("div",{className:"pt-4 space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs($e,{variant:"secondary",children:[e.jsx(ji,{className:"h-3 w-3 mr-1"}),b3t[a.property_type]]}),a.lot_size&&e.jsxs($e,{variant:"secondary",children:["Lot: ",a.lot_size]}),a.has_hoa&&e.jsx($e,{variant:"secondary",children:"HOA"})]}),a.description&&e.jsxs("div",{children:[e.jsx("h3",{className:"font-medium mb-2",children:"Description"}),e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:a.description})]}),a.agent_notes&&a.agent_notes_public&&e.jsxs("div",{children:[e.jsx("h3",{className:"font-medium mb-2",children:"Agent Notes"}),e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:a.agent_notes})]}),a.co_agent_name&&e.jsxs("div",{children:[e.jsx("h3",{className:"font-medium mb-2",children:"Co-Listing Agent"}),e.jsxs("div",{className:"flex items-center gap-3 rounded-lg border p-3",children:[a.co_agent_photo_url?e.jsx("img",{src:a.co_agent_photo_url,alt:a.co_agent_name,className:"h-12 w-12 rounded-full object-cover"}):e.jsx("div",{className:"h-12 w-12 rounded-full bg-muted flex items-center justify-center text-sm font-medium",children:a.co_agent_name.charAt(0)}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:a.co_agent_name}),a.co_agent_brokerage&&e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:a.co_agent_brokerage}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:[a.co_agent_email,a.co_agent_phone].filter(Boolean).join(" · ")})]})]})]}),a.mls_link&&e.jsx($,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:a.mls_link,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Fr,{className:"h-4 w-4 mr-2"}),"View on MLS"]})})]}),e.jsxs("div",{className:"flex items-center gap-4 pt-4 mt-4 border-t text-sm text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ca,{className:"h-4 w-4"}),a.view_count," views"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Fd,{className:"h-4 w-4"}),a.share_count," shares"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Jo,{className:"h-4 w-4"}),a.save_count," saves"]})]})]})}),a.allow_sharing&&e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-lg",children:"Share Content"})}),e.jsx(Ie,{className:"space-y-4",children:["just_listed","price_improvement","teaser"].map(Ne=>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:[Ne.replace("_"," ")," Caption"]}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>{navigator.clipboard.writeText(ce(Ne)),re.success("Caption copied!")},children:e.jsx(Ha,{className:"h-3 w-3"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground whitespace-pre-wrap",children:ce(Ne)})]},Ne))})]}),e.jsx(PXn,{listingId:a.id,ownerOnly:ae})]}),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(Ie,{children:[e.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx("span",{className:"text-lg font-semibold text-primary",children:((Se=(Ee=a.agent)==null?void 0:Ee.name)==null?void 0:Se.charAt(0))||"?"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((Le=a.agent)==null?void 0:Le.name)||"Unknown"}),((ke=(Fe=a.agent)==null?void 0:Fe.brokerage)==null?void 0:ke.name)&&e.jsx("p",{className:"text-sm text-muted-foreground",children:a.agent.brokerage.name})]})]}),!ae&&e.jsx("div",{className:"space-y-2",children:((Be=a.agent)==null?void 0:Be.email)&&e.jsx($,{variant:"outline",className:"w-full",asChild:!0,children:e.jsxs("a",{href:`mailto:${a.agent.email}`,children:[e.jsx(mn,{className:"h-4 w-4 mr-2"}),"Email Agent"]})})})]})]}),ae&&e.jsx(VXn,{listing:a}),!ae&&a.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(Ie,{children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Have a buyer interested in this property? Send a referral to the listing agent."}),e.jsx($,{className:"w-full",onClick:()=>y(!0),children:"Send Referral"})]})]})]})]})]}),e.jsx(zs,{open:!!W,onOpenChange:()=>V(null),children:e.jsx(Os,{className:"max-w-4xl",children:e.jsx("img",{src:W||"",alt:"Full size",className:"w-full h-auto"})})}),e.jsx(zs,{open:f,onOpenChange:g,children:e.jsxs(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Delete Listing"}),e.jsx(Pr,{children:"Are you sure you want to delete this listing? This action cannot be undone."})]}),e.jsxs(Sr,{children:[e.jsx($,{variant:"outline",onClick:()=>g(!1),children:"Cancel"}),e.jsx($,{variant:"destructive",onClick:te,disabled:h.isPending,children:h.isPending?"Deleting...":"Delete"})]})]})}),e.jsx(zs,{open:x,onOpenChange:y,children:e.jsxs(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Send Buyer Referral"}),e.jsx(Pr,{children:"Submit buyer information to the listing agent"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Buyer Name *"}),e.jsx(pe,{value:G.buyerName,onChange:Ne=>Y({...G,buyerName:Ne.target.value}),placeholder:"Enter buyer's name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Buyer Type"}),e.jsxs(ms,{value:G.buyerType,onValueChange:Ne=>Y({...G,buyerType:Ne}),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(Ls,{value:G.notes,onChange:Ne=>Y({...G,notes:Ne.target.value}),placeholder:"Any additional information..."})]})]}),e.jsxs(Sr,{children:[e.jsx($,{variant:"outline",onClick:()=>y(!1),children:"Cancel"}),e.jsx($,{onClick:J,disabled:m.isPending,children:m.isPending?"Sending...":"Send Referral"})]})]})}),e.jsx(NUt,{open:O,onOpenChange:U,url:`https://listings.relevelup.com/${a.slug||a.id}`,title:a.property_address||`${a.city}, ${a.state}`,fileBase:a.slug||a.property_address||a.city}),e.jsx(y6e,{open:v,onOpenChange:b,listingId:(a==null?void 0:a.id)||"",listingSlug:(a==null?void 0:a.slug)||null,listingTitle:(a==null?void 0:a.property_address)||`${a==null?void 0:a.city}, ${a==null?void 0:a.state}`}),a&&e.jsx(DUt,{open:I,onOpenChange:P,listing:a}),e.jsx(tnt,{listingId:(a==null?void 0:a.id)||null,open:R,onOpenChange:D,initialStatus:YEe(a==null?void 0:a.status)}),e.jsx(Trs,{listingId:(a==null?void 0:a.id)||null,open:w,onOpenChange:S,listingAddress:(a==null?void 0:a.property_address)||`${a==null?void 0:a.city}, ${a==null?void 0:a.state}`,listingSlug:(a==null?void 0:a.slug)||null,autoGenerate:!0})]})}function KXn({onImport:s}){const[t,n]=j.useState(""),[r,a]=j.useState([]),[i,l]=j.useState(!1),[o,c]=j.useState(!1),[d,u]=j.useState(null),h=j.useRef(),m=j.useRef(null);j.useEffect(()=>{const b=w=>{m.current&&!m.current.contains(w.target)&&c(!1)};return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[]);const f=async b=>{if(b.trim().length<3){a([]),c(!1);return}l(!0);try{const{data:w,error:S}=await q.functions.invoke("mls-listing-search",{body:{query:b}});if(S)throw S;a((w==null?void 0:w.listings)||[]),c(!0)}catch(w){console.error("MLS search error:",w),a([])}finally{l(!1)}},g=b=>{n(b),h.current&&clearTimeout(h.current),h.current=setTimeout(()=>f(b),400)},x=b=>{u(b.mlsNumber),s(b),c(!1),n(`${b.address}, ${b.city}`),re.success(`Imported: ${b.address}`,{description:"Property details and photos have been auto-filled."}),u(null)},y=b=>b?`$${b.toLocaleString()}`:"",v=b=>{const w=(b||"").toLowerCase();return w.includes("single")||w.includes("detached")?"Single Family":w.includes("condo")?"Condo":w.includes("town")?"Townhouse":w.includes("land")||w.includes("lot")?"Land":w.includes("multi")?"Multi-Family":w.includes("commercial")?"Commercial":b||"Other"};return e.jsxs(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(xi,{className:"h-4 w-4 text-primary"}),"Import from MLS"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Search by address to auto-fill property details and photos from MLS"})]}),e.jsx(Ie,{children:e.jsxs("div",{ref:m,className:"relative",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Zr,{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(pr,{className:"h-4 w-4"})})]}),o&&e.jsx("div",{className:"absolute z-50 w-full mt-1 bg-popover border rounded-lg shadow-lg max-h-[400px] overflow-y-auto",children:r.length===0&&!i?e.jsx("div",{className:"p-4 text-center text-sm text-muted-foreground",children:"No properties found. Try a different address."}):r.map(b=>e.jsxs("button",{type:"button",onClick:()=>x(b),disabled:d===b.mlsNumber,className:"w-full text-left p-3 hover:bg-accent/50 transition-colors border-b last:border-0 flex items-start gap-3",children:[b.photos[0]?e.jsx("img",{src:b.photos[0],alt:"",className:"w-16 h-12 rounded object-cover flex-shrink-0"}):e.jsx("div",{className:"w-16 h-12 rounded bg-muted flex items-center justify-center flex-shrink-0",children:e.jsx(ci,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:b.address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[b.city,", ",b.state," ",b.zip]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-muted-foreground",children:[e.jsx("span",{className:"font-semibold text-foreground",children:y(b.price)}),b.bedrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(r2,{className:"h-3 w-3"})," ",b.bedrooms]}),b.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(A0,{className:"h-3 w-3"})," ",b.bathrooms]}),b.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(P4,{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:v(b.propertyType)}),b.photos.length>0&&e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[b.photos.length," photos"]})]})]},b.mlsNumber))})]})})]})}function YXn({selectedVideoId:s,onVideoSelect:t,listingId:n}){const r=Xn(),{user:a}=bs(),[i,l]=j.useState(!1),[o,c]=j.useState([]),[d,u]=j.useState(!1),[h,m]=j.useState(null),[f,g]=j.useState({});j.useEffect(()=>{s&&a?x():m(null)},[s,a]);const x=async()=>{if(!s)return;const{data:R,error:D}=await q.from("agent_videos").select("id, bunny_video_id, title, thumbnail_url, preview_url, playback_url, duration_seconds, status, created_at").eq("id",s).eq("is_deleted",!1).single();!D&&R&&(m(R),y(R))},y=async R=>{try{const{data:D,error:O}=await q.functions.invoke("bunny-upload",{body:{action:"asset-urls",videoId:R.bunny_video_id,isAgentVideo:!0}});!O&&(D!=null&&D.thumbnailUrl)&&g(U=>({...U,[R.id]:{thumbnailUrl:D.thumbnailUrl}}))}catch(D){console.warn("Failed to get signed URL",D)}},v=async()=>{if(a){u(!0);try{const{data:R,error:D}=await q.from("agent_videos").select("id, bunny_video_id, title, thumbnail_url, preview_url, playback_url, duration_seconds, status, created_at").eq("owner_user_id",a.id).eq("is_deleted",!1).eq("status","ready").order("created_at",{ascending:!1});if(D)throw D;c(R||[]),R!=null&&R.length&&b(R)}catch(R){console.error("Error fetching videos:",R),re.error("Failed to load videos")}finally{u(!1)}}},b=async R=>{var D;try{const O=R.map(Y=>Y.bunny_video_id),{data:U,error:W}=await q.functions.invoke("bunny-upload",{body:{action:"bulk-asset-urls",videoIds:O,isAgentVideo:!0}});if(W)throw W;const V=(U==null?void 0:U.assets)||{},G={};for(const Y of R)(D=V[Y.bunny_video_id])!=null&&D.thumbnailUrl&&(G[Y.id]={thumbnailUrl:V[Y.bunny_video_id].thumbnailUrl});g(Y=>({...Y,...G}))}catch(O){console.warn("Failed to bulk-fetch signed URLs",O)}},w=()=>{l(!0),v()},S=R=>{t(R.id),m(R),l(!1),re.success("Video selected")},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(Ie,{className:"p-0",children:e.jsxs("div",{className:"flex items-start gap-4 p-4",children:[e.jsxs("div",{className:"relative w-32 h-20 bg-muted rounded-lg overflow-hidden flex-shrink-0",children:[P(h)?e.jsx("img",{src:P(h),alt:h.title||"Video thumbnail",className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(ua,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx("div",{className:"absolute inset-0 bg-black/30 flex items-center justify-center",children:e.jsx(zu,{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(pr,{className:"h-4 w-4"})})]})]})})}):e.jsx(je,{className:"border-dashed",children:e.jsx(Ie,{className:"p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx(ua,{className:"h-10 w-10 mx-auto text-muted-foreground mb-3"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Add a video walkthrough to showcase this property"}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2 justify-center",children:[e.jsxs($,{type:"button",variant:"outline",onClick:w,className:"gap-2",children:[e.jsx(d2,{className:"h-4 w-4"}),"Select from Library"]}),e.jsxs($,{type:"button",variant:"outline",onClick:E,className:"gap-2",children:[e.jsx(Sx,{className:"h-4 w-4"}),"Record New Video"]})]})]})})}),e.jsx(zs,{open:i,onOpenChange:l,children:e.jsxs(Os,{className:"max-w-2xl max-h-[80vh] overflow-hidden flex flex-col",children:[e.jsx(Us,{children:e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(d2,{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(ua,{className:"h-12 w-12 mx-auto text-muted-foreground mb-3"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"No videos in your library yet"}),e.jsxs($,{onClick:E,className:"gap-2",children:[e.jsx(Sx,{className:"h-4 w-4"}),"Record Your First Video"]})]}):e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3 p-1",children:o.map(R=>e.jsxs("button",{type:"button",onClick:()=>S(R),className:`group relative rounded-lg overflow-hidden border-2 transition-all text-left ${s===R.id?"border-primary ring-2 ring-primary/20":"border-transparent hover:border-muted-foreground/30"}`,children:[e.jsxs("div",{className:"aspect-video bg-muted relative",children:[P(R)?e.jsx("img",{src:P(R),alt:R.title||"Video",className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(ua,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx("div",{className:"absolute inset-0 bg-black/0 group-hover:bg-black/30 transition-colors flex items-center justify-center",children:e.jsx(zu,{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(Sx,{className:"h-4 w-4"}),"Record New Video"]}),e.jsx($,{type:"button",variant:"outline",onClick:()=>l(!1),children:"Cancel"})]})]})})]})}const ZXn=s=>s<1024?`${s} B`:s<1024*1024?`${(s/1024).toFixed(0)} KB`:`${(s/(1024*1024)).toFixed(1)} MB`;function XXn({listingId:s}){const t=j.useRef(null),{data:n=[],isLoading:r}=i6e(s),a=B$t(),i=$$t(),l=Tqs(),o=async d=>{if(!(!d||d.length===0)){for(const u of Array.from(d)){if(u.size>25*1024*1024){re.error(`${u.name} exceeds 25MB limit`);continue}try{await a.mutateAsync({listingId:s,file:u})}catch(h){re.error(`Failed to upload ${u.name}: ${h.message}`)}}t.current&&(t.current.value=""),re.success("Documents uploaded")}},c=async d=>{try{const u=await Gst(d);window.open(u,"_blank")}catch{re.error("Failed to open document")}};return e.jsxs("div",{className:"space-y-3",children:[e.jsx("input",{ref:t,type:"file",multiple:!0,accept:".pdf,application/pdf",className:"hidden",onChange:d=>o(d.target.files)}),e.jsxs($,{type:"button",variant:"outline",onClick:()=>{var d;return(d=t.current)==null?void 0:d.click()},disabled:a.isPending,className:"w-full",children:[a.isPending?e.jsx(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(Jr,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-sm font-medium truncate",children:d.file_name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:ZXn(d.file_size)})]}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[d.visible_on_exchange?e.jsx(Ca,{className:"h-3 w-3"}):e.jsx($g,{className:"h-3 w-3"}),e.jsx("span",{className:"hidden sm:inline",children:d.visible_on_exchange?"Visible":"Hidden"}),e.jsx(Sn,{checked:d.visible_on_exchange,onCheckedChange:u=>l.mutate({id:d.id,visible:u,listingId:s}),className:"ml-1"})]}),e.jsx($,{type:"button",variant:"ghost",size:"icon",onClick:()=>c(d.storage_path),children:e.jsx(xi,{className:"h-4 w-4"})}),e.jsx($,{type:"button",variant:"ghost",size:"icon",onClick:async()=>{await fo(`Delete ${d.file_name}?`)&&i.mutate({id:d.id,storage_path:d.storage_path,listingId:s})},children:e.jsx(pr,{className:"h-4 w-4 text-destructive"})})]},d.id))})]})}const QXn=[{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"}],JXn=[{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 eQn({id:s,url:t,index:n,onRemove:r}){const{attributes:a,listeners:i,setNodeRef:l,transform:o,transition:c,isDragging:d}=x6e({id:s}),u={transform:PL.Transform.toString(o),transition:c};return e.jsxs("div",{ref:l,style:u,className:`relative aspect-square rounded-lg overflow-hidden bg-muted group ${d?"opacity-50 ring-2 ring-primary z-50":""}`,children:[e.jsx("img",{src:t,alt:"",className:"w-full h-full object-cover"}),e.jsx("button",{type:"button",...a,...i,className:"absolute top-1 left-1 p-1 bg-black/60 text-white rounded cursor-grab active:cursor-grabbing opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx(Ug,{className:"h-3.5 w-3.5"})}),e.jsx("button",{type:"button",onClick:()=>r(n),className:"absolute top-1 right-1 p-1 bg-destructive text-destructive-foreground rounded-full hover:bg-destructive/90 opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx(pr,{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 tQn({photoUrls:s,pendingPhotos:t,onRemove:n,onReorder:r,uploading:a,onUpload:i}){const l=l6e(EG(dK,{activationConstraint:{distance:5}})),o=s.map((d,u)=>`pending-${u}`),c=d=>{const{active:u,over:h}=d;if(!h||u.id===h.id)return;const m=o.indexOf(u.id),f=o.indexOf(h.id),g=[...s],x=[...t],[y]=g.splice(m,1),[v]=x.splice(m,1);g.splice(f,0,y),x.splice(f,0,v),r(g,x)};return e.jsxs("div",{className:"space-y-2",children:[s.length>1&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Drag photos to reorder. First photo will be primary."}),e.jsx(f6e,{sensors:l,collisionDetection:c6e,onDragEnd:c,children:e.jsx(g6e,{items:o,strategy:eie,children:e.jsxs("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-4",children:[s.map((d,u)=>e.jsx(eQn,{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 _3t(){const{listingId:s}=Wi(),[t]=gc(),n=t.get("brokerage"),r=Xn(),{user:a}=bs(),{hasLeadSite:i}=ng(),l=!!s&&s!=="new",o=!!n&&!l,[c,d]=j.useState([]),[u,h]=j.useState({open:!1,listingId:null,nextPath:"/mission-control/listings"}),{data:m,isLoading:f}=Zae(l?s:""),g=M$t(),x=xqs(),y=P$t(),v=L$t(),b=R$t(),w=D$t(),S=F$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=[]}=Mae(),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 Ve=Array.from(new Set((Ae||[]).map(dt=>dt.user_id)));if(!Ve.length)return[];const{data:ze,error:qe}=await q.from("profiles").select("id, name, email, phone, avatar_url, brokerage_name").in("id",Ve).order("name");if(qe)throw qe;return ze||[]},enabled:D.length>0}),[W,V]=j.useState(""),G=W||(a==null?void 0:a.id)||"",Y=O&&!o&&U.length>1,[X,ae]=j.useState(!1),[le,ne]=j.useState([]),[te,J]=j.useState([]),[ce,_e]=j.useState(!1),he=async Ae=>{if(Ae.size>5*1024*1024){re.error("Image must be under 5MB");return}_e(!0);try{const Ce=Ae.name.split(".").pop()||"jpg",Ve=`${(a==null?void 0:a.id)||"anon"}/co-agents/${Date.now()}.${Ce}`,{error:ze}=await q.storage.from("listing-photos").upload(Ve,Ae,{upsert:!0});if(ze)throw ze;const{data:qe}=q.storage.from("listing-photos").getPublicUrl(Ve);ve(dt=>({...dt,co_agent_photo_url:qe.publicUrl})),re.success("Headshot uploaded")}catch(Ce){re.error((Ce==null?void 0:Ce.message)||"Failed to upload headshot")}finally{_e(!1)}},[ue,ve]=j.useState({property_address:"",city:"",state:"",neighborhood:"",price:"",property_type:"single_family",status:"active",bedrooms:"",bathrooms:"",square_footage:"",lot_size:"",year_built:"",has_hoa:!1,description:"",agent_notes:"",agent_notes_public:!1,mls_link:"",video_link:"",video_id:null,co_agent_name:"",co_agent_email:"",co_agent_phone:"",co_agent_brokerage:"",co_agent_photo_url:"",allow_sharing:!0,open_to_referrals:!0,open_to_social_promotion:!0,share_with_brokerage:!1,is_public:!0,site_only:!1,show_on_lead_site:!0});j.useEffect(()=>{var Ae,Ce,Ve,ze,qe;m&&l&&(ve({property_address:m.property_address||"",city:m.city||"",state:m.state||"",neighborhood:m.neighborhood||"",price:((Ae=m.price)==null?void 0:Ae.toString())||"",property_type:m.property_type,status:m.status,bedrooms:((Ce=m.bedrooms)==null?void 0:Ce.toString())||"",bathrooms:((Ve=m.bathrooms)==null?void 0:Ve.toString())||"",square_footage:((ze=m.square_footage)==null?void 0:ze.toString())||"",lot_size:m.lot_size||"",year_built:((qe=m.year_built)==null?void 0:qe.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 qe,dt;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"},Ve=(Ae.propertyType||"").toLowerCase(),ze=((qe=Object.entries(Ce).find(([Xe])=>Ve.includes(Xe)))==null?void 0:qe[1])||"other";ve(Xe=>({...Xe,property_address:Ae.address||Xe.property_address,city:Ae.city||Xe.city,state:Ae.state||Xe.state,price:Ae.price?String(Ae.price):Xe.price,property_type:ze,bedrooms:Ae.bedrooms?String(Ae.bedrooms):Xe.bedrooms,bathrooms:Ae.bathrooms?String(Ae.bathrooms):Xe.bathrooms,square_footage:Ae.sqft?String(Ae.sqft):Xe.square_footage,lot_size:Ae.lotSize?String(Ae.lotSize):Xe.lot_size,year_built:Ae.yearBuilt?String(Ae.yearBuilt):Xe.year_built,description:Ae.description||Xe.description})),((dt=Ae.photos)==null?void 0:dt.length)>0&&(d(Ae.photos),te.forEach(Xe=>URL.revokeObjectURL(Xe)),ne([]),J([]))},Se=Ae=>{if(!Ae)return;const Ce=Array.from(Ae);ne(ze=>[...ze,...Ce]);const Ve=Ce.map(ze=>URL.createObjectURL(ze));J(ze=>[...ze,...Ve])},Le=Ae=>{URL.revokeObjectURL(te[Ae]),ne(Ce=>Ce.filter((Ve,ze)=>ze!==Ae)),J(Ce=>Ce.filter((Ve,ze)=>ze!==Ae))},Fe=async Ae=>{var Ce;if(!(!Ae||!m)){ae(!0);try{for(const Ve of Array.from(Ae)){const ze=Ve.name.split(".").pop(),qe=`${a==null?void 0:a.id}/${m.id}/${Date.now()}.${ze}`,{error:dt}=await q.storage.from("listing-photos").upload(qe,Ve);if(dt)throw dt;const{data:{publicUrl:Xe}}=q.storage.from("listing-photos").getPublicUrl(qe);await v.mutateAsync({listingId:m.id,photoUrl:Xe,isPrimary:!((Ce=m.photos)!=null&&Ce.length)})}re.success("Photos uploaded!")}catch(Ve){console.error("Upload error:",Ve),re.error("Failed to upload photos")}finally{ae(!1)}}},ke=async Ae=>{for(let Ce=0;Ce{if(m)try{await b.mutateAsync({photoId:Ae,listingId:m.id}),re.success("Photo removed")}catch{re.error("Failed to remove photo")}},Ne=async Ae=>{if(Ae.preventDefault(),!ue.city.trim()||!ue.state.trim()||!ue.price){re.error("Please fill in required fields (City, State, Price)");return}if(o&&!E){re.error("Please select an agent to assign this listing to");return}try{const Ce={property_address:ue.property_address||null,city:ue.city,state:ue.state,neighborhood:ue.neighborhood||null,price:Number(ue.price),property_type:ue.property_type,status:ue.status,bedrooms:ue.bedrooms?Number(ue.bedrooms):null,bathrooms:ue.bathrooms?Number(ue.bathrooms):null,square_footage:ue.square_footage?Number(ue.square_footage):null,lot_size:ue.lot_size||null,year_built:ue.year_built?Number(ue.year_built):null,has_hoa:ue.has_hoa,description:ue.description||null,agent_notes:ue.agent_notes||null,agent_notes_public:ue.agent_notes_public,mls_link:ue.mls_link||null,video_link:ue.video_link||null,video_id:ue.video_id||null,co_agent_name:ue.co_agent_name||null,co_agent_email:ue.co_agent_email||null,co_agent_phone:ue.co_agent_phone||null,co_agent_brokerage:ue.co_agent_brokerage||null,co_agent_photo_url:ue.co_agent_photo_url||null,allow_sharing:ue.allow_sharing,open_to_referrals:ue.open_to_referrals,open_to_social_promotion:ue.open_to_social_promotion,share_with_brokerage:ue.share_with_brokerage,is_public:ue.site_only?!1:ue.is_public,site_only:ue.site_only,show_on_lead_site:ue.site_only?!0:ue.show_on_lead_site};if(l){const Ve=Y&&G&&G!==(m==null?void 0:m.agent_id)?{agent_id:G}:{},ze=m==null?void 0:m.status;await y.mutateAsync({id:s,...Ce,...Ve}),re.success("Listing updated!");const qe=`/mission-control/listings/${s}`;ze&&ze!==ue.status?h({open:!0,listingId:s,nextPath:qe,socialStatus:YEe(ue.status)}):r(qe)}else{ae(!0);let Ve;if(o&&E?Ve=await x.mutateAsync({agentId:E,...Ce}):Y&&G&&G!==(a==null?void 0:a.id)?Ve=await x.mutateAsync({agentId:G,...Ce}):Ve=await g.mutateAsync(Ce),le.length>0)try{await ke(Ve.id),te.forEach(qe=>URL.revokeObjectURL(qe)),ne([]),J([])}catch(qe){console.error("Photo upload error:",qe),re.error("Listing created but some photos failed to upload")}if(c.length>0)try{for(let qe=0;qer(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(Ie,{children:[e.jsxs(ms,{value:E,onValueChange:I,children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Select an agent..."})}),e.jsx(hs,{children: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."})]})]}),Y&&e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{children:"Primary Listing Agent"})}),e.jsxs(Ie,{children:[e.jsxs(ms,{value:G,onValueChange:V,children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Select the listing agent..."})}),e.jsx(hs,{children:U.map(Ae=>e.jsx(Ge,{value:Ae.id,children:(Ae.name||Ae.email)+(Ae.id===(a==null?void 0:a.id)?" (you)":"")},Ae.id))})]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:"As a team leader you can credit this listing to any agent on your team. It will appear on their Listing Exchange and website."})]})]}),!l&&i&&!o&&e.jsx(KXn,{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(xi,{className:"h-4 w-4 text-primary"}),"MLS Photos (",c.length,")"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"These photos will be imported when you save the listing."})]}),e.jsxs(Ie,{children:[e.jsxs("div",{className:"grid grid-cols-4 sm:grid-cols-6 gap-2",children:[c.slice(0,12).map((Ae,Ce)=>e.jsx("div",{className:"aspect-square rounded overflow-hidden bg-muted",children:e.jsx("img",{src:Ae,alt:"",className:"w-full h-full object-cover"})},Ce)),c.length>12&&e.jsxs("div",{className:"aspect-square rounded bg-muted flex items-center justify-center text-sm text-muted-foreground font-medium",children:["+",c.length-12]})]}),e.jsxs($,{type:"button",variant:"ghost",size:"sm",className:"mt-2 text-destructive",onClick:()=>d([]),children:[e.jsx(pr,{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(Ie,{className:"space-y-4",children:e.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"sm:col-span-2 space-y-2",children:[e.jsx(ee,{children:"Property Address"}),e.jsx(pe,{value:ue.property_address,onChange:Ae=>ve({...ue,property_address:Ae.target.value}),placeholder:"123 Main St"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"City *"}),e.jsx(pe,{value:ue.city,onChange:Ae=>ve({...ue,city:Ae.target.value}),placeholder:"City",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"State *"}),e.jsx(pe,{value:ue.state,onChange:Ae=>ve({...ue,state:Ae.target.value}),placeholder:"State",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Neighborhood"}),e.jsx(pe,{value:ue.neighborhood,onChange:Ae=>ve({...ue,neighborhood:Ae.target.value}),placeholder:"Neighborhood"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Price *"}),e.jsx(pe,{type:"number",value:ue.price,onChange:Ae=>ve({...ue,price:Ae.target.value}),placeholder:"500000",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Property Type"}),e.jsxs(ms,{value:ue.property_type,onValueChange:Ae=>ve({...ue,property_type:Ae}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:JXn.map(Ae=>e.jsx(Ge,{value:Ae.value,children:Ae.label},Ae.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Status"}),e.jsxs(ms,{value:ue.status,onValueChange:Ae=>ve({...ue,status:Ae}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:QXn.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(Ie,{children:e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Bedrooms"}),e.jsx(pe,{type:"number",value:ue.bedrooms,onChange:Ae=>ve({...ue,bedrooms:Ae.target.value}),placeholder:"3"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Bathrooms"}),e.jsx(pe,{type:"number",step:"0.5",value:ue.bathrooms,onChange:Ae=>ve({...ue,bathrooms:Ae.target.value}),placeholder:"2"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Sq Ft"}),e.jsx(pe,{type:"number",value:ue.square_footage,onChange:Ae=>ve({...ue,square_footage:Ae.target.value}),placeholder:"2000"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Lot Size"}),e.jsx(pe,{value:ue.lot_size,onChange:Ae=>ve({...ue,lot_size:Ae.target.value}),placeholder:"0.25 acres"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Year Built"}),e.jsx(pe,{type:"number",value:ue.year_built,onChange:Ae=>ve({...ue,year_built:Ae.target.value}),placeholder:"2005"})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-6",children:[e.jsx(Sn,{checked:ue.has_hoa,onCheckedChange:Ae=>ve({...ue,has_hoa:Ae})}),e.jsx(ee,{children:"Has HOA"})]})]})})]}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{children:"Description & Links"})}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Description"}),e.jsx(Ls,{value:ue.description,onChange:Ae=>ve({...ue,description:Ae.target.value}),placeholder:"Tell the story of this property...",rows:4})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Agent Notes"}),e.jsx(Ls,{value:ue.agent_notes,onChange:Ae=>ve({...ue,agent_notes:Ae.target.value}),placeholder:"Notes for other agents...",rows:2}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sn,{checked:ue.agent_notes_public,onCheckedChange:Ae=>ve({...ue,agent_notes_public:Ae})}),e.jsx(ee,{className:"text-sm text-muted-foreground",children:"Make notes visible to other agents"})]})]}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"MLS Link"}),e.jsx(pe,{value:ue.mls_link,onChange:Ae=>ve({...ue,mls_link:Ae.target.value}),placeholder:"https://..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Video Link"}),e.jsx(pe,{value:ue.video_link,onChange:Ae=>ve({...ue,video_link:Ae.target.value}),placeholder:"YouTube or Vimeo URL"})]})]})]})]}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{children:"Co-Listing Agent (optional)"})}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Credit a second agent on this listing. Their info appears on the listing page alongside yours."}),U.length>1&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Choose a team member"}),e.jsxs(ms,{value:"",onValueChange:Ae=>{const Ce=U.find(Ve=>Ve.id===Ae);Ce&&(ve(Ve=>({...Ve,co_agent_name:Ce.name||Ve.co_agent_name,co_agent_email:Ce.email||"",co_agent_phone:Ce.phone||"",co_agent_brokerage:Ce.brokerage_name||Ve.co_agent_brokerage,co_agent_photo_url:Ce.avatar_url||""})),re.success("Co-listing agent details filled in"))},children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Auto-fill from your team..."})}),e.jsx(hs,{children:U.filter(Ae=>Ae.id!==G).map(Ae=>e.jsx(Ge,{value:Ae.id,children:Ae.name||Ae.email},Ae.id))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Details fill in automatically and stay editable. For agents outside your team, just type below."})]}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Name"}),e.jsx(pe,{value:ue.co_agent_name,onChange:Ae=>ve({...ue,co_agent_name:Ae.target.value}),placeholder:"Jordan Ellis"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Brokerage"}),e.jsx(pe,{value:ue.co_agent_brokerage,onChange:Ae=>ve({...ue,co_agent_brokerage:Ae.target.value}),placeholder:"Brokerage name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Email"}),e.jsx(pe,{type:"email",value:ue.co_agent_email,onChange:Ae=>ve({...ue,co_agent_email:Ae.target.value}),placeholder:"agent@email.com"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Phone"}),e.jsx(pe,{value:ue.co_agent_phone,onChange:Ae=>ve({...ue,co_agent_phone:Ae.target.value}),placeholder:"(555) 123-4567"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Headshot"}),e.jsxs("div",{className:"flex items-center gap-4",children:[ue.co_agent_photo_url?e.jsx("img",{src:ue.co_agent_photo_url,alt:"Co-listing agent headshot",className:"h-20 w-20 rounded-full object-cover border"}):e.jsx("div",{className:"h-20 w-20 rounded-full border border-dashed flex items-center justify-center text-muted-foreground",children:e.jsx(ni,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{id:"co-agent-headshot",type:"file",accept:"image/*",className:"hidden",onChange:Ae=>{var Ve;const Ce=(Ve=Ae.target.files)==null?void 0:Ve[0];Ae.target.value="",Ce&&he(Ce)}}),e.jsx($,{type:"button",variant:"outline",disabled:ce,onClick:()=>{var Ae;return(Ae=document.getElementById("co-agent-headshot"))==null?void 0:Ae.click()},children:ce?e.jsxs(e.Fragment,{children:[e.jsx(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:()=>ve(Ae=>({...Ae,co_agent_photo_url:""})),children:[e.jsx(pr,{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(ua,{className:"h-5 w-5"}),"Property Video"]})}),e.jsx(Ie,{children:e.jsx(YXn,{selectedVideoId:ue.video_id,onVideoSelect:Ae=>ve({...ue,video_id:Ae}),listingId:l?s:void 0})})]}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{children:"Photos"})}),e.jsx(Ie,{children:l&&(m!=null&&m.photos)?e.jsx(uUt,{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(tQn,{photoUrls:te,onRemove:Le,onReorder:(Ae,Ce)=>{J(Ae),ne(Ce)},pendingPhotos:le,uploading:X,onUpload:Se})})]}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(xi,{className:"h-5 w-5"}),"Documents & Disclosures"]})}),e.jsx(Ie,{children:l&&s?e.jsx(XXn,{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(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Allow Sharing"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Other agents can share this listing"})]}),e.jsx(Sn,{checked:ue.allow_sharing,onCheckedChange:Ae=>ve({...ue,allow_sharing:Ae})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Open to Referrals"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Accept buyer referrals"})]}),e.jsx(Sn,{checked:ue.open_to_referrals,onCheckedChange:Ae=>ve({...ue,open_to_referrals:Ae})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Social Promotion"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Can be promoted on social media"})]}),e.jsx(Sn,{checked:ue.open_to_social_promotion,onCheckedChange:Ae=>ve({...ue,open_to_social_promotion:Ae})})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Share with Brokerage"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Visible to agents in your brokerage"})]}),e.jsx(Sn,{checked:ue.share_with_brokerage,onCheckedChange:Ae=>ve({...ue,share_with_brokerage:Ae})})]}),i&&e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"My Website Only"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Hide from the Listing Exchange and other agents — only show it on your own website"})]}),e.jsx(Sn,{checked:ue.site_only,onCheckedChange:Ae=>ve({...ue,site_only:Ae,is_public:Ae?!1:ue.is_public,show_on_lead_site:Ae?!0:ue.show_on_lead_site,share_with_brokerage:Ae?!1:ue.share_with_brokerage})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Make Public"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Publish on listings.relevelup.com to get leads"})]}),e.jsx(Sn,{checked:ue.is_public,disabled:ue.site_only,onCheckedChange:Ae=>ve({...ue,is_public:Ae})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Show on My Website"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:ue.status==="sold"?"Sold listings are hidden from the Listing Exchange and public marketplace — they only build your track record on your website's Sold page.":"Feature this listing on your lead site homepage and listings page"})]}),e.jsx(Sn,{checked:ue.show_on_lead_site,onCheckedChange:Ae=>ve({...ue,show_on_lead_site:Ae})})]})]})]}),e.jsx($,{type:"submit",className:"w-full",size:"lg",disabled:g.isPending||y.isPending,children:g.isPending||y.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),"Saving..."]}):l?"Update Listing":"Create Listing"})]})]})]}),e.jsx(tnt,{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 LXe=[{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"}],Ors=[{type:"extra_video",label:"Extra Video / Reel",icon:ua,desc:"Add a YouTube, Vimeo, or MP4 embed",accent:"from-rose-500/20 to-rose-500/5"},{type:"tour_3d",label:"3D Tour",icon:mJ,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:h2,desc:"A quote from a past client",accent:"from-amber-500/20 to-amber-500/5"},{type:"countdown",label:"Offer Countdown",icon:da,desc:'"Offers due Friday 5pm"',accent:"from-emerald-500/20 to-emerald-500/5"},{type:"custom_cta",label:"Custom CTA Button",icon:Sd,desc:"Link to a brochure or booking page",accent:"from-violet-500/20 to-violet-500/5"}],sQn=["#0f172a","#406E71","#c9a84c","#b91c1c","#0d7a5f","#4f46e5","#e85d3a","#111827"],D$e={sections:Object.fromEntries(LXe.map(s=>[s.key,!0])),hero_style:"photo",accent_color:null,custom_note:"",addons:[]},nQn=()=>Math.random().toString(36).slice(2,10);function rQn(){const{listingId:s}=Wi(),t=Xn(),{user:n}=bs(),r=Wt(),[a,i]=j.useState("desktop"),[l,o]=j.useState(D$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({...D$e,...m.page_config||{},sections:{...D$e.sections,...((D=m.page_config)==null?void 0:D.sections)||{}},addons:((O=m.page_config)==null?void 0:O.addons)||[]})},[m==null?void 0:m.id]);const g=!!n&&!!m&&n.id===m.agent_id,x=j.useMemo(()=>m?`/public/listing/${m.slug||m.id}?preview=1&t=${u}`:"",[m,u]),y=j.useMemo(()=>m?`https://listings.relevelup.com/${m.slug||m.id}`:"",[m]),v=mt({mutationFn:async()=>{const{error:D}=await q.from("listings").update({page_config:l}).eq("id",s);if(D)throw D},onSuccess:()=>{re.success("Saved. Your public page is live."),d(!1),r.invalidateQueries({queryKey:["listing-customize",s]}),r.invalidateQueries({queryKey:["public-listing"]}),h(D=>D+1)},onError:D=>re.error(`Save failed: ${D.message||"Try again"}`)}),b=D=>{o(O=>({...O,...D})),d(!0)},w=(D,O)=>b({sections:{...l.sections||{},[D]:O}}),S=D=>b({addons:[...l.addons||[],{id:nQn(),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(XN,{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(x1,{className:"h-3.5 w-3.5"})," Mobile"]})]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>h(D=>D+1),children:[e.jsx(ro,{className:"h-3.5 w-3.5 mr-1.5"})," Refresh"]}),e.jsx($,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:y,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Fr,{className:"h-3.5 w-3.5 mr-1.5"})," Open live"]})}),e.jsx($,{size:"sm",onClick:()=>v.mutate(),disabled:!c||v.isPending,children:v.isPending?"Saving…":e.jsxs(e.Fragment,{children:[e.jsx(tl,{className:"h-3.5 w-3.5 mr-1.5"})," Save & Publish"]})})]})]}),e.jsxs("div",{className:"grid lg:grid-cols-[minmax(360px,440px)_1fr] gap-6 mt-4",children:[e.jsx(uo,{className:"lg:h-[calc(100vh-140px)] pr-2",children:e.jsxs("div",{className:"space-y-6 pb-16",children:[e.jsx(mX,{icon:e.jsx(Nn,{className:"h-4 w-4"}),title:"Hero",desc:"What visitors see first",children:e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Hero style"}),e.jsx("div",{className:"mt-2 grid grid-cols-3 gap-2",children:["photo","video","slideshow"].map(D=>e.jsx("button",{onClick:()=>b({hero_style:D}),className:`text-xs rounded-lg border py-3 capitalize transition ${l.hero_style===D?"border-primary bg-primary/5 text-primary font-medium":"border-border hover:bg-muted"}`,children:D},D))})]})}),e.jsx(mX,{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"}),sQn.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(mX,{icon:e.jsx(ey,{className:"h-4 w-4"}),title:"Personal note",desc:"Shows in a beautiful callout on the public page",children:e.jsx(Ls,{value:l.custom_note||"",onChange:D=>b({custom_note:D.target.value}),placeholder:"Why we love this home… (optional)",rows:3})}),e.jsx(mX,{icon:e.jsx(LA,{className:"h-4 w-4"}),title:"Page sections",desc:"Toggle any default section on or off",rightLabel:`${R} of ${LXe.length} on`,children:e.jsx("div",{className:"divide-y rounded-xl border",children:LXe.map(D=>{var U;const O=((U=l.sections)==null?void 0:U[D.key])!==!1;return e.jsxs("div",{className:"flex items-center justify-between p-3.5",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:D.label}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:D.hint})]}),e.jsx(Sn,{checked:O,onCheckedChange:W=>w(D.key,W)})]},D.key)})})}),e.jsxs(mX,{icon:e.jsx(dn,{className:"h-4 w-4"}),title:"Add-on modules",desc:"Drop in extras to make this page unique",rightLabel:P?`${P} added`:void 0,children:[e.jsx("div",{className:"grid grid-cols-2 gap-2",children:Ors.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(aQn,{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:()=>v.mutate(),disabled:!c||v.isPending,children:v.isPending?"Saving…":e.jsxs(e.Fragment,{children:[e.jsx(tl,{className:"h-4 w-4 mr-1.5"})," Save & Publish"]})})})]})}),e.jsx("div",{className:"lg:h-[calc(100vh-140px)]",children:e.jsxs(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(Ca,{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(ca,{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(XN,{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(x1,{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 mX({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 aQn({addon:s,onChange:t,onRemove:n,onMoveUp:r,onMoveDown:a}){const i=Ors.find(o=>o.type===s.type),l=i.icon;return e.jsxs("div",{className:"rounded-xl border bg-background p-3.5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx("div",{className:"flex flex-col -my-1",children:e.jsx("button",{onClick:r,disabled:!r,className:"text-muted-foreground/50 hover:text-foreground disabled:opacity-30 leading-none",children:e.jsx(Ug,{className:"h-3.5 w-3.5"})})}),e.jsx("div",{className:"h-7 w-7 rounded-md bg-primary/10 text-primary flex items-center justify-center",children:e.jsx(l,{className:"h-3.5 w-3.5"})}),e.jsx("p",{className:"text-sm font-medium flex-1",children:i.label}),e.jsxs("div",{className:"flex items-center gap-1",children:[a&&e.jsx($,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:a,"aria-label":"Move down",children:e.jsx(Ug,{className:"h-3.5 w-3.5 rotate-180"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-7 w-7 text-destructive hover:text-destructive",onClick:n,"aria-label":"Remove",children:e.jsx(Hn,{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(Ls,{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(Ls,{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 zrs="teleprompter_settings",F$e={scrollSpeed:30,fontSize:24,lineHeight:1.6,opacity:.85,position:"top",isMirrored:!1};function iQn(){try{const s=localStorage.getItem(zrs);return s?{...F$e,...JSON.parse(s)}:F$e}catch{return F$e}}function oQn(s){try{localStorage.setItem(zrs,JSON.stringify(s))}catch{}}function Got({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(iQn),{scrollSpeed:f,fontSize:g,lineHeight:x,opacity:y,position:v,isMirrored:b}=h,w=j.useCallback((U,W)=>{m(V=>{const G={...V,[U]:W};return oQn(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:Y,clientHeight:X}=o.current;if(G+X>=Y){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(Ca,{className:"h-4 w-4 mr-2"}),"Show Script"]})});const O={top:"top-0 pt-16",center:"top-1/2 -translate-y-1/2",bottom:"bottom-0 pb-24"};return e.jsxs("div",{className:Pt("absolute inset-0 pointer-events-none",l),children:[E!==null&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center z-20 pointer-events-none",children:e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx("div",{className:"text-white font-bold drop-shadow-lg animate-scale-in",style:{fontSize:"96px",lineHeight:1,textShadow:"0 4px 16px rgba(0,0,0,0.8)"},children:E},E),e.jsx("p",{className:"text-white/80 text-lg font-medium drop-shadow-md",children:"Get ready…"})]})}),e.jsx("div",{className:Pt("absolute left-0 right-0 h-[60%] overflow-hidden pointer-events-auto",O[v],E!==null&&"opacity-30"),style:{opacity:E!==null?.3:y},children:e.jsxs("div",{ref:o,className:Pt("mx-auto max-w-2xl px-6 overflow-y-auto scrollbar-hide h-full",b&&"scale-x-[-1]"),style:{maskImage:"linear-gradient(to bottom, transparent, black 10%, black 90%, transparent)",WebkitMaskImage:"linear-gradient(to bottom, transparent, black 10%, black 90%, transparent)"},children:[e.jsx("div",{className:"h-full",style:{minHeight:"100%"}}),e.jsx("p",{className:"text-white text-center font-medium drop-shadow-lg",style:{fontSize:`${g}px`,lineHeight:x,textShadow:"0 2px 4px rgba(0,0,0,0.8)"},children:s}),e.jsx("div",{className:"h-full"})]})}),e.jsxs("div",{className:"absolute top-4 right-4 flex items-center gap-2 pointer-events-auto",children:[e.jsxs(Kd,{children:[e.jsx(Yd,{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(Od,{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(Nx,{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(Nx,{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(Nx,{value:[x*10],onValueChange:([U])=>w("lineHeight",U/10),min:12,max:24,step:1})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{className:"text-xs",children:"Opacity"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[Math.round(y*100),"%"]})]}),e.jsx(Nx,{value:[y*100],onValueChange:([U])=>w("opacity",U/100),min:30,max:100,step:5})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-xs",children:"Position"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{variant:v==="top"?"default":"outline",size:"sm",onClick:()=>w("position","top"),children:e.jsx(yb,{className:"h-4 w-4"})}),e.jsx($,{variant:v==="center"?"default":"outline",size:"sm",onClick:()=>w("position","center"),children:e.jsx(ZN,{className:"h-4 w-4"})}),e.jsx($,{variant:v==="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(Sn,{checked:b,onCheckedChange:U=>w("isMirrored",U)})]})]})})]}),e.jsx($,{variant:"secondary",size:"icon",onClick:D,className:"h-9 w-9 bg-black/50 hover:bg-black/70 text-white border-0",children:S?e.jsx(Av,{className:"h-4 w-4"}):e.jsx(zu,{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(Ax,{className:"h-4 w-4"})}),e.jsxs($,{variant:"secondary",size:"sm",onClick:n,className:"bg-black/50 hover:bg-black/70 text-white border-0",children:[e.jsx($g,{className:"h-4 w-4 mr-2"}),"Hide"]})]})]})}function lQn({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}=v9n(),{data:f,isLoading:g}=b9n(),{data:x,isLoading:y}=_9n(),v=w9n(),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 v.mutateAsync(I),a({title:"Script saved to My Scripts"})}catch{a({title:"Failed to save script",variant:"destructive"})}},E=m||g||y;return e.jsxs("div",{className:Pt("flex flex-col h-full",r),children:[e.jsx("div",{className:"p-4 border-b",children:e.jsxs("div",{className:"relative",children:[e.jsx(Zr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search scripts...",value:i,onChange:I=>l(I.target.value),className:"pl-9"})]})}),e.jsxs(ha,{value:d,onValueChange:I=>u(I),className:"flex-1 flex flex-col",children:[e.jsxs(ma,{className:"mx-4 mt-4 grid grid-cols-2",children:[e.jsxs(Zt,{value:"levelup",children:[e.jsx(Jr,{className:"h-4 w-4 mr-2"}),"LevelUp Scripts"]}),e.jsxs(Zt,{value:"my-scripts",children:[e.jsx(E0,{className:"h-4 w-4 mr-2"}),"My Scripts"]})]}),e.jsxs(Xt,{value:"levelup",className:"flex-1 flex flex-col mt-0 p-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-2 mb-4",children:[e.jsx($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(uo,{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(Jr,{className:"h-12 w-12 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"No scripts found"})]}):e.jsx("div",{className:"space-y-2",children:b.map(I=>e.jsxs(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(E0,{className:"h-4 w-4"})}),e.jsx(Di,{className:"h-4 w-4 text-muted-foreground"})]})]})}),e.jsx(Ie,{className:"p-3 pt-0",children:e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2",children:I.script_text})})]},I.id))})})]}),e.jsxs(Xt,{value:"my-scripts",className:"flex-1 flex flex-col mt-0 p-4",children:[t&&e.jsxs($,{variant:"outline",className:"mb-4",onClick:t,children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Create New Script"]}),e.jsx(uo,{className:"flex-1 max-h-[50vh]",children:y?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(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(E0,{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(Ie,{className:"p-3 pt-0",children:e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2",children:I.script_text})})]},I.id))})})]})]})]})}function cQn({selectedTemplate:s,onSelect:t,contactName:n,saving:r=!1}){const[a,i]=j.useState(()=>{const o=_V(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:uqs.map(o=>{const c=hqs(o.id),d=a.has(o.id),u=c.some(h=>h.id===s);return e.jsxs(v1,{open:d,onOpenChange:()=>l(o.id),children:[e.jsxs(b1,{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(_1,{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(ca,{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: "',_V(s).headerText(n),'"']})]})}function Brs({open:s,onOpenChange:t,video:n,contactName:r,onTemplateUpdated:a}){const[i,l]=j.useState(n.page_template||"default"),[o,c]=j.useState(!1),[d,u]=j.useState(!1),[h,m]=j.useState(n.page_template||"default"),[f,g]=j.useState([]),[x,y]=j.useState(n.contact_id&&r?{id:n.contact_id,name:r,email:null}:null),[v,b]=j.useState(!1),[w,S]=j.useState(!1),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:Y}=await q.from("innercircle_contacts").select("id, first_name, last_name, email").order("first_name",{ascending:!0}).limit(500);if(Y)throw Y;const X=(G||[]).map(ae=>({id:ae.id,name:[ae.first_name,ae.last_name].filter(Boolean).join(" ")||"Unnamed",email:ae.email||null}));g(X)}catch(G){console.error("Failed to fetch contacts:",G)}finally{S(!1)}},I=async G=>{y(G),b(!1),c(!0);try{const{error:Y}=await q.from("agent_videos").update({contact_id:(G==null?void 0:G.id)||null,recipient_name:(G==null?void 0:G.name)||null}).eq("id",n.id);if(Y)throw Y;re.success(G?`Assigned to ${G.name}`:"Contact removed"),a==null||a()}catch(Y){console.error("Failed to update contact:",Y),re.error("Failed to update contact")}finally{c(!1)}},P=async G=>{l(G),c(!0);try{const{error:Y}=await q.from("agent_videos").update({page_template:G}).eq("id",n.id);if(Y)throw Y;m(G),re.success("Template saved!"),a==null||a()}catch(Y){console.error("Failed to save template:",Y),re.error("Failed to save template"),l(h)}finally{c(!1)}},R=(x==null?void 0:x.name)||null,D=()=>{const G=n.title||"Video Message",Y=n.share_token?`https://video.relevelup.com/thumb/${n.share_token}`:n.thumbnail_url||"";return``},O=async()=>{if(!n.thumbnail_url){re.error("Video thumbnail not available yet");return}const G=D(),Y=`Watch: ${n.title||"Video Message"} ${A}`;try{const X=new Blob([G],{type:"text/html"}),ae=new Blob([Y],{type:"text/plain"}),le=new ClipboardItem({"text/html":X,"text/plain":ae});await navigator.clipboard.write([le]),re.success("Copied! Paste into Gmail - the thumbnail will appear after sending.")}catch{await navigator.clipboard.writeText(Y+` `+G),re.success("Copied! Paste into your email.")}},U=async()=>{await navigator.clipboard.writeText(A),u(!0),re.success("Share link copied!"),setTimeout(()=>u(!1),2e3)},W=()=>{const Y=_V(i).headerText(R),X=i==="default"?`Check out this video: ${A}`:`${Y} Check out this special video: ${A}`;window.open(`sms:?body=${encodeURIComponent(X)}`,"_self")},V=()=>{const G=_V(i),Y=G.headerText(R),X=i==="default"?n.title||"Video Message":Y,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(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(Sd,{className:"h-5 w-5"}),"Share Video"]}),e.jsx(Pr,{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(Kd,{open:v,onOpenChange:b,children:[e.jsx(Yd,{asChild:!0,children:e.jsxs($,{variant:"outline",role:"combobox","aria-expanded":v,className:"flex-1 justify-between",disabled:o,children:[x?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(sl,{className:"h-4 w-4 text-muted-foreground"}),x.name]}):e.jsx("span",{className:"text-muted-foreground",children:"Select a contact..."}),e.jsx(Sw,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Od,{className:"w-[300px] p-0",align:"start",children:e.jsxs(S2,{children:[e.jsx(C2,{placeholder:"Search contacts..."}),e.jsxs(A2,{children:[e.jsx(E2,{children:w?"Loading...":"No contacts found."}),e.jsx(Dw,{children:f.map(G=>e.jsxs(m1,{value:G.name,onSelect:()=>I(G),children:[e.jsx(ca,{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(pr,{className:"h-4 w-4"})})]}),x&&i!=="default"&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:['Page will show: "',_V(i).headerText(x.name),'"']})]}),e.jsx(cQn,{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(ca,{className:"h-4 w-4"}),"Copied"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ha,{className:"h-4 w-4"}),"Copy"]})})]})]}),n.thumbnail_url&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Share for Email"}),e.jsxs($,{variant:"outline",className:"w-full gap-2",onClick:O,children:[e.jsx(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(eo,{className:"h-4 w-4"}),"Text"]}),e.jsxs($,{variant:"outline",className:"flex-1 gap-2",onClick:V,children:[e.jsx(mn,{className:"h-4 w-4"}),"Email"]})]})]})]}),e.jsx(Sr,{children:e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Done"})})]})})}function dQn(){var Ve;const s=Xn(),[t]=gc(),{toast:n}=Bi(),r=t.get("contact_id"),a=t.get("task_id"),{canRecord:i,remainingMb:l,usagePercent:o,isNearLimit:c}=IQt(),{data:d}=R_(),u=p3(),h=C9n(),[m,f]=j.useState("record"),[g,x]=j.useState(""),[y,v]=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),[Y,X]=j.useState(r||""),[ae,le]=j.useState(""),[ne,te]=j.useState(""),[J,ce]=j.useState(null),[_e,he]=j.useState(null),[ue,ve]=j.useState(null),[Ee,Se]=j.useState(!1),Le=j.useCallback(async(ze,qe)=>{I(ze),f("uploading");try{const{videoId:dt,uploadUrl:Xe}=await A6(ae||"Quick Video Touch");W(dt);const{apiKey:at}=await E6(dt),rt=new XMLHttpRequest;rt.upload.onprogress=gt=>{gt.lengthComputable&&R(gt.loaded/gt.total*100)},await new Promise((gt,ss)=>{rt.onload=()=>{rt.status>=200&&rt.status<300?gt():ss(new Error(`Upload failed: ${rt.status}`))},rt.onerror=()=>ss(new Error("Upload failed")),rt.open("PUT",Xe),rt.setRequestHeader("AccessKey",at),rt.send(ze)}),f("processing");let Ke=0;const Je=Date.now(),pt=90*1e3;for(;Ke<4;){if(await new Promise(ss=>setTimeout(ss,3e3)),Date.now()-Je>pt){const ss=ze.size/1048576,Yt=`https://iframe.mediadelivery.net/play/${dt}/${dt}`;await u.mutateAsync({bunny_video_id:dt,playback_url:Yt,file_size_mb:ss,title:ae||"Quick Video Touch",notes:ne||void 0,contact_id:Y&&Y!=="none"?Y:void 0,status:"processing",touch_type:"video_touch"}),n({title:"Video saved — still processing",description:'Your video has been saved and will appear in your library with a "processing" badge. It will be ready to share once encoding completes (usually within a few minutes).',duration:8e3}),s("/mission-control/video-library");return}const gt=await mk(dt);if(Ke=gt.status,O(gt.encodeProgress||0),Ke===4)G({playbackUrl:gt.directPlayUrl,thumbnailUrl:gt.thumbnailUrl,previewUrl:gt.previewUrl||null,duration:gt.length||qe,fileSizeMb:(gt.storageSize||ze.size)/(1024*1024)});else if(Ke===5||Ke===6)throw new Error("Video processing failed")}f("details")}catch(dt){console.error("Upload error:",dt),n({title:"Upload failed",description:"Please try recording again.",variant:"destructive"}),f("record")}},[ae,n]),Fe=async()=>{if(!(!U||!V))try{const ze=Y&&Y!=="none"?Y:null,qe=await u.mutateAsync({bunny_video_id:U,contact_id:ze,playback_url:V.playbackUrl,thumbnail_url:V.thumbnailUrl,preview_url:V.previewUrl,duration_seconds:V.duration,file_size_mb:V.fileSizeMb,title:ae||"Quick Video Touch",notes:ne,task_id:a||null,status:"ready"});ce(qe.id),he(qe.share_token||null),ze&&await h.mutateAsync({contactId:ze,videoId:qe.id,notes:ne}),n({title:"Video saved successfully!"}),f("share")}catch(ze){console.error("Save video error:",ze),n({title:"Failed to save video",description:(ze==null?void 0:ze.message)||"Please try again.",variant:"destructive"})}},ke=(ze,qe)=>{navigator.clipboard.writeText(qe),ve(ze),setTimeout(()=>ve(null),2e3),n({title:"Copied to clipboard!"})},Be=()=>_e?`https://video.relevelup.com/${_e}`:(V==null?void 0:V.playbackUrl)||"",Ne=()=>{const ze=d==null?void 0:d.find(rt=>rt.id===Y),qe=ze?`${ze.first_name}`:"",dt=(ze==null?void 0:ze.phone)||"",Xe=(ze==null?void 0:ze.email)||"",at=Be();return{text:`Hey${qe?` ${qe}`:""}! I recorded a quick video for you: ${at}`,link:at,contactPhone:dt,contactEmail:Xe}},Ae=()=>{const{text:ze,contactPhone:qe}=Ne(),dt=qe?`sms:${qe}?body=${encodeURIComponent(ze)}`:`sms:?body=${encodeURIComponent(ze)}`;window.open(dt,"_self")},Ce=()=>{const{link:ze,contactEmail:qe}=Ne(),dt="Check out this video",Xe=`I recorded a quick video for you: ${ze}`,at=qe?`mailto:${qe}?subject=${encodeURIComponent(dt)}&body=${encodeURIComponent(Xe)}`:`mailto:?subject=${encodeURIComponent(dt)}&body=${encodeURIComponent(Xe)}`;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(Jr,{className:"h-4 w-4"}),"Video Library"]}),c&&e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"text-sm text-warning",children:["Storage: ",o.toFixed(0),"% used"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[l.toFixed(0)," MB remaining"]})]})]})]}),m==="record"&&e.jsxs("div",{className:"grid gap-6 lg:grid-cols-3",children:[e.jsxs("div",{className:"lg:col-span-2",children:[e.jsx(FT,{maxDurationSeconds:600,onRecordingComplete:Le,onRecordingStateChange:A,className:"w-full",teleprompterContent:y&&g&&e.jsx(Got,{text:g,isVisible:y,onToggleVisibility:()=>v(!1),isRecording:S,startCountdown:!1})}),!y&&g&&e.jsxs($,{variant:"outline",className:"mt-4",onClick:()=>v(!0),children:[e.jsx(Jr,{className:"h-4 w-4 mr-2"}),"Show Teleprompter"]})]}),e.jsxs(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(Ie,{className:"space-y-4",children:[e.jsx(Ls,{placeholder:"Type or paste your script here...",value:g,onChange:ze=>x(ze.target.value),rows:6}),e.jsxs(Gy,{open:b,onOpenChange:w,children:[e.jsx(Pae,{asChild:!0,children:e.jsxs($,{variant:"outline",className:"w-full",children:[e.jsx(Jr,{className:"h-4 w-4 mr-2"}),"Browse Scripts"]})}),e.jsxs(my,{side:"right",className:"w-[400px] sm:w-[540px] p-0",children:[e.jsx(L0,{className:"p-4 border-b",children:e.jsx(R0,{children:"Select a Script"})}),e.jsx(lQn,{onSelectScript:ze=>{x(ze.text),w(!1),v(!0)},className:"h-[calc(100vh-80px)]"})]})]}),g&&e.jsx($,{className:"w-full",onClick:()=>v(!0),children:"Use Script"})]})]})]}),m==="uploading"&&e.jsx(je,{className:"max-w-md mx-auto",children:e.jsxs(Ie,{className:"pt-6 text-center",children:[e.jsx(ni,{className:"h-12 w-12 mx-auto mb-4 text-primary animate-pulse"}),e.jsx("h2",{className:"text-lg font-semibold mb-2",children:"Uploading Video..."}),e.jsx(Yi,{value:P,className:"mb-2"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[P.toFixed(0),"%"]})]})}),m==="processing"&&e.jsx(je,{className:"max-w-md mx-auto",children:e.jsxs(Ie,{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(Ie,{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:Y,onValueChange:X,children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"No contact - use anywhere"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"none",children:e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(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(Ls,{value:ne,onChange:ze=>te(ze.target.value),placeholder:"Add notes about this video...",rows:3})]}),e.jsxs($,{className:"w-full",onClick:Fe,disabled:u.isPending,children:[u.isPending&&e.jsx(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(ca,{className:"h-5 w-5 text-green-500"}),"Video Saved!"]})}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsx("p",{className:"text-muted-foreground",children:"Share your video with one click:"}),e.jsxs("div",{className:"grid gap-3",children:[e.jsxs($,{variant:"outline",className:"justify-start",onClick:Ae,children:[e.jsx(eo,{className:"h-4 w-4 mr-2"}),"Text Contact Video"]}),e.jsxs($,{variant:"outline",className:"justify-start",onClick:Ce,children:[e.jsx(mn,{className:"h-4 w-4 mr-2"}),"Email Contact Video"]}),e.jsxs($,{variant:"outline",className:"justify-start",onClick:()=>ke("link",Ne().link),children:[e.jsx(Sd,{className:"h-4 w-4 mr-2"}),"Copy Video Link",ue==="link"&&e.jsx(ca,{className:"h-4 w-4 ml-auto text-green-500"})]}),e.jsxs($,{variant:"outline",className:"justify-start",onClick:()=>Se(!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&&_e&&e.jsx(Brs,{open:Ee,onOpenChange:Se,video:{id:J,share_token:_e,title:ae||null,contact_id:Y||null,thumbnail_url:(V==null?void 0:V.thumbnailUrl)||null},contactName:((Ve=d==null?void 0:d.find(ze=>ze.id===Y))==null?void 0:Ve.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 uQn({open:s,onOpenChange:t,video:n,gmailEmail:r,signedThumbnailUrl:a,onSendComplete:i}){const[l,o]=j.useState([]),[c,d]=j.useState(null),[u,h]=j.useState(!1),[m,f]=j.useState(!1),[g,x]=j.useState(""),[y,v]=j.useState(""),[b,w]=j.useState(""),[S,A]=j.useState(!1),E=AQt(),I=n.share_token?`https://video.relevelup.com/share/video/${n.share_token}`:"",P=n.share_token?`https://video.relevelup.com/thumb/${n.share_token}`:a||n.thumbnail_url||"",R=n.title||"Video Message";j.useEffect(()=>{s&&l.length===0&&D()},[s]),j.useEffect(()=>{if(s&&(v(`I recorded a video for you — ${R}`),w("Hey! I recorded a quick video just for you. Click below to watch it:"),d(null),x(""),n.contact_id)){const Y=l.find(X=>X.id===n.contact_id);Y&&(d(Y),x(Y.email||""))}},[s,n.contact_id,l]);const D=async()=>{f(!0);try{const{data:Y,error:X}=await q.from("innercircle_contacts").select("id, first_name, last_name, email").order("first_name",{ascending:!0}).limit(500);if(X)throw X;o(Y||[])}catch{console.error("Failed to fetch contacts")}finally{f(!1)}},O=Y=>{d(Y),h(!1),x(Y.email||""),w(`Hey ${Y.first_name}! I recorded a quick video just for you. Click below to watch it:`),v(`I recorded a video for you — ${R}`)},U=()=>{d(null),x(""),w("Hey! I recorded a quick video just for you. Click below to watch it:")},W=Y=>{const X=`${Y.first_name||""} ${Y.last_name||""}`.replace(/<[^>]*>/g," ").replace(/\s+/g," ").trim();return X?X.length>60?`${X.slice(0,60)}…`:X:Y.email||"Unnamed contact"},V=Y=>{const X=b.split(/\n\n+/).map(ne=>`

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

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

▶ Watch Video

${le}
`},G=async()=>{var Y;if(!g){re.error("Please enter a recipient email");return}if(!I){re.error("Video does not have a share link");return}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:ne}=await q.functions.invoke("gmail-send",{body:{to:g,subject:y,body:ae,contactId:(c==null?void 0:c.id)||null}});let te=null;if(ne&&((Y=ne.context)!=null&&Y.json))try{te=await ne.context.json()}catch{}if((te==null?void 0:te.error)==="insufficient_scope"||(le==null?void 0:le.error)==="insufficient_scope"){re.error((te==null?void 0:te.message)||"Gmail is missing send permission. Please disconnect and reconnect Gmail, allowing 'Send email on your behalf'.",{duration:1e4});return}if(ne)throw new Error((te==null?void 0:te.message)||ne.message);if(!(le!=null&&le.success))throw new Error((le==null?void 0:le.error)||"Failed to send");re.success("Video email sent!"),t(!1),i==null||i()}catch(X){console.error("Gmail send error:",X),re.error("Failed to send: "+(X instanceof Error?X.message:"Unknown error"))}finally{A(!1)}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-[560px] max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(mn,{className:"h-5 w-5 text-red-500"}),"Send Video via Gmail"]}),r&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Sending from ",e.jsx("span",{className:"font-medium",children:r})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Send to Contact"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Kd,{open:u,onOpenChange:h,children:[e.jsx(Yd,{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(Sw,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Od,{className:"w-[350px] p-0",align:"start",children:e.jsxs(S2,{children:[e.jsx(C2,{placeholder:"Search contacts..."}),e.jsxs(A2,{children:[e.jsx(E2,{children:m?"Loading...":"No contacts found."}),e.jsx(Dw,{children:l.filter(Y=>Y.email).map(Y=>e.jsxs(m1,{value:`${W(Y)} ${Y.email||""}`,onSelect:()=>O(Y),children:[e.jsx(ca,{className:Pt("mr-2 h-4 w-4",(c==null?void 0:c.id)===Y.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-medium truncate",children:W(Y)}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:Y.email})]})]},Y.id))})]})]})})]}),c&&e.jsx($,{variant:"ghost",size:"icon",onClick:U,className:"shrink-0",children:e.jsx(pr,{className:"h-4 w-4"})})]})]}),!c&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"video-to",children:"Or type email address"}),e.jsx(pe,{id:"video-to",value:g,onChange:Y=>x(Y.target.value),placeholder:"recipient@example.com",type:"email"})]}),e.jsx(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:y,onChange:Y=>v(Y.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"video-message",children:"Personal Message"}),e.jsx(Ls,{id:"video-message",value:b,onChange:Y=>w(Y.target.value),rows:4,className:"resize-y"})]}),e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3 space-y-2",children:[e.jsx(ee,{className:"text-xs text-muted-foreground",children:"Video Preview (embedded in email)"}),e.jsxs("div",{className:"relative rounded-lg overflow-hidden bg-black",style:{maxWidth:320},children:[P?e.jsx("img",{src:P,alt:R,className:"w-full aspect-video object-cover"}):e.jsx("div",{className:"w-full aspect-video flex items-center justify-center bg-muted",children:e.jsx(zu,{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(zu,{className:"h-5 w-5 text-primary ml-0.5"})})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Recipients will see the thumbnail with a play button. Clicking opens the video page."})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),disabled:S,children:"Cancel"}),e.jsxs($,{onClick:G,disabled:S||!g||!y,className:"gap-2",children:[S?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Kr,{className:"h-4 w-4"}),S?"Sending...":"Send Video Email"]})]})]})]})})}const hQn=()=>{const{user:s}=bs();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 mQn({recipient:s}){return s.watched_at?e.jsxs($e,{className:"bg-emerald-100 text-emerald-800 text-[10px]",children:[e.jsx(zu,{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(cb,{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(Ca,{className:"h-2.5 w-2.5 mr-0.5"}),"Opened"]}):e.jsxs($e,{variant:"outline",className:"text-[10px]",children:[e.jsx(Kr,{className:"h-2.5 w-2.5 mr-0.5"}),"Sent"]})}function fQn({open:s,onOpenChange:t,videoId:n,videoTitle:r}){const{data:a=[],isLoading:i}=s9n(n);return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-2xl max-h-[80vh]",children:[e.jsx(Us,{children:e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(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(uo,{className:"h-[400px]",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Recipient"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{children:"Sent"}),e.jsx(Dt,{children:"Last Activity"})]})}),e.jsx(fi,{children:a.map(l=>e.jsxs(En,{children:[e.jsx(_t,{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(_t,{children:e.jsx(mQn,{recipient:l})}),e.jsx(_t,{className:"text-xs text-muted-foreground",children:en(new Date(l.sent_at),"MMM d, h:mm a")}),e.jsx(_t,{className:"text-xs text-muted-foreground",children:l.last_activity_at?hu(new Date(l.last_activity_at),{addSuffix:!0}):"—"})]},l.id))})]})})]})]})})}function pQn(){const{data:s,isLoading:t}=n9n(),{data:n=[],isLoading:r}=r9n(),[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(Ie,{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(Kr,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Ie,{children:e.jsx("div",{className:"text-2xl font-bold",children:(s==null?void 0:s.totalSent)||0})})]}),e.jsxs(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(Ca,{className:"h-4 w-4 text-amber-500"})]}),e.jsxs(Ie,{children:[e.jsxs("div",{className:"text-2xl font-bold",children:[(s==null?void 0:s.openRate)||0,"%"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(s==null?void 0:s.totalOpened)||0," opened"]})]})]}),e.jsxs(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(cb,{className:"h-4 w-4 text-blue-500"})]}),e.jsxs(Ie,{children:[e.jsxs("div",{className:"text-2xl font-bold",children:[(s==null?void 0:s.clickRate)||0,"%"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(s==null?void 0:s.totalClicked)||0," clicked"]})]})]})]}),e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{className:"text-sm font-medium",children:"Send History by Video"}),e.jsx(Gn,{children:"Click a video to see individual recipient tracking"})]}),e.jsx(Ie,{children:Object.keys(o).length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No tracked sends yet. Send a video via Gmail to start tracking."}):e.jsx("div",{className:"space-y-2",children:Object.values(o).map(c=>{const d=c.recipients.filter(h=>h.opened_at).length,u=c.recipients.filter(h=>h.clicked_at).length;return e.jsxs("button",{onClick:()=>i({id:c.videoId,title:c.title}),className:"w-full flex items-center gap-3 p-3 rounded-lg border hover:bg-muted/50 transition-colors text-left",children:[e.jsx("div",{className:"h-10 w-16 rounded bg-muted overflow-hidden flex-shrink-0",children:c.thumbnailUrl?e.jsx("img",{src:c.thumbnailUrl,alt:"",className:"h-full w-full object-cover",referrerPolicy:"no-referrer",onError:h=>{const m=h.currentTarget;m.style.display="none",m.parentElement.innerHTML='
'}}):e.jsx("div",{className:"h-full w-full flex items-center justify-center",children:e.jsx(ua,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:c.title}),e.jsxs("div",{className:"flex items-center gap-3 mt-0.5",children:[e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Kr,{className:"h-3 w-3"})," ",c.recipients.length]}),e.jsxs("span",{className:"text-xs text-amber-600 flex items-center gap-1",children:[e.jsx(Ca,{className:"h-3 w-3"})," ",d]}),e.jsxs("span",{className:"text-xs text-blue-600 flex items-center gap-1",children:[e.jsx(cb,{className:"h-3 w-3"})," ",u]})]})]}),e.jsx(Zl,{className:"h-4 w-4 text-muted-foreground"})]},c.videoId)})})})]}),e.jsx(fQn,{open:!!a,onOpenChange:c=>!c&&i(null),videoId:(a==null?void 0:a.id)||null,videoTitle:(a==null?void 0:a.title)||""})]})}function gQn({previewSrc:s,thumbnailSrc:t,alt:n,isHovered:r}){const[a,i]=j.useState(!1),[l,o]=j.useState(!1),c=r&&s&&!a,d=t&&!l;return!d&&!c?e.jsx("div",{className:"w-full h-full flex items-center justify-center absolute inset-0 bg-muted",children:e.jsx(ua,{className:"h-12 w-12 text-muted-foreground"})}):e.jsxs(e.Fragment,{children:[d&&e.jsx("img",{src:t,alt:n,loading:"lazy",className:`w-full h-full object-cover absolute inset-0 transition-opacity duration-200 ${c?"opacity-0":"opacity-100"}`,onError:()=>o(!0)}),c&&e.jsx("img",{src:s,alt:n,className:"w-full h-full object-cover absolute inset-0",onError:()=>i(!0)})]})}function xQn({video:s,previewSrc:t,thumbnailSrc:n,onOpen:r,onDelete:a,onRename:i,onNavigateToContact:l,onGetEmbedCode:o,onCopyEmailHtml:c,onEmbedToCrm:d,onShareWithTemplate:u,onSendViaGmail:h,isGmailConnected:m,getContactName:f,getShareUrl:g,copyToClipboard:x,formatDuration:y}){const[v,b]=j.useState(!1);return e.jsxs(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(gQn,{previewSrc:t,thumbnailSrc:n,alt:s.title||"Video preview",isHovered:v}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx("div",{className:"w-12 h-12 rounded-full bg-white/90 flex items-center justify-center",children:e.jsx(zu,{className:"h-6 w-6 text-primary ml-1"})})}),e.jsx("div",{className:"absolute bottom-2 right-2 bg-black/70 text-white text-xs px-1.5 py-0.5 rounded",children:y(s.duration_seconds)}),s.status!=="ready"&&e.jsx($e,{variant:s.status==="processing"?"secondary":"destructive",className:"absolute top-2 left-2",children:s.status})]}),e.jsx(Ie,{className:"p-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h3",{className:"font-medium truncate",children:s.title||"Untitled Video"}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground mt-1",children:[e.jsx(sl,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:f(s.contact_id)})]}),e.jsxs("div",{className:"flex items-center gap-4 text-xs text-muted-foreground mt-0.5",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(da,{className:"h-3 w-3"}),e.jsx("span",{children:en(new Date(s.created_at),"MMM d, yyyy")})]}),(s.view_count??0)>0&&e.jsxs("div",{className:"flex items-center gap-1 text-primary",children:[e.jsx(Ca,{className:"h-3 w-3"}),e.jsxs("span",{children:[s.view_count," ",s.view_count===1?"view":"views"]})]})]}),m&&s.share_token&&e.jsxs($,{variant:"outline",size:"sm",className:"mt-2 gap-1.5 text-xs h-7",onClick:w=>{w.stopPropagation(),h==null||h()},children:[e.jsx(mn,{className:"h-3 w-3"}),"Send via Gmail"]}),e.jsx("h3",{className:"font-medium truncate",children:s.title||"Untitled Video"}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground mt-1",children:[e.jsx(sl,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:f(s.contact_id)})]}),e.jsxs("div",{className:"flex items-center gap-4 text-xs text-muted-foreground mt-0.5",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(da,{className:"h-3 w-3"}),e.jsx("span",{children:en(new Date(s.created_at),"MMM d, yyyy")})]}),(s.view_count??0)>0&&e.jsxs("div",{className:"flex items-center gap-1 text-primary",children:[e.jsx(Ca,{className:"h-3 w-3"}),e.jsxs("span",{children:[s.view_count," ",s.view_count===1?"view":"views"]})]})]})]}),e.jsxs($u,{children:[e.jsx(Uu,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:w=>w.stopPropagation(),children:e.jsx(Jx,{className:"h-4 w-4"})})}),e.jsxs(Au,{align:"end",className:"bg-popover",children:[e.jsxs(ja,{onClick:w=>{w.stopPropagation(),r()},children:[e.jsx(Ca,{className:"h-4 w-4 mr-2"}),"Watch"]}),e.jsx(I0,{}),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(CE,{className:"h-4 w-4 mr-2"}),"Get Embed Code"]}),e.jsxs(ja,{onClick:w=>{w.stopPropagation(),c()},children:[e.jsx(mn,{className:"h-4 w-4 mr-2"}),"Copy HTML for Email"]}),e.jsxs(ja,{onClick:w=>{w.stopPropagation(),d()},children:[e.jsx(Fr,{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(Kr,{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(I0,{}),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(Hn,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})]})})]})}function yQn(){var ts,ys;const s=Xn(),{data:t,isLoading:n,refetch:r}=j9n(),{data:a}=iDe(),{data:i}=R_(),l=S9n(),o=k9n(),{isGmailConnected:c,gmailEmail:d}=gy(),{data:u}=zw(),{data:h=[],isLoading:m}=hQn(),[f,g]=j.useState("my"),[x,y]=j.useState(""),[v,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,Y]=j.useState(!1),[X,ae]=j.useState(!1),[le,ne]=j.useState(!1),[te,J]=j.useState(!1),[ce,_e]=j.useState(""),[he,ue]=j.useState({}),ve=Bt=>{if(!Bt)return"Unassigned";const Ft=i==null?void 0:i.find(as=>as.id===Bt);return Ft?`${Ft.first_name} ${Ft.last_name||""}`.trim():"Unknown"},Ee=Bt=>{if(!Bt)return"0:00";const Ft=Math.floor(Bt/60),as=Bt%60;return`${Ft}:${as.toString().padStart(2,"0")}`},[Se,Le]=j.useState("all"),Fe=t==null?void 0:t.filter(Bt=>{const Ft=Bt.category||"general";if(Se==="general"&&Ft!=="general"||Se==="open_house"&&Ft!=="open_house")return!1;if(!x)return!0;const as=ve(Bt.contact_id).toLowerCase(),kt=(Bt.title||"").toLowerCase(),Ks=(Bt.notes||"").toLowerCase();return as.includes(x.toLowerCase())||kt.includes(x.toLowerCase())||Ks.includes(x.toLowerCase())}),ke=(t==null?void 0:t.filter(Bt=>(Bt.category||"general")==="open_house").length)||0,Be=(t==null?void 0:t.filter(Bt=>(Bt.category||"general")==="general").length)||0,Ne=(t||[]).filter(Bt=>Bt.status==="processing"&&Bt.bunny_video_id).map(Bt=>Bt.id).join(",");j.useEffect(()=>{(async()=>{if(!(t!=null&&t.length))return;const Ft=t.filter(kt=>kt.status==="processing"&&kt.bunny_video_id);if(!Ft.length)return;let as=!1;for(const kt of Ft)try{const{data:Ks,error:wt}=await q.functions.invoke("bunny-upload",{body:{action:"status",videoId:kt.bunny_video_id,isAgentVideo:!0}});if(wt||!Ks)continue;Ks.status===4&&(await q.from("agent_videos").update({status:"ready",playback_url:Ks.directPlayUrl,thumbnail_url:Ks.thumbnailUrl,preview_url:Ks.previewUrl,duration_seconds:Ks.length||kt.duration_seconds,updated_at:new Date().toISOString()}).eq("id",kt.id),as=!0)}catch(Ks){console.warn("Reconcile check failed for video",kt.id,Ks)}as&&r()})()},[Ne,r]),j.useEffect(()=>{(async()=>{if(!(t!=null&&t.length))return;const Ft=t.filter(gs=>(gs==null?void 0:gs.bunny_video_id)&&!he[gs.id]);if(!Ft.length)return;const as=Ft.map(gs=>gs.bunny_video_id),{data:kt,error:Ks}=await q.functions.invoke("bunny-upload",{body:{action:"bulk-asset-urls",videoIds:as,isAgentVideo:!0}});if(Ks)throw Ks;const wt=(kt==null?void 0:kt.assets)||{};ue(gs=>{const ks={...gs};for(const Is of Ft)wt[Is.bunny_video_id]&&(ks[Is.id]={previewUrl:wt[Is.bunny_video_id].previewUrl,thumbnailUrl:wt[Is.bunny_video_id].thumbnailUrl});return ks})})().catch(Ft=>console.warn("Failed to load signed Bunny asset URLs",Ft))},[t,he]);const Ae=(a==null?void 0:a.total_storage_mb)||0,Ce=(a==null?void 0:a.max_storage_mb)||1024,Ve=Ae/Ce*100,ze=Ve>=80,qe=Ve>=100,dt=async(Bt,Ft)=>{await navigator.clipboard.writeText(Bt),re.success(`${Ft} copied to clipboard`)},Xe=Bt=>Bt.share_token?`https://video.relevelup.com/${Bt.share_token}`:Bt.playback_url||"",at=Bt=>{const Ft=Xe(Bt),as=i==null?void 0:i.find(Is=>Is.id===Bt.contact_id),kt=ve(Bt.contact_id),Ks=kt!=="Unassigned"?kt.split(" ")[0]:"",wt=(as==null?void 0:as.phone)||"",gs=`Hey${Ks?` ${Ks}`:""}! I recorded a quick video message for you. Check it out: ${Ft}`,ks=wt?`sms:${wt}?body=${encodeURIComponent(gs)}`:`sms:?body=${encodeURIComponent(gs)}`;window.open(ks,"_self")},rt=Bt=>{const Ft=i==null?void 0:i.find(ks=>ks.id===Bt.contact_id),as=(Ft==null?void 0:Ft.email)||"",kt=Xe(Bt),Ks="Check out this video",wt=`I recorded a quick video for you: ${kt}`,gs=as?`mailto:${as}?subject=${encodeURIComponent(Ks)}&body=${encodeURIComponent(wt)}`:`mailto:?subject=${encodeURIComponent(Ks)}&body=${encodeURIComponent(wt)}`;window.open(gs,"_self")},Ke=Bt=>{var Ks;const Ft=Xe(Bt),as=Bt.title||"Video Message",kt=Bt.share_token?`https://video.relevelup.com/thumb/${Bt.share_token}`:((Ks=he[Bt.id])==null?void 0:Ks.thumbnailUrl)||Bt.thumbnail_url||"";return``},Je=async Bt=>{if(!Bt.thumbnail_url&&!Bt.share_token){re.error("Video thumbnail not available yet");return}const Ft=Ke(Bt),as=Xe(Bt),kt=`Watch: ${Bt.title||"Video Message"} ${as}`;try{const Ks=new Blob([Ft],{type:"text/html"}),wt=new Blob([kt],{type:"text/plain"}),gs=new ClipboardItem({"text/html":Ks,"text/plain":wt});await navigator.clipboard.write([gs]),re.success("Copied! Paste into Gmail - the thumbnail will appear after sending.")}catch{await navigator.clipboard.writeText(kt+` `+Ft),re.success("Copied! Paste into your email.")}},pt=async Bt=>{try{re.loading("Preparing download...",{id:"download"});const{data:Ft,error:as}=await q.functions.invoke("bunny-upload",{body:{action:"download-url",videoId:Bt.bunny_video_id,isAgentVideo:!0}});if(as||!(Ft!=null&&Ft.downloadUrl))throw new Error((as==null?void 0:as.message)||"Failed to get download URL");const Ks=`${((Bt.title||"video").toString().trim()||"video").replace(/[\\/:*?"<>|]+/g,"-")}.mp4`,wt=await fetch(Ft.downloadUrl);if(!wt.ok)throw new Error("Failed to fetch video file");const gs=await wt.blob(),ks=URL.createObjectURL(gs),Is=document.createElement("a");Is.href=ks,Is.download=Ks,Is.rel="noreferrer",document.body.appendChild(Is),Is.click(),Is.remove(),URL.revokeObjectURL(ks),re.success("Download started",{id:"download"})}catch(Ft){console.error("Download error:",Ft),re.error("Could not force download (your browser may block it).",{id:"download"})}},gt=async Bt=>{b(Bt),Y(!0),V(""),U(!0);try{const{data:Ft,error:as}=await q.functions.invoke("bunny-upload",{body:{action:"crm-embed",videoId:Bt.bunny_video_id,title:Bt.title,isAgentVideo:!0,shareToken:Bt.share_token}});if(as||!(Ft!=null&&Ft.html))throw new Error("Failed to generate CRM embed code");V(Ft.html)}catch(Ft){console.error("CRM embed error:",Ft),re.error("Failed to generate CRM embed code"),U(!1)}finally{Y(!1)}},ss=Bt=>{b(Bt),S(!0)},Yt=async()=>{if(v)try{await l.mutateAsync({id:v.id,bunnyVideoId:v.bunny_video_id,hardDelete:!0}),E(!1),b(null),re.success("Video deleted successfully")}catch{re.error("Failed to delete video")}};return e.jsx(Vs,{title:"Video Library",description:"Manage your video touches",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Video Library"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage and share your video touches"})]}),e.jsxs("div",{className:"flex bg-muted rounded-lg p-1 gap-0.5 ml-2",children:[e.jsx("button",{onClick:()=>g("my"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors ${f==="my"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:"My Videos"}),u&&((ts=u.team)==null?void 0:ts.shared_videos_enabled)&&e.jsxs("button",{onClick:()=>g("team"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors flex items-center gap-1.5 ${f==="team"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(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(dn,{className:"h-4 w-4 mr-2"}),"Record New Video"]})]})]}),f==="team"?e.jsx(vQn,{videos:h,isLoading:m,searchTerm:x,setSearchTerm:y}):f==="analytics"?e.jsx(pQn,{}):e.jsxs(e.Fragment,{children:[e.jsx(je,{className:ze?"border-amber-500":qe?"border-destructive":"",children:e.jsxs(Ie,{className:"py-4",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(CJ,{className:`h-5 w-5 ${qe?"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(Ve,100),className:`h-2 ${qe?"[&>div]:bg-destructive":ze?"[&>div]:bg-amber-500":""}`})]}),ze&&!qe&&e.jsxs($e,{variant:"outline",className:"border-amber-500 text-amber-600",children:[e.jsx(ll,{className:"h-3 w-3 mr-1"}),"Near Limit"]}),qe&&e.jsxs($e,{variant:"destructive",children:[e.jsx(ll,{className:"h-3 w-3 mr-1"}),"At Limit"]})]}),qe&&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:ke}].map(Bt=>e.jsxs("button",{onClick:()=>Le(Bt.id),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors ${Se===Bt.id?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[Bt.label," ",e.jsx("span",{className:"ml-1 text-xs text-muted-foreground",children:Bt.count})]},Bt.id))}),e.jsxs("div",{className:"relative",children:[e.jsx(Zr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search videos by contact, title, or notes...",value:x,onChange:Bt=>y(Bt.target.value),className:"pl-10"})]}),n?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full"})}):(Fe==null?void 0:Fe.length)===0?e.jsx(je,{children:e.jsxs(Ie,{className:"py-12 text-center",children:[e.jsx(ua,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"font-semibold mb-2",children:"No videos yet"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Record your first video touch to get started"}),e.jsxs($,{onClick:()=>s("/mission-control/video/record"),children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Record Video"]})]})}):e.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 gap-4",children:Fe==null?void 0:Fe.map(Bt=>{var Ft,as;return e.jsx(xQn,{video:Bt,previewSrc:(Ft=he[Bt.id])==null?void 0:Ft.previewUrl,thumbnailSrc:(as=he[Bt.id])==null?void 0:as.thumbnailUrl,onOpen:()=>ss(Bt),onDelete:()=>{b(Bt),E(!0)},onRename:()=>{b(Bt),_e(Bt.title||""),J(!0)},onNavigateToContact:()=>s(`/mission-control/contacts/${Bt.contact_id}`),onGetEmbedCode:()=>{b(Bt),D(!0)},onCopyEmailHtml:()=>Je(Bt),onEmbedToCrm:()=>gt(Bt),onShareWithTemplate:()=>{b(Bt),ae(!0)},onSendViaGmail:()=>{b(Bt),ne(!0)},isGmailConnected:c,getContactName:ve,getShareUrl:Xe,copyToClipboard:dt,formatDuration:Ee},Bt.id)})}),e.jsx(zs,{open:w,onOpenChange:S,children:e.jsxs(Os,{className:"max-w-2xl",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:(v==null?void 0:v.title)||"Video Preview"}),e.jsx(Pr,{children:(v==null?void 0:v.contact_id)&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(sl,{className:"h-3 w-3"}),ve(v.contact_id)]})})]}),v&&e.jsxs("div",{className:"space-y-4",children:[v.status==="processing"?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 px-6 bg-muted/50 rounded-lg border border-dashed border-border text-center space-y-4",children:[e.jsx("div",{className:"relative",children:e.jsx("div",{className:"h-16 w-16 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx(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(ro,{className:"h-4 w-4 mr-2"}),"Refresh Library"]})]}):e.jsx("div",{className:"relative w-full",style:{paddingBottom:"56.25%"},children:v.playback_url?(()=>{let Bt=v.playback_url;return Bt.includes("iframe.mediadelivery.net/play/")&&(Bt=Bt.replace("/play/","/embed/"),Bt+=(Bt.includes("?")?"&":"?")+"autoplay=false&responsive=true"),Bt.includes("iframe.mediadelivery.net")?e.jsx("iframe",{src:Bt,title:v.title||"Video preview",className:"absolute top-0 left-0 w-full h-full rounded-lg",style:{border:0},allow:"accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture",allowFullScreen:!0}):e.jsx("video",{src:v.playback_url,controls:!0,playsInline:!0,preload:"metadata",poster:v.thumbnail_url||void 0,className:"absolute top-0 left-0 w-full h-full rounded-lg object-cover",onError:()=>re.error("Video preview failed to load")},v.playback_url)})():e.jsxs("div",{className:"absolute inset-0 flex items-center justify-center bg-muted rounded-lg",children:[e.jsx(ua,{className:"h-12 w-12 text-muted-foreground"}),e.jsx("p",{className:"text-muted-foreground ml-2",children:"Video not available"})]})}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs($,{variant:"outline",onClick:()=>at(v),children:[e.jsx(eo,{className:"h-4 w-4 mr-2"}),"Text Contact Video"]}),!c&&e.jsxs($,{variant:"outline",onClick:()=>rt(v),children:[e.jsx(mn,{className:"h-4 w-4 mr-2"}),"Email Contact Video"]}),e.jsxs($,{variant:"outline",onClick:()=>dt(Xe(v),"Share link"),children:[e.jsx(Ha,{className:"h-4 w-4 mr-2"}),"Copy Share Link"]}),e.jsxs($,{variant:"outline",onClick:()=>Je(v),children:[e.jsx(mn,{className:"h-4 w-4 mr-2"}),"Copy HTML for Email"]}),e.jsxs($,{variant:"outline",onClick:()=>pt(v),children:[e.jsx(xi,{className:"h-4 w-4 mr-2"}),"Download Video"]}),e.jsxs($,{variant:"outline",onClick:()=>{S(!1),gt(v)},children:[e.jsx(Fr,{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&&(v==null?void 0:v.share_token)&&e.jsxs($,{variant:"outline",onClick:()=>{S(!1),ne(!0)},children:[e.jsx(Kr,{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(Hn,{className:"h-4 w-4 mr-2"}),"Delete Video"]})})]})]})}),e.jsx(zs,{open:A,onOpenChange:E,children:e.jsxs(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Delete Video"}),e.jsx(Pr,{children:"Are you sure you want to delete this video? This action cannot be undone."})]}),e.jsxs(Sr,{children:[e.jsx($,{variant:"outline",onClick:()=>E(!1),children:"Cancel"}),e.jsx($,{variant:"destructive",onClick:Yt,disabled:l.isPending,children:l.isPending?"Deleting...":"Delete"})]})]})}),e.jsx(LQt,{open:I,onOpenChange:P}),e.jsx(zs,{open:R,onOpenChange:D,children:e.jsxs(Os,{className:"sm:max-w-lg",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Embed Video"}),e.jsx(Pr,{children:"Copy this code to embed the video on your website."})]}),v&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Embed Code"}),e.jsx(Ls,{readOnly:!0,rows:5,value:``,className:"font-mono text-xs"})]}),e.jsx("div",{className:"flex gap-2",children:e.jsxs($,{className:"flex-1",onClick:()=>{const Bt=``;dt(Bt,"Embed code")},children:[e.jsx(Ha,{className:"h-4 w-4 mr-2"}),"Copy Embed Code"]})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Paste this code into your website's HTML where you want the video to appear. The video will automatically resize to fit its container."})]})]})}),v&&e.jsx(Brs,{open:X,onOpenChange:ae,video:v,contactName:ve(v.contact_id)}),v&&e.jsx(uQn,{open:le,onOpenChange:ne,video:v,gmailEmail:d,signedThumbnailUrl:(ys=he[v.id])==null?void 0:ys.thumbnailUrl}),e.jsx(zs,{open:te,onOpenChange:J,children:e.jsxs(Os,{className:"max-w-sm",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Rename Video"}),e.jsx(Pr,{children:"Enter a new title for this video."})]}),e.jsx(pe,{value:ce,onChange:Bt=>_e(Bt.target.value),placeholder:"Video title",autoFocus:!0,onKeyDown:Bt=>{Bt.key==="Enter"&&ce.trim()&&o.mutate({id:v.id,title:ce.trim()},{onSuccess:()=>{re.success("Video renamed"),J(!1)}})}}),e.jsxs(Sr,{children:[e.jsx($,{variant:"outline",onClick:()=>J(!1),children:"Cancel"}),e.jsx($,{disabled:!ce.trim()||o.isPending,onClick:()=>{o.mutate({id:v.id,title:ce.trim()},{onSuccess:()=>{re.success("Video renamed"),J(!1)}})},children:o.isPending?"Saving...":"Save"})]})]})}),e.jsx(zs,{open:O,onOpenChange:U,children:e.jsxs(Os,{className:"sm:max-w-lg",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(Fr,{className:"h-5 w-5"}),"Embed to CRM"]}),e.jsx(Pr,{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(Ls,{readOnly:!0,rows:12,value:W,className:"font-mono text-xs"})]}),e.jsxs($,{className:"w-full",onClick:()=>{dt(W,"CRM embed code")},children:[e.jsx(Ha,{className:"h-4 w-4 mr-2"}),"Copy CRM Embed Code"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Paste this into your CRM's email HTML editor. The recipient will see the video thumbnail and can click to watch. Works with Follow Up Boss, KvCORE, BoomTown, Sierra, and more."})]}):null]})})]})]})})}function vQn({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(Zr,{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(Ie,{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(ua,{className:"h-10 w-10 text-muted-foreground"}),d.duration_seconds&&e.jsx("span",{className:"absolute bottom-2 right-2 bg-black/70 text-white text-xs px-1.5 py-0.5 rounded",children:l(d.duration_seconds)})]}),e.jsxs(Ie,{className:"p-3",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:d.title||"Untitled"}),e.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-muted-foreground",children:[d.recipient_name&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(sl,{className:"h-3 w-3"}),d.recipient_name]}),d.view_count!=null&&d.view_count>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ca,{className:"h-3 w-3"}),d.view_count]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(da,{className:"h-3 w-3"}),en(new Date(d.created_at),"MMM d")]})]})]})]},d.id))})]},o))})]})}const bQn=()=>{const{user:s}=bs();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})},w3t=["#8B5CF6","#EC4899","#F59E0B","#10B981","#3B82F6","#EF4444","#06B6D4","#F97316"];function _Qn({open:s,onOpenChange:t}){const{data:n,isLoading:r}=bQn(),[a,i]=j.useState(""),[l,o]=j.useState("all"),c=j.useMemo(()=>{if(!n)return new Map;const g=new Map;let x=0;return n.forEach(y=>{g.has(y.owner_user_id)||(g.set(y.owner_user_id,{name:y.owner_name||"Unknown",avatar:y.owner_avatar_url,color:w3t[x%w3t.length]}),x++)}),g},[n]),d=j.useMemo(()=>Array.from(c.entries()).map(([g,x])=>({id:g,...x})),[c]),u=j.useMemo(()=>{if(!n)return[];let g=n;if(l!=="all"&&(g=g.filter(x=>x.owner_user_id===l)),a.trim()){const x=a.toLowerCase();g=g.filter(y=>{var v,b,w,S;return y.deal_name.toLowerCase().includes(x)||((v=y.contact_name)==null?void 0:v.toLowerCase().includes(x))||((b=y.property_address)==null?void 0:b.toLowerCase().includes(x))||((w=y.city)==null?void 0:w.toLowerCase().includes(x))||((S=y.owner_name)==null?void 0:S.toLowerCase().includes(x))})}return g},[n,a,l]),h=j.useMemo(()=>{const g=new Map;return u.forEach(x=>{const y=x.stage_name||"Unknown";g.has(y)||g.set(y,{name:y,color:x.stage_color,icon:x.stage_icon,deals:[],totalValue:0});const v=g.get(y);v.deals.push(x),v.totalValue+=x.sale_price||0}),Array.from(g.values())},[u]),m=g=>g>=1e6?`$${(g/1e6).toFixed(1)}M`:g>=1e3?`$${(g/1e3).toFixed(0)}K`:`$${g.toFixed(0)}`,f=g=>g?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(g):null;return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-[95vw] w-full max-h-[90vh] flex flex-col",children:[e.jsx(Us,{children:e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(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(Zr,{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&&$Ie[g.icon]||Og;return e.jsxs("div",{className:"flex flex-col h-full min-w-[260px] max-w-[300px] flex-1 bg-muted/30 rounded-xl border border-border/50",children:[e.jsxs("div",{className:"p-3 border-b border-border/50 shrink-0",style:{borderTopColor:g.color||"hsl(var(--border))",borderTopWidth:3},children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-6 h-6 rounded-md flex items-center justify-center",style:{backgroundColor:g.color?`${g.color}20`:void 0},children:e.jsx(x,{className:"h-3.5 w-3.5",style:{color:g.color||void 0}})}),e.jsx("h3",{className:"font-semibold text-sm",children:g.name})]}),e.jsx($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(uo,{className:"flex-1 p-2",children:e.jsx("div",{className:"space-y-2",children:g.deals.map(y=>{const v=c.get(y.owner_user_id);return e.jsx(wQn,{deal:y,ownerColor:(v==null?void 0:v.color)||"#888",ownerName:(v==null?void 0:v.name)||"Unknown",ownerAvatar:(v==null?void 0:v.avatar)||null,formatPrice:f},y.id)})})})]},g.name)})})}),e.jsxs("p",{className:"text-xs text-muted-foreground text-center pt-2 border-t shrink-0",children:[u.length," deal",u.length!==1?"s":""," across ",h.length," stage",h.length!==1?"s":""," from ",d.length," member",d.length!==1?"s":""]})]})})}function wQn({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(nu,{className:"h-3 w-3 text-emerald-500 shrink-0"}),e.jsx("span",{className:"font-semibold text-foreground",children:a(s.sale_price)})]})]})}function jQn({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(uo,{className:"flex-1 p-2",children:[e.jsxs("div",{className:"space-y-1",children:[l&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{onClick:l,className:Pt("w-full flex items-center gap-2 px-2 py-2 rounded-lg text-left transition-colors",i?"bg-primary/10 hover:bg-primary/15":"hover:bg-muted/50"),children:[e.jsx("div",{className:"h-7 w-7 rounded-full bg-primary/20 flex items-center justify-center shrink-0",children:e.jsx(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(Sn,{checked:i,onCheckedChange:l,className:"scale-75",onClick:c=>c.stopPropagation()})]}),e.jsx("div",{className:"h-px bg-border/60 my-1"})]}),s.map(c=>{const d=t.has(c.id);return e.jsxs("button",{onClick:()=>n(c.id),className:Pt("w-full flex items-center gap-2 px-2 py-2 rounded-lg text-left transition-colors",d?"bg-primary/10 hover:bg-primary/15":"hover:bg-muted/50"),children:[e.jsxs("div",{className:"relative",children:[e.jsxs(Oa,{className:"h-7 w-7",children:[e.jsx(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(Sn,{checked:d,onCheckedChange:()=>n(c.id),className:"scale-75",onClick:u=>u.stopPropagation()})]},c.id)})]}),s.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground text-center py-4",children:"No team members"})]}):e.jsxs("div",{className:"flex-1 flex flex-col items-center pt-2 gap-2",children:[s.slice(0,5).map(c=>{const d=t.has(c.id);return e.jsx("button",{onClick:()=>n(c.id),className:"relative",title:c.name,children:e.jsxs(Oa,{className:Pt("h-7 w-7 transition-all",d?"ring-2 ring-offset-1 ring-offset-background":"opacity-50"),style:d?{"--tw-ring-color":c.color}:{},children:[e.jsx(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 j3t=["#8B5CF6","#EC4899","#F59E0B","#10B981","#3B82F6","#EF4444","#06B6D4","#F97316"];function NQn(){const s=Sa(),{data:t}=zw(),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:j3t[h%j3t.length]}))},enabled:!!r&&!!s&&n,staleTime:5*60*1e3});return{isTeamLeader:n,teamMembers:a.data||[],isLoadingMembers:a.isLoading}}function kQn(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 SQn(){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 $rs({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($u,{open:a,onOpenChange:i,children:[e.jsx(Uu,{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(Au,{align:"end",className:"w-48 z-50 bg-popover",onClick:c=>c.stopPropagation(),children:s.map(c=>{const d=c.icon&&$Ie[c.icon]||Og,u=c.id===t;return e.jsxs(ja,{onClick:()=>o(c),className:Pt("flex items-center gap-2 cursor-pointer",u&&"bg-accent"),children:[e.jsx("div",{className:"w-5 h-5 rounded flex items-center justify-center shrink-0",style:{backgroundColor:`${c.color}20`},children:e.jsx(d,{className:"h-3 w-3",style:{color:c.color}})}),e.jsx("span",{className:"flex-1",children:c.name}),u&&e.jsx(ca,{className:"h-4 w-4 text-primary"})]},c.id)})})]})}const CQn={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"}},AQn={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 Urs({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=FK(),m=CQn[s.deal_type],f=AQn[s.priority],g=j.useMemo(()=>s.target_close_date?dk(kh(s.target_close_date),new Date):null,[s.target_close_date]),x=l||o||!!s.actual_close_date,y=!x&&g!==null&&g<0,v=!x&&g!==null&&g<=7&&g>=0,b=j.useMemo(()=>{var D;if(s.deal_type!=="seller"&&s.deal_type!=="dual")return null;const P=((D=s.listing)==null?void 0:D.created_at)||s.listing_date;if(!P)return null;const R=s.contract_date?kh(s.contract_date):new Date;return dk(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",y&&"border-red-200 bg-red-50/30",w&&"border-amber-300 bg-amber-50/30 dark:bg-amber-950/20"),onClick:t,style:c?{borderLeftWidth:4,borderLeftColor:c.color}:void 0,children:[!c&&e.jsx("div",{className:Pt("h-1 w-full",f.stripe),"aria-hidden":!0}),e.jsxs(Ie,{className:"p-3 space-y-2.5",children:[c&&e.jsxs("div",{className:"flex items-center gap-1.5 -mt-0.5 mb-1",children:[e.jsxs(Oa,{className:"h-4 w-4",children:[e.jsx(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(Wd,{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(Cu,{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(nu,{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=xw(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(Cv,{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($Qt,{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($rs,{stages:r,currentStageId:s.stage_id||"",onStageSelect:(P,R)=>a(s.id,P,R)}):s.target_close_date?e.jsxs("div",{className:Pt("flex items-center gap-1 text-[10px]",y&&"text-red-600",v&&!y&&"text-amber-600",!y&&!v&&"text-muted-foreground"),children:[y?e.jsx(ll,{className:"h-3 w-3"}):e.jsx(Ta,{className:"h-3 w-3"}),e.jsx("span",{children:y?`${Math.abs(g)}d overdue`:v?`${g}d left`:en(kh(s.target_close_date),"MMM d")})]}):null]})]})]})}function EQn({stage:s,deals:t,onDealClick:n,onAddDeal:r,onDragStart:a,onDragOver:i,onDrop:l,isDragOver:o,isWonStage:c=!1,isLostStage:d=!1,getOwnerInfo:u,tagsByDeal:h={},overdueTasksByDeal:m={}}){const f=j.useRef(null),[g,x]=j.useState(!1),y=t.reduce((A,E)=>A+(E.expected_price||0),0),v=t.reduce((A,E)=>A+(E.expected_commission||0),0),b=t.reduce((A,E)=>A+(xw(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&&$Ie[s.icon]||Og;return g?e.jsxs("div",{className:"flex h-full w-12 shrink-0 flex-col items-center gap-3 rounded-xl border border-border/50 bg-muted/30 py-3",style:{borderTopColor:s.color,borderTopWidth:3},children:[e.jsx("button",{onClick:()=>x(!1),"aria-label":`Expand ${s.name}`,className:"text-muted-foreground transition-colors hover:text-foreground",children:e.jsx(Di,{className:"h-4 w-4"})}),e.jsx($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"})})]})]}),y>0&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground flex-wrap",children:[e.jsx("span",{className:"font-medium text-foreground",children:w(y)}),e.jsx("span",{children:"•"}),e.jsxs("span",{children:[w(v)," GCI"]}),b>0&&b!==v&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsxs("span",{className:"text-teal-600 dark:text-teal-400",children:[w(b)," Net"]})]})]})]}),e.jsx(uo,{className:"flex-1 p-2",children:e.jsxs("div",{className:"space-y-2",children:[t.map(A=>e.jsx("div",{draggable:!0,onDragStart:E=>{E.dataTransfer.effectAllowed="move",a(A.id,s.id)},children:e.jsx(Urs,{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(dn,{className:"h-4 w-4 mr-2"}),"Add Deal"]})})]})}const rk=q;function TQn(s,t=!1){return st({queryKey:["commission-plans",s,t],enabled:!!s,queryFn:async()=>{let n=rk.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 MQn(s){const t=Wt();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 rk.from("brokerage_commission_plans").update(r).eq("id",n.id);if(a)throw a}else{const{error:a}=await rk.from("brokerage_commission_plans").insert(r);if(a)throw a}},onSuccess:()=>{t.invalidateQueries({queryKey:["commission-plans",s]}),re.success("Commission plan saved")},onError:n=>re.error(n.message||"Could not save plan")})}function PQn(s){return st({queryKey:["cap-progress",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await rk.rpc("get_agent_cap_progress",{_agent_user_id:s});if(n)throw n;return(t||[])[0]??null}})}function IQn(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 rk.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 rk.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 rk.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 LQn(s){const t=Wt();return mt({mutationFn:async n=>{const{error:r}=await rk.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 rk.from("agent_plan_assignments").insert({agent_user_id:n.agent_user_id,brokerage_id:s,plan_id:n.plan_id,start_date:n.start_date,anniversary_date:n.anniversary_date||null,notes:n.notes||null});if(a)throw a},onSuccess:()=>{t.invalidateQueries({queryKey:["agent-plan-roster",s]}),re.success("Plan assigned")},onError:n=>re.error(n.message||"Could not assign plan")})}function RQn(s){const t=Wt();return mt({mutationFn:async n=>{const r=new Date().toISOString().slice(0,10),{error:a}=await rk.from("agent_plan_assignments").update({end_date:r}).eq("id",n);if(a)throw a},onSuccess:()=>{t.invalidateQueries({queryKey:["agent-plan-roster",s]}),re.success("Plan removed from agent")},onError:n=>re.error(n.message||"Could not remove plan")})}function qrs(){const{user:s}=bs();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 rk.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 rk.from("brokerage_commission_plans").select("*").eq("id",t.plan_id).maybeSingle();if(a)throw a;return r?{assignment:t,plan:r}:null}})}function DQn({formData:s,onChange:t,isEditing:n}){const{isAdmin:r}=bs(),[a,i]=j.useState(s.portal_enabled);if(!r)return e.jsxs("div",{className:"border rounded-lg p-4 opacity-60",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Nn,{className:"h-4 w-4 text-primary"}),e.jsx("h4",{className:"font-medium text-sm",children:"Client Portal"}),e.jsx($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(v1,{open:a,onOpenChange:i,children:e.jsxs("div",{className:"border rounded-lg",children:[e.jsxs(b1,{className:"w-full p-4 flex items-center justify-between hover:bg-muted/50 transition-colors rounded-t-lg",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Nn,{className:"h-4 w-4 text-primary"}),e.jsx("h4",{className:"font-medium text-sm",children:"Client Portal"}),s.portal_enabled&&e.jsx($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(_1,{children:e.jsxs("div",{className:"px-4 pb-4 space-y-5 border-t pt-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm font-medium",children:"Enable Client Portal"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Create a beautiful portal your client can track their deal from"})]}),e.jsx(Sn,{checked:s.portal_enabled,onCheckedChange:o=>l({portal_enabled:o})})]}),s.portal_enabled&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(ee,{className:"text-sm font-medium",children:"Portal Visibility"}),e.jsxs(vw,{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(pc,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-sm font-medium",children:"Private"})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Link-only access"})]})]}),e.jsxs("label",{className:Pt("flex items-center gap-3 p-3 rounded-lg border cursor-pointer transition-colors",s.visibility==="public"?"border-primary bg-primary/5":"hover:bg-muted/50"),children:[e.jsx(Km,{value:"public"}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(dl,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-sm font-medium",children:"Public"})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Shareable link"})]})]})]})]}),e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg bg-muted/30",children:[e.jsx(ai,{id:"require_onboarding",checked:s.require_onboarding,onCheckedChange:o=>l({require_onboarding:!!o}),className:"mt-0.5"}),e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"require_onboarding",className:"text-sm font-medium cursor-pointer",children:"Require client onboarding before portal access"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Client confirms contact details + preferences before viewing portal. Info is saved to your contacts."})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ai,{id:"allow_spouse",checked:s.allow_spouse,onCheckedChange:o=>l({allow_spouse:!!o})}),e.jsx(ee,{htmlFor:"allow_spouse",className:"text-sm cursor-pointer",children:"Allow client to add spouse/partner during onboarding"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(ee,{className:"text-sm font-medium",children:"Client Invite Details"}),e.jsxs("div",{className:"grid grid-cols-1 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs text-muted-foreground",children:"Client Full Name"}),e.jsx(pe,{value:s.client_name,onChange:o=>l({client_name:o.target.value}),placeholder:"Jane Smith"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs text-muted-foreground",children:"Email"}),e.jsx(pe,{type:"email",value:s.client_email,onChange:o=>l({client_email:o.target.value}),placeholder:"jane@example.com"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs text-muted-foreground",children:"Phone"}),e.jsx(pe,{type:"tel",value:s.client_phone,onChange:o=>l({client_phone:o.target.value}),placeholder:"(555) 123-4567"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs text-muted-foreground",children:"Preferred Invite Method"}),e.jsxs(ms,{value:s.invite_method,onValueChange:o=>l({invite_method:o}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"email",children:"Email"}),e.jsxs(Ge,{value:"sms",disabled:!s.client_phone,children:["SMS ",!s.client_phone&&"(add phone first)"]})]})]})]})]})]})]})]})})]})})}const FQn=[{value:"buyer",label:"Buyer"},{value:"seller",label:"Seller"},{value:"dual",label:"Dual Agency"},{value:"referral",label:"Referral"},{value:"lease",label:"Lease"}],OQn=[{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"},{value:"urgent",label:"Urgent"}];function O$e({label:s,date:t,onChange:n,placeholder:r="Pick a date",disabled:a}){const[i,l]=j.useState(t?en(t,"MM/dd/yyyy"):"");j.useEffect(()=>{const c=yvt(i);t&&c&&c.getTime()===t.getTime()||l(t?en(t,"MM/dd/yyyy"):"")},[t]);const o=c=>{l(c);const d=yvt(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(Kd,{children:[e.jsx(Yd,{asChild:!0,children:e.jsxs($,{variant:"outline",className:Pt("w-full justify-start text-left font-normal",!t&&"text-muted-foreground"),disabled:a,children:[e.jsx(Ta,{className:"mr-2 h-4 w-4"}),t?en(t,"PPP"):r]})}),e.jsxs(Od,{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(T2,{mode:"single",selected:t,onSelect:c=>{n(c),l(c?en(c,"MM/dd/yyyy"):"")},initialFocus:!0,className:"pointer-events-auto",captionLayout:"dropdown",fromYear:1900,toYear:2100})]})]})]})}function zQn({open:s,onOpenChange:t,deal:n,defaultStageId:r}){const{data:a}=Yie(),{data:i}=R_(),{data:l}=Hst(),o=v6e(),c=Drs(),d=Frs(),u=bit(),{data:h}=qrs(),{data:m}=Mae(),f=((m==null?void 0:m.length)??0)>0,g=j.useMemo(()=>{const X=h==null?void 0:h.plan;return X?{brokerage_split_pct:String(Math.max(0,100-(X.agent_split_pct??100))),team_split_pct:f&&X.team_split_pct?String(X.team_split_pct):"",franchise_fee_pct:X.franchise_fee_pct?String(X.franchise_fee_pct):"",transaction_fee:X.transaction_fee?String(X.transaction_fee):"",referral_fee_pct:X.referral_fee_pct!=null?String(X.referral_fee_pct):"",commission_calc_method:X.commission_calc_method||"standard"}:{brokerage_split_pct:"",team_split_pct:"",franchise_fee_pct:"",transaction_fee:"",referral_fee_pct:"",commission_calc_method:"standard"}},[h,f]);j.useEffect(()=>{if(!s||n||!h)return;const X=h.plan;O(ae=>ae.brokerage_split_pct||ae.franchise_fee_pct||ae.transaction_fee||ae.referral_fee_pct||ae.team_split_pct?ae:{...ae,brokerage_split_pct:String(Math.max(0,100-(X.agent_split_pct??100))),team_split_pct:f&&X.team_split_pct?String(X.team_split_pct):"",franchise_fee_pct:X.franchise_fee_pct?String(X.franchise_fee_pct):"",transaction_fee:X.transaction_fee?String(X.transaction_fee):"",referral_fee_pct:X.referral_fee_pct!=null?String(X.referral_fee_pct):"",commission_calc_method:X.commission_calc_method||"standard"})},[h,s,n,f]);const[x,y]=j.useState({portal_enabled:!1,visibility:"private",require_onboarding:!0,allow_spouse:!1,client_name:"",client_email:"",client_phone:"",invite_method:"email"}),[v,b]=j.useState(""),[w,S]=j.useState(!1),[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,ne,te,J,ce,_e,he,ue;s&&(n?(O({deal_name:n.deal_name,deal_type:n.deal_type,stage_id:n.stage_id||"",contact_id:n.contact_id||"",listing_id:n.listing_id||"",property_address:n.property_address||"",city:n.city||"",state:n.state||"",zip_code:n.zip_code||"",expected_price:((X=n.expected_price)==null?void 0:X.toString())||"",commission_percentage:((ae=n.commission_percentage)==null?void 0:ae.toString())||"3",brokerage_split_pct:((le=n.brokerage_split_pct)==null?void 0:le.toString())||"",team_split_pct:((ne=n.team_split_pct)==null?void 0:ne.toString())||"",referral_fee_pct:((te=n.referral_fee_pct)==null?void 0:te.toString())||"",franchise_fee_pct:((J=n.franchise_fee_pct)==null?void 0:J.toString())||"",transaction_fee:((ce=n.transaction_fee)==null?void 0:ce.toString())||"",bonus_amount:((_e=n.bonus_amount)==null?void 0:_e.toString())||"",commission_calc_method:n.commission_calc_method||"standard",target_close_date:n.target_close_date?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||((he=a==null?void 0:a[0])==null?void 0:he.id)||"",contact_id:"",listing_id:"",property_address:"",city:"",state:"",zip_code:"",expected_price:"",commission_percentage:"3",brokerage_split_pct:g.brokerage_split_pct,team_split_pct:g.team_split_pct,referral_fee_pct:g.referral_fee_pct,franchise_fee_pct:g.franchise_fee_pct,transaction_fee:g.transaction_fee,bonus_amount:"",commission_calc_method:g.commission_calc_method,target_close_date:void 0,contract_date:void 0,listing_date:void 0,priority:"medium",probability:String(((ue=a==null?void 0:a.find(ve=>{var Ee;return ve.id===(r||((Ee=a==null?void 0:a[0])==null?void 0:Ee.id))}))==null?void 0:ue.default_probability)??50),notes:""}),b(""),y({portal_enabled:!1,visibility:"private",require_onboarding:!0,allow_spouse:!1,client_name:"",client_email:"",client_phone:"",invite_method:"email"})))},[s,n,r,a]);const U=i==null?void 0:i.filter(X=>{var ue,ve,Ee,Se,Le;const ae=v.toLowerCase().trim();if(!ae)return!0;const le=((ue=X.first_name)==null?void 0:ue.toLowerCase())||"",ne=((ve=X.last_name)==null?void 0:ve.toLowerCase())||"",te=((Ee=X.email)==null?void 0:Ee.toLowerCase())||"",J=((Le=(Se=X.phone)==null?void 0:Se.toLowerCase)==null?void 0:Le.call(Se))||"",ce=`${le} ${ne}`.trim(),_e=`${ne} ${le}`.trim();if(ce.includes(ae)||_e.includes(ae)||le.includes(ae)||ne.includes(ae)||te.includes(ae)||J.includes(ae))return!0;const he=ae.split(/\s+/).filter(Boolean);return he.length>1?he.every(Fe=>le.includes(Fe)||ne.includes(Fe)||te.includes(Fe)||J.includes(Fe)):!1}).slice(0,8),W=()=>{const X=parseFloat(D.expected_price)||0,ae=parseFloat(D.commission_percentage)||0;return X*(ae/100)},V=()=>{const X=W(),ae=parseFloat(D.bonus_amount)||0;if(!X)return ae>0?ae:null;const le=parseFloat(D.brokerage_split_pct)||0,ne=parseFloat(D.team_split_pct)||0,te=parseFloat(D.referral_fee_pct)||0,J=parseFloat(D.franchise_fee_pct)||0,ce=parseFloat(D.transaction_fee)||0,_e=parseFloat(D.bonus_amount)||0;if(D.commission_calc_method==="referral_first"){let ue=X;te&&(ue-=X*te/100);let ve=ue;return le&&(ve-=ue*le/100),ne&&(ve-=X*ne/100),J&&(ve-=X*J/100),ce&&(ve-=ce),Math.max(0,ve)+_e}let he=X;return le&&(he=he*((100-le)/100)),ne&&(he=he*((100-ne)/100)),te&&(he=he-X*te/100),J&&(he=he-X*J/100),ce&&(he=he-ce),Math.max(0,he)+_e},G=async X=>{var ae,le,ne;if(X.preventDefault(),!D.deal_name.trim()){re.error("Please enter a deal name");return}try{const te={deal_name:D.deal_name,deal_type:D.deal_type,stage_id:D.stage_id||null,contact_id:D.contact_id||null,listing_id:D.listing_id||null,property_address:D.property_address||null,city:D.city||null,state:D.state||null,zip_code:D.zip_code||null,expected_price:D.expected_price?parseFloat(D.expected_price):null,expected_commission:W()||null,commission_percentage:D.commission_percentage?parseFloat(D.commission_percentage):3,brokerage_split_pct:D.brokerage_split_pct?parseFloat(D.brokerage_split_pct):null,team_split_pct:D.team_split_pct?parseFloat(D.team_split_pct):null,referral_fee_pct:D.referral_fee_pct?parseFloat(D.referral_fee_pct):null,franchise_fee_pct:D.franchise_fee_pct?parseFloat(D.franchise_fee_pct):null,transaction_fee:D.transaction_fee?parseFloat(D.transaction_fee):null,bonus_amount:D.bonus_amount?parseFloat(D.bonus_amount):null,commission_calc_method:D.commission_calc_method,target_close_date:((ae=D.target_close_date)==null?void 0:ae.toISOString().split("T")[0])||null,contract_date:((le=D.contract_date)==null?void 0:le.toISOString().split("T")[0])||null,listing_date:((ne=D.listing_date)==null?void 0:ne.toISOString().split("T")[0])||null,priority:D.priority,probability:parseInt(D.probability)||50,notes:D.notes||null};if(n)await d.mutateAsync({id:n.id,...te}),re.success("Deal updated successfully");else{const J=await c.mutateAsync(te);if(re.success("Deal created successfully"),x.portal_enabled&&(J!=null&&J.id))try{await u.mutateAsync({deal_id:J.id,visibility:x.visibility,require_onboarding:x.require_onboarding,allow_spouse:x.allow_spouse,client_name:x.client_name||null,client_email:x.client_email||null,client_phone:x.client_phone||null,invite_method:x.invite_method}),re.success("Client portal created!")}catch{re.error("Deal created, but portal setup failed")}}t(!1)}catch{re.error("Failed to save deal")}},Y=c.isPending||d.isPending;return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:n?"Edit Deal":"Add New Deal"}),e.jsx(Pr,{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:FQn.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(ne=>ne.id===ae);O(ne=>({...ne,stage_id:ae,probability:typeof(le==null?void 0:le.default_probability)=="number"?String(le.default_probability):ne.probability}))},children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Select stage"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"none",children:"No Stage"}),a==null?void 0:a.map(X=>e.jsx(Ge,{value:X.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full",style:{backgroundColor:X.color}}),X.name]})},X.id))]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Link to Contact"}),e.jsxs("div",{className:"relative",children:[e.jsx(Zr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{value:v,onChange:X=>{b(X.target.value),S(!0),E(!1),X.target.value||O(ae=>({...ae,contact_id:""}))},onFocus:()=>S(!0),placeholder:"Search contacts...",className:"pl-9"}),w&&v&&e.jsxs("div",{className:"absolute z-10 w-full mt-1 bg-background border rounded-lg shadow-lg max-h-60 overflow-y-auto",children:[U&&U.length>0?U.map(X=>e.jsxs("button",{type:"button",className:"w-full px-3 py-2 text-left hover:bg-muted flex items-center gap-2",onClick:()=>{O(ae=>({...ae,contact_id:X.id})),b(`${X.first_name} ${X.last_name}`),S(!1)},children:[e.jsx(sl,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:[X.first_name," ",X.last_name]}),X.email&&e.jsx("span",{className:"text-xs text-muted-foreground ml-auto",children:X.email})]},X.id)):e.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:"No contacts found"}),e.jsxs("button",{type:"button",className:"w-full px-3 py-2 text-left hover:bg-muted flex items-center gap-2 border-t text-primary font-medium",onClick:()=>{const X=v.trim().split(/\s+/);P({first_name:X[0]||"",last_name:X.slice(1).join(" ")||"",email:"",phone:""}),E(!0),S(!1)},children:[e.jsx(lc,{className:"h-4 w-4"}),e.jsxs("span",{children:['Create new contact "',v.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(Wd,{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(ne=>ne.id===ae);O(le?ne=>{var te;return{...ne,listing_id:ae,deal_type:"seller",property_address:le.property_address||ne.property_address,city:le.city||ne.city,state:le.state||ne.state,expected_price:((te=le.price)==null?void 0:te.toString())||ne.expected_price}}:ne=>({...ne,listing_id:ae}))},children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Select a listing to sync status..."})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"none",children:"None"}),R.map(X=>e.jsx(Ge,{value:X.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{children:X.property_address||`${X.city}, ${X.state}`}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["$",(X.price/1e3).toFixed(0),"K"]})]})},X.id))]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Status changes will sync automatically between the deal and listing."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"font-medium text-sm",children:"Property Details"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"col-span-2 space-y-2",children:[e.jsx(ee,{htmlFor:"property_address",children:"Address"}),e.jsx(pe,{id:"property_address",value:D.property_address,onChange:X=>O(ae=>({...ae,property_address:X.target.value})),placeholder:"123 Main Street"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"city",children:"City"}),e.jsx(pe,{id:"city",value:D.city,onChange:X=>O(ae=>({...ae,city:X.target.value}))})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"state",children:"State"}),e.jsx(pe,{id:"state",value:D.state,onChange:X=>O(ae=>({...ae,state:X.target.value})),maxLength:2,placeholder:"TX"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"zip_code",children:"ZIP"}),e.jsx(pe,{id:"zip_code",value:D.zip_code,onChange:X=>O(ae=>({...ae,zip_code:X.target.value}))})]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"font-medium text-sm",children:"Financial Details"}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"expected_price",children:"Expected Price"}),e.jsxs("div",{className:"relative",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground",children:"$"}),e.jsx(pe,{id:"expected_price",type:"number",value:D.expected_price,onChange:X=>O(ae=>({...ae,expected_price:X.target.value})),className:"pl-7",placeholder:"500000"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"commission_percentage",children:"Commission %"}),e.jsxs("div",{className:"relative",children:[e.jsx(pe,{id:"commission_percentage",type:"number",step:"0.1",value:D.commission_percentage,onChange:X=>O(ae=>({...ae,commission_percentage:X.target.value})),className:"pr-7"}),e.jsx("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground",children:"%"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Expected GCI"}),e.jsx(pe,{value:W()?`$${W().toLocaleString()}`:"-",disabled:!0,className:"bg-muted"})]})]}),e.jsxs("details",{className:"group",children:[e.jsxs("summary",{className:"text-xs font-medium text-muted-foreground cursor-pointer hover:text-foreground flex items-center gap-1 py-1",children:[e.jsx("span",{className:"group-open:rotate-90 transition-transform text-[10px]",children:"▶"}),"Commission Splits (optional)"]}),e.jsxs("div",{className:"space-y-3 mt-3",children:[e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg bg-muted/50",children:[e.jsx(ee,{className:"text-xs whitespace-nowrap",children:"Calculation Method:"}),e.jsxs(ms,{value:D.commission_calc_method,onValueChange:X=>O(ae=>({...ae,commission_calc_method:X})),children:[e.jsx(us,{className:"h-7 text-xs",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"standard",children:"Standard (all splits on GCI)"}),e.jsx(Ge,{value:"referral_first",children:"Referral First (brokerage split after referral)"})]})]})]}),D.commission_calc_method==="referral_first"&&e.jsx("p",{className:"text-[10px] text-muted-foreground bg-blue-50 dark:bg-blue-950/30 p-2 rounded",children:"💡 Referral fee is deducted from GCI first, then the brokerage split is applied to the remaining amount."}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Brokerage Split"}),e.jsxs("div",{className:"relative",children:[e.jsx(pe,{type:"number",step:"1",min:"0",max:"100",value:D.brokerage_split_pct,onChange:X=>O(ae=>({...ae,brokerage_split_pct:X.target.value})),className:"pr-7 h-8 text-sm",placeholder:"30"}),e.jsx("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground text-xs",children:"%"})]}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"% that goes to brokerage"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Team Split"}),e.jsxs("div",{className:"relative",children:[e.jsx(pe,{type:"number",step:"1",min:"0",max:"100",value:D.team_split_pct,onChange:X=>O(ae=>({...ae,team_split_pct:X.target.value})),className:"pr-7 h-8 text-sm",placeholder:"0"}),e.jsx("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground text-xs",children:"%"})]}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"% that goes to team lead"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Referral Fee"}),e.jsxs("div",{className:"relative",children:[e.jsx(pe,{type:"number",step:"1",min:"0",max:"100",value:D.referral_fee_pct,onChange:X=>O(ae=>({...ae,referral_fee_pct:X.target.value})),className:"pr-7 h-8 text-sm",placeholder:"0"}),e.jsx("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground text-xs",children:"%"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Franchise Fee"}),e.jsxs("div",{className:"relative",children:[e.jsx(pe,{type:"number",step:"1",min:"0",max:"100",value:D.franchise_fee_pct,onChange:X=>O(ae=>({...ae,franchise_fee_pct:X.target.value})),className:"pr-7 h-8 text-sm",placeholder:"0"}),e.jsx("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground text-xs",children:"%"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Transaction Fee"}),e.jsxs("div",{className:"relative",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground text-xs",children:"$"}),e.jsx(pe,{type:"number",step:"1",min:"0",value:D.transaction_fee,onChange:X=>O(ae=>({...ae,transaction_fee:X.target.value})),className:"pl-7 h-8 text-sm",placeholder:"500"})]}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Flat fee deducted"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Bonus"}),e.jsxs("div",{className:"relative",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground text-xs",children:"$"}),e.jsx(pe,{type:"number",step:"1",min:"0",value:D.bonus_amount,onChange:X=>O(ae=>({...ae,bonus_amount:X.target.value})),className:"pl-7 h-8 text-sm",placeholder:"5000"})]}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Builder/other bonus — paid on top, not split"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Net to Agent"}),e.jsx(pe,{value:V()?`$${Math.round(V()).toLocaleString()}`:"-",disabled:!0,className:"bg-muted h-8 text-sm font-semibold"})]})]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"font-medium text-sm",children:"Dates & Status"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx(O$e,{label:"Target Close Date",date:D.target_close_date,onChange:X=>O(ae=>({...ae,target_close_date:X}))}),e.jsx(O$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(O$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:OQn.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(Ls,{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(DQn,{formData:x,onChange:y}),e.jsxs("div",{className:"flex justify-end gap-3 pt-4 border-t",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{type:"submit",disabled:Y,children:[Y&&e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),n?"Update Deal":"Create Deal"]})]})]})]})})}function BQn({dealId:s}){const t=Sa(),n=Wt(),[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(v=>v.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(pr,{className:"h-3 w-3"})})]},g.id)),!i&&e.jsxs("button",{type:"button",onClick:()=>l(!0),className:"flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground px-2 py-0.5 rounded border border-dashed border-border hover:border-primary transition-colors",children:[e.jsx(dn,{className:"h-3 w-3"})," Add tag"]})]}),i&&e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx(pe,{value:r,onChange:g=>a(g.target.value),onKeyDown:g=>{g.key==="Enter"&&(g.preventDefault(),h()),g.key==="Escape"&&(l(!1),a(""))},placeholder:"Type tag name...",className:"h-8 text-xs flex-1",autoFocus:!0}),e.jsx("button",{type:"button",onClick:h,disabled:!r.trim()||d.isPending,className:"h-8 px-3 rounded-md bg-primary text-primary-foreground text-xs font-medium disabled:opacity-50 shrink-0",children:"Add"}),e.jsx("button",{type:"button",onClick:()=>{l(!1),a("")},className:"h-8 px-2 rounded-md bg-muted text-muted-foreground text-xs shrink-0",children:"Cancel"})]}),r&&f.length>0&&e.jsx("div",{className:"absolute z-20 w-full mt-1 bg-background border rounded shadow-lg max-h-32 overflow-y-auto",children:f.map(g=>e.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-xs hover:bg-muted active:bg-muted",onClick:x=>{x.preventDefault(),d.mutate(g)},children:g},g))})]})]})}function $Qn(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 UQn(){const s=Sa(),t=Wt();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 qQn(){const s=Wt();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 VQn(){const s=Wt();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 HQn(s){const{data:t,error:n}=await q.storage.from("deal-files").createSignedUrl(s,3600);if(n)throw n;return t.signedUrl}const GQn={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"},WQn={pending:"Needed",submitted:"In review",approved:"Approved",rejected:"Changes requested"};function Vrs({dealId:s,canReview:t=!1,canUpload:n=!1}){const{data:r=[],isLoading:a}=Ozt(s),{data:i=[]}=zLs(s),l=FLs(),o=BLs(),[c,d]=j.useState(null),[u,h]=j.useState(""),[m,f]=j.useState(null),[g,x]=j.useState(null),y=j.useRef(null),v=j.useRef(null),b=A=>{var E;v.current=A,(E=y.current)==null||E.click()},w=async A=>{const E=v.current;if(!(!A||!E)){x(E.id);try{await o.mutateAsync({item:E,file:A}),re.success("Document uploaded for review")}catch(I){re.error(I.message||"Upload failed")}finally{x(null),v.current=null,y.current&&(y.current.value="")}}},S=async A=>{try{await l.mutateAsync({item:A,status:"rejected",note:u.trim()||"Changes requested"}),d(null),h("")}catch(E){re.error(E.message||"Could not update item")}};return a?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(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:y,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(da,{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(Aw,{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:()=>Pyt(I.storage_path),children:e.jsx(xi,{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(_J,{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(Nu,{className:"h-4 w-4 text-destructive"})})]})]})]}),c===A.id&&e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(Ls,{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:()=>Pyt(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 Hrs({dealId:s,brokerageId:t,role:n,counterpartName:r}){const{user:a}=bs(),{data:i=[],isLoading:l}=$Ls(s),o=ULs(),c=qLs(),[d,u]=j.useState(""),h=j.useRef(null),m=j.useRef(null);j.useEffect(()=>{var g;(g=h.current)==null||g.scrollIntoView({block:"nearest"})},[i.length]),j.useEffect(()=>{if(l||m.current===s)return;i.some(x=>x.sender_role!==n&&!x.read_at)&&(m.current=s,c.mutate({dealId:s,senderRole:n}))},[s,l,i,n,c]);const f=async()=>{const g=d.trim();if(g)try{await o.mutateAsync({dealId:s,brokerageId:t,body:g,senderRole:n}),u(""),re.success("Message sent — an email notification is on the way")}catch(x){re.error(x.message||"Could not send the message")}};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("p",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(mn,{className:"h-3.5 w-3.5"}),n==="staff"?`Private thread with ${r||"the agent"} — they get an email for every message.`:"Private thread with your transaction team — they get an email for every message."]}),e.jsxs("div",{className:"max-h-[320px] space-y-3 overflow-y-auto rounded-lg border bg-muted/20 p-3",children:[l?e.jsx("div",{className:"flex justify-center py-6",children:e.jsx(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(Ls,{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(Kr,{className:"h-4 w-4"}),"Send & notify"]})})]})]})}function KQn({dealId:s}){var a;const{data:t=[]}=Ozt(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(Vrs,{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(Hrs,{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 RXe=function(s,t){return RXe=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])},RXe(s,t)};function Si(s,t){RXe(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+=uq[(s[r]&3)<<4|s[r+1]>>4],t+=uq[(s[r+1]&15)<<2|s[r+2]>>6],t+=uq[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},N3t=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},XQn=/^(data)?:?([\w\/\+]+)?;?(charset=[\w-]+|base64)?.*,/i,QQn=function(s){var t=s.trim(),n=t.substring(0,100),r=n.match(XQn);if(!r)return N3t(t);var a=r[0],i=t.substring(a.length);return N3t(i)},Oc=function(s){return s.charCodeAt(0)},JQn=function(s){return s.codePointAt(0)},Zie=function(s,t){return zS(s.toString(16),t,"0").toUpperCase()},BDe=function(s){return Zie(s,2)},WE=function(s){return String.fromCharCode(s)},eJn=function(s){return WE(parseInt(s,16))},zS=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]},nJn=function(s){for(var t=[],n=0,r=s.length;nn&&d(),l+=m,o+=f}}return d(),c},iJn=/^D:(\d\d\d\d)(\d\d)?(\d\d)?(\d\d)?(\d\d)?(\d\d)?([+\-Z])?(\d\d)?'?(\d\d)?'?$/,Zrs=function(s){var t=s.match(iJn);if(t){var n=t[1],r=t[2],a=r===void 0?"01":r,i=t[3],l=i===void 0?"01":i,o=t[4],c=o===void 0?"00":o,d=t[5],u=d===void 0?"00":d,h=t[6],m=h===void 0?"00":h,f=t[7],g=f===void 0?"Z":f,x=t[8],y=x===void 0?"00":x,v=t[9],b=v===void 0?"00":v,w=g==="Z"?"Z":""+g+y+":"+b,S=new Date(n+"-"+a+"-"+l+"T"+c+":"+u+":"+m+w);return S}},Wot=function(s,t){for(var n,r=0,a;r=0&&s<=65535},xJn=function(s){return s>=65536&&s<=1114111},Qrs=function(s){return Math.floor((s-65536)/1024)+55296},Jrs=function(s){return(s-65536)%1024+56320},fL;(function(s){s.BigEndian="BigEndian",s.LittleEndian="LittleEndian"})(fL||(fL={}));var pX="�".codePointAt(0),eas=function(s,t){if(t===void 0&&(t=!0),s.length<=1)return String.fromCodePoint(pX);for(var n=t?vJn(s):fL.BigEndian,r=t?2:0,a=[];s.length-r>=2;){var i=S3t(s[r++],s[r++],n);if(yJn(i))if(s.length-r<2)a.push(pX);else{var l=S3t(s[r++],s[r++],n);k3t(l)?a.push(i,l):a.push(pX)}else k3t(i)?(r+=2,a.push(pX)):a.push(i)}return r=55296&&s<=56319},k3t=function(s){return s>=56320&&s<=57343},S3t=function(s,t,n){if(n===fL.LittleEndian)return t<<8|s;if(n===fL.BigEndian)return s<<8|t;throw new Error("Invalid byteOrder: "+n)},vJn=function(s){return tas(s)?fL.BigEndian:sas(s)?fL.LittleEndian:fL.BigEndian},tas=function(s){return s[0]===254&&s[1]===255},sas=function(s){return s[0]===255&&s[1]===254},nas=function(s){return tas(s)||sas(s)},bJn=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},uAe=function(s){return Math.ceil(s.toString(2).length/8)},G$=function(s){for(var t=new Uint8Array(uAe(s)),n=1;n<=t.length;n++)t[n-1]=s>>(t.length-n)*8;return t},Qie=function(s){throw new Error(s)},OT={};(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,ras=1,kJn=2,SJn=3,CJn=258,Kot=29,eoe=256,vne=eoe+1+Kot,$V=30,Yot=19,aas=2*vne+1,j8=15,z$e=16,AJn=7,Zot=256,ias=16,oas=17,las=18,FXe=[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],hAe=[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],EJn=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],cas=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],TJn=512,RA=new Array((vne+2)*2);sY(RA);var nte=new Array($V*2);sY(nte);var bne=new Array(TJn);sY(bne);var _ne=new Array(CJn-SJn+1);sY(_ne);var Xot=new Array(Kot);sY(Xot);var wPe=new Array($V);sY(wPe);function B$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 das,uas,has;function $$e(s,t){this.dyn_tree=s,this.max_code=0,this.stat_desc=t}function mas(s){return s<256?bne[s]:bne[256+(s>>>7)]}function wne(s,t){s.pending_buf[s.pending++]=t&255,s.pending_buf[s.pending++]=t>>>8&255}function _w(s,t,n){s.bi_valid>z$e-n?(s.bi_buf|=t<>z$e-s.bi_valid,s.bi_valid+=n-z$e):(s.bi_buf|=t<>>=1,n<<=1;while(--t>0);return n>>>1}function MJn(s){s.bi_valid===16?(wne(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 PJn(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<=j8;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 pas(s,t,n){var r=new Array(j8+1),a=0,i,l;for(i=1;i<=j8;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]=fas(r[o]++,o))}}function IJn(){var s,t,n,r,a,i=new Array(j8+1);for(n=0,r=0;r>=7;r<$V;r++)for(wPe[r]=a<<7,s=0;s<1<8?wne(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 LJn(s,t,n,r){xas(s),wne(s,n),wne(s,~n),_Jn.arraySet(s.pending_buf,s.window,t,n,s.pending),s.pending+=n}function E3t(s,t,n,r){var a=t*2,i=n*2;return s[a]>1;l>=1;l--)U$e(s,n,l);d=i;do l=s.heap[1],s.heap[1]=s.heap[s.heap_len--],U$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++,U$e(s,n,1);while(s.heap_len>=2);s.heap[--s.heap_max]=s.heap[1],PJn(s,t),pas(n,c,s.bl_count)}function M3t(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[cas[t]*2+1]===0;t--);return s.opt_len+=3*(t+1)+5+5+4,t}function DJn(s,t,n,r){var a;for(_w(s,t-257,5),_w(s,n-1,5),_w(s,r-4,4),a=0;a>>=1)if(t&1&&s.dyn_ltree[n*2]!==0)return C3t;if(s.dyn_ltree[9*2]!==0||s.dyn_ltree[10*2]!==0||s.dyn_ltree[13*2]!==0)return A3t;for(n=32;n0?(s.strm.data_type===jJn&&(s.strm.data_type=FJn(s)),OXe(s,s.l_desc),OXe(s,s.d_desc),l=RJn(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?yas(s,t,n,r):s.strategy===wJn||i===a?(_w(s,(ras<<1)+(r?1:0),3),T3t(s,RA,nte)):(_w(s,(kJn<<1)+(r?1:0),3),DJn(s,s.l_desc.max_code+1,s.d_desc.max_code+1,l+1),T3t(s,s.dyn_ltree,s.dyn_dtree)),gas(s),r&&xas(s)}function $Jn(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[(_ne[n]+eoe+1)*2]++,s.dyn_dtree[mas(t)*2]++),s.last_lit===s.lit_bufsize-1}tY._tr_init=OJn;tY._tr_stored_block=yas;tY._tr_flush_block=BJn;tY._tr_tally=$Jn;tY._tr_align=zJn;function UJn(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 vas=UJn;function qJn(){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 VJn=qJn();function HJn(s,t,n,r){var a=VJn,i=r+n;s^=-1;for(var l=r;l>>8^a[(s^t[l])&255];return s^-1}var bas=HJn,Qot={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"},u_=OT,ak=tY,_as=vas,QM=bas,GJn=Qot,p9=0,WJn=1,KJn=3,pL=4,L3t=5,h4=0,R3t=1,ik=-2,YJn=-3,q$e=-5,ZJn=-1,XJn=1,Due=2,QJn=3,JJn=4,eer=0,ter=2,$De=8,ser=9,ner=15,rer=8,aer=29,ier=256,zXe=ier+1+aer,oer=30,ler=19,cer=2*zXe+1,der=15,Qu=3,NI=258,dC=NI+Qu+1,uer=32,UDe=42,BXe=69,mAe=73,fAe=91,pAe=103,N8=113,$Q=666,j0=1,toe=2,yB=3,nY=4,her=3;function kI(s,t){return s.msg=GJn[t],t}function D3t(s){return(s<<1)-(s>4?9:0)}function TP(s){for(var t=s.length;--t>=0;)s[t]=0}function JM(s){var t=s.state,n=t.pending;n>s.avail_out&&(n=s.avail_out),n!==0&&(u_.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 pb(s,t){ak._tr_flush_block(s,s.block_start>=0?s.block_start:-1,s.strstart-s.block_start,t),s.block_start=s.strstart,JM(s.strm)}function Fh(s,t){s.pending_buf[s.pending++]=t}function gX(s,t){s.pending_buf[s.pending++]=t>>>8&255,s.pending_buf[s.pending++]=t&255}function mer(s,t,n,r){var a=s.avail_in;return a>r&&(a=r),a===0?0:(s.avail_in-=a,u_.arraySet(t,s.input,s.next_in,a,n),s.state.wrap===1?s.adler=_as(s.adler,t,a,n):s.state.wrap===2&&(s.adler=QM(s.adler,t,a,n)),s.next_in+=a,s.total_in+=a,a)}function was(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-dC?s.strstart-(s.w_size-dC):0,d=s.window,u=s.w_mask,h=s.prev,m=s.strstart+NI,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 vB(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-dC)){u_.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=mer(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(vB(s),s.lookahead===0&&t===p9)return j0;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,pb(s,!1),s.strm.avail_out===0)||s.strstart-s.block_start>=s.w_size-dC&&(pb(s,!1),s.strm.avail_out===0))return j0}return s.insert=0,t===pL?(pb(s,!0),s.strm.avail_out===0?yB:nY):(s.strstart>s.block_start&&(pb(s,!1),s.strm.avail_out===0),j0)}function V$e(s,t){for(var n,r;;){if(s.lookahead=Qu&&(s.ins_h=(s.ins_h<=Qu)if(r=ak._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=ak._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+NI;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=ak._tr_tally(s,1,s.match_length-Qu),s.lookahead-=s.match_length,s.strstart+=s.match_length,s.match_length=0):(n=ak._tr_tally(s,0,s.window[s.strstart]),s.lookahead--,s.strstart++),n&&(pb(s,!1),s.strm.avail_out===0))return j0}return s.insert=0,t===pL?(pb(s,!0),s.strm.avail_out===0?yB:nY):s.last_lit&&(pb(s,!1),s.strm.avail_out===0)?j0:toe}function ger(s,t){for(var n;;){if(s.lookahead===0&&(vB(s),s.lookahead===0)){if(t===p9)return j0;break}if(s.match_length=0,n=ak._tr_tally(s,0,s.window[s.strstart]),s.lookahead--,s.strstart++,n&&(pb(s,!1),s.strm.avail_out===0))return j0}return s.insert=0,t===pL?(pb(s,!0),s.strm.avail_out===0?yB:nY):s.last_lit&&(pb(s,!1),s.strm.avail_out===0)?j0:toe}function o5(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 hq;hq=[new o5(0,0,0,0,fer),new o5(4,4,8,4,V$e),new o5(4,5,16,8,V$e),new o5(4,6,32,32,V$e),new o5(4,4,16,16,W$),new o5(8,16,32,32,W$),new o5(8,16,128,128,W$),new o5(8,32,128,256,W$),new o5(32,128,258,1024,W$),new o5(32,258,258,4096,W$)];function xer(s){s.window_size=2*s.w_size,TP(s.head),s.max_lazy_match=hq[s.level].max_lazy,s.good_match=hq[s.level].good_length,s.nice_match=hq[s.level].nice_length,s.max_chain_length=hq[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 yer(){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=$De,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 u_.Buf16(cer*2),this.dyn_dtree=new u_.Buf16((2*oer+1)*2),this.bl_tree=new u_.Buf16((2*ler+1)*2),TP(this.dyn_ltree),TP(this.dyn_dtree),TP(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new u_.Buf16(der+1),this.heap=new u_.Buf16(2*zXe+1),TP(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new u_.Buf16(2*zXe+1),TP(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 jas(s){var t;return!s||!s.state?kI(s,ik):(s.total_in=s.total_out=0,s.data_type=ter,t=s.state,t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap?UDe:N8,s.adler=t.wrap===2?0:1,t.last_flush=p9,ak._tr_init(t),h4)}function Nas(s){var t=jas(s);return t===h4&&xer(s.state),t}function ver(s,t){return!s||!s.state||s.state.wrap!==2?ik:(s.state.gzhead=t,h4)}function kas(s,t,n,r,a,i){if(!s)return ik;var l=1;if(t===ZJn&&(t=6),r<0?(l=0,r=-r):r>15&&(l=2,r-=16),a<1||a>ser||n!==$De||r<8||r>15||t<0||t>9||i<0||i>JJn)return kI(s,ik);r===8&&(r=9);var o=new yer;return s.state=o,o.strm=s,o.wrap=l,o.gzhead=null,o.w_bits=r,o.w_size=1<L3t||t<0)return s?kI(s,ik):ik;if(r=s.state,!s.output||!s.input&&s.avail_in!==0||r.status===$Q&&t!==pL)return kI(s,s.avail_out===0?q$e:ik);if(r.strm=s,n=r.last_flush,r.last_flush=t,r.status===UDe)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>=Due||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=QM(s.adler,r.pending_buf,r.pending,0)),r.gzindex=0,r.status=BXe):(Fh(r,0),Fh(r,0),Fh(r,0),Fh(r,0),Fh(r,0),Fh(r,r.level===9?2:r.strategy>=Due||r.level<2?4:0),Fh(r,her),r.status=N8);else{var l=$De+(r.w_bits-8<<4)<<8,o=-1;r.strategy>=Due||r.level<2?o=0:r.level<6?o=1:r.level===6?o=2:o=3,l|=o<<6,r.strstart!==0&&(l|=uer),l+=31-l%31,r.status=N8,gX(r,l),r.strstart!==0&&(gX(r,s.adler>>>16),gX(r,s.adler&65535)),s.adler=1}if(r.status===BXe)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=QM(s.adler,r.pending_buf,r.pending-a,a)),JM(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=QM(s.adler,r.pending_buf,r.pending-a,a)),r.gzindex===r.gzhead.extra.length&&(r.gzindex=0,r.status=mAe)}else r.status=mAe;if(r.status===mAe)if(r.gzhead.name){a=r.pending;do{if(r.pending===r.pending_buf_size&&(r.gzhead.hcrc&&r.pending>a&&(s.adler=QM(s.adler,r.pending_buf,r.pending-a,a)),JM(s),a=r.pending,r.pending===r.pending_buf_size)){i=1;break}r.gzindexa&&(s.adler=QM(s.adler,r.pending_buf,r.pending-a,a)),i===0&&(r.gzindex=0,r.status=fAe)}else r.status=fAe;if(r.status===fAe)if(r.gzhead.comment){a=r.pending;do{if(r.pending===r.pending_buf_size&&(r.gzhead.hcrc&&r.pending>a&&(s.adler=QM(s.adler,r.pending_buf,r.pending-a,a)),JM(s),a=r.pending,r.pending===r.pending_buf_size)){i=1;break}r.gzindexa&&(s.adler=QM(s.adler,r.pending_buf,r.pending-a,a)),i===0&&(r.status=pAe)}else r.status=pAe;if(r.status===pAe&&(r.gzhead.hcrc?(r.pending+2>r.pending_buf_size&&JM(s),r.pending+2<=r.pending_buf_size&&(Fh(r,s.adler&255),Fh(r,s.adler>>8&255),s.adler=0,r.status=N8)):r.status=N8),r.pending!==0){if(JM(s),s.avail_out===0)return r.last_flush=-1,h4}else if(s.avail_in===0&&D3t(t)<=D3t(n)&&t!==pL)return kI(s,q$e);if(r.status===$Q&&s.avail_in!==0)return kI(s,q$e);if(s.avail_in!==0||r.lookahead!==0||t!==p9&&r.status!==$Q){var c=r.strategy===Due?ger(r,t):r.strategy===QJn?per(r,t):hq[r.level].func(r,t);if((c===yB||c===nY)&&(r.status=$Q),c===j0||c===yB)return s.avail_out===0&&(r.last_flush=-1),h4;if(c===toe&&(t===WJn?ak._tr_align(r):t!==L3t&&(ak._tr_stored_block(r,0,0,!1),t===KJn&&(TP(r.head),r.lookahead===0&&(r.strstart=0,r.block_start=0,r.insert=0))),JM(s),s.avail_out===0))return r.last_flush=-1,h4}return t!==pL?h4:r.wrap<=0?R3t:(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)):(gX(r,s.adler>>>16),gX(r,s.adler&65535)),JM(s),r.wrap>0&&(r.wrap=-r.wrap),r.pending!==0?h4:R3t)}function wer(s){var t;return!s||!s.state?ik:(t=s.state.status,t!==UDe&&t!==BXe&&t!==mAe&&t!==fAe&&t!==pAe&&t!==N8&&t!==$Q?kI(s,ik):(s.state=null,t===N8?kI(s,YJn):h4))}function jer(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!==UDe||r.lookahead))return ik;for(l===1&&(s.adler=_as(s.adler,t,n,0)),r.wrap=0,n>=r.w_size&&(l===0&&(TP(r.head),r.strstart=0,r.block_start=0,r.insert=0),u=new u_.Buf8(r.w_size),u_.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,vB(r);r.lookahead>=Qu;){a=r.strstart,i=r.lookahead-(Qu-1);do r.ins_h=(r.ins_h<=252?6:TM>=248?5:TM>=240?4:TM>=224?3:TM>=192?2:1;jne[254]=jne[254]=1;g9.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 Aas(s,t){if(t<65534&&(s.subarray&&Cas||!s.subarray&&Sas))return String.fromCharCode.apply(null,qDe.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 Aas(o,r)};g9.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+jne[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 Eas=Ner,rte=j3,ate=OT,$Xe=g9,UXe=Qot,ker=Eas,Tas=Object.prototype.toString,Ser=0,H$e=4,UV=0,F3t=1,O3t=2,Cer=-1,Aer=0,Eer=8;function bB(s){if(!(this instanceof bB))return new bB(s);this.options=ate.assign({level:Cer,method:Eer,chunkSize:16384,windowBits:15,memLevel:8,strategy:Aer,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 ker,this.strm.avail_out=0;var n=rte.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(n!==UV)throw new Error(UXe[n]);if(t.header&&rte.deflateSetHeader(this.strm,t.header),t.dictionary){var r;if(typeof t.dictionary=="string"?r=$Xe.string2buf(t.dictionary):Tas.call(t.dictionary)==="[object ArrayBuffer]"?r=new Uint8Array(t.dictionary):r=t.dictionary,n=rte.deflateSetDictionary(this.strm,r),n!==UV)throw new Error(UXe[n]);this._dict_set=!0}}bB.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?H$e:Ser,typeof s=="string"?n.input=$Xe.string2buf(s):Tas.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),a=rte.deflate(n,i),a!==F3t&&a!==UV)return this.onEnd(a),this.ended=!0,!1;(n.avail_out===0||n.avail_in===0&&(i===H$e||i===O3t))&&(this.options.to==="string"?this.onData($Xe.buf2binstring(ate.shrinkBuf(n.output,n.next_out))):this.onData(ate.shrinkBuf(n.output,n.next_out)))}while((n.avail_in>0||n.avail_out===0)&&a!==F3t);return i===H$e?(a=rte.deflateEnd(this.strm),this.onEnd(a),this.ended=!0,a===UV):(i===O3t&&(this.onEnd(UV),n.avail_out=0),!0)};bB.prototype.onData=function(s){this.chunks.push(s)};bB.prototype.onEnd=function(s){s===UV&&(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 Jot(s,t){var n=new bB(t);if(n.push(s,!0),n.err)throw n.msg||UXe[n.err];return n.result}function Ter(s,t){return t=t||{},t.raw=!0,Jot(s,t)}function Mer(s,t){return t=t||{},t.gzip=!0,Jot(s,t)}Jie.Deflate=bB;Jie.deflate=Jot;Jie.deflateRaw=Ter;Jie.gzip=Mer;var soe={},MC={},Fue=30,Per=12,Ier=function(t,n){var r,a,i,l,o,c,d,u,h,m,f,g,x,y,v,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,y=r.lencode,v=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=Fue;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=Fue;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=Fue;break e}else{S=v[(S&65535)+(g&(1<>3,a-=E,x-=E<<3,g&=(1<=1&&U[f]===0;f--);if(g>f&&(g=f),f===0)return i[l++]=1<<24|64<<16|0,i[l++]=1<<24|64<<16|0,c.bits=1,0;for(m=1;m0&&(t===U3t||f!==1))return-1;for(W[1]=0,u=1;uB3t||t===q3t&&b>$3t)return 1;for(;;){Y=u-y,o[h]O?(X=V[G+o[h]],ae=R[D+o[h]]):(X=96,ae=0),S=1<>y)+A]=Y<<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(y===0&&(y=g),P+=m,x=u-y,v=1<B3t||t===q3t&&b>$3t)return 1;E=w&I,i[E]=g<<24|x<<16|P-l|0}}return w!==0&&(i[P+w]=u-y<<24|64<<16|0),c.bits=g,0},e2=OT,qXe=vas,l5=bas,zer=Ier,ite=Oer,Ber=0,Mas=1,Pas=2,V3t=4,$er=5,Oue=6,_B=0,Uer=1,qer=2,gk=-2,Ias=-3,Las=-4,Ver=-5,H3t=8,Ras=1,G3t=2,W3t=3,K3t=4,Y3t=5,Z3t=6,X3t=7,Q3t=8,J3t=9,eAt=10,jPe=11,dA=12,W$e=13,tAt=14,K$e=15,sAt=16,nAt=17,rAt=18,aAt=19,zue=20,Bue=21,iAt=22,oAt=23,lAt=24,cAt=25,dAt=26,Y$e=27,uAt=28,hAt=29,Op=30,Das=31,Her=32,Ger=852,Wer=592,Ker=15,Yer=Ker;function mAt(s){return(s>>>24&255)+(s>>>8&65280)+((s&65280)<<8)+((s&255)<<24)}function Zer(){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 e2.Buf16(320),this.work=new e2.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function Fas(s){var t;return!s||!s.state?gk:(t=s.state,s.total_in=s.total_out=t.total=0,s.msg="",t.wrap&&(s.adler=t.wrap&1),t.mode=Ras,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new e2.Buf32(Ger),t.distcode=t.distdyn=new e2.Buf32(Wer),t.sane=1,t.back=-1,_B)}function Oas(s){var t;return!s||!s.state?gk:(t=s.state,t.wsize=0,t.whave=0,t.wnext=0,Fas(s))}function zas(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))?gk:(r.window!==null&&r.wbits!==t&&(r.window=null),r.wrap=n,r.wbits=t,Oas(s))}function Bas(s,t){var n,r;return s?(r=new Zer,s.state=r,r.window=null,n=zas(s,t),n!==_B&&(s.state=null),n):gk}function Xer(s){return Bas(s,Yer)}var fAt=!0,Z$e,X$e;function Qer(s){if(fAt){var t;for(Z$e=new e2.Buf32(512),X$e=new e2.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(ite(Mas,s.lens,0,288,Z$e,0,s.work,{bits:9}),t=0;t<32;)s.lens[t++]=5;ite(Pas,s.lens,0,32,X$e,0,s.work,{bits:5}),fAt=!1}s.lencode=Z$e,s.lenbits=9,s.distcode=X$e,s.distbits=5}function $as(s,t,n,r){var a,i=s.state;return i.window===null&&(i.wsize=1<=i.wsize?(e2.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),e2.arraySet(i.window,t,n-r,a,i.wnext),r-=a,r?(e2.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=l5(n.check,R,2,0),d=0,u=0,n.mode=G3t;break}if(n.flags=0,n.head&&(n.head.done=!1),!(n.wrap&1)||(((d&255)<<8)+(d>>8))%31){s.msg="incorrect header check",n.mode=Op;break}if((d&15)!==H3t){s.msg="unknown compression method",n.mode=Op;break}if(d>>>=4,u-=4,I=(d&15)+8,n.wbits===0)n.wbits=I;else if(I>n.wbits){s.msg="invalid window size",n.mode=Op;break}n.dmax=1<>8&1),n.flags&512&&(R[0]=d&255,R[1]=d>>>8&255,n.check=l5(n.check,R,2,0)),d=0,u=0,n.mode=W3t;case W3t: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=l5(n.check,R,4,0)),d=0,u=0,n.mode=K3t;case K3t: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=l5(n.check,R,2,0)),d=0,u=0,n.mode=Y3t;case Y3t:if(n.flags&1024){for(;u<16;){if(o===0)break e;o--,d+=r[i++]<>>8&255,n.check=l5(n.check,R,2,0)),d=0,u=0}else n.head&&(n.head.extra=null);n.mode=Z3t;case Z3t: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)),e2.arraySet(n.head.extra,r,i,f,I)),n.flags&512&&(n.check=l5(n.check,r,f,i)),o-=f,i+=f,n.length-=f),n.length))break e;n.length=0,n.mode=X3t;case X3t: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=dA;break;case eAt:for(;u<32;){if(o===0)break e;o--,d+=r[i++]<>>=u&7,u-=u&7,n.mode=Y$e;break}for(;u<3;){if(o===0)break e;o--,d+=r[i++]<>>=1,u-=1,d&3){case 0:n.mode=tAt;break;case 1:if(Qer(n),n.mode=zue,t===Oue){d>>>=2,u-=2;break e}break;case 2:n.mode=nAt;break;case 3:s.msg="invalid block type",n.mode=Op}d>>>=2,u-=2;break;case tAt:for(d>>>=u&7,u-=u&7;u<32;){if(o===0)break e;o--,d+=r[i++]<>>16^65535)){s.msg="invalid stored block lengths",n.mode=Op;break}if(n.length=d&65535,d=0,u=0,n.mode=K$e,t===Oue)break e;case K$e:n.mode=sAt;case sAt:if(f=n.length,f){if(f>o&&(f=o),f>c&&(f=c),f===0)break e;e2.arraySet(a,r,i,f,l),o-=f,i+=f,c-=f,l+=f,n.length-=f;break}n.mode=dA;break;case nAt:for(;u<14;){if(o===0)break e;o--,d+=r[i++]<>>=5,u-=5,n.ndist=(d&31)+1,d>>>=5,u-=5,n.ncode=(d&15)+4,d>>>=4,u-=4,n.nlen>286||n.ndist>30){s.msg="too many length or distance symbols",n.mode=Op;break}n.have=0,n.mode=rAt;case rAt: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=ite(Ber,n.lens,0,19,n.lencode,0,n.work,D),n.lenbits=D.bits,P){s.msg="invalid code lengths set",n.mode=Op;break}n.have=0,n.mode=aAt;case aAt:for(;n.have>>24,b=y>>>16&255,w=y&65535,!(v<=u);){if(o===0)break e;o--,d+=r[i++]<>>=v,u-=v,n.lens[n.have++]=w;else{if(w===16){for(O=v+2;u>>=v,u-=v,n.have===0){s.msg="invalid bit length repeat",n.mode=Op;break}I=n.lens[n.have-1],f=3+(d&3),d>>>=2,u-=2}else if(w===17){for(O=v+3;u>>=v,u-=v,I=0,f=3+(d&7),d>>>=3,u-=3}else{for(O=v+7;u>>=v,u-=v,I=0,f=11+(d&127),d>>>=7,u-=7}if(n.have+f>n.nlen+n.ndist){s.msg="invalid bit length repeat",n.mode=Op;break}for(;f--;)n.lens[n.have++]=I}}if(n.mode===Op)break;if(n.lens[256]===0){s.msg="invalid code -- missing end-of-block",n.mode=Op;break}if(n.lenbits=9,D={bits:n.lenbits},P=ite(Mas,n.lens,0,n.nlen,n.lencode,0,n.work,D),n.lenbits=D.bits,P){s.msg="invalid literal/lengths set",n.mode=Op;break}if(n.distbits=6,n.distcode=n.distdyn,D={bits:n.distbits},P=ite(Pas,n.lens,n.nlen,n.ndist,n.distcode,0,n.work,D),n.distbits=D.bits,P){s.msg="invalid distances set",n.mode=Op;break}if(n.mode=zue,t===Oue)break e;case zue:n.mode=Bue;case Bue: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,zer(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===dA&&(n.back=-1);break}for(n.back=0;y=n.lencode[d&(1<>>24,b=y>>>16&255,w=y&65535,!(v<=u);){if(o===0)break e;o--,d+=r[i++]<>S)],v=y>>>24,b=y>>>16&255,w=y&65535,!(S+v<=u);){if(o===0)break e;o--,d+=r[i++]<>>=S,u-=S,n.back+=S}if(d>>>=v,u-=v,n.back+=v,n.length=w,b===0){n.mode=dAt;break}if(b&32){n.back=-1,n.mode=dA;break}if(b&64){s.msg="invalid literal/length code",n.mode=Op;break}n.extra=b&15,n.mode=iAt;case iAt:if(n.extra){for(O=n.extra;u>>=n.extra,u-=n.extra,n.back+=n.extra}n.was=n.length,n.mode=oAt;case oAt:for(;y=n.distcode[d&(1<>>24,b=y>>>16&255,w=y&65535,!(v<=u);){if(o===0)break e;o--,d+=r[i++]<>S)],v=y>>>24,b=y>>>16&255,w=y&65535,!(S+v<=u);){if(o===0)break e;o--,d+=r[i++]<>>=S,u-=S,n.back+=S}if(d>>>=v,u-=v,n.back+=v,b&64){s.msg="invalid distance code",n.mode=Op;break}n.offset=w,n.extra=b&15,n.mode=lAt;case lAt:if(n.extra){for(O=n.extra;u>>=n.extra,u-=n.extra,n.back+=n.extra}if(n.offset>n.dmax){s.msg="invalid distance too far back",n.mode=Op;break}n.mode=cAt;case cAt:if(c===0)break e;if(f=m-c,n.offset>f){if(f=n.offset-f,f>n.whave&&n.sane){s.msg="invalid distance too far back",n.mode=Op;break}f>n.wnext?(f-=n.wnext,g=n.wsize-f):g=n.wnext-f,f>n.length&&(f=n.length),x=n.window}else x=a,g=l-n.offset,f=n.length;f>c&&(f=c),c-=f,n.length-=f;do a[l++]=x[g++];while(--f);n.length===0&&(n.mode=Bue);break;case dAt:if(c===0)break e;a[l++]=n.length,c--,n.mode=Bue;break;case Y$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 atr,this.strm.avail_out=0;var n=qV.inflateInit2(this.strm,t.windowBits);if(n!==Kx.Z_OK)throw new Error(VXe[n]);if(this.header=new itr,qV.inflateGetHeader(this.strm,this.header),t.dictionary&&(typeof t.dictionary=="string"?t.dictionary=gAe.string2buf(t.dictionary):qas.call(t.dictionary)==="[object ArrayBuffer]"&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(n=qV.inflateSetDictionary(this.strm,t.dictionary),n!==Kx.Z_OK)))throw new Error(VXe[n])}wB.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?Kx.Z_FINISH:Kx.Z_NO_FLUSH,typeof s=="string"?n.input=gAe.binstring2buf(s):qas.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 ote.Buf8(r),n.next_out=0,n.avail_out=r),i=qV.inflate(n,Kx.Z_NO_FLUSH),i===Kx.Z_NEED_DICT&&a&&(i=qV.inflateSetDictionary(this.strm,a)),i===Kx.Z_BUF_ERROR&&u===!0&&(i=Kx.Z_OK,u=!1),i!==Kx.Z_STREAM_END&&i!==Kx.Z_OK)return this.onEnd(i),this.ended=!0,!1;n.next_out&&(n.avail_out===0||i===Kx.Z_STREAM_END||n.avail_in===0&&(l===Kx.Z_FINISH||l===Kx.Z_SYNC_FLUSH))&&(this.options.to==="string"?(o=gAe.utf8border(n.output,n.next_out),c=n.next_out-o,d=gAe.buf2string(n.output,o),n.next_out=c,n.avail_out=r-c,c&&ote.arraySet(n.output,n.output,o,c,0),this.onData(d)):this.onData(ote.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!==Kx.Z_STREAM_END);return i===Kx.Z_STREAM_END&&(l=Kx.Z_FINISH),l===Kx.Z_FINISH?(i=qV.inflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===Kx.Z_OK):(l===Kx.Z_SYNC_FLUSH&&(this.onEnd(Kx.Z_OK),n.avail_out=0),!0)};wB.prototype.onData=function(s){this.chunks.push(s)};wB.prototype.onEnd=function(s){s===Kx.Z_OK&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=ote.flattenChunks(this.chunks)),this.chunks=[],this.err=s,this.msg=this.strm.msg};function elt(s,t){var n=new wB(t);if(n.push(s,!0),n.err)throw n.msg||VXe[n.err];return n.result}function otr(s,t){return t=t||{},t.raw=!0,elt(s,t)}soe.Inflate=wB;soe.inflate=elt;soe.inflateRaw=otr;soe.ungzip=elt;var ltr=OT.assign,ctr=Jie,dtr=soe,utr=Uas,Vas={};ltr(Vas,ctr,dtr,utr);var htr=Vas;const VDe=ru(htr);var pAt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",UQ=new Uint8Array(256);for(var $ue=0;$ue>4,d[a++]=(l&15)<<4|o>>2,d[a++]=(o&3)<<6|c&63;return d},ftr=function(s){for(var t="",n=0;nr)throw new Error(h0(t)+" must be at least "+n+" and at most "+r+", but was actually "+s)},aS=function(s,t,n,r){Mr(s,t,["number","undefined"]),typeof s=="number"&&t2(s,t,n,r)},Was=function(s,t,n){if(Mr(s,t,["number"]),s%n!==0)throw new Error(h0(t)+" must be a multiple of "+n+", but was actually "+s)},$tr=function(s,t){if(!Number.isInteger(s))throw new Error(h0(t)+" must be an integer, but was actually "+s)},GDe=function(s,t){if(![1,0].includes(Math.sign(s)))throw new Error(h0(t)+" must be a positive number or 0, but was actually "+s)},Kc=new Uint16Array(256);for(var Vue=0;Vue<256;Vue++)Kc[Vue]=Vue;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 Kas=function(s){for(var t=new Array(s.length),n=0,r=s.length;n=un.ExclamationPoint&&s<=un.Tilde&&!rlt[s]},wAt={},jAt=new Map,sn=function(s){Si(t,s);function t(n,r){var a=this;if(n!==wAt)throw new tlt("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+=fb(this.encodedName,n,r),this.encodedName.length},t.of=function(n){var r=asr(n),a=jAt.get(r);return a||(a=new t(wAt,r),jAt.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}(C_),osr=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}(C_);const mw=new osr;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===mw&&!r))return a},t.prototype.has=function(n){var r=this.dict.get(n);return r!==void 0&&r!==mw},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}(),ilt=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+=fb(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}(),dsr=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}(),Xas=function(s){Si(t,s);function t(n,r,a){a===void 0&&(a=!0);var i=s.call(this,n.obj({}),a)||this;return i.objects=r,i.offsets=i.computeObjectOffsets(),i.offsetsString=i.computeOffsetsString(),i.dict.set(sn.of("Type"),sn.of("ObjStm")),i.dict.set(sn.of("N"),Ac.of(i.objects.length)),i.dict.set(sn.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),y>o[2]&&(o[2]=y)}return o},i.entries=r||[],i.entryTuplesCache=KE.populatedBy(i.computeEntryTuples),i.maxByteWidthsCache=KE.populatedBy(i.computeMaxEntryByteWidths),i.indexCache=KE.populatedBy(i.computeIndex),n.set(sn.of("Type"),sn.of("XRef")),i}return t.prototype.addDeletedEntry=function(n,r){var a=vP.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=vP.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=vP.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=uJn(n);return r*this.entries.length},t.prototype.updateDict=function(){s.prototype.updateDict.call(this);var n=this.maxByteWidthsCache.access(),r=this.indexCache.access(),a=this.dict.context;this.dict.set(sn.of("W"),a.obj(n)),this.dict.set(sn.of("Index"),a.obj(r))},t.create=function(n,r){r===void 0&&(r=!0);var a=new t(n,[],r);return a.addDeletedEntry(rm.of(0,65535),0),a},t.of=function(n,r,a){return a===void 0&&(a=!0),new t(n,r,a)},t}(alt),hsr=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,v,h,m,y,f,g,x,y,v,b,w,S,A;return pd(this,function(E){switch(E.label){case 0:n=this.context.largestObjectNumber+1,r=WDe.forVersion(1,7),a=r.sizeInBytes()+2,i=usr.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+=fb(this.value,n,r),n[r++]=un.GreaterThan,this.value.length+2},t.of=function(n){return new t(n)},t.fromText=function(n){for(var r=pJn(n),a="",i=0,l=r.length;i> def /CMapName /Adobe-Identity-UCS def /CMapType 2 def 1 begincodespacerange <0000> endcodespacerange `+s.length+` beginbfchar `+s.map(function(t){var n=t[0],r=t[1];return n+" "+r}).join(` `)+` endbfchar endcmap CMapName currentdict /CMap defineresource pop end end`},CAt=function(){for(var s=[],t=0;t"},xAe=function(s){return Zie(s,4)},psr=function(s){if(gJn(s))return xAe(s);if(xJn(s)){var t=Qrs(s),n=Jrs(s);return""+xAe(t)+xAe(n)}var r=BDe(s),a="0x"+r+" is not a valid UTF-8 or UTF-16 codepoint.";throw new Error(a)},gsr=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 nas(n)?eas(n):Kas(n)},t.prototype.decodeDate=function(){var n=this.decodeText(),r=Zrs(n);if(!r)throw new Yas(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+=fb(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=zS(String(n.getUTCFullYear()),4,"0"),a=zS(String(n.getUTCMonth()+1),2,"0"),i=zS(String(n.getUTCDate()),2,"0"),l=zS(String(n.getUTCHours()),2,"0"),o=zS(String(n.getUTCMinutes()),2,"0"),c=zS(String(n.getUTCSeconds()),2,"0");return new t("D:"+r+a+i+l+o+c+"Z")},t}(C_),olt=function(){function s(t,n,r,a){var i=this;this.allGlyphsInFontSortedById=function(){for(var l=new Array(i.font.characterSet.length),o=0,c=l.length;o>3)]>>7-((f&7)<<0)&1,O=3*D;o[w]=S[O],o[w+1]=S[O+1],o[w+2]=S[O+2],o[w+3]=D>2)]>>6-((f&3)<<1)&3,O=3*D;o[w]=S[O],o[w+1]=S[O+1],o[w+2]=S[O+2],o[w+3]=D>1)]>>4-((f&1)<<2)&15,O=3*D;o[w]=S[O],o[w+1]=S[O+1],o[w+2]=S[O+2],o[w+3]=D>>3)]>>>7-(Y&7)&1),X=W==y*255?0:255;c[G+Y]=X<<24|W<<16|W<<8|W}else if(u==2)for(var Y=0;Y>>2)]>>>6-((Y&3)<<1)&3),X=W==y*85?0:255;c[G+Y]=X<<24|W<<16|W<<8|W}else if(u==4)for(var Y=0;Y>>1)]>>>4-((Y&1)<<2)&15),X=W==y*17?0:255;c[G+Y]=X<<24|W<<16|W<<8|W}else if(u==8)for(var Y=0;Y>>2<<3));a==0;){if(a=y(t,m,1),i=y(t,m+1,2),m+=3,i==0){m&7&&(m+=8-(m&7));var P=(m>>>3)+4,R=t[P-4]|t[P-3]<<8;I&&(n=s.H.W(n,h+R)),n.set(new r(t.buffer,t.byteOffset+P,R),h),m=P+R<<3,h+=R;continue}if(I&&(n=s.H.W(n,h+(1<<17))),i==1&&(f=E.J,g=E.h,d=511,u=31),i==2){l=v(t,m,5)+257,o=v(t,m+5,5)+1,c=v(t,m+10,4)+4,m+=14;for(var D=1,O=0;O<38;O+=2)E.Q[O]=0,E.Q[O+1]=0;for(var O=0;OD&&(D=U)}m+=3*c,w(E.Q,D),S(E.Q,D,E.u),f=E.w,g=E.d,m=b(E.u,(1<>>4;if(!(Y>>>8))n[h++]=Y;else{if(Y==256)break;var X=h+Y-254;if(Y>264){var ae=E.q[Y-257];X=h+(ae>>>3)+v(t,m,ae&7),m+=ae&7}var le=g[A(t,m)&u];m+=le&15;var ne=le>>>4,te=E.c[ne],J=(te>>>4)+y(t,m,te&15);for(m+=te&15;h>>4;if(h<=15)l[d]=h,d++;else{var m=0,f=0;h==16?(f=3+o(a,i,2),i+=2,m=l[d-1]):h==17?(f=3+o(a,i,3),i+=3):h==18&&(f=11+o(a,i,7),i+=7);for(var g=d+f;d>>1;li&&(i=c),l++}for(;l>1,d=t[o+1],u=c<<4|d,h=n-d,m=t[o]<>>15-n;r[g]=u,m++}},s.H.l=function(t,n){for(var r=s.H.m.r,a=15-n,i=0;i>>a}},s.H.M=function(t,n,r){r=r<<(n&7);var a=n>>>3;t[a]|=r,t[a+1]|=r>>>8},s.H.I=function(t,n,r){r=r<<(n&7);var a=n>>>3;t[a]|=r,t[a+1]|=r>>>8,t[a+2]|=r>>>16},s.H.e=function(t,n,r){return(t[n>>>3]|t[(n>>>3)+1]<<8)>>>(n&7)&(1<>>3]|t[(n>>>3)+1]<<8|t[(n>>>3)+2]<<16)>>>(n&7)&(1<>>3]|t[(n>>>3)+1]<<8|t[(n>>>3)+2]<<16)>>>(n&7)},s.H.i=function(t,n){return(t[n>>>3]|t[(n>>>3)+1]<<8|t[(n>>>3)+2]<<16|t[(n>>>3)+3]<<24)>>>(n&7)},s.H.m=function(){var t=Uint16Array,n=Uint32Array;return{K:new t(16),j:new t(16),X:[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],S:[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,999,999,999],T:[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0],q:new t(32),p:[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,65535,65535],z:[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0],c:new n(32),J:new t(512),_:[],h:new t(32),$:[],w:new t(32768),C:[],v:[],d:new t(32768),D:[],u:new t(512),Q:[],r:new t(32768),s:new n(286),Y:new n(30),a:new n(19),t:new n(15e3),k:new t(65536),g:new t(32768)}}(),function(){for(var t=s.H.m,n=32768,r=0;r>>1|(a&1431655765)<<1,a=(a&3435973836)>>>2|(a&858993459)<<2,a=(a&4042322160)>>>4|(a&252645135)<<4,a=(a&4278255360)>>>8|(a&16711935)<<8,t.r[r]=(a>>>16|a<<16)>>>17}function i(l,o,c){for(;o--!=0;)l.push(0,c)}for(var r=0;r<32;r++)t.q[r]=t.S[r]<<3|t.T[r],t.c[r]=t.p[r]<<4|t.z[r];i(t._,144,8),i(t._,112,9),i(t._,24,7),i(t._,8,8),s.H.n(t._,9),s.H.A(t._,9,t.J),s.H.l(t._,9),i(t.$,32,5),s.H.n(t.$,5),s.H.A(t.$,5,t.h),s.H.l(t.$,5),i(t.Q,19,0),i(t.C,286,0),i(t.D,30,0),i(t.v,320,0)}(),s.H.N}();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],y=0,v=0,b=d[f];b>3];R=R>>7-(P&7)&1,o[E*l+(I>>3)]|=R<<7-((I&7)<<0)}if(a==2){var R=s[P>>3];R=R>>6-(P&7)&3,o[E*l+(I>>2)]|=R<<6-((I&3)<<1)}if(a==4){var R=s[P>>3];R=R>>4-(P&7)&15,o[E*l+(I>>1)]|=R<<4-((I&1)<<2)}if(a>=8)for(var D=E*l+I*i,O=0;O>3)+O];P+=a,I+=x}A++,E+=g}y*v!=0&&(c+=v*(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,y=s[h]*x,v=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]=(y+S*I)*R,r[m+1]=(v+A*I)*R,r[m+2]=(b+E*I)*R}else if(c==2){var x=s[h+3],y=s[h],v=s[h+1],b=s[h+2],w=r[m+3],S=r[m],A=r[m+1],E=r[m+2];x==w&&y==S&&v==A&&b==E?(r[m]=0,r[m+1]=0,r[m+2]=0,r[m+3]=0):(r[m]=y,r[m+1]=v,r[m+2]=b,r[m+3]=x)}else if(c==3){var x=s[h+3],y=s[h],v=s[h+1],b=s[h+2],w=r[m+3],S=r[m],A=r[m+1],E=r[m+2];if(x==w&&y==S&&v==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;v[d+w+0]=A,v[d+w+1]=E,v[d+w+2]=I}if(d+=f*3,l(v,d,i(v,d-f*3-4,f*3+4)),d+=4,h){l(v,d,f),d+=4,c(v,d,"tRNS"),d+=4;for(var g=0;g>>24&255;d+=f,l(v,d,i(v,d-f-4,f+4)),d+=4}}for(var P=0,x=0;x>2,U>>2));for(var f=0;fG&&X==V[y-G])Y[y]=Y[y-G];else{var ae=w[X];if(ae==null&&(w[X]=ae=S.length,S.push(X),S.length>=300))break;Y[y]=ae}}}var 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)]|=he[ve+Ee]<<4-(Ee&1)*4;else if(h==2)for(var Ee=0;Ee>2)]|=he[ve+Ee]<<6-(Ee&3)*2;else if(h==1)for(var Ee=0;Ee>3)]|=he[ve+Ee]<<7-(Ee&7)*1}te=_e,u=3,ce=1}else if(v==!1&&b.length==1){for(var _e=new Uint8Array(G*ne*3),Se=G*ne,y=0;yI&&(I=D),RP&&(P=R))}I==-1&&(A=E=I=P=0),a&&((A&1)==1&&A--,(E&1)==1&&E--);var U=(I-A+1)*(P-E+1);Uy&&(y=S),Av&&(v=A))}y==-1&&(g=x=y=v=0),l&&((g&1)==1&&g--,(x&1)==1&&x--),i={x:g,y:x,width:y-g+1,height:v-x+1};var P=r[a];P.rect=i,P.blend=1,P.img=new Uint8Array(i.width*i.height*4),r[a-1].dispose==0?(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:VDe,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]=v.ind,d[m>>2]=v.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=wsr(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=_sr(n.ctype),this.width=n.width,this.height=n.height,this.bitsPerComponent=8}return s.load=function(t){return new s(t)},s}(),tis=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=jsr.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}(),sis=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),noe=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 sis(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 HN(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}(noe),Ssr=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}(noe),TAt=new Int32Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Csr=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]),Asr=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]),Esr=[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],Tsr=[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],Msr=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=Csr[W];var V=W>>16;V>0&&(V=this.getBits(V)),r=(W&65535)+V,W=this.getCode(f),W=Asr[W],V=W>>16,V>0&&(V=this.getBits(V));var G=(W&65535)+V;U+r>=O&&(n=this.ensureBuffer(U+r),O=n.length);for(var Y=0;Y>n,this.codeSize=a-=n,l},t.prototype.getCode=function(n){for(var r=this.stream,a=n[0],i=n[1],l=this.codeSize,o=this.codeBuf,c;l>16,h=d&65535;if(u<1||l>u,this.codeSize=l-u,h},t.prototype.generateHuffmanTable=function(n){var r=n.length,a=0,i;for(i=0;ia&&(a=n[i]);for(var l=1<>=1;for(i=m;i0;if(!A||A<256)y[0]=A,v=1;else if(A>=258)if(A=0;l--)y[l]=h[o],o=f[o];else y[v++]=y[0];else if(A===256){g=9,u=258,v=0;continue}else{this.eof=!0,delete this.lzwState;break}if(E&&(f[u]=x,m[u]=m[x]+1,h[u]=y[0],u++,g=u+d&u+d-1?g:Math.min(Math.log(u+d)/.6931471805599453+1,12)|0),x=A,b+=v,r>>r&(1<0){var l=this.stream.getBytes(i);r.set(l,a),a+=i}}else{i=257-i;var o=n[1];r=this.ensureBuffer(a+i+1);for(var c=0;cr.size())throw new kPe(n,0,r.size());r.remove(n)}else{if(n!==0)throw new kPe(n,0,0);this.setKids([])}},t.prototype.normalizedEntries=function(){var n=this.Kids();return n||(n=this.dict.context.obj([this.ref]),this.dict.set(sn.of("Kids"),n)),{Kids:n}},t.fromDict=function(n,r){return new t(n,r)},t}(ais),llt=function(s){Si(t,s);function t(){return s!==null&&s.apply(this,arguments)||this}return t.prototype.Opt=function(){return this.dict.lookupMaybe(sn.of("Opt"),sm,mc,jh)},t.prototype.setOpt=function(n){this.dict.set(sn.of("Opt"),this.dict.context.obj(n))},t.prototype.getExportValues=function(){var n=this.Opt();if(n){if(n instanceof sm||n instanceof mc)return[n];for(var r=[],a=0,i=n.size();ar.size())throw new kPe(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 Wtr;this.dict.set(sn.of("V"),this.dict.context.obj(n))}this.updateSelectedIndices(n)},t.prototype.valuesAreValid=function(n){for(var r=this.getOptions(),a=function(c,d){var u=n[c].decodeText();if(!r.find(function(h){return u===(h.display||h.value).decodeText()}))return{value:!1}},i=0,l=n.length;i1){for(var r=new Array(n.length),a=this.getOptions(),i=function(c,d){var u=n[c].decodeText();r[c]=a.findIndex(function(h){return u===(h.display||h.value).decodeText()})},l=0,o=n.length;l0){var o=l.lookup(0,sm,mc),c=l.lookupMaybe(1,sm,mc);r.push({value:o,display:c||o})}}return r}return[]},t}(rY),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:"Ch",Ff:Jh.Combo,Kids:[]}),a=n.register(r);return new t(r,a)},t}(iis),APe=function(s){Si(t,s);function t(){return s!==null&&s.apply(this,arguments)||this}return t.prototype.addField=function(n){var r=this.normalizedEntries().Kids;r==null||r.push(n)},t.prototype.normalizedEntries=function(){var n=this.Kids();return n||(n=this.dict.context.obj([]),this.dict.set(sn.of("Kids"),n)),{Kids:n}},t.fromDict=function(n,r){return new t(n,r)},t.create=function(n){var r=n.obj({}),a=n.register(r);return new t(r,a)},t}(ais),clt=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}(rY),ZDe=function(s){Si(t,s);function t(){return s!==null&&s.apply(this,arguments)||this}return t.prototype.MaxLen=function(){var n=this.dict.lookup(sn.of("MaxLen"));if(n instanceof Ac)return n},t.prototype.Q=function(){var n=this.dict.lookup(sn.of("Q"));if(n instanceof Ac)return n},t.prototype.setMaxLength=function(n){this.dict.set(sn.of("MaxLen"),Ac.of(n))},t.prototype.removeMaxLength=function(){this.dict.delete(sn.of("MaxLen"))},t.prototype.getMaxLength=function(){var n;return(n=this.MaxLen())===null||n===void 0?void 0:n.asNumber()},t.prototype.setQuadding=function(n){this.dict.set(sn.of("Q"),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(sn.of("V"),n)},t.prototype.removeValue=function(){this.dict.delete(sn.of("V"))},t.prototype.getValue=function(){var n=this.V();if(n instanceof 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}(rY),XDe=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:TN.PushButton,Kids:[]}),a=n.register(r);return new t(r,a)},t}(llt),QDe=function(s){Si(t,s);function t(){return s!==null&&s.apply(this,arguments)||this}return t.prototype.setValue=function(n){var r=this.getOnValues();if(!r.includes(n)&&n!==sn.of("Off"))throw new nlt;this.dict.set(sn.of("V"),n);for(var a=this.getWidgets(),i=0,l=a.length;ii)throw new vAt(r,i);for(var l=r,o=0,c=a.size();ol)return u.insertLeafNode(n,l)||d;l-=u.Count().asNumber()}u instanceof YE&&(l-=1)}if(l===0){this.insertLeafKid(a.size(),n);return}throw new bAt(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 vAt(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 YE)if(l===0){this.removeKid(o);return}else l-=1}throw new bAt(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()&&zT[this.bytes.peek()];)this.bytes.next()},s.prototype.skipLine=function(){for(;!this.bytes.done();){var t=this.bytes.peek();if(t===IAt||t===LAt)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===IAt||t===LAt)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(nis(t).decode())},s}(),Vsr=un.Space,vX=un.CarriageReturn,bX=un.Newline,_X=[un.s,un.t,un.r,un.e,un.a,un.m],Gue=[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:_X,streamEOF1:Ju(_X,[Vsr,vX,bX]),streamEOF2:Ju(_X,[vX,bX]),streamEOF3:Ju(_X,[vX]),streamEOF4:Ju(_X,[bX]),endstream:Gue,EOF1endstream:Ju([vX,bX],Gue),EOF2endstream:Ju([vX],Gue),EOF3endstream:Ju([bX],Gue)},uis=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 kne.True;if(this.matchKeyword(Gm.false))return kne.False;if(this.matchKeyword(Gm.null))return mw;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(hlt[n])return this.parseNumberOrRef();throw new Xtr(this.bytes.position(),n)},t.prototype.parseNumberOrRef=function(){var n=this.parseRawNumber();this.skipWhitespaceAndComments();var r=this.bytes.offset();if(C1[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+=WE(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+=WE(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 esr(this.bytes.position())},t.prototype.parseName=function(){this.bytes.assertNext(un.ForwardSlash);for(var n="";!this.bytes.done();){var r=this.bytes.peek();if(zT[r]||Mk[r])break;n+=WE(r),this.bytes.next()}return sn.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(sn.of("Type"));return i===sn.of("Catalog")?cis.fromMapWithContext(n,this.context):i===sn.of("Pages")?dis.fromMapWithContext(n,this.context):i===sn.of("Page")?YE.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(sn.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 Sne.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 Jtr(n);return a},t.forBytes=function(n,r,a){return new t(tFe.of(n),r,a)},t.forByteStream=function(n,r,a){return a===void 0&&(a=!1),new t(n,r,a)},t}(qsr),Hsr=function(s){Si(t,s);function t(n,r){var a=s.call(this,tFe.fromPDFRawStream(n),n.dict.context)||this,i=n.dict;return a.alreadyParsed=!1,a.shouldWaitForTick=r||function(){return!1},a.firstOffset=i.lookup(sn.of("First"),Ac).asNumber(),a.objectCount=i.lookup(sn.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 slt("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}(uis),c5=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},inr=function(s){al=il=Iu=Lu=qQ=VQ=0;for(var t=[],n=0;n1&&(m=Math.sqrt(m),n*=m,r*=m);var f=h/n,g=u/n,x=-u/r,y=h/r,v=f*o+g*c,b=x*o+y*c,w=f*s+g*t,S=x*s+y*t,A=(w-v)*(w-v)+(S-b)*(S-b),E=1/A-.25;E<0&&(E=0);var I=Math.sqrt(E);i===a&&(I=-I);var P=.5*(v+w)-I*(S-b),R=.5*(b+S)+I*(w-v),D=Math.atan2(b-R,v-P),O=Math.atan2(S-R,w-P),U=O-D;U<0&&i===1?U+=2*Math.PI:U>0&&i===0&&(U-=2*Math.PI);for(var W=Math.ceil(Math.abs(U/(Math.PI*.5+.001))),V=[],G=0;Gs.length)return a-1;var y=t.heightAtSize(a),v=y+y*.2,b=v*i;if(b>Math.abs(n.height))return a-1;a+=1}return a},Anr=function(s,t,n,r){for(var a=n.width/r,i=n.height,l=Eis,o=nJn(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},Enr=function(s){for(var t=s.length;t>0;t--)if(/\s/.test(s[t]))return t},Tnr=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}),v=E==null?void 0:E.trim()}return{fontSize:r,lineHeight:c,lines:d,bounds:{x:u,y:h,width:m-u,height:f-h}}},Mnr=function(s,t){var n=t.fontSize,r=t.font,a=t.bounds,i=t.cellCount,l=Krs(Xie(s));if(l.length>i)throw new knr(l.length,i);(n===void 0||n===0)&&(n=Anr(l,r,a,i));for(var o=a.width/i,c=r.heightAtSize(n,{descender:!1}),d=a.y+(a.height/2-c/2),u=[],h=a.x,m=a.y,f=a.x+a.width,g=a.y+a.height,x=0,y=0;xf&&(f=I+A),d+c>g&&(g=d+c),u.push({text:l,encoded:S,width:A,height:c,x:I,y:d}),x+=1,y+=w}return{fontSize:n,cells:u,bounds:{x:h,y:m,width:f-h,height:g-m}}},LPe=function(s,t){var n=t.alignment,r=t.fontSize,a=t.font,i=t.bounds,l=Krs(Xie(s));(r===void 0||r===0)&&(r=Mis([l],a,i));var o=a.encodeText(l),c=a.widthOfTextAtSize(l,r),d=a.heightAtSize(r,{descender:!1}),u=n===x0.Left?i.x:n===x0.Center?i.x+i.width/2-c/2:n===x0.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}}},iY=function(s){return"normal"in s?s:{normal:s}},Pnr=/\/([^\0\t\n\f\r\ ]+)[\0\t\n\f\r\ ]+(\d*\.\d+|\d+)[\0\t\n\f\r\ ]+Tf/,HL=function(s){var t,n,r=(t=s.getDefaultAppearance())!==null&&t!==void 0?t:"",a=(n=Wot(r,Pnr).match)!==null&&n!==void 0?n:[],i=Number(a[2]);return isFinite(i)?i:void 0},Inr=/(\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)/,xk=function(s){var t,n=(t=s.getDefaultAppearance())!==null&&t!==void 0?t:"",r=Wot(n,Inr).match,a=r??[],i=a[1],l=a[2],o=a[3],c=a[4],d=a[5];if(d==="g"&&i)return Nis(Number(i));if(d==="rg"&&i&&l&&o)return Sh(Number(i),Number(l),Number(o));if(d==="k"&&i&&l&&o&&c)return kis(Number(i),Number(l),Number(o),Number(c))},yk=function(s,t,n,r){var a;r===void 0&&(r=0);var i=[v9(t).toString(),glt((a=n==null?void 0:n.name)!==null&&a!==void 0?a:"dummy__noop",r).toString()].join(` `);s.setDefaultAppearance(i)},Lnr=function(s,t){var n,r,a,i=xk(t),l=xk(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=BT(c==null?void 0:c.getRotation()),m=x9(o,h),f=m.width,g=m.height,x=L6(qc(qc({},o),{rotation:h})),y=Sh(0,0,0),v=(r=A_(c==null?void 0:c.getBorderColor()))!==null&&r!==void 0?r:y,b=A_(c==null?void 0:c.getBackgroundColor()),w=A_(c==null?void 0:c.getBackgroundColor(),.8),S=(a=i??l)!==null&&a!==void 0?a:y;yk(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:v,markColor:S};return{normal:{on:Ju(x,Yue(qc(qc({},A),{color:b,filled:!0}))),off:Ju(x,Yue(qc(qc({},A),{color:b,filled:!1})))},down:{on:Ju(x,Yue(qc(qc({},A),{color:w,filled:!0}))),off:Ju(x,Yue(qc(qc({},A),{color:w,filled:!1})))}}},Rnr=function(s,t){var n,r,a,i=xk(t),l=xk(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=BT(c==null?void 0:c.getRotation()),m=x9(o,h),f=m.width,g=m.height,x=L6(qc(qc({},o),{rotation:h})),y=Sh(0,0,0),v=(r=A_(c==null?void 0:c.getBorderColor()))!==null&&r!==void 0?r:y,b=A_(c==null?void 0:c.getBackgroundColor()),w=A_(c==null?void 0:c.getBackgroundColor(),.8),S=(a=i??l)!==null&&a!==void 0?a:y;yk(i?t:s.acroField,S);var A={x:f/2,y:g/2,width:f-u,height:g-u,borderWidth:u,borderColor:v,dotColor:S};return{normal:{on:Ju(x,Zue(qc(qc({},A),{color:b,filled:!0}))),off:Ju(x,Zue(qc(qc({},A),{color:b,filled:!1})))},down:{on:Ju(x,Zue(qc(qc({},A),{color:w,filled:!0}))),off:Ju(x,Zue(qc(qc({},A),{color:w,filled:!1})))}}},Dnr=function(s,t,n){var r,a,i,l,o,c=xk(t),d=xk(s.acroField),u=HL(t),h=HL(s.acroField),m=t.getRectangle(),f=t.getAppearanceCharacteristics(),g=t.getBorderStyle(),x=f==null?void 0:f.getCaptions(),y=(r=x==null?void 0:x.normal)!==null&&r!==void 0?r:"",v=(i=(a=x==null?void 0:x.down)!==null&&a!==void 0?a:y)!==null&&i!==void 0?i:"",b=(l=g==null?void 0:g.getWidth())!==null&&l!==void 0?l:0,w=BT(f==null?void 0:f.getRotation()),S=x9(m,w),A=S.width,E=S.height,I=L6(qc(qc({},m),{rotation:w})),P=Sh(0,0,0),R=A_(f==null?void 0:f.getBorderColor()),D=A_(f==null?void 0:f.getBackgroundColor()),O=A_(f==null?void 0:f.getBackgroundColor(),.8),U={x:b,y:b,width:A-b*2,height:E-b*2},W=LPe(y,{alignment:x0.Center,fontSize:u??h,font:n,bounds:U}),V=LPe(v,{alignment:x0.Center,fontSize:u??h,font:n,bounds:U}),G=Math.min(W.fontSize,V.fontSize),Y=(o=c??d)!==null&&o!==void 0?o:P;yk(c||u!==void 0?t:s.acroField,Y,n,G);var X={x:0+b/2,y:0+b/2,width:A-b,height:E-b,borderWidth:b,borderColor:R,textColor:Y,font:n.name,fontSize:G};return{normal:Ju(I,$At(qc(qc({},X),{color:D,textLines:[W.line]}))),down:Ju(I,$At(qc(qc({},X),{color:O,textLines:[V.line]})))}},Fnr=function(s,t,n){var r,a,i,l,o=xk(t),c=xk(s.acroField),d=HL(t),u=HL(s.acroField),h=t.getRectangle(),m=t.getAppearanceCharacteristics(),f=t.getBorderStyle(),g=(r=s.getText())!==null&&r!==void 0?r:"",x=(a=f==null?void 0:f.getWidth())!==null&&a!==void 0?a:0,y=BT(m==null?void 0:m.getRotation()),v=x9(h,y),b=v.width,w=v.height,S=L6(qc(qc({},h),{rotation:y})),A=Sh(0,0,0),E=A_(m==null?void 0:m.getBorderColor()),I=A_(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=Pis(g,{alignment:s.getAlignment(),fontSize:d??u,font:n,bounds:O});P=U.lines,R=U.fontSize}else if(s.isCombed()){var U=Mnr(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=LPe(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;yk(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,Cis(V))},Onr=function(s,t,n){var r,a,i,l=xk(t),o=xk(s.acroField),c=HL(t),d=HL(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=BT(h==null?void 0:h.getRotation()),y=x9(u,x),v=y.width,b=y.height,w=L6(qc(qc({},u),{rotation:x})),S=Sh(0,0,0),A=A_(h==null?void 0:h.getBorderColor()),E=A_(h==null?void 0:h.getBackgroundColor()),I=1,P={x:g+I,y:g+I,width:v-(g+I)*2,height:b-(g+I)*2},R=LPe(f,{alignment:x0.Left,fontSize:c??d,font:n,bounds:P}),D=R.line,O=R.fontSize,U=(i=l??o)!==null&&i!==void 0?i:S;yk(l||c!==void 0?t:s.acroField,U,n,O);var W={x:0+g/2,y:0+g/2,width:v-g,height:b-g,borderWidth:g??0,borderColor:A,textColor:U,font:n.name,fontSize:O,color:E,textLines:[D],padding:I};return Ju(w,Cis(W))},znr=function(s,t,n){var r,a,i=xk(t),l=xk(s.acroField),o=HL(t),c=HL(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=BT(u==null?void 0:u.getRotation()),g=x9(d,f),x=g.width,y=g.height,v=L6(qc(qc({},d),{rotation:f})),b=Sh(0,0,0),w=A_(u==null?void 0:u.getBorderColor()),S=A_(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 Snr(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?x0.Left:n===1?x0.Center:n===2?x0.Right:x0.Left},t.prototype.setAlignment=function(n){SI(n,"alignment",x0),this.markAsDirty(),this.acroField.setQuadding(n)},t.prototype.getMaxLength=function(){return this.acroField.getMaxLength()},t.prototype.setMaxLength=function(n){if(aS(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 Cnr(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===x0.Center?gL.Center:r===x0.Right?gL.Right:gL.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:Lis(i),page:l}})}catch{r=[]}return{pageCount:n.length,hasAcroform:r.length>0,fields:r}}function UAt(s,t){return s.mapping_mode==="blank"?"":s.mapping_mode==="static"||!s.merge_key?s.static_value||"":t[s.merge_key]??""}async function Ris(s,t,n){const r=await t3.load(s,{updateMetadata:!1}),a=await r.embedFont(kW.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=UAt(h,n),f=h.pdf_field_name;if(!m){l.push(f);continue}try{const g=u.getField(f),x=Lis(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=UAt(h,n),f=h.pdf_field_name||h.merge_key||h.field_kind||"overlay",g=u[h.page_index??0];if(!m||!g||h.pos_x==null||h.pos_y==null){l.push(f);continue}const{width:x,height:y}=g.getSize(),v=!!h.coords_normalized,b=Number(h.pos_x)*(v?x:1),w=Number(h.width??(v?.2:120))*(v?x:1),S=Number(h.height??(v?.03:18))*(v?y:1),A=Number(h.pos_y)*(v?y:1),E=v?y-A-S:A,I=Number(h.font_size)||(v?Math.min(11,Math.max(7,S*.7)):10);g.drawText(m,{x:v?b+1:b,y:v?E+Math.max(2,(S-I)/2):E,size:I,font:a,color:Sh(0,0,0),maxWidth:v?Math.max(10,w-2):void 0}),i[f]=m}}return{bytes:await r.save(),applied:i,skipped:l}}function wlt(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 Dis=20*1024*1024,jlt=[{value:"purchase",label:"Purchase"},{value:"listing",label:"Listing"},{value:"disclosure",label:"Disclosure"},{value:"addendum",label:"Addendum"},{value:"other",label:"Other"}];function wx(s){var t;return(t=s==null?void 0:s.versions)!=null&&t.length?[...s.versions].sort((n,r)=>r.version_number-n.version_number)[0]:null}function Nlt(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 Wnr(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 Knr(){const s=Sa(),t=Wt();return mt({mutationFn:async({name:n,description:r,category:a,file:i,templateId:l,brokerageId:o})=>{var v;if(!s)throw new Error("Not authenticated");if(i.type!=="application/pdf"&&!i.name.toLowerCase().endsWith(".pdf"))throw new Error("Only PDF files can be uploaded.");if(i.size>Dis)throw new Error("That PDF is larger than the 20MB limit.");let c;try{c=await Gnr(await i.arrayBuffer())}catch(b){throw new Error(wlt(b))}let d=l;if(!d){const{data:b,error:w}=await q.from("form_templates").insert({owner_user_id:s,name:n,description:r||null,category:a,source_type:o?"brokerage":"user_upload",brokerage_id:o||null,is_published:!1}).select().single();if(w)throw w;d=b.id}const{data:u,error:h}=await q.from("form_template_versions").select("version_number").eq("template_id",d).order("version_number",{ascending:!1}).limit(1);if(h)throw h;const m=(((v=u==null?void 0:u[0])==null?void 0:v.version_number)??0)+1,f=`${s}/${d}/v${m}-${crypto.randomUUID()}.pdf`,{error:g}=await q.storage.from("form-templates").upload(f,i,{contentType:"application/pdf"});if(g)throw g;const{data:x,error:y}=await q.from("form_template_versions").insert({template_id:d,version_number:m,storage_path:f,file_name:i.name,file_size:i.size,page_count:c.pageCount,has_acroform:c.hasAcroform,detected_fields:c.fields,mapping_status:c.hasAcroform?"needs_mapping":"needs_placement",effective_date:new Date().toISOString().slice(0,10),created_by:s}).select().single();if(y)throw await q.storage.from("form-templates").remove([f]),y;return{templateId:d,version:x}},onSuccess:()=>{t.invalidateQueries({queryKey:["form-templates"]}),t.invalidateQueries({queryKey:["form-template"]})}})}function Fis(){const s=Wt();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 Ynr(){const s=Sa(),t=Wt();return mt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const r=wx(n);if(!r)throw new Error("That template has no uploaded PDF yet.");const a=await iFe(r.storage_path),{data:i,error:l}=await q.from("form_templates").insert({owner_user_id:s,name:`${n.name} (copy)`,description:n.description,category:n.category,source_type:"user_upload"}).select().single();if(l)throw l;const o=`${s}/${i.id}/v1-${crypto.randomUUID()}.pdf`,{error:c}=await q.storage.from("form-templates").upload(o,new Blob([a],{type:"application/pdf"}),{contentType:"application/pdf"});if(c)throw c;const{data:d,error:u}=await q.from("form_template_versions").insert({template_id:i.id,version_number:1,storage_path:o,file_name:r.file_name,file_size:r.file_size,page_count:r.page_count,has_acroform:r.has_acroform,detected_fields:r.detected_fields,mapping_status:r.mapping_status,effective_date:new Date().toISOString().slice(0,10),created_by:s}).select().single();if(u)throw await q.storage.from("form-templates").remove([o]),u;const{data:h}=await q.from("form_field_mappings").select("*").eq("version_id",r.id);if(h!=null&&h.length){const m=h.map(({id:g,created_at:x,updated_at:y,version_id:v,...b})=>({...b,version_id:d.id})),{error:f}=await q.from("form_field_mappings").insert(m);if(f)throw f}return i.id},onSuccess:()=>{t.invalidateQueries({queryKey:["form-templates"]})}})}function Ois(){const s=Wt();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 iFe(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 sS(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 Znr(){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 Xnr(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 klt(s){return s?s<1024*1024?`${(s/1024).toFixed(0)} KB`:`${(s/(1024*1024)).toFixed(1)} MB`:"0 KB"}const SW=[{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"]}],zis=new Map(SW.map(s=>[s.key,s])),Qnr={buyer:"Buyer",seller:"Seller",dual:"Dual",referral:"Referral",lease:"Lease"};function Jnr(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":Qnr[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":Xnr(l),"deal.contract_date":sS(t.contract_date),"deal.target_close_date":sS(t.target_close_date),"deal.actual_close_date":sS(t.actual_close_date),"deal.listing_date":sS(t.listing_date),"deal.inspection_date":sS(t.inspection_date),"deal.inspection_contingency_date":sS(t.inspection_contingency_date),"deal.appraisal_date":sS(t.appraisal_date),"deal.loan_approval_date":sS(t.loan_approval_date),"deal.earnest_money_due_date":sS(t.earnest_money_due_date),"deal.title_docs_due_date":sS(t.title_docs_due_date),"deal.final_walkthrough_date":sS(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:Znr()}}function Slt(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:Jnr(o)}}})}function err(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 trr(){const s=Sa(),t=Wt();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 iFe(a.storage_path);let d;try{d=await Ris(c,l,i)}catch(w){throw new Error(wlt(w))}const h=`${r.name.replace(/[^a-zA-Z0-9-_ ]/g,"").trim()||"Form"} - v${a.version_number}.pdf`,m=d.bytes.buffer.slice(d.bytes.byteOffset,d.bytes.byteOffset+d.bytes.byteLength),f=new Blob([m],{type:"application/pdf"}),g=`${s}/${n}/${crypto.randomUUID()}.pdf`,{error:x}=await q.storage.from("deal-files").upload(g,f,{contentType:"application/pdf"});if(x)throw x;const{data:y,error:v}=await q.from("deal_files").insert({deal_id:n,owner_user_id:s,file_name:h,file_size:f.size,file_type:"application/pdf",storage_path:g}).select().single();if(v)throw v;const{error:b}=await q.from("form_generations").insert({owner_user_id:s,deal_id:n,template_id:r.id,version_id:a.id,deal_file_id:y.id,merge_snapshot:{values:i,applied:d.applied,skipped:d.skipped}});if(b)throw b;return await q.from("deal_activities").insert({deal_id:n,activity_type:"document",title:`Generated ${r.name}`,description:`${h} was generated from a LevelUp form template (v${a.version_number}).`,metadata:{template_id:r.id,version_id:a.id,deal_file_id:y.id}}),{dealFile:y,blob:f,fileName:h,skipped:d.skipped}},onSuccess:(n,r)=>{t.invalidateQueries({queryKey:["deal-files",r.dealId]}),t.invalidateQueries({queryKey:["deal-activities"]}),t.invalidateQueries({queryKey:["form-generations",r.dealId]})}})}function ooe(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 srr(){const s=Wt();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 Bis({open:s,onOpenChange:t,dealId:n,dealName:r,initialTemplateId:a}){const{data:i=[],isLoading:l}=Nlt(),[o,c]=j.useState(a),{data:d,isLoading:u,error:h}=Slt(s?n:void 0),m=trr(),f=j.useMemo(()=>i.find(E=>E.id===o),[i,o]),g=wx(f),{data:x=[],isLoading:y}=ooe(s?g==null?void 0:g.id:void 0);j.useEffect(()=>{s&&a&&c(a)},[s,a]);const v=i.filter(E=>{var I;return((I=wx(E))==null?void 0:I.mapping_status)==="mapped"}),b=j.useMemo(()=>d?x.filter(E=>E.merge_key||E.static_value).map(E=>{var I;return{field:E.pdf_field_name||E.merge_key||"",label:E.merge_key?((I=zis.get(E.merge_key))==null?void 0:I.label)||E.merge_key:"Fixed text",value:E.mapping_mode==="static"?E.static_value||"":d.values[E.merge_key||""]||""}}):[],[x,d]),w=b.filter(E=>!E.value).length,S=async()=>{if(!(!f||!g||!d))try{const E=await m.mutateAsync({dealId:n,template:f,version:g,values:d.values});re.success(`${E.fileName} saved to this deal's files`),t(!1)}catch(E){re.error((E==null?void 0:E.message)||"Could not generate the form")}},A=(g==null?void 0:g.mapping_status)==="mapped";return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-hidden flex flex-col",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Prepare a form"}),e.jsx(Pr,{children:r?`Fill a template with data from ${r}.`:"Fill a template with this deal’s data."})]}),e.jsxs("div",{className:"space-y-4 overflow-y-auto",children:[e.jsxs(ms,{value:o,onValueChange:c,disabled:l,children:[e.jsx(us,{children:e.jsx(fs,{placeholder:l?"Loading templates…":"Choose a template"})}),e.jsx(hs,{children:i.map(E=>{const I=wx(E);return e.jsxs(Ge,{value:E.id,disabled:(I==null?void 0:I.mapping_status)!=="mapped",children:[E.name,E.scope==="brokerage"?" · Brokerage":"",(I==null?void 0:I.mapping_status)!=="mapped"?" — needs mapping":""]},E.id)})})]}),!l&&i.length===0&&e.jsx("p",{className:"rounded-lg border border-dashed p-6 text-center text-sm text-muted-foreground",children:"No form templates yet. Upload one in Forms Library first."}),!l&&i.length>0&&v.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"None of your templates are mapped yet. Finish mapping one in Forms Library."}),h&&e.jsx("p",{className:"text-sm text-destructive",children:"Could not load this deal’s data. Please try again."}),f&&e.jsxs(e.Fragment,{children:[(u||y)&&e.jsx("div",{className:"flex justify-center py-6",children:e.jsx(Ct,{className:"h-5 w-5 animate-spin text-muted-foreground"})}),!u&&!y&&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(uo,{className:"max-h-[280px]",children:e.jsxs("div",{className:"divide-y",children:[b.map((E,I)=>e.jsxs("div",{className:"flex items-center gap-3 px-3 py-2 text-sm",children:[e.jsx("span",{className:"w-1/3 shrink-0 truncate text-muted-foreground",children:E.label}),e.jsx("span",{className:E.value?"truncate":"truncate italic text-muted-foreground/60",children:E.value||"not set"})]},`${E.field}-${I}`)),b.length===0&&e.jsx("p",{className:"p-4 text-center text-sm text-muted-foreground",children:"This template has no mapped fields yet."})]})})]}),!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(Sr,{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(zz,{className:"mr-2 h-4 w-4"}),m.isPending?"Generating…":"Generate & save to deal"]})]})]})})}const nrr=["Client","Co-Buyer","Co-Seller","Spouse","Lender","Title Company","Inspector","Appraiser","Attorney","Contractor","Other"];function $is(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 rrr(){const s=Wt();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]}),re.success("Contact linked to deal")},onError:t=>{var n;(n=t.message)!=null&&n.includes("duplicate")?re.error("This contact is already linked to this deal"):re.error("Failed to link contact")}})}function arr(){const s=Wt();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]}),re.success("Contact removed from deal")},onError:()=>{re.error("Failed to remove contact")}})}const Clt=[{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 oFe(s){var t;return((t=Clt.find(n=>n.value===s))==null?void 0:t.label)||s||"Signer"}function irr(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 orr(){const s=Sa(),t=Wt();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 lrr(){const s=Wt();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 Uis(){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 Alt(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 crr(){const s=Sa(),t=Wt();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 drr(){const s=Wt();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 urr(){const s=Sa(),t=Wt();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=Alt(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 qis({open:s,onOpenChange:t,dealId:n,dealName:r,initialTemplateId:a}){const{data:i=[],isLoading:l}=Nlt(),[o,c]=j.useState(a),{data:d,isLoading:u}=Slt(s?n:void 0),{data:h=[]}=$is(n),{data:m=[]}=Uis(),f=orr(),g=urr(),[x,y]=j.useState("single"),[v,b]=j.useState(void 0),w=j.useMemo(()=>m.find(ce=>ce.id===v),[m,v]),S=j.useMemo(()=>Alt(w,i),[w,i]),{data:A=[],isLoading:E}=st({queryKey:["packet-signer-roles",v,S.map(ce=>{var _e;return(_e=wx(ce))==null?void 0:_e.id}).join(",")],enabled:x==="packet"&&S.length>0,queryFn:async()=>{const ce=S.map(ve=>{var Ee;return(Ee=wx(ve))==null?void 0:Ee.id}).filter(Boolean);if(!ce.length)return[];const{data:_e,error:he}=await q.from("form_field_mappings").select("field_kind, signer_role").in("version_id",ce);if(he)throw he;const ue=new Set;for(const ve of _e||[])ve.field_kind&&ve.field_kind!=="data"&&ve.signer_role&&ue.add(ve.signer_role);return[...ue]}}),I=j.useMemo(()=>i.find(ce=>ce.id===o),[i,o]),P=wx(I),{data:R=[],isLoading:D}=ooe(s?P==null?void 0:P.id:void 0),[O,U]=j.useState(""),[W,V]=j.useState(""),[G,Y]=j.useState({});j.useEffect(()=>{s&&a&&c(a)},[s,a]);const X=j.useMemo(()=>{const ce=new Set;if(x==="packet")for(const he of A)ce.add(he);else for(const he of R)he.field_kind&&he.field_kind!=="data"&&he.signer_role&&ce.add(he.signer_role);const _e=Clt.map(he=>he.value);return[...ce].sort((he,ue)=>_e.indexOf(he)-_e.indexOf(ue))},[R,x,A]);j.useEffect(()=>{var ue,ve,Ee;const ce={},_e=h.filter(Se=>Se.contact);let he=0;for(const Se of X)if(Se==="agent"){const Le=(ue=d==null?void 0:d.sources)==null?void 0:ue.profile;ce[Se]={name:(Le==null?void 0:Le.full_name)||"",email:(Le==null?void 0:Le.email)||"",contact_id:null}}else{const Le=_e[he++],Fe=Le!=null&&Le.contact?`${Le.contact.first_name||""} ${Le.contact.last_name||""}`.trim():"";ce[Se]={name:Fe,email:((ve=Le==null?void 0:Le.contact)==null?void 0:ve.email)||"",contact_id:((Ee=Le==null?void 0:Le.contact)==null?void 0:Ee.id)||null}}Y(ce),x==="single"&&I&&!O&&U(r?`${I.name} – ${r}`:I.name)},[X,h,d,o,v,x]);const ae=(P==null?void 0:P.mapping_status)==="mapped",le=(ce,_e)=>Y(he=>({...he,[ce]:{...he[ce],..._e}})),ne=X.length>0&&X.every(ce=>{var _e,he,ue;return((he=(_e=G[ce])==null?void 0:_e.name)==null?void 0:he.trim())&&/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(((ue=G[ce])==null?void 0:ue.email)||"")}),te=f.isPending||g.isPending,J=async()=>{if(!d)return;const ce=X.map((_e,he)=>({full_name:G[_e].name.trim(),email:G[_e].email.trim(),signer_role:_e,contact_id:G[_e].contact_id,is_agent:_e==="agent",order_index:he}));try{if(x==="packet"){if(!w)return;await g.mutateAsync({dealId:n,packet:w,templates:i,titlePrefix:r||"",message:W.trim()||void 0,values:d.values,signers:ce}),re.success(`${S.length} documents sent to ${ce[0].full_name}`)}else{if(!I||!P)return;await f.mutateAsync({dealId:n,template:I,version:P,title:O.trim()||I.name,message:W.trim()||void 0,values:d.values,signers:ce}),re.success(`Signature request sent to ${ce[0].full_name}`)}t(!1)}catch(_e){re.error((_e==null?void 0:_e.message)||"Could not send the signature request")}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"flex max-h-[90vh] max-w-xl flex-col overflow-hidden",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Send for signature"}),e.jsx(Pr,{children:r?`Fill a template with ${r}'s data, then email it for e-signature.`:"Fill a template with this deal’s data, then email it for e-signature."})]}),e.jsxs("div",{className:"space-y-4 overflow-y-auto",children:[m.length>0&&e.jsx("div",{className:"flex gap-1 rounded-lg bg-muted p-1",children:["single","packet"].map(ce=>e.jsx("button",{onClick:()=>y(ce),className:`flex-1 rounded-md px-3 py-1.5 text-xs font-medium transition-colors ${x===ce?"bg-background shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:ce==="single"?"One form":"Packet"},ce))}),x==="packet"?e.jsxs(e.Fragment,{children:[e.jsxs(ms,{value:v,onValueChange:b,children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Choose a packet"})}),e.jsx(hs,{children:m.map(ce=>{var _e;return e.jsxs(Ge,{value:ce.id,children:[ce.name," (",((_e=ce.items)==null?void 0:_e.length)??0," forms)"]},ce.id)})})]}),S.length>0&&e.jsxs("div",{className:"rounded-lg border bg-muted/40 p-3 text-xs",children:[e.jsx("p",{className:"mb-1.5 font-semibold",children:"Signers move through these in one session:"}),e.jsx("ol",{className:"ml-4 list-decimal space-y-0.5 text-muted-foreground",children:S.map(ce=>{var _e;return e.jsxs("li",{children:[ce.name,((_e=wx(ce))==null?void 0:_e.mapping_status)!=="mapped"?" — not ready":""]},ce.id)})})]})]}):e.jsxs(ms,{value:o,onValueChange:c,disabled:l,children:[e.jsx(us,{children:e.jsx(fs,{placeholder:l?"Loading templates…":"Choose a template"})}),e.jsx(hs,{children:i.map(ce=>{const _e=wx(ce);return e.jsxs(Ge,{value:ce.id,disabled:(_e==null?void 0:_e.mapping_status)!=="mapped",children:[ce.name,ce.scope==="brokerage"?" · Brokerage":"",(_e==null?void 0:_e.mapping_status)!=="mapped"?" — not ready":""]},ce.id)})})]}),(x==="packet"?w:I)&&(u||D||E)&&e.jsx("div",{className:"flex justify-center py-6",children:e.jsx(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,_e)=>{var he,ue,ve;return e.jsxs("div",{className:"space-y-2 rounded-lg border p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-xs font-semibold",children:[_e+1,". ",oFe(ce)]}),ce!=="agent"&&h.length>0&&e.jsxs(ms,{value:((he=G[ce])==null?void 0:he.contact_id)||"",onValueChange:Ee=>{const Se=h.find(Le=>{var Fe;return((Fe=Le.contact)==null?void 0:Fe.id)===Ee});Se!=null&&Se.contact&&le(ce,{contact_id:Ee,name:`${Se.contact.first_name||""} ${Se.contact.last_name||""}`.trim(),email:Se.contact.email||""})},children:[e.jsx(us,{className:"h-7 w-44 text-[11px]",children:e.jsx(fs,{placeholder:"Pick deal contact…"})}),e.jsx(hs,{children:h.map(Ee=>Ee.contact?e.jsxs(Ge,{value:Ee.contact.id,className:"text-xs",children:[Ee.contact.first_name," ",Ee.contact.last_name]},Ee.contact.id):null)})]})]}),e.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[e.jsx(pe,{className:"h-8 text-xs",placeholder:"Full name",value:((ue=G[ce])==null?void 0:ue.name)||"",onChange:Ee=>le(ce,{name:Ee.target.value,contact_id:null})}),e.jsx(pe,{className:"h-8 text-xs",type:"email",placeholder:"Email address",value:((ve=G[ce])==null?void 0:ve.email)||"",onChange:Ee=>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(Ls,{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(Sr,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{onClick:J,disabled:!ne||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 hrr({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 mrr({envelope:s}){const t=Xn(),n=lrr(),r=[...s.signers||[]].sort((m,f)=>m.order_index-f.order_index),a=r.some((m,f)=>m.is_agent&&m.status!=="signed"&&r.slice(0,f).every(g=>g.status==="signed")),i=s.status==="sent"||s.status==="partially_signed",l=r.find(m=>m.declined_at),o=i&&s.expires_at?Math.ceil((new Date(s.expires_at).getTime()-Date.now())/864e5):null,c=async()=>{try{const m=await n.mutateAsync({envelopeId:s.id,action:"audit_pdf"});if(!(m!=null&&m.pdf_base64))throw new Error("No audit trail was returned");const f=atob(m.pdf_base64),g=new Uint8Array(f.length);for(let v=0;v{if(!s.completed_storage_path)return;const{data:m,error:f}=await q.storage.from("deal-files").createSignedUrl(s.completed_storage_path,300);if(f||!m)return re.error("Could not download the signed document");window.open(m.signedUrl,"_blank")},u=async()=>{try{const m=await n.mutateAsync({envelopeId:s.id,action:"agent_link"});m!=null&&m.path&&t(m.path)}catch(m){re.error((m==null?void 0:m.message)||"Could not open countersigning")}},h=async()=>{const m=window.prompt("Why is this being voided? (optional)")??void 0;if(m!==void 0)try{await n.mutateAsync({envelopeId:s.id,action:"void",reason:m}),re.success("Envelope voided")}catch(f){re.error((f==null?void 0:f.message)||"Could not void")}};return e.jsxs("div",{className:"rounded-lg border bg-background p-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded bg-primary/10",children:e.jsx(_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} (${oFe(m.signer_role)}): ${m.status.replace("_"," ")}`).join(" · ")})]}),e.jsx(hrr,{status:s.status})]}),l&&e.jsxs("div",{className:"mt-2 ml-11 rounded-md border border-destructive/30 bg-destructive/5 p-2 text-xs text-destructive",children:[e.jsxs("span",{className:"font-semibold",children:[l.full_name," declined."]})," ",l.decline_reason||"No reason was given."]}),o!==null&&o<=4&&e.jsx("p",{className:"mt-2 ml-11 text-xs text-amber-600",children:o>0?`Expires in ${o} day${o===1?"":"s"} — reminders go out automatically.`:"Expires today — reminders go out automatically."}),(i||s.status==="completed"||s.status==="declined")&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-2 pl-11",children:[i&&e.jsxs($,{variant:"outline",size:"sm",className:"h-7 text-xs",disabled:n.isPending,onClick:async()=>{try{await n.mutateAsync({envelopeId:s.id,action:"remind"}),re.success("Reminder sent")}catch(m){re.error((m==null?void 0:m.message)||"Could not send a reminder")}},children:[e.jsx(ZS,{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(IE,{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(xi,{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(Qq,{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(Rz,{className:"mr-1 h-3 w-3"})," Void"]})]})]})}function frr({dealId:s,dealName:t}){const[n,r]=j.useState(!1),[a,i]=j.useState(!1),{data:l=[],isLoading:o,error:c}=err(s),{data:d=[]}=irr(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(Mq,{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(Fr,{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(mrr,{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(Jr,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:((h=u.template)==null?void 0:h.name)||"Deleted template"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["v",((m=u.version)==null?void 0:m.version_number)??"—"," · ",en(new Date(u.created_at),"MMM d, yyyy")]})]})]},u.id)})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Signature requests email each signer a secure link and remind them automatically on day 3 and day 10. The completed, audit-certified PDF lands in this deal’s Files tab and is emailed to everyone who signed."}),e.jsx(Bis,{open:n,onOpenChange:r,dealId:s,dealName:t}),e.jsx(qis,{open:a,onOpenChange:i,dealId:s,dealName:t})]})}const qAt={text:"Short Text",textarea:"Long Text",dropdown:"Dropdown",toggle:"Yes / No"};function Vis({open:s,onOpenChange:t}){const{data:n,isLoading:r}=aUn(),a=iUn(),i=oUn(),l=lUn(),[o,c]=j.useState(!1),[d,u]=j.useState({question_text:"",field_type:"text",options:[],is_required:!1}),[h,m]=j.useState(""),f=async()=>{if(d.question_text.trim())try{await a.mutateAsync({question_text:d.question_text.trim(),field_type:d.field_type,options:d.field_type==="dropdown"?d.options:[],is_required:d.is_required,sort_order:((n==null?void 0:n.length)||0)+1}),u({question_text:"",field_type:"text",options:[],is_required:!1}),m(""),c(!1),re.success("Question added")}catch{re.error("Failed to add question")}},g=async b=>{try{await l.mutateAsync(b),re.success("Question removed")}catch{re.error("Failed to remove question")}},x=async(b,w)=>{try{await i.mutateAsync({id:b,is_required:w})}catch{re.error("Failed to update question")}},y=()=>{h.trim()&&(u(b=>({...b,options:[...b.options,h.trim()]})),m(""))},v=b=>{u(w=>({...w,options:w.options.filter((S,A)=>A!==b)}))};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-md max-h-[85vh] flex flex-col",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Custom Intake Questions"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"These questions appear on all your portal onboarding forms."})]}),e.jsx(uo,{className:"flex-1",children:e.jsxs("div",{className:"space-y-3 pr-2",children:[r&&e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(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(Ug,{className:"h-4 w-4 text-muted-foreground/40 mt-0.5 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:b.question_text}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx($e,{variant:"secondary",className:"text-xs",children:qAt[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(Sn,{checked:b.is_required,onCheckedChange:S=>x(b.id,S),className:"scale-75"}),e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive",onClick:()=>g(b.id),children:e.jsx(Hn,{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(qAt).map(([b,w])=>e.jsx("button",{type:"button",onClick:()=>u(S=>({...S,field_type:b,options:[]})),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${d.field_type===b?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:w},b))})]}),d.field_type==="dropdown"&&e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm font-medium",children:"Options"}),e.jsxs("div",{className:"space-y-1.5 mt-1.5",children:[d.options.map((b,w)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"flex-1 text-sm bg-muted/50 rounded px-2 py-1",children:b}),e.jsx("button",{onClick:()=>v(w),className:"text-muted-foreground hover:text-destructive",children:e.jsx(pr,{className:"h-3.5 w-3.5"})})]},w)),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{value:h,onChange:b=>m(b.target.value),onKeyDown:b=>b.key==="Enter"&&(b.preventDefault(),y()),placeholder:"Add option...",className:"h-8 text-sm"}),e.jsx($,{variant:"outline",size:"sm",onClick:y,disabled:!h.trim(),className:"h-8",children:e.jsx(dn,{className:"h-3 w-3"})})]})]})]}),e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sn,{checked:d.is_required,onCheckedChange:b=>u(w=>({...w,is_required:b}))}),e.jsx(ee,{className:"text-xs text-muted-foreground",children:"Required"})]})}),e.jsxs("div",{className:"flex gap-2 pt-1",children:[e.jsx($,{variant:"outline",size:"sm",onClick:()=>c(!1),className:"flex-1",children:"Cancel"}),e.jsxs($,{size:"sm",onClick:f,disabled:!d.question_text.trim()||a.isPending,className:"flex-1",children:[a.isPending?e.jsx(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(dn,{className:"h-4 w-4 mr-1"})," Add Question"]}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>t(!1),children:"Done"})]})]})})}function prr({override:s,onChange:t}){const n=Sa(),{data:r}=e$t(),[a,i]=j.useState(null),l=d=>t({...s,...d}),o=async(d,u)=>{if(n){if(d.size>5*1024*1024){re.error("Image must be under 5MB");return}i(u);try{const h=await t$t(n,d,`${u}`);l(u==="logo"?{logo_url:h}:{cover_photo_url:h})}catch(h){re.error(`Upload failed: ${h.message||h}`)}finally{i(null)}}},c=Object.values(s||{}).some(d=>d!=null&&d!=="");return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-2 p-3 rounded-md bg-primary/5 border border-primary/10",children:[e.jsx(Nn,{className:"h-4 w-4 text-primary shrink-0 mt-0.5"}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["These settings ",e.jsx("span",{className:"font-medium text-foreground",children:"override your global Portal Branding"})," for this deal only. Leave any field empty to use your global default."]})]}),e.jsx(VAt,{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(VAt,{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(HAt,{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(HAt,{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(Hn,{className:"h-3 w-3 mr-1"}),"Clear all overrides"]})]})}function VAt({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(Hn,{className:"h-3.5 w-3.5"})})]})]})]})}function HAt({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(Hn,{className:"h-3 w-3"})})]})]})}function grr({portalId:s,agentUserId:t}){const n=Wt(),{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:y},{data:v},{data:b}]=await Promise.all([g.order("sort_order",{ascending:!0}).order("name",{ascending:!0}),q.from("agent_vendor_selections").select("vendor_id, is_visible").eq("agent_user_id",t),q.from("portal_vendor_overrides").select("vendor_id, is_visible").eq("portal_id",s)]);if(y)throw y;const w=new Map;(v||[]).forEach(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=>re.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(vb,{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=iK.find(f=>f.value===h))==null?void 0:m.label)||h};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Choose which vendors from your library appear in ",e.jsx("em",{children:"this specific portal"}),". Changes here only affect this deal — your global vendor library and other portals are unaffected."]}),e.jsx(uo,{className:"h-[400px] rounded-lg border",children:e.jsx("div",{className:"divide-y",children:l.map(h=>{const m=d(h);return e.jsxs("div",{className:"flex items-center gap-3 p-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-muted border flex items-center justify-center overflow-hidden shrink-0",children:h.logo_url?e.jsx("img",{src:h.logo_url,alt:h.name,className:"w-full h-full object-cover"}):e.jsx("span",{className:"text-sm font-semibold text-muted-foreground",children:h.name.charAt(0)})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:h.company||h.name}),e.jsx($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(Sn,{checked:m,disabled:h.is_required||i.isPending,onCheckedChange:f=>i.mutate({vendorId:h.id,isVisible:f})})]},h.id)})})})]})}function xrr({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 v,b,w,S;const y=x.deal_pipeline;return((v=x.client_name)==null?void 0:v.toLowerCase().includes(g))||((b=x.client_email)==null?void 0:b.toLowerCase().includes(g))||((w=y==null?void 0:y.deal_name)==null?void 0:w.toLowerCase().includes(g))||((S=y==null?void 0:y.property_address)==null?void 0:S.toLowerCase().includes(g))})},[d,i]);if(r){const g=h==null?void 0:h.deal_pipeline;return e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-sm font-medium",children:"Linked Portal"}),e.jsxs("div",{className:"flex items-center gap-2 bg-primary/5 border border-primary/20 rounded-lg p-3",children:[e.jsx(Wd,{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(n7,{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(Wd,{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(Wd,{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(Zr,{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 Elt({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=p3(),h=()=>{i("record"),o(0),d(0)},m=g=>{!g&&(a==="uploading"||a==="processing")||(r(g),g||h())},f=j.useCallback(async(g,x)=>{i("uploading");try{const y="Card Video",{videoId:v,libraryId:b}=await A6(y),{uploadUrl:w,apiKey:S}=await E6(v),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}/${v}`;for(;E<4;){if(await new Promise(W=>setTimeout(W,3e3)),Date.now()-I>P){const W=g.size/1048576;await u.mutateAsync({bunny_video_id:v,playback_url:`https://iframe.mediadelivery.net/play/${b}/${v}`,file_size_mb:W,title:y,contact_id:s||void 0,status:"processing",touch_type:"video"}),t(R),re.success("Video saved — still encoding. It will be ready shortly."),i("done"),setTimeout(()=>{r(!1),h()},1500);return}const U=await mk(v);if(E=U.status,d(U.encodeProgress||0),E===5||E===6)throw new Error("Video processing failed")}const D=await mk(v),O=(D.storageSize||g.size)/(1024*1024);await u.mutateAsync({bunny_video_id:v,contact_id:s||void 0,playback_url:D.directPlayUrl||R,thumbnail_url:D.thumbnailUrl,preview_url:D.previewUrl||null,duration_seconds:D.length||x,file_size_mb:O,title:y,status:"ready",touch_type:"video"}),t(R),re.success("Video recorded & added to your library!"),i("done"),setTimeout(()=>{r(!1),h()},1500)}catch(y){console.error("Recording upload error:",y),re.error("Failed to process video. Please try again."),i("record")}},[s,t,u]);return e.jsxs(zs,{open:n,onOpenChange:m,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:"gap-1.5 w-full",children:[e.jsx(ua,{className:"h-3.5 w-3.5"}),"Record Video"]})}),e.jsxs(Os,{className:"sm:max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Record a Video for Your Card"})}),a==="record"&&e.jsx(FT,{maxDurationSeconds:600,onRecordingComplete:f,onError:g=>re.error(g)}),a==="uploading"&&e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12",children:[e.jsx(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 yrr=s=>`portal-settings-draft:${s}`;function Tlt({open:s,onOpenChange:t,portal:n,dealOwnerId:r}){const a=OK(),[i,l]=j.useState(!1),o=j.useMemo(()=>yrr(n.id),[n.id]),[c,d]=j.useState(!1),[u,h]=j.useState(n.next_step_text||""),[m,f]=j.useState(n.next_step_video_url||""),[g,x]=j.useState(n.inspection_date||""),[y,v]=j.useState(n.appraisal_date||""),[b,w]=j.useState(n.welcome_message||""),[S,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),[Y,X]=j.useState(n.stage_mapping||[]),[ae,le]=j.useState(null),[ne,te]=j.useState(n.linked_portal_id||null),[J,ce]=j.useState(n.referral_enabled??!0),[_e,he]=j.useState(n.referral_reward_text||""),[ue,ve]=j.useState(n.referral_cta_headline||""),[Ee,Se]=j.useState(n.homeowner_hub_video_url||""),[Le,Fe]=j.useState(n.branding_override||{}),ke=()=>{h(n.next_step_text||""),f(n.next_step_video_url||""),x(n.inspection_date||""),v(n.appraisal_date||""),w(n.welcome_message||""),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),he(n.referral_reward_text||""),ve(n.referral_cta_headline||""),Se(n.homeowner_hub_video_url||""),Fe(n.branding_override||{})};j.useEffect(()=>{d(!1);const qe=localStorage.getItem(o);if(qe)try{const dt=JSON.parse(qe);h(dt.nextStepText||""),f(dt.nextStepVideo||""),x(dt.inspectionDate||""),v(dt.appraisalDate||""),w(dt.welcomeMessage||""),A(dt.reviewUrl||""),I(!!dt.showPostClose),R(!!dt.notifyClient),O(!!dt.requireOnboarding),W(!!dt.allowSpouse),G(dt.visibility||n.visibility),X(dt.stageMapping||[]),te(dt.linkedPortalId??null),ce(dt.referralEnabled??!0),he(dt.referralRewardText||""),ve(dt.referralCtaHeadline||""),Se(dt.homeownerHubVideoUrl||""),Fe(dt.brandingOverride||{}),d(!0);return}catch{localStorage.removeItem(o)}ke(),d(!0)},[o,n]),j.useEffect(()=>{if(!c)return;const qe={nextStepText:u,nextStepVideo:m,inspectionDate:g,appraisalDate:y,welcomeMessage:b,reviewUrl:S,showPostClose:E,notifyClient:P,requireOnboarding:D,allowSpouse:U,visibility:V,stageMapping:Y,linkedPortalId:ne,referralEnabled:J,referralRewardText:_e,referralCtaHeadline:ue,homeownerHubVideoUrl:Ee,brandingOverride:Le};u!==(n.next_step_text||"")||m!==(n.next_step_video_url||"")||g!==(n.inspection_date||"")||y!==(n.appraisal_date||"")||b!==(n.welcome_message||"")||S!==(n.review_url||"")||E!==n.show_post_close_tips||P!==n.notify_client||D!==n.require_onboarding||U!==n.allow_spouse||V!==n.visibility||JSON.stringify(Y)!==JSON.stringify(n.stage_mapping||[])||ne!==(n.linked_portal_id||null)||J!==(n.referral_enabled??!0)||_e!==(n.referral_reward_text||"")||ue!==(n.referral_cta_headline||"")||Ee!==(n.homeowner_hub_video_url||"")||JSON.stringify(Le)!==JSON.stringify(n.branding_override||{})?localStorage.setItem(o,JSON.stringify(qe)):localStorage.removeItem(o)},[u,m,g,y,b,S,E,P,D,U,V,Y,ne,J,_e,ue,Ee,Le,o,c,n]);const Be=()=>{localStorage.removeItem(o),ke()},Ne=async()=>{try{await a.mutateAsync({id:n.id,next_step_text:u||null,next_step_video_url:m||null,inspection_date:g||null,appraisal_date:y||null,welcome_message:b||null,review_url:S||null,show_post_close_tips:E,notify_client:P,require_onboarding:D,allow_spouse:U,visibility:V,stage_mapping:Y.length>0?Y:null,linked_portal_id:ne,referral_enabled:J,referral_reward_text:_e||null,referral_cta_headline:ue||null,homeowner_hub_video_url:Ee||null,branding_override:Object.values(Le).some(dt=>dt!=null&&dt!=="")?Le:null});const qe=n.linked_portal_id;ne&&ne!==qe&&await q.from("client_portals").update({linked_portal_id:n.id}).eq("id",ne),!ne&&qe&&await q.from("client_portals").update({linked_portal_id:null}).eq("id",qe),localStorage.removeItem(o),re.success("Portal settings saved"),t(!1)}catch{re.error("Failed to save settings")}},Ae=()=>{X([...Y,{label:""}])},Ce=qe=>{X(Y.filter((dt,Xe)=>Xe!==qe)),ae===qe&&le(null)},Ve=(qe,dt,Xe)=>{const at=[...Y];at[qe]={...at[qe],[dt]:Xe},X(at)},ze=()=>{const dt=JLe(null).map(Xe=>({label:Xe.label,description:Xe.description,stageId:void 0}));X(dt)};return e.jsxs(e.Fragment,{children:[e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-lg max-h-[85vh] flex flex-col",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Portal Settings"})}),e.jsxs(ha,{defaultValue:"general",className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(ma,{className:"grid grid-cols-5 shrink-0",children:[e.jsx(Zt,{value:"general",children:"General"}),e.jsx(Zt,{value:"timeline",children:"Timeline"}),e.jsx(Zt,{value:"content",children:"Content"}),e.jsx(Zt,{value:"vendors",children:"Vendors"}),e.jsx(Zt,{value:"branding",children:"Branding"})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto mt-4 min-h-0",children:[e.jsxs(Xt,{value:"general",className:"space-y-4 mt-0 px-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm font-medium",children:"Visibility"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Public portals appear without restrictions"})]}),e.jsx("div",{className:"flex gap-1",children:["private","public"].map(qe=>e.jsx("button",{onClick:()=>G(qe),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${V===qe?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:qe.charAt(0).toUpperCase()+qe.slice(1)},qe))})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm font-medium",children:"Require Onboarding"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Clients must fill out intake form"})]}),e.jsx(Sn,{checked:D,onCheckedChange:O})]}),D&&e.jsxs("div",{className:"flex items-center justify-between pl-4 border-l-2 border-primary/20",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm font-medium",children:"Custom Questions"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Manage intake form questions"})]}),e.jsx($,{variant:"outline",size:"sm",onClick:()=>l(!0),className:"text-xs",children:"Manage"})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm font-medium",children:"Allow Spouse/Partner"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show spouse fields on onboarding"})]}),e.jsx(Sn,{checked:U,onCheckedChange:W})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm font-medium",children:"Post-Close Celebration"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show congrats card when deal closes"})]}),e.jsx(Sn,{checked:E,onCheckedChange:I})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm font-medium",children:"Notify Client on Updates"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Email client when you post portal updates"})]}),e.jsx(Sn,{checked:P,onCheckedChange:R})]}),e.jsx("div",{className:"border-t pt-4",children:e.jsx(xrr,{portalId:n.id,ownerId:r,clientEmail:n.client_email,linkedPortalId:ne,onLink:te})}),e.jsx("div",{children:e.jsx(pe,{type:"date",value:g,onChange:qe=>x(qe.target.value),className:"mt-1"})}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm font-medium",children:"Appraisal Date"}),e.jsx(pe,{type:"date",value:y,onChange:qe=>v(qe.target.value),className:"mt-1"})]})]}),e.jsx(Xt,{value:"timeline",className:"space-y-4 mt-0 px-1",children:e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm font-medium",children:"Client-Facing Stages"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Customize the client-friendly stage labels shown on the portal timeline"})]}),e.jsx($,{variant:"outline",size:"sm",onClick:ze,className:"text-xs",children:"Auto-map"})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground bg-muted/50 rounded-md p-2",children:'💡 These labels are what clients see. Click "More" on any stage to customize its description and add a video link. Internal pipeline stages are automatically translated to friendly names.'}),Y.length===0&&e.jsxs("div",{className:"border border-dashed rounded-lg p-4 text-center",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"No custom mapping — using default client-friendly journey stages"}),e.jsx($,{variant:"outline",size:"sm",onClick:ze,children:"Customize journey labels"})]}),e.jsx("div",{className:"space-y-2 mt-2",children:Y.map((qe,dt)=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ug,{className:"h-4 w-4 text-muted-foreground/50 flex-shrink-0"}),e.jsx(pe,{value:qe.label,onChange:Xe=>Ve(dt,"label",Xe.target.value),placeholder:`Stage ${dt+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===dt?null:dt),children:ae===dt?"Less":"More"}),e.jsx($,{variant:"ghost",size:"icon",className:"h-9 w-9 text-muted-foreground hover:text-destructive",onClick:()=>Ce(dt),children:e.jsx(Hn,{className:"h-3.5 w-3.5"})})]}),ae===dt&&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:qe.description||"",onChange:Xe=>Ve(dt,"description",Xe.target.value),placeholder:"e.g. Now it's time to start actively looking at homes",className:"mt-0.5 w-full rounded-md border border-input bg-background px-3 py-2 text-xs min-h-[50px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs text-muted-foreground",children:"Video"}),qe.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:qe.video_url.length>40?qe.video_url.slice(0,40)+"...":qe.video_url}),e.jsx($,{variant:"ghost",size:"sm",className:"h-7 text-xs text-destructive hover:text-destructive",onClick:()=>Ve(dt,"video_url",""),children:"Remove"})]}):e.jsxs("div",{className:"mt-1 flex items-center gap-1.5",children:[e.jsx(Elt,{onVideoReady:Xe=>Ve(dt,"video_url",Xe)}),e.jsx(s9,{userId:r,onSelect:Xe=>Ve(dt,"video_url",Xe),triggerSize:"sm",triggerClassName:"gap-1.5 shrink-0 flex-1"}),e.jsxs($,{variant:"ghost",size:"sm",className:"gap-1 text-xs text-muted-foreground flex-1",onClick:()=>{const Xe=prompt("Paste a YouTube or Loom URL:");Xe&&Ve(dt,"video_url",Xe)},children:[e.jsx(Sd,{className:"h-3 w-3"}),"Paste URL"]})]})]})]})]},dt))}),Y.length>0&&e.jsxs($,{variant:"outline",size:"sm",onClick:Ae,className:"mt-2 text-xs w-full",children:[e.jsx(dn,{className:"h-3 w-3 mr-1"})," Add Stage"]})]})}),e.jsxs(Xt,{value:"content",className:"space-y-4 mt-0 px-1",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm font-medium",children:"Welcome Message"}),e.jsx("textarea",{value:b,onChange:qe=>w(qe.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:qe=>h(qe.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:qe=>f(qe.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:qe=>A(qe.target.value),className:"mt-1",placeholder:"https://g.page/r/..."})]}),e.jsxs("div",{className:"border-t pt-4 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-base",children:"🎁"}),e.jsx(ee,{className:"text-sm font-semibold",children:"Homeowner Hub & Referrals"})]}),e.jsx("p",{className:"text-xs text-muted-foreground -mt-2",children:'Shown automatically when the deal is in a "won" stage.'}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm font-medium",children:"Show Referral Card"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Big CTA asking client to refer friends"})]}),e.jsx(Sn,{checked:J,onCheckedChange:ce})]}),J&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm font-medium",children:"Headline"}),e.jsx(pe,{value:ue,onChange:qe=>ve(qe.target.value),className:"mt-1",placeholder:"Know someone buying or selling?"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm font-medium",children:"Reward (optional)"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"What the client gets for a successful referral"}),e.jsx(pe,{value:_e,onChange:qe=>he(qe.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:qe=>Se(qe.target.value),className:"mt-1",placeholder:"YouTube, Loom, or direct video URL"})]})]})]})]}),e.jsx(Xt,{value:"vendors",className:"space-y-4 mt-0 px-1",children:e.jsx(grr,{portalId:n.id,agentUserId:r})}),e.jsx(Xt,{value:"branding",className:"space-y-4 mt-0 px-1",children:e.jsx(prr,{override:Le,onChange:Fe})})]})]}),e.jsxs("div",{className:"flex justify-between gap-2 pt-4 border-t shrink-0",children:[e.jsx($,{variant:"ghost",onClick:Be,children:"Reset Draft"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Close"}),e.jsxs($,{onClick:Ne,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(Vis,{open:i,onOpenChange:l})]})}const vrr=s=>`portal-update-draft:${s}`;function Mlt({open:s,onOpenChange:t,portalId:n,portalSlug:r,notifyClient:a}){const i=j.useMemo(()=>vrr(n),[n]),[l,o]=j.useState(""),[c,d]=j.useState(""),[u,h]=j.useState(""),[m,f]=j.useState(!1),[g,x]=j.useState(a??!0),[y,v]=j.useState(!1),b=QQt();j.useEffect(()=>{v(!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),v(!0);return}catch{localStorage.removeItem(i)}o(""),d(""),h(""),f(!1),x(a??!0),v(!0)},[i,a]),j.useEffect(()=>{if(!y)return;const 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,y,i,a]);const w=()=>{localStorage.removeItem(i),o(""),d(""),h(""),f(!1),x(a??!0)},S=async()=>{if(l.trim())try{if(await b.mutateAsync({portal_id:n,title:l.trim(),content:c.trim()||void 0,video_url:u.trim()||void 0,is_stage_change:m}),g&&r)try{const A=lC(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?re.success("Update posted & client emailed"):re.success(`Update posted (${(E==null?void 0:E.reason)||"no email sent"})`)}catch(A){console.error("Notification failed:",A),re.success("Update posted (notification failed to send)")}else re.success("Update posted to portal");w(),t(!1)}catch{re.error("Failed to post update")}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-md",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Post Portal Update"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm font-medium",children:"Title *"}),e.jsx(pe,{value:l,onChange: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(ua,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"})]})]}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx("button",{type:"button",onClick:()=>f(!m),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${m?"bg-emerald-500/10 text-emerald-700 border-emerald-200":"bg-background text-muted-foreground border-input"}`,children:"📊 Stage Change"}),e.jsxs("button",{type:"button",onClick:()=>x(!g),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors flex items-center gap-1.5 ${g?"bg-blue-500/10 text-blue-700 border-blue-200":"bg-background text-muted-foreground border-input"}`,children:[g?e.jsx(Uy,{className:"h-3 w-3"}):e.jsx(YS,{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(Kr,{className:"h-4 w-4 mr-2"}),"Post Update"]})]})]})]})})}function Plt({open:s,onOpenChange:t,portal:n,dealName:r}){const a=OK(),{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=lC(n.slug),y=o.split(" ")[0]||"there",v=`Your Transaction Portal – ${r}`,b=`Hi ${y}, I've set up a dedicated portal where you can track the progress of your transaction in real-time. Here's your link: ${x} You can view your timeline, key dates, documents, and any updates I post along the way. Let me know if you have any questions!`,w=()=>{navigator.clipboard.writeText(x),g(!0),setTimeout(()=>g(!1),2e3),re.success("Portal link copied!")},S=async()=>{if(!d.trim()){re.error("Please enter the client email");return}m(!0);try{await a.mutateAsync({id:n.id,client_name:o||null,client_email:d||null,invite_sent_at:new Date().toISOString(),invite_method:"email"});const{error:E}=await q.functions.invoke("gmail-send",{body:{to:d,subject:v,body:b.replace(/\n/g,"
")}});if(E){let I="";try{const P=E==null?void 0:E.context;if(P&&typeof P.json=="function"){const R=await P.json();I=(R==null?void 0:R.message)||(R==null?void 0:R.error)||""}}catch{}throw new Error(I||E.message||"Failed to send invite")}re.success(`Invite sent to ${d}`),t(!1)}catch(E){re.error(E.message||"Failed to send invite")}finally{m(!1)}},A=()=>{const E=encodeURIComponent(v),I=encodeURIComponent(b);window.open(`mailto:${d}?subject=${E}&body=${I}`,"_blank"),a.mutateAsync({id:n.id,client_name:o||null,client_email:d||null,invite_sent_at:new Date().toISOString(),invite_method:"email"}).catch(()=>{})};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-md",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Invite Client to Portal"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm font-medium",children:"Client Name"}),e.jsx(pe,{value:o,onChange:E=>c(E.target.value),className:"mt-1",placeholder:"John Doe"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm font-medium",children:"Client Email"}),e.jsx(pe,{type:"email",value:d,onChange:E=>u(E.target.value),className:"mt-1",placeholder:"john@example.com"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm font-medium",children:"Portal Link"}),e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[e.jsx("div",{className:"flex-1 bg-muted/50 rounded-md px-3 py-2",children:e.jsx("p",{className:"text-xs font-mono text-muted-foreground truncate",children:x})}),e.jsx($,{variant:"outline",size:"icon",onClick:w,className:"shrink-0",children:f?e.jsx(ca,{className:"h-4 w-4 text-emerald-600"}):e.jsx(Ha,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2 pt-2 border-t",children:[i?e.jsxs($,{onClick:S,disabled:h||!d.trim(),className:"w-full",children:[h?e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(mn,{className:"h-4 w-4 mr-2"}),"Send via Gmail (",l,")"]}):e.jsxs($,{onClick:A,disabled:!d.trim(),className:"w-full",variant:"outline",children:[e.jsx(Fr,{className:"h-4 w-4 mr-2"}),"Open in Email App"]}),e.jsxs($,{variant:"ghost",onClick:w,className:"w-full text-muted-foreground",children:[e.jsx(Ha,{className:"h-4 w-4 mr-2"}),"Just Copy Link"]})]})]})]})})}function brr({deal:s}){const{isAdmin:t,user:n}=bs(),{data:r,isLoading:a}=nUn(s.id),i=bit(),l=OK(),[o,c]=j.useState(!1),[d,u]=j.useState(!1),[h,m]=j.useState(!1),[f,g]=j.useState(!1),x=`portal-management-ui:${s.id}`;if(j.useEffect(()=>{const E=sessionStorage.getItem(x);if(E)try{const I=JSON.parse(E);u(!!I.settingsOpen),m(!!I.composerOpen),g(!!I.inviteOpen)}catch{sessionStorage.removeItem(x)}},[x]),j.useEffect(()=>{d||h||f?sessionStorage.setItem(x,JSON.stringify({settingsOpen:d,composerOpen:h,inviteOpen:f})):sessionStorage.removeItem(x)},[d,h,f,x]),a)return e.jsx("div",{className:"border rounded-lg p-4",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Nn,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"font-medium text-sm",children:"Client Portal"}),e.jsx(Ct,{className:"h-3 w-3 animate-spin ml-auto"})]})});const y=async()=>{var E,I;c(!0);try{await i.mutateAsync({deal_id:s.id,visibility:"private",require_onboarding:!0,client_name:s.contact?`${s.contact.first_name} ${s.contact.last_name}`:void 0,client_email:((E=s.contact)==null?void 0:E.email)||void 0,client_phone:((I=s.contact)==null?void 0:I.phone)||void 0}),re.success("Client portal enabled!")}catch{re.error("Failed to create portal")}finally{c(!1)}},v=async E=>{if(r)try{await l.mutateAsync({id:r.id,is_enabled:E}),re.success(E?"Portal enabled":"Portal disabled")}catch{re.error("Failed to update portal")}},b=()=>{if(!r)return;const E=lC(r.slug);navigator.clipboard.writeText(E),re.success("Portal link copied!")},w=()=>{if(!r)return;const E=lC(r.slug);window.open(E,"_blank")};if(!r)return e.jsxs("div",{className:"border rounded-lg p-4 border-dashed",children:[e.jsx("div",{className:"flex items-center justify-between mb-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Nn,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"font-medium text-sm",children:"Client Portal"})]})}),e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"Create a beautiful portal so your client can track their deal progress in real-time."}),e.jsxs($,{onClick:y,disabled:o,size:"sm",className:"w-full",children:[o?e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Nn,{className:"h-4 w-4 mr-2"}),"Enable Client Portal"]})]});const S=lC(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(Nn,{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(Sn,{checked:r.is_enabled,onCheckedChange:v})]}),e.jsxs("div",{className:"space-y-1.5 mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:"Visibility:"}),e.jsx($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(Ha,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Copy"})]}),e.jsxs($,{variant:"outline",size:"sm",onClick:w,className:"text-xs w-full min-w-0 px-2",children:[e.jsx(Fr,{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(Kr,{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(m4,{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(wr,{to:"/mission-control/portal-referrals",className:"mt-2 flex items-center justify-center gap-1.5 text-[11px] text-muted-foreground hover:text-primary transition-colors py-1.5",children:[e.jsx(ul,{className:"h-3 w-3"}),"View incoming referrals"]})]}),e.jsx(Tlt,{open:d,onOpenChange:u,portal:r,dealOwnerId:A}),e.jsx(Mlt,{open:h,onOpenChange:m,portalId:r.id,portalSlug:r.slug,notifyClient:r.notify_client}),e.jsx(Plt,{open:f,onOpenChange:g,portal:r,dealName:s.deal_name})]})}function _rr({dealId:s,primaryContactId:t}){const n=Xn(),{data:r,isLoading:a}=$is(s),{data:i}=R_(),l=rrr(),o=arr(),[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),y=w=>{l.mutate({dealId:s,contactId:w,role:m}),d(!1),h("")},v=w=>{o.mutate({id:w,dealId:s})},b={Client:"bg-primary/10 text-primary","Co-Buyer":"bg-blue-500/10 text-blue-600","Co-Seller":"bg-emerald-500/10 text-emerald-600",Spouse:"bg-pink-500/10 text-pink-600",Lender:"bg-amber-500/10 text-amber-600","Title Company":"bg-purple-500/10 text-purple-600",Inspector:"bg-orange-500/10 text-orange-600",Appraiser:"bg-cyan-500/10 text-cyan-600",Attorney:"bg-slate-500/10 text-slate-600",Contractor:"bg-lime-500/10 text-lime-600",Other:"bg-muted text-muted-foreground"};return!(r!=null&&r.length)&&!c?e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("h4",{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Yn,{className:"h-4 w-4"}),"Additional Contacts"]})}),e.jsxs(Kd,{open:c,onOpenChange:d,children:[e.jsx(Yd,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:"w-full text-muted-foreground",children:[e.jsx(dn,{className:"h-3.5 w-3.5 mr-1"}),"Link a contact (lender, spouse, vendor...)"]})}),e.jsx(Od,{className:"w-80 p-3",align:"start",children:e.jsx(GAt,{search:u,setSearch:h,selectedRole:m,setSelectedRole:f,filteredContacts:x,onAdd:y})})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h4",{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(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(Kd,{open:c,onOpenChange:d,children:[e.jsx(Yd,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"sm",className:"h-7 px-2",children:e.jsx(dn,{className:"h-3.5 w-3.5"})})}),e.jsx(Od,{className:"w-80 p-3",align:"end",children:e.jsx(GAt,{search:u,setSearch:h,selectedRole:m,setSelectedRole:f,filteredContacts:x,onAdd:y})})]})]}),e.jsx("div",{className:"space-y-1.5",children:r==null?void 0:r.map(w=>{var S,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(mn,{className:"h-3 w-3"})})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6 text-destructive",onClick:()=>v(w.id),children:e.jsx(Hn,{className:"h-3 w-3"})})]})]},w.id)})})]})}function GAt({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:nrr.map(l=>e.jsx(Ge,{value:l,children:l},l))})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Zr,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(pe,{value:s,onChange:l=>t(l.target.value),placeholder:"Search contacts...",className:"pl-7 h-8 text-sm",autoFocus:!0})]}),e.jsx(uo,{className:"max-h-40",children:a&&a.length>0?e.jsx("div",{className:"space-y-0.5",children:a.map(l=>e.jsxs("button",{onClick:()=>i(l.id),className:"w-full text-left px-2 py-1.5 rounded hover:bg-accent transition-colors",children:[e.jsxs("div",{className:"text-sm font-medium truncate",children:[l.first_name," ",l.last_name]}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:[l.phone,l.email].filter(Boolean).join(" · ")||"No contact info"})]},l.id))}):e.jsx("p",{className:"text-xs text-muted-foreground text-center py-3",children:s?"No contacts found":"Type to search"})})]})}const WQ=[{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"}],wrr=[{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 jrr(){const s=Wt();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=Wt();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 krr(){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 Srr(){const s=Sa(),t=Wt();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 y=g==="stage_entry"?null:u[g],v=y?new Date(`${y}T12:00:00`):new Date;return v.setDate(v.getDate()+(x||0)),v.toISOString().split("T")[0]},m=l.filter(g=>!d.has(String(g.title).toLowerCase())).map((g,x)=>({owner_user_id:s,deal_id:r,contact_id:u.contact_id,stage_id:u.stage_id,title:g.title,description:g.description,priority:g.priority,status:"todo",due_date:h(g.due_anchor,g.due_offset_days),sort_order:x}));if(m.length===0)return 0;const{error:f}=await q.from("deal_tasks").insert(m);if(f)throw f;return m.length},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-tasks"]}),t.invalidateQueries({queryKey:["tc-dashboard"]})}})}function Crr(){const s=Sa(),t=Wt();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 Arr(){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 Ilt(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 S5(s){const t=Ilt(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 Err(s){return s===null?"none":s<0?"overdue":s===0?"today":s<=3?"soon":"upcoming"}const Trr={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 nUe(s){const t=Ilt(s);return t?t.toLocaleDateString("en-US",{month:"short",day:"numeric"}):null}function WAt(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 Mrr({deal:s,compact:t=!1}){const n=jrr(),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={};WQ.forEach(Y=>{G[Y.key]=(s==null?void 0:s[Y.key])??""}),o(G),i(!0)},x=async()=>{try{await n.mutateAsync({dealId:s.id,dates:l}),re.success("Transaction dates updated"),i(!1)}catch(G){re.error((G==null?void 0:G.message)||"Could not save dates")}},y=async(G,Y)=>{const X=f;u(G);try{await r.mutateAsync({dealId:s.id,completed:G}),re.success(Y)}catch(ae){u(X),re.error((ae==null?void 0:ae.message)||"Could not update milestone")}},v=j.useMemo(()=>WQ.map(G=>{const Y=(s==null?void 0:s[G.key])??null,X=S5(Y),ae=f.includes(G.key),le=Y?ae?"done":Err(X):"none";return{...G,value:Y,days:X,isDone:ae,state:le}}),[s,f.join(",")]),b=v.filter(G=>G.value).length,w=v.filter(G=>G.state==="done").length,S=S5(s==null?void 0:s.target_close_date),A=v.filter(G=>G.value&&!G.isDone&&G.days!==null&&G.days>=0).sort((G,Y)=>(G.days??0)-(Y.days??0))[0],E=v.filter(G=>G.state==="overdue"),I=()=>{const G=Array.from(new Set([...f,...E.map(Y=>Y.key)]));y(G,"Past milestones marked complete")},P=(G,Y)=>{const X=Y?f.filter(ae=>ae!==G):[...f,G];y(X,Y?"Marked as not complete":"Milestone completed")},[R,D]=j.useState(null),[O,U]=j.useState(""),W=G=>{U((s==null?void 0:s[G])??""),D(G)},V=async(G,Y)=>{try{await n.mutateAsync({dealId:s.id,dates:{[G]:Y}}),re.success(Y?"Date saved":"Date cleared"),D(null)}catch(X){re.error((X==null?void 0:X.message)||"Could not save date")}};return e.jsx(bk,{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(Cu,{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${nUe((s==null?void 0:s.actual_close_date)||(s==null?void 0:s.target_close_date))?` ${nUe((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 ${WQ.length} key dates set`})]})]}),e.jsxs(zs,{open:a,onOpenChange:G=>G?g():i(!1),children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:"shrink-0 gap-1.5",children:[e.jsx(pi,{className:"h-3.5 w-3.5"}),t?"":"Edit dates"]})}),e.jsxs(Os,{className:"max-w-lg",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Key transaction dates"})}),e.jsx("div",{className:"grid sm:grid-cols-2 gap-3 max-h-[60vh] overflow-y-auto pr-1",children:WQ.map(G=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(ee,{htmlFor:`kd-${G.key}`,className:"text-xs text-muted-foreground",children:G.label}),e.jsx(pe,{id:`kd-${G.key}`,type:"date",value:l[G.key]??"",onChange:Y=>o(X=>({...X,[G.key]:Y.target.value})),className:"h-9"})]},G.key))}),e.jsxs(Sr,{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(ca,{className:"h-3.5 w-3.5 mr-1"}),"Save all"]})]})]})]})]}),e.jsxs("div",{className:"p-3",children:[e.jsx("div",{className:"grid grid-cols-3 sm:grid-cols-3 gap-2",children:v.map(G=>{const Y=!!G.value;return e.jsxs("div",{className:"relative",children:[e.jsxs(iy,{children:[e.jsx(oy,{asChild:!0,children:e.jsxs("button",{type:"button",disabled:r.isPending,onClick:()=>Y?P(G.key,G.isDone):W(G.key),className:Pt("relative text-left rounded-lg border px-2.5 py-2 transition-colors w-full",Trr[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:nUe(G.value)??"Set date"}),G.value&&e.jsx("p",{className:"text-[10px] opacity-80 truncate",children:WAt(G.state,G.days)}),Y&&e.jsx("span",{className:Pt("absolute top-1.5 right-7 h-4 w-4 rounded-full border flex items-center justify-center",G.isDone?"bg-emerald-500 border-emerald-500 text-white":"border-current opacity-40"),children:G.isDone&&e.jsx(ca,{className:"h-2.5 w-2.5"})})]})}),e.jsx(jx,{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(Kd,{open:R===G.key,onOpenChange:X=>X?W(G.key):D(null),children:[e.jsx(Yd,{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(Od,{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(ca,{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(Dz,{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," · ",WAt(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(Dz,{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 Prr={Home:va,FileSignature:c_,Handshake:vb,CalendarClock:Cu,Sparkles:Nn,ClipboardCheck:KN},Irr={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 Lrr(s,t){var a;const n=((a=wrr.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 His({open:s,onOpenChange:t,dealId:n,dealName:r}){const{data:a,isLoading:i}=krr(),{data:l}=Yie(),o=Srr(),c=Crr(),[d,u]=j.useState(null),[h,m]=j.useState({}),f=y=>{if(h[y.id])return h[y.id];const v=l==null?void 0:l.find(b=>{var w,S;return((w=b.name)==null?void 0:w.toLowerCase())===((S=y.target_stage_name)==null?void 0:S.toLowerCase())});return(v==null?void 0:v.id)??""},g=async y=>{if(n){u(y.id);try{const v=await o.mutateAsync({playbookId:y.id,dealId:n});re.success(v>0?`Added ${v} task${v===1?"":"s"} to this deal`:"All tasks already exist on this deal"),v>0&&t(!1)}catch(v){re.error((v==null?void 0:v.message)||"Could not apply playbook")}finally{u(null)}}},x=async y=>{const v=f(y);if(!v){re.error("Pick which stage this playbook should trigger on");return}u(`install-${y.id}`);try{const b=await c.mutateAsync({playbookId:y.id,stageId:v});re.success(b>0?`Automated — ${b} task${b===1?"":"s"} will now be created every time a deal reaches this stage`:"This playbook is already automated for that stage")}catch(b){re.error((b==null?void 0:b.message)||"Could not automate playbook")}finally{u(null)}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-2xl max-h-[85vh] flex flex-col p-0",children:[e.jsx(Us,{className:"p-6 pb-4 border-b",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-9 w-9 rounded-lg bg-primary/10 flex items-center justify-center",children:e.jsx(Xf,{className:"h-4.5 w-4.5 text-primary"})}),e.jsxs("div",{children:[e.jsx(Bs,{children:"Transaction Playbooks"}),e.jsx(Pr,{children:r?`Drop a proven checklist onto ${r} — deadlines calculate from its real dates.`:"Proven checklists that run themselves. Automate one and every future deal gets it."})]})]})}),e.jsx(uo,{className:"flex-1 min-h-0 overflow-y-auto",children:e.jsx("div",{className:"p-6 pt-4",children:i?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsx(UB,{type:"single",collapsible:!0,className:"space-y-3",children:(a||[]).map(y=>{const v=Prr[y.icon||"ClipboardCheck"]||KN,b=y.accent_color||"hsl(var(--primary))";return e.jsxs(h6,{value:y.id,className:"border rounded-xl px-0 overflow-hidden bg-card",children:[e.jsx(m6,{className:"px-4 py-3 hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-3 text-left flex-1 min-w-0",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg flex items-center justify-center shrink-0",style:{backgroundColor:`${b}1a`},children:e.jsx(v,{className:"h-5 w-5",style:{color:b}})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-semibold text-sm",children:y.name}),e.jsxs($e,{variant:"secondary",className:"text-[10px]",children:[y.tasks.length," steps"]}),y.deal_type&&e.jsx($e,{variant:"outline",className:"text-[10px] capitalize",children:y.deal_type})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:y.description})]})]})}),e.jsxs(f6,{className:"px-4 pb-4",children:[e.jsx("div",{className:"space-y-1.5 mb-4",children:y.tasks.map((w,S)=>e.jsxs("div",{className:"flex items-start gap-2.5 rounded-lg border bg-background px-3 py-2",children:[e.jsx("span",{className:"text-[10px] font-mono text-muted-foreground mt-0.5 w-4 shrink-0",children:S+1}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm font-medium leading-tight",children:w.title}),w.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:w.description}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-1",children:Lrr(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",Irr[w.priority]),children:w.priority})]},w.id))}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2 pt-2 border-t",children:[n&&e.jsxs($,{size:"sm",className:"gap-1.5",onClick:()=>g(y),disabled:d===y.id,children:[d===y.id?e.jsx(Ct,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(eg,{className:"h-3.5 w-3.5"}),"Add to this deal"]}),e.jsxs("div",{className:"flex gap-2 flex-1",children:[e.jsxs(ms,{value:f(y),onValueChange:w=>m(S=>({...S,[y.id]:w})),children:[e.jsx(us,{className:"h-9 text-xs flex-1",children:e.jsx(fs,{placeholder:"Trigger stage"})}),e.jsx(hs,{children:(l||[]).map(w=>e.jsx(Ge,{value:w.id,children:w.name},w.id))})]}),e.jsxs($,{size:"sm",variant:"outline",className:"gap-1.5 shrink-0",onClick:()=>x(y),disabled:d===`install-${y.id}`,children:[d===`install-${y.id}`?e.jsx(Ct,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(FE,{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."]})]})]},y.id)})})})})]})})}function Rrr(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 Drr(s){const t=Wt();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 Frr(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 Orr({dealId:s}){const{data:t=[],isLoading:n,error:r}=Rrr(s),a=Drr(s);return e.jsxs("section",{"aria-labelledby":"linked-emails-heading",className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h3",{id:"linked-emails-heading",className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(mn,{className:"h-4 w-4 text-primary"})," Linked emails"]}),t.length>0&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:[t.length," connected"]})]}),n?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading linked emails…"}):r?e.jsx("p",{className:"rounded-md border border-destructive/30 bg-destructive/5 p-3 text-sm text-destructive",children:"We couldn't load the emails linked to this transaction. Please refresh and try again."}):t.length===0?e.jsx("p",{className:"rounded-md border border-dashed p-3 text-sm text-muted-foreground",children:"No emails linked yet — attach one from Gmail with the LevelUp Companion extension."}):e.jsx("div",{className:"divide-y rounded-md border",children:t.map(i=>{const l=i.sent_at||i.created_at;return e.jsxs("div",{className:"flex items-start gap-3 p-3",children:[e.jsx(mn,{className:"mt-0.5 h-4 w-4 shrink-0 text-muted-foreground"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:i.subject||"Email from Gmail"}),e.jsxs("p",{className:"truncate text-xs text-muted-foreground",children:[i.from_address||"Unknown sender",l?` · ${en(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:Frr(i.gmail_thread_id,i.gmail_message_id),target:"_blank",rel:"noreferrer",children:e.jsx(Fr,{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(Hn,{className:"h-4 w-4"})})]},i.id)})})]})}const zrr=10*1024*1024;function Brr({dealId:s,photoUrl:t}){const n=j.useRef(null),r=Wt(),[a,i]=j.useState(!1),l=async d=>{const{error:u}=await q.from("deal_pipeline").update({property_photo_url:d}).eq("id",s);if(u)throw u;r.invalidateQueries({queryKey:["deal-pipeline-deals"]}),r.invalidateQueries({queryKey:["deals"]})},o=async d=>{var u;if(!d.type.startsWith("image/")){re.error("Please choose an image file");return}if(d.size>zrr){re.error("Image must be under 10MB");return}i(!0);try{const{data:h}=await q.auth.getUser(),m=(d.name.split(".").pop()||"jpg").toLowerCase(),f=`deal-photos/${(u=h.user)==null?void 0:u.id}/${s}-${Date.now()}.${m}`,{error:g}=await q.storage.from("agent-uploads").upload(f,d,{upsert:!0,contentType:d.type});if(g)throw g;const{data:x}=q.storage.from("agent-uploads").getPublicUrl(f);await l(x.publicUrl),re.success("Property photo updated")}catch(h){re.error(h.message||"Upload failed")}finally{i(!1),n.current&&(n.current.value="")}},c=async()=>{i(!0);try{await l(null),re.success("Photo removed")}catch(d){re.error(d.message||"Could not remove photo")}finally{i(!1)}};return e.jsxs("div",{className:"col-span-2",children:[e.jsxs("button",{type:"button",onClick:()=>{var d;return(d=n.current)==null?void 0:d.click()},disabled:a,className:"group relative w-full h-36 rounded-lg overflow-hidden border border-border bg-muted/40 focus:outline-none focus-visible:ring-2 focus-visible:ring-ring","aria-label":t?"Change property photo":"Add property photo",children:[t?e.jsx("img",{src:t,alt:"Property",className:"h-full w-full object-cover"}):e.jsxs("span",{className:"flex h-full w-full flex-col items-center justify-center gap-1 text-muted-foreground",children:[e.jsx(va,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"Add property photo"})]}),e.jsx("span",{className:"absolute inset-0 bg-foreground/50 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center",children:a?e.jsx(Ct,{className:"h-5 w-5 text-background animate-spin"}):e.jsx(Sx,{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(Hn,{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 $rr={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"}},Urr={note:eo,call:Da,email:mn,meeting:Ta,stage_change:Fr,task_completed:Vr,document:va,system:da};function qrr({deal:s,open:t,onOpenChange:n,onEdit:r,onAddToScorecard:a,isWonStage:i}){var Le,Fe;const l=Xn(),{data:o,isLoading:c}=RXn((s==null?void 0:s.id)||""),{data:d,isLoading:u}=FXn((s==null?void 0:s.id)||""),h=DXn(),m=zXn(),f=OXn(),g=LXn(),{data:x,isLoading:y}=$Qn((s==null?void 0:s.id)||""),v=UQn(),b=qQn(),w=VQn(),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=$rr[s.deal_type],Y=(()=>{var Ne;if(s.deal_type!=="seller"&&s.deal_type!=="dual")return null;const ke=((Ne=s.listing)==null?void 0:Ne.created_at)||s.listing_date;if(!ke)return null;const Be=s.contract_date?kh(s.contract_date):new Date;return dk(Be,kh(ke))})(),X=ke=>ke?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(ke):"-",ae=async()=>{if(A.trim())try{await h.mutateAsync({deal_id:s.id,activity_type:"note",title:"Note added",description:A}),E(""),re.success("Note added")}catch{re.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(""),re.success("Task added")}catch{re.error("Failed to add task")}},ne=async(ke,Be)=>{try{await f.mutateAsync({id:ke,is_completed:Be,deal_id:s.id})}catch{re.error("Failed to update task")}},te=async()=>{try{await g.mutateAsync(s.id),re.success("Deal deleted"),n(!1)}catch{re.error("Failed to delete deal")}},J=(d==null?void 0:d.filter(ke=>ke.is_completed).length)||0,ce=(d==null?void 0:d.length)||0,_e=(x==null?void 0:x.length)||0,he=ke=>ke<1024?`${ke} B`:ke<1024*1024?`${(ke/1024).toFixed(1)} KB`:`${(ke/(1024*1024)).toFixed(1)} MB`,ue=ke=>ke?ke.startsWith("image/")?Hc:ke.includes("pdf")?Jr:Pq:Pq,ve=async ke=>{const Be=ke.target.files;if(!(!Be||!s)){V(!0);try{for(const Ne of Array.from(Be)){if(Ne.size>20*1024*1024){re.error(`${Ne.name} exceeds 20MB limit`);continue}await v.mutateAsync({dealId:s.id,file:Ne})}re.success("File(s) uploaded")}catch{re.error("Failed to upload file")}finally{V(!1),S.current&&(S.current.value="")}}},Ee=async(ke,Be)=>{if(s)try{await b.mutateAsync({fileId:ke,storagePath:Be,dealId:s.id}),re.success("File deleted")}catch{re.error("Failed to delete file")}},Se=async(ke,Be)=>{try{const Ne=await HQn(ke),Ae=document.createElement("a");Ae.href=Ne,Ae.download=Be,Ae.target="_blank",document.body.appendChild(Ae),Ae.click(),document.body.removeChild(Ae)}catch{re.error("Failed to download file")}};return e.jsxs(e.Fragment,{children:[e.jsx(Gy,{open:t,onOpenChange:n,children:e.jsxs(my,{className:"w-full sm:max-w-xl p-0 flex flex-col",children:[e.jsx(L0,{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(R0,{className:"text-xl",children:s.deal_name}),e.jsx("div",{className:"mt-2",children:e.jsx(BQn,{dealId:s.id})})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",size:"icon",onClick:()=>r(s),children:e.jsx(_p,{className:"h-4 w-4"})}),e.jsx($,{variant:"outline",size:"icon",className:"text-destructive hover:bg-destructive/10",onClick:()=>U(!0),children:e.jsx(Hn,{className:"h-4 w-4"})})]})]})}),e.jsx(uo,{className:"flex-1 [&>[data-radix-scroll-area-viewport]>div]:!block [&>[data-radix-scroll-area-viewport]>div]:!w-full",children:e.jsxs("div",{className:"p-6 space-y-6 min-w-0",children:[s.contact&&e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-muted/50 rounded-lg",children:[e.jsxs("button",{type:"button",onClick:()=>{n(!1),l(`/mission-control/contacts/${s.contact_id}`)},className:"flex items-center gap-3 flex-1 min-w-0 text-left hover:opacity-80 transition-opacity group",children:[e.jsx(Oa,{className:"h-10 w-10",children:e.jsxs(za,{className:"bg-primary/10 text-primary",children:[(Le=s.contact.first_name)==null?void 0:Le[0],(Fe=s.contact.last_name)==null?void 0:Fe[0]]})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:"font-medium group-hover:text-primary group-hover:underline truncate",children:[s.contact.first_name," ",s.contact.last_name]}),s.contact.email&&e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:s.contact.email})]})]}),e.jsxs("div",{className:"flex gap-2 shrink-0",children:[s.contact.phone&&e.jsx($,{variant:"outline",size:"icon",asChild:!0,children:e.jsx("a",{href:`tel:${s.contact.phone}`,children:e.jsx(Da,{className:"h-4 w-4"})})}),s.contact.email&&e.jsx($,{variant:"outline",size:"icon",asChild:!0,children:e.jsx("a",{href:`mailto:${s.contact.email}`,children:e.jsx(mn,{className:"h-4 w-4"})})}),e.jsx($,{variant:"outline",size:"icon",title:"Open contact record",onClick:()=>{n(!1),l(`/mission-control/contacts/${s.contact_id}`)},children:e.jsx(Fr,{className:"h-4 w-4"})})]})]}),e.jsx(_rr,{dealId:s.id,primaryContactId:s.contact_id}),e.jsx(Orr,{dealId:s.id}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx(Brr,{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)]})]}),xw(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(xw(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"})]}),Y!==null&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 col-span-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Days on Market"}),e.jsxs("p",{className:Pt("text-lg font-bold",Y>90?"text-red-600":Y>60?"text-amber-600":"text-foreground"),children:[Y," ",s.contract_date?"(final)":"days"]})]}),s.target_close_date&&e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(Ta,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Close: ",en(kh(s.target_close_date),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(nu,{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(Mrr,{deal:s}),e.jsx(brr,{deal:s}),e.jsxs(ha,{defaultValue:"tasks",className:"w-full",children:[e.jsxs(ma,{className:"w-full grid grid-cols-4",children:[e.jsxs(Zt,{value:"tasks",className:"gap-1",children:[e.jsx(Vr,{className:"h-4 w-4"}),"Tasks ",ce>0&&`(${J}/${ce})`]}),e.jsxs(Zt,{value:"files",className:"gap-1",children:[e.jsx(ZI,{className:"h-4 w-4"}),"Files ",_e>0&&`(${_e})`]}),e.jsxs(Zt,{value:"forms",className:"gap-1",children:[e.jsx(c_,{className:"h-4 w-4"}),"Forms"]}),e.jsxs(Zt,{value:"activity",className:"gap-1",children:[e.jsx(da,{className:"h-4 w-4"}),"Activity"]})]}),e.jsx(Xt,{value:"forms",className:"mt-4",children:e.jsx(frr,{dealId:s.id,dealName:s.deal_name})}),e.jsxs(Xt,{value:"tasks",className:"mt-4 space-y-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{placeholder:"Add a new task...",value:I,onChange:ke=>P(ke.target.value),onKeyDown:ke=>ke.key==="Enter"&&le()}),e.jsx($,{onClick:le,disabled:!I.trim(),children:e.jsx(dn,{className:"h-4 w-4"})}),e.jsxs($,{variant:"outline",className:"gap-1.5 shrink-0",onClick:()=>D(!0),children:[e.jsx(Xf,{className:"h-4 w-4"}),"Playbooks"]})]}),e.jsxs("div",{className:"space-y-2",children:[d==null?void 0:d.map(ke=>e.jsxs("div",{className:Pt("flex items-center gap-3 p-3 rounded-lg border transition-colors",ke.is_completed?"bg-muted/50 border-border":"bg-background"),children:[e.jsx(ai,{checked:ke.is_completed,onCheckedChange:Be=>ne(ke.id,!!Be)}),e.jsx("span",{className:Pt("flex-1 text-sm",ke.is_completed&&"line-through text-muted-foreground"),children:ke.title}),ke.due_date&&e.jsx("span",{className:"text-xs text-muted-foreground",children:en(new Date(ke.due_date),"MMM d")})]},ke.id)),(d==null?void 0:d.length)===0&&e.jsx("p",{className:"text-center text-muted-foreground text-sm py-4",children:"No tasks yet. Add one above!"})]})]}),e.jsxs(Xt,{value:"files",className:"mt-4 space-y-3",children:[(s==null?void 0:s.id)&&e.jsx(KQn,{dealId:s.id}),e.jsx("input",{type:"file",ref:S,className:"hidden",multiple:!0,onChange:ve,accept:".pdf,.doc,.docx,.xls,.xlsx,.jpg,.jpeg,.png,.webp,.gif,.txt,.csv"}),e.jsxs($,{variant:"outline",className:"w-full border-dashed",onClick:()=>{var ke;return(ke=S.current)==null?void 0:ke.click()},disabled:W,children:[W?e.jsx(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(ke=>{const Be=ue(ke.file_type);return e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border bg-background",children:[e.jsx("div",{className:"w-8 h-8 rounded bg-muted flex items-center justify-center shrink-0",children:e.jsx(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:ke.file_name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[he(ke.file_size)," · ",en(new Date(ke.created_at),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(bk,{children:e.jsxs(iy,{children:[e.jsx(oy,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:`h-8 w-8 transition-colors ${ke.visible_on_portal?"text-primary bg-primary/10 hover:bg-primary/20":"text-muted-foreground/40 hover:text-muted-foreground"}`,onClick:()=>w.mutate({fileId:ke.id,visible:!ke.visible_on_portal,dealId:s.id}),children:ke.visible_on_portal?e.jsx(Ca,{className:"h-4 w-4"}):e.jsx($g,{className:"h-4 w-4"})})}),e.jsx(jx,{side:"top",children:ke.visible_on_portal?"Visible on client portal":"Hidden from client portal"})]})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>Se(ke.storage_path,ke.file_name),children:e.jsx(xi,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",onClick:()=>Ee(ke.id,ke.storage_path),children:e.jsx(pr,{className:"h-4 w-4"})})]})]},ke.id)}),(x==null?void 0:x.length)===0&&e.jsx("p",{className:"text-center text-muted-foreground text-sm py-4",children:"No files yet. Upload contracts, disclosures, or other documents."})]})]}),e.jsxs(Xt,{value:"activity",className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ls,{placeholder:"Add a note...",value:A,onChange:ke=>E(ke.target.value),rows:2}),e.jsxs($,{onClick:ae,disabled:!A.trim(),size:"sm",className:"w-full",children:[e.jsx(Kr,{className:"h-4 w-4 mr-2"}),"Add Note"]})]}),e.jsxs("div",{className:"space-y-3",children:[o==null?void 0:o.map(ke=>{const Be=Urr[ke.activity_type]||da;return e.jsxs("div",{className:"flex gap-3",children:[e.jsx("div",{className:"w-8 h-8 rounded-full bg-muted flex items-center justify-center shrink-0",children:e.jsx(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:ke.title}),ke.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-0.5",children:ke.description}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:hu(new Date(ke.created_at),{addSuffix:!0})})]})]},ke.id)}),(o==null?void 0:o.length)===0&&e.jsx("p",{className:"text-center text-muted-foreground text-sm py-4",children:"No activity yet"})]})]})]})]})})]})}),e.jsx(His,{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 Vrr({open:s,onOpenChange:t,deal:n,onComplete:r}){const a=S6e(),i=Frs(),{data:l}=BB(),{data:o}=qw(),[c,d]=j.useState({property_address:"",city:"",state:"",zip:"",transaction_type:"buyer",close_date:en(new Date,"yyyy-MM-dd"),sale_price:0,commission_amount:0,lead_source_id:"",client_type_id:"",notes:""});j.useEffect(()=>{if(n&&s){const m=n.deal_type==="seller"?"seller":"buyer",f=n.expected_price||0,g=n.commission_percentage||3,x=n.expected_commission||f*g/100;d({property_address:n.property_address||n.deal_name||"",city:n.city||"",state:n.state||"",zip:n.zip_code||"",transaction_type:m,close_date:n.actual_close_date||n.target_close_date||en(new Date,"yyyy-MM-dd"),sale_price:f,commission_amount:x,lead_source_id:"",client_type_id:"",notes:n.notes||""})}},[n,s]);const u=async m=>{if(m.preventDefault(),!!n)try{const f=await a.mutateAsync({property_address:c.property_address,city:c.city||null,state:c.state||null,zip:c.zip||null,transaction_type:c.transaction_type,close_date:c.close_date,sale_price:c.sale_price,commission_amount:c.commission_amount||null,brokerage_split_pct:n.brokerage_split_pct||null,team_split_pct:n.team_split_pct||null,franchise_fee_pct:n.franchise_fee_pct||null,referral_fee_pct:n.referral_fee_pct||null,transaction_fee:n.transaction_fee||null,lead_source_id:c.lead_source_id||null,client_type_id:c.client_type_id||null,contact_id:n.contact_id||null,notes:c.notes||null,is_win:!0});await i.mutateAsync({id:n.id,scorecard_transaction_id:f.id,actual_close_date:c.close_date}),re.success("Deal added to Scorecard! 🎉"),t(!1),r==null||r()}catch(f){console.error("Error syncing to scorecard:",f),re.error("Failed to add to scorecard")}},h=m=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:0}).format(m);return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-[550px] max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{className:"space-y-3",children:[e.jsx("div",{className:"mx-auto flex h-12 w-12 items-center justify-center rounded-full bg-green-100 dark:bg-green-900/20",children:e.jsx(Kl,{className:"h-6 w-6 text-green-600 dark:text-green-400"})}),e.jsx(Bs,{className:"text-center text-xl",children:"Congratulations on Closing! 🎉"}),e.jsx(Pr,{className:"text-center",children:"Review and confirm the details before adding this deal to your Scorecard."})]}),e.jsxs("form",{onSubmit:u,className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{htmlFor:"property_address",className:"flex items-center gap-2",children:[e.jsx(va,{className:"h-4 w-4 text-muted-foreground"}),"Property Address *"]}),e.jsx(pe,{id:"property_address",value:c.property_address,onChange:m=>d(f=>({...f,property_address:m.target.value})),placeholder:"123 Main St",required:!0})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"city",children:"City"}),e.jsx(pe,{id:"city",value:c.city,onChange:m=>d(f=>({...f,city:m.target.value})),placeholder:"City"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"state",children:"State"}),e.jsx(pe,{id:"state",value:c.state,onChange:m=>d(f=>({...f,state:m.target.value})),placeholder:"TX",maxLength:2})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"zip",children:"Zip"}),e.jsx(pe,{id:"zip",value:c.zip,onChange:m=>d(f=>({...f,zip:m.target.value})),placeholder:"75001"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Transaction Type *"}),e.jsxs(ms,{value:c.transaction_type,onValueChange:m=>d(f=>({...f,transaction_type:m})),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"buyer",children:"Buyer"}),e.jsx(Ge,{value:"seller",children:"Seller"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{htmlFor:"close_date",className:"flex items-center gap-2",children:[e.jsx(Ta,{className:"h-4 w-4 text-muted-foreground"}),"Close Date *"]}),e.jsx(pe,{id:"close_date",type:"date",value:c.close_date,onChange:m=>d(f=>({...f,close_date:m.target.value})),required:!0})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{htmlFor:"sale_price",className:"flex items-center gap-2",children:[e.jsx(nu,{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(Ew,{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(Ls,{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(Sr,{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 Hrr={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"}},KAt={urgent:0,high:1,medium:2,low:3};function Grr({deals:s,stages:t,onDealClick:n,onStageChange:r}){const[a,i]=j.useState("target_close_date"),[l,o]=j.useState("asc"),c=f=>{a===f?o(g=>g==="asc"?"desc":"asc"):(i(f),o("asc"))},d=j.useMemo(()=>[...s].sort((f,g)=>{var y,v;let x=0;switch(a){case"deal_name":x=f.deal_name.localeCompare(g.deal_name);break;case"stage":{const b=((y=t.find(S=>S.id===f.stage_id))==null?void 0:y.sort_order)||0,w=((v=t.find(S=>S.id===g.stage_id))==null?void 0:v.sort_order)||0;x=b-w;break}case"expected_price":x=(f.expected_price||0)-(g.expected_price||0);break;case"expected_commission":x=(f.expected_commission||0)-(g.expected_commission||0);break;case"target_close_date":{const b=f.target_close_date?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=KAt[f.priority]-KAt[g.priority];break}return l==="asc"?x:-x}),[s,t,a,l]),u=f=>f?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(f):"—",h=f=>f?t.find(g=>g.id===f):null,m=({field:f,children:g})=>e.jsxs($,{variant:"ghost",size:"sm",className:"h-8 -ml-3 font-medium",onClick:()=>c(f),children:[g,a===f?l==="asc"?e.jsx(Zf,{className:"ml-2 h-4 w-4"}):e.jsx(Dg,{className:"ml-2 h-4 w-4"}):e.jsx(zy,{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(En,{className:"bg-muted/50",children:[e.jsx(Dt,{className:"w-[250px]",children:e.jsx(m,{field:"deal_name",children:"Deal Name"})}),e.jsx(Dt,{className:"w-[150px]",children:e.jsx(m,{field:"stage",children:"Stage"})}),e.jsx(Dt,{className:"w-[100px]",children:"Type"}),e.jsx(Dt,{className:"w-[120px]",children:e.jsx(m,{field:"expected_price",children:"Price"})}),e.jsx(Dt,{className:"w-[120px]",children:e.jsx(m,{field:"expected_commission",children:"GCI"})}),e.jsx(Dt,{className:"w-[130px]",children:e.jsx(m,{field:"target_close_date",children:"Close Date"})}),e.jsx(Dt,{className:"w-[100px]",children:e.jsx(m,{field:"priority",children:"Priority"})})]})}),e.jsx(fi,{children:d.map(f=>{const g=h(f.stage_id),x=Hrr[f.deal_type],y=f.target_close_date?dk(kh(f.target_close_date),new Date):null,v=!!(g!=null&&g.is_won_stage)||!!(g!=null&&g.is_lost_stage)||!!f.actual_close_date,b=!v&&y!==null&&y<0,w=!v&&y!==null&&y<=7&&y>=0;return e.jsxs(En,{className:Pt("cursor-pointer hover:bg-muted/50 transition-colors",b&&"bg-red-50/50"),onClick:()=>n(f),children:[e.jsx(_t,{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(_t,{onClick:S=>S.stopPropagation(),children:e.jsx($rs,{stages:t,currentStageId:f.stage_id||"",onStageSelect:(S,A)=>r(f.id,S,A)})}),e.jsx(_t,{children:e.jsx($e,{variant:"outline",className:Pt("text-xs",x.color),children:x.label})}),e.jsx(_t,{children:e.jsx("span",{className:"font-medium",children:u(f.expected_price)})}),e.jsx(_t,{children:e.jsx("span",{className:"text-emerald-600",children:u(f.expected_commission)})}),e.jsx(_t,{children:f.target_close_date?e.jsxs("div",{className:Pt("flex items-center gap-1 text-sm",b&&"text-red-600",w&&!b&&"text-amber-600"),children:[b&&e.jsx(ll,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:en(kh(f.target_close_date),"MMM d, yyyy")})]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(_t,{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 Gis(){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 Wrr(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 Krr(){const s=Sa(),t=Wt();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 Yrr(){const s=Wt();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 Zrr(){const s=Wt();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 lFe(){const s=Wt();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 Xrr(){const s=Wt();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 Qrr(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 Jrr(){const s=Sa(),t=Wt();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 ear(){const s=Wt();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 tar(){const s=Sa(),t=Wt();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 sar={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function nar({open:s,onOpenChange:t,dealId:n,dealName:r,fromStageName:a,toStageName:i,toStageId:l,onConfirm:o}){const{data:c,isLoading:d}=Wrr(s?n:void 0),u=Xrr(),h=tar(),[m,f]=j.useState(new Set),[g,x]=j.useState(!1),y=(c||[]).filter(S=>S.status!=="done");j.useEffect(()=>{y.length>0&&f(new Set(y.map(S=>S.id)))},[c]);const v=S=>{f(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),re.error((S==null?void 0:S.message)||"Failed to move deal. Please try again.")}finally{x(!1)}},w=async()=>{x(!0);try{await o(),await h.mutateAsync({dealId:n,stageId:l}),t(!1)}catch(S){console.error("Stage move (skip) failed:",S),re.error((S==null?void 0:S.message)||"Failed to move deal. Please try again.")}finally{x(!1)}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-[480px]",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Move Deal"}),e.jsxs(Pr,{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"})}):y.length>0?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["You have ",e.jsx("span",{className:"font-medium text-foreground",children:y.length})," incomplete task",y.length!==1?"s":"",". Select which to mark as done:"]}),e.jsx(uo,{className:"max-h-[250px]",children:e.jsx("div",{className:"space-y-1",children:y.map(S=>e.jsxs("label",{className:"flex items-center gap-3 px-3 py-2 rounded-lg hover:bg-muted/50 cursor-pointer transition-colors",children:[e.jsx(ai,{checked:m.has(S.id),onCheckedChange:()=>v(S.id)}),e.jsxs("span",{className:"text-sm flex-1",children:[sar[S.priority]," ",S.title]}),S.stage&&e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full",style:{backgroundColor:S.stage.color+"20",color:S.stage.color},children:S.stage.name})]},S.id))})}),e.jsxs("div",{className:"flex items-center justify-between gap-2 pt-2",children:[e.jsx($,{variant:"ghost",size:"sm",onClick:()=>{m.size===y.length?f(new Set):f(new Set(y.map(S=>S.id)))},children:m.size===y.length?"Deselect All":"Select All"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",size:"sm",onClick:w,disabled:g,children:"Skip"}),e.jsxs($,{size:"sm",onClick:b,disabled:g,children:[g&&e.jsx(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 rar=[{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"}],aar=[{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 Wis({open:s,onOpenChange:t}){const n=Sa(),{data:r,isLoading:a}=e$t(),i=E9s(),[l,o]=j.useState({logo_url:null,cover_photo_url:null,brand_color:null,accent_color:null,tagline:null,welcome_message:null,portal_theme:"noir"}),[c,d]=j.useState(null);j.useEffect(()=>{s&&o({logo_url:(r==null?void 0:r.logo_url)??null,cover_photo_url:(r==null?void 0:r.cover_photo_url)??null,brand_color:(r==null?void 0:r.brand_color)??null,accent_color:(r==null?void 0:r.accent_color)??null,tagline:(r==null?void 0:r.tagline)??null,welcome_message:(r==null?void 0:r.welcome_message)??null,portal_theme:(r==null?void 0:r.portal_theme)??"noir"})},[s,r]);const u=f=>o(g=>({...g,...f})),h=async(f,g)=>{if(n){if(f.size>5*1024*1024){re.error("Image must be under 5MB");return}d(g);try{const x=await t$t(n,f,g);u(g==="logo"?{logo_url:x}:{cover_photo_url:x})}catch(x){re.error(`Upload failed: ${x.message||x}`)}finally{d(null)}}},m=async()=>{try{await i.mutateAsync(l),re.success("Portal branding saved"),t(!1)}catch{re.error("Failed to save branding")}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-lg max-h-[90vh] flex flex-col",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(yd,{className:"h-5 w-5 text-primary"}),"Portal Branding"]}),e.jsx(Pr,{children:"Customize how your client portals look. These defaults apply to every portal — you can override them per deal."})]}),e.jsx(uo,{className:"flex-1 pr-3 -mr-3",children:a?e.jsx("div",{className:"py-12 flex justify-center",children:e.jsx(Ct,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-6 py-2",children:[e.jsx(iar,{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:aar.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(YAt,{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(YAt,{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:rar.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(ZAt,{label:"Brand",value:l.brand_color,onChange:f=>u({brand_color:f})}),e.jsx(ZAt,{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 iar({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 YAt({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(Hn,{className:"h-3.5 w-3.5"})})]})]})]})}function ZAt({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 oar(){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 lar({dealId:s,dealName:t,contactName:n,portal:r,onSettingsOpen:a,onComposerOpen:i,onInviteOpen:l,onDeleteConfirm:o}){const c=bit(),d=OK(),u=YQt(),h=ZQt(),[m,f]=j.useState(!1),g=!!(r!=null&&r.archived_at),x=async()=>{f(!0);try{await c.mutateAsync({deal_id:s,visibility:"private",require_onboarding:!0}),re.success("Portal enabled!")}catch{re.error("Failed to create portal")}finally{f(!1)}},y=async A=>{if(r)try{await d.mutateAsync({id:r.id,is_enabled:A}),re.success(A?"Portal enabled":"Portal disabled")}catch{re.error("Failed to update portal")}},v=()=>{r&&(navigator.clipboard.writeText(lC(r.slug)),re.success("Link copied!"))},b=()=>{r&&window.open(lC(r.slug),"_blank")},w=async()=>{if(r)try{await u.mutateAsync(r.id),re.success("Portal archived")}catch{re.error("Failed to archive portal")}},S=async()=>{if(r)try{await h.mutateAsync(r.id),re.success("Portal restored")}catch{re.error("Failed to restore portal")}};return r?g?e.jsxs("div",{className:"flex items-center gap-4 p-4 border rounded-lg opacity-60 bg-muted/30",children:[e.jsxs(wr,{to:`/mission-control/client-portals/${r.id}`,className:"flex-1 min-w-0 hover:opacity-80",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:t}),e.jsx($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(zI,{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(Hn,{className:"h-3.5 w-3.5"}),"Delete"]})]})]}):e.jsxs("div",{className:"flex items-center gap-4 p-4 border rounded-lg hover:border-primary/40 hover:bg-muted/30 transition-colors group",children:[e.jsxs(wr,{to:`/mission-control/client-portals/${r.id}`,className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-medium text-sm truncate group-hover:text-primary transition-colors",children:t}),e.jsx($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:v,title:"Copy link",children:e.jsx(Ha,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:b,title:"Preview",children:e.jsx(Fr,{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(Kr,{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(m4,{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($u,{children:[e.jsx(Uu,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(l_,{className:"h-3.5 w-3.5"})})}),e.jsx(Au,{align:"end",children:e.jsxs(ja,{onClick:w,children:[e.jsx(jv,{className:"h-4 w-4 mr-2"}),"Archive Portal"]})})]}),e.jsx(Sn,{checked:r.is_enabled,onCheckedChange:y,className:"ml-1"})]})]}):e.jsxs("div",{className:"flex items-center justify-between p-4 border rounded-lg border-dashed bg-muted/20",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:t}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:n||"No contact"})]}),e.jsxs($,{size:"sm",onClick:x,disabled:m,className:"shrink-0 ml-4",children:[m?e.jsx(Ct,{className:"h-3 w-3 animate-spin mr-1"}):e.jsx(Nn,{className:"h-3 w-3 mr-1"}),"Enable Portal"]})]})}function Kis(){const{data:s,isLoading:t}=eY(),{data:n,isLoading:r}=oar(),[a,i]=j.useState(""),[l,o]=j.useState("all"),c=XQt(),[d,u]=j.useState(null),[h,m]=j.useState(null),[f,g]=j.useState(null),[x,y]=j.useState(null),[v,b]=j.useState(!1),w=Sa(),S=t||r,A=new Map;n==null||n.forEach(U=>A.set(U.deal_id,U));const I=[...(s||[]).filter(U=>{var X,ae,le,ne,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))||((ne=(le=U.contact)==null?void 0:le.last_name)==null?void 0:ne.toLowerCase().includes(V))||((te=W==null?void 0:W.client_name)==null?void 0:te.toLowerCase().includes(V));let Y=!0;return l==="active"?Y=!!(W!=null&&W.is_enabled)&&!(W!=null&&W.archived_at):l==="disabled"?Y=!!W&&!W.is_enabled&&!W.archived_at:l==="archived"?Y=!!(W!=null&&W.archived_at):l==="none"?Y=!W:l==="all"&&(Y=!(W!=null&&W.archived_at)||!W),G&&Y})].sort((U,W)=>{const V=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}),re.success("Portal permanently deleted"),y(null)}catch{re.error("Failed to delete portal")}};return S?e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsx(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(Nn,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{className:"font-medium",children:[P," Portals"]})]}),e.jsxs("span",{className:"text-muted-foreground",children:[R," active · ",P-R," disabled",D>0&&` · ${D} archived`]})]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>b(!0),className:"gap-1.5",children:[e.jsx(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(Zr,{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(pr,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"flex bg-muted rounded-lg p-1 gap-0.5",children:["all","active","disabled","archived","none"].map(U=>e.jsx($,{variant:l===U?"secondary":"ghost",size:"sm",onClick:()=>o(U),className:"text-xs px-3 capitalize",children:U==="none"?"No Portal":U},U))})]}),e.jsx(uo,{className:"h-[calc(100vh-22rem)]",children:e.jsxs("div",{className:"space-y-2 pb-4",children:[I.map(U=>{const W=A.get(U.id)||null,V=U.contact?`${U.contact.first_name||""} ${U.contact.last_name||""}`.trim():"";return e.jsx(lar,{dealId:U.id,dealName:U.deal_name,contactName:V,portal:W,onSettingsOpen:u,onComposerOpen:G=>m(G),onInviteOpen:(G,Y)=>g({portal:G,dealName:Y}),onDeleteConfirm:y},U.id)}),I.length===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx("div",{className:"w-12 h-12 mx-auto mb-3 bg-muted rounded-full flex items-center justify-center",children:e.jsx(Nn,{className:"h-5 w-5 text-muted-foreground"})}),e.jsx("p",{className:"text-sm font-medium",children:"No matching deals"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Try adjusting your search or filters"})]})]})})]}),d&&e.jsx(Tlt,{open:!!d,onOpenChange:U=>!U&&u(null),portal:d,dealOwnerId:w||""}),h&&e.jsx(Mlt,{open:!!h,onOpenChange:U=>!U&&m(null),portalId:h.id,portalSlug:h.slug,notifyClient:h.notify_client}),f&&e.jsx(Plt,{open:!!f,onOpenChange:U=>!U&&g(null),portal:f.portal,dealName:f.dealName}),e.jsx(Wis,{open:v,onOpenChange:b}),e.jsx(fc,{open:!!x,onOpenChange:U=>!U&&y(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 car({summary:s,stats:t,search:n,onSearchChange:r,onAddDeal:a,onRefresh:i,onTeam:l,viewControls:o,filters:c,activeFilters:d=[],onClearAll:u,resultLabel:h,showSearch:m=!0}){return e.jsx("section",{className:"hub-ink relative overflow-hidden rounded-2xl p-4 sm:p-6",children:e.jsxs("div",{className:"relative flex flex-col gap-4",children:[e.jsxs("div",{className:"flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-xs uppercase tracking-wider hub-ink-muted",children:"Agent OS"}),e.jsx("h1",{className:"mt-1 text-2xl font-bold sm:text-3xl",children:"Deal Pipeline"}),e.jsx("p",{className:"mt-1 text-sm hub-ink-muted",children:s})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("button",{onClick:a,className:"inline-flex items-center gap-2 rounded-full bg-background px-4 py-2 text-sm font-semibold text-foreground shadow-sm transition-transform hover:scale-[1.02]",children:[e.jsx(dn,{className:"h-4 w-4"}),"Add Deal"]}),l&&e.jsxs("button",{onClick:l,className:"hub-glass inline-flex items-center gap-2 rounded-full px-4 py-2 text-sm font-medium transition-colors",children:[e.jsx(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(ro,{className:"h-4 w-4"})}),o]})]}),t.length>0&&e.jsx("div",{className:"-mx-1 flex gap-2 overflow-x-auto px-1 pb-1 sm:grid sm:grid-cols-3 sm:overflow-visible lg:grid-cols-5",children:t.map(f=>{const g=f.onClick?"button":"div";return e.jsxs(g,{type:f.onClick?"button":void 0,onClick:f.onClick,title:f.hint,className:Pt("hub-glass min-w-[130px] shrink-0 rounded-xl px-3 py-2.5 text-left transition-all sm:min-w-0",f.onClick&&"hover:scale-[1.02]",f.active&&"ring-2"),style:f.active?{boxShadow:"0 0 0 2px hsl(var(--hub-glow))"}:void 0,children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wide hub-ink-muted",children:f.label}),e.jsx("p",{className:"mt-0.5 text-lg font-bold leading-tight",children:f.value}),f.subtitle&&e.jsx("p",{className:"text-[11px] hub-ink-muted",children:f.subtitle})]},f.label)})}),m&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"relative min-w-[200px] flex-1 sm:max-w-sm",children:[e.jsx(Zr,{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(pr,{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(pr,{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 dar={closing_soon:{label:"Closing in 7 days",icon:Cu,tone:"text-primary"},past_due:{label:"Past close date",icon:Al,tone:"text-destructive"},overdue_tasks:{label:"Overdue tasks",icon:Vj,tone:"text-amber-600 dark:text-amber-400"},stalled:{label:"Stalled 14+ days",icon:EJ,tone:"text-muted-foreground"}};function uar({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=dar[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 E7=s=>{const t=Number(s);return Number.isFinite(t)?t:0};function PC(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 CW(s){return E7(s.sale_price)||E7(s.expected_price)}function AW(s){const t=E7(s.expected_commission);if(t>0)return t;const n=E7(s.commission_percentage);return n>0?CW(s)*n/100:0}function Ene(s){const t=AW(s);return t*E7(s.brokerage_split_pct)/100+t*E7(s.franchise_fee_pct)/100+E7(s.transaction_fee)}const har=s=>!!s.actual_close_date,mar=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function far(s){const t=new Date,n=t.getFullYear(),r=t.getMonth()+1,a=n*1e4+r*100+t.getDate(),i=new Date(t.getTime()+30*864e5),l=i.getFullYear()*1e4+(i.getMonth()+1)*100+i.getDate(),o={activeDeals:0,closedThisYear:0,pipelineVolume:0,pipelineGci:0,brokerageShare:0,closingThisMonth:0,closingNext30:0,closedVolumeThisYear:0,closedCompanyDollarYtd:0,needsReview:0,changesRequested:0,overdueItems:0,agents:[],outlook:[],totalVolume:0},c=new Map,d=new Map;for(let u=0;u<6;u++){const h=(r-1+u)%12+1,m=n+Math.floor((r-1+u)/12),f=`${m}-${String(h).padStart(2,"0")}`;d.set(f,{key:f,label:`${mar[h-1]} ${String(m).slice(2)}`,deals:0,volume:0,gci:0,closed:!1})}return s.forEach(u=>{const h=CW(u),m=AW(u),f=har(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=PC(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+=Ene(u));else if(o.activeDeals+=1,o.pipelineVolume+=h,o.pipelineGci+=m,o.brokerageShare+=Ene(u),g){const y=g.y*1e4+g.m*100+g.d;g.y===n&&g.m===r&&(o.closingThisMonth+=1),y>=a&&y<=l&&(o.closingNext30+=1)}if(g){const y=`${g.y}-${String(g.m).padStart(2,"0")}`,v=d.get(y);v&&(v.deals+=1,v.volume+=h,v.gci+=m,f&&(v.closed=!0))}const x=c.get(u.owner_user_id)||{userId:u.owner_user_id,name:u.agent_name||"Agent",avatarUrl:u.agent_avatar_url,activeDeals:0,closedDeals:0,volume:0,gci:0,overdue:0};f?x.closedDeals+=1:x.activeDeals+=1,x.volume+=h,x.gci+=m,x.overdue+=u.overdue_items,c.set(u.owner_user_id,x)}),o.agents=Array.from(c.values()).sort((u,h)=>h.volume-u.volume||h.activeDeals-u.activeDeals),o.outlook=Array.from(d.values()).sort((u,h)=>u.key.localeCompare(h.key)),o}function 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 par(){var i;const{user:s}=bs(),{data:t}=qrs(),{data:n}=PQn(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(Ie,{className:"flex flex-col gap-3 p-4 sm:flex-row sm:items-center sm:gap-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-teal-500/10 text-teal-600",children:e.jsx(Ew,{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 gar 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 wX="deal-pipeline-detail-sheet";function jX(s){return s>=1e6?`$${(s/1e6).toFixed(1)}M`:s>=1e3?`$${(s/1e3).toFixed(0)}K`:`$${Math.round(s).toLocaleString()}`}function xar(){var kr;const s=FK(),{data:t,isLoading:n}=Yie(),{data:r,isLoading:a,refetch:i}=eY(),{data:l,isLoading:o}=BXn(),c=Rrs(),d=IXn(),[u,h]=j.useState("board"),[m,f]=j.useState(!1),[g,x]=j.useState(!1),[y,v]=j.useState(null),[b,w]=j.useState(null),[S,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"),[Y,X]=j.useState("all"),[ae,le]=j.useState("all"),[ne,te]=j.useState(null),{data:J}=Gis(),{data:ce}=SQn(),[_e,he]=j.useState(!1),[ue,ve]=j.useState(!1),[Ee,Se]=j.useState(new Set),[Le,Fe]=j.useState(!0),ke=j.useRef(!1),[Be,Ne]=j.useState(null),{data:Ae}=zw(),{isTeamLeader:Ce,teamMembers:Ve}=NQn(),ze=j.useMemo(()=>Array.from(Ee),[Ee]),{data:qe}=kQn(ze),dt=j.useMemo(()=>{const $n=new Map;return Ve.forEach(kn=>$n.set(kn.id,{name:kn.name,avatar_url:kn.avatar_url,color:kn.color})),$n},[Ve]),Xe=j.useCallback($n=>$n.owner_user_id&&dt.get($n.owner_user_id)||null,[dt]),at=j.useCallback($n=>{Se(kn=>{const Fn=new Set(kn);return Fn.has($n)?Fn.delete($n):Fn.add($n),Fn})},[]);j.useEffect(()=>{!n&&t&&t.length===0&&c.mutate()},[n,t]);const[rt,Ke]=gc(),Je=j.useRef(!1);j.useEffect(()=>{const $n=rt.get("deal");if($n&&r&&r.length>0&&!Je.current){const kn=r.find(Fn=>Fn.id===$n);kn&&(Je.current=!0,v(kn),x(!0),rt.delete("deal"),Ke(rt,{replace:!0}))}},[r,rt]);const pt=j.useMemo(()=>{if(!qe||!t)return[];const $n=new Map(t.map(kn=>[kn.name,kn.id]));return qe.map(kn=>{const Fn=kn._stage_name&&$n.get(kn._stage_name)||null;return{...kn,stage_id:Fn||kn.stage_id}})},[qe,t]),gt=j.useMemo(()=>[...Ce&&!Le?[]:r||[],...pt],[r,pt,Ce,Le]);j.useEffect(()=>{if(ke.current||gt.length===0)return;ke.current=!0;const $n=sessionStorage.getItem(wX);if($n)try{const kn=JSON.parse($n);if(!kn.open||!kn.dealId)return;const Fn=gt.find(bn=>bn.id===kn.dealId);Fn&&(v(Fn),x(!0))}catch{sessionStorage.removeItem(wX)}},[gt]),j.useEffect(()=>{g&&(y!=null&&y.id)?sessionStorage.setItem(wX,JSON.stringify({dealId:y.id,open:!0})):sessionStorage.removeItem(wX)},[g,y==null?void 0:y.id]);const ss=j.useMemo(()=>{const $n={},kn=new Date;return kn.setHours(0,0,0,0),(J||[]).forEach(Fn=>{!Fn.deal_id||Fn.status==="done"||!Fn.due_date||kh(Fn.due_date){const $n=new Set((t||[]).filter(Or=>Or.is_won_stage).map(Or=>Or.id)),kn=new Set((t||[]).filter(Or=>Or.is_lost_stage).map(Or=>Or.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 Lr={closing_soon:new Set,past_due:new Set,overdue_tasks:new Set,stalled:new Set};return gt.forEach(Or=>{if(!(Or.stage_id&&($n.has(Or.stage_id)||kn.has(Or.stage_id)))){if(Or.target_close_date){const Qn=kh(Or.target_close_date);Qn[{key:"closing_soon",count:ys.closing_soon.size},{key:"past_due",count:ys.past_due.size},{key:"overdue_tasks",count:ys.overdue_tasks.size},{key:"stalled",count:ys.stalled.size}],[ys]),Ft=gt.filter($n=>{var Un,dr,Pa,ii,$i,Rn;const kn=U.toLowerCase(),Fn=Yt[$n.id]||[],bn=!kn||$n.deal_name.toLowerCase().includes(kn)||((dr=(Un=$n.contact)==null?void 0:Un.first_name)==null?void 0:dr.toLowerCase().includes(kn))||((ii=(Pa=$n.contact)==null?void 0:Pa.last_name)==null?void 0:ii.toLowerCase().includes(kn))||(($i=$n.property_address)==null?void 0:$i.toLowerCase().includes(kn))||((Rn=$n.city)==null?void 0:Rn.toLowerCase().includes(kn))||Fn.some(xa=>xa.toLowerCase().includes(kn)),xs=V==="all"||$n.deal_type===V,Lr=Y==="all"||Fn.includes(Y),Or=$n.actual_close_date||$n.target_close_date||$n.contract_date||$n.created_at,la=Or?String(Or).slice(0,4):null,Qn=ae==="all"||la===ae,Cr=!ne||ys[ne].has($n.id);return bn&&xs&&Lr&&Qn&&Cr}),as=j.useMemo(()=>{const $n=new Set;return $n.add(String(new Date().getFullYear())),gt.forEach(kn=>{const Fn=kn.actual_close_date||kn.target_close_date||kn.contract_date||kn.created_at;Fn&&$n.add(String(Fn).slice(0,4))}),Array.from($n).sort((kn,Fn)=>Number(Fn)-Number(kn))},[gt]),kt=j.useMemo(()=>{if(!t)return l||null;const $n=new Set(t.filter(Or=>Or.is_won_stage).map(Or=>Or.id)),kn=new Set(t.filter(Or=>Or.is_lost_stage).map(Or=>Or.id)),Fn=gt.filter(Or=>Or.stage_id&&!$n.has(Or.stage_id)&&!kn.has(Or.stage_id)),bn=gt.filter(Or=>Or.stage_id&&$n.has(Or.stage_id)),xs=new Date().getFullYear(),Lr=bn.filter(Or=>Or.actual_close_date?new Date(Or.actual_close_date).getFullYear()===xs:!0);return{totalDeals:gt.length,activeDeals:Fn.length,wonDeals:bn.length,pipelineValue:Fn.reduce((Or,la)=>Or+(la.expected_price||0),0),expectedCommission:Fn.reduce((Or,la)=>Or+(la.expected_commission||0),0),expectedNetToAgent:Fn.reduce((Or,la)=>Or+(xw(la)||0),0),wonValue:bn.reduce((Or,la)=>Or+(la.expected_price||0),0),weightedGCI:Fn.reduce((Or,la)=>Or+(la.expected_commission||0)*((la.probability??50)/100),0),weightedNet:Fn.reduce((Or,la)=>Or+(xw(la)||0)*((la.probability??50)/100),0),ytdWonDeals:Lr.length,ytdWonGCI:Lr.reduce((Or,la)=>Or+(la.expected_commission||0),0),ytdWonNet:Lr.reduce((Or,la)=>Or+(xw(la)||0),0),projectedAnnualNet:Lr.reduce((Or,la)=>Or+(xw(la)||0),0)+Fn.reduce((Or,la)=>Or+(xw(la)||0)*((la.probability??50)/100),0)}},[gt,t,l]),Ks=$n=>{v($n),x(!0)},wt=$n=>{w($n||null),v(null),f(!0)},gs=$n=>{v($n),x(!1),f(!0)},ks=$n=>{x($n),$n||sessionStorage.removeItem(wX)},Is=($n,kn)=>{A($n)},Xs=($n,kn)=>{$n.preventDefault(),$n.dataTransfer.dropEffect="move",I(kn)},ds=async($n,kn)=>{if($n.preventDefault(),I(null),!S)return;const Fn=r==null?void 0:r.find(Lr=>Lr.id===S),bn=t==null?void 0:t.find(Lr=>Lr.id===kn),xs=t==null?void 0:t.find(Lr=>Lr.id===(Fn==null?void 0:Fn.stage_id));if(!Fn||!bn||Fn.stage_id===kn){A(null);return}Ne({dealId:S,dealName:Fn.deal_name,fromStageName:(xs==null?void 0:xs.name)||"Unknown",toStageName:bn.name,toStageId:kn,isWonStage:bn.is_won_stage,deal:Fn}),A(null)},Ss=async()=>{if(!Be)return;const{dealId:$n,toStageId:kn,toStageName:Fn,isWonStage:bn,deal:xs}=Be;if(await d.mutateAsync({dealId:$n,stageId:kn,stageName:Fn}),re.success(`Moved to ${Fn}`),bn&&!xs.scorecard_transaction_id){const Lr={...xs,stage_id:kn};O(Lr),R(!0)}},yn=j.useCallback(async($n,kn,Fn)=>{const bn=r==null?void 0:r.find(Or=>Or.id===$n),xs=t==null?void 0:t.find(Or=>Or.id===kn),Lr=t==null?void 0:t.find(Or=>Or.id===(bn==null?void 0:bn.stage_id));!bn||!xs||bn.stage_id===kn||Ne({dealId:$n,dealName:bn.deal_name,fromStageName:(Lr==null?void 0:Lr.name)||"Unknown",toStageName:Fn,toStageId:kn,isWonStage:xs.is_won_stage,deal:bn})},[r,t]),Js=$n=>Ft.filter(kn=>kn.stage_id===$n),Ut=n||a,hn=s?"list":u,hr=[{label:"Active Deals",value:(kt==null?void 0:kt.activeDeals)||0,hint:"Deals still in play"},{label:"Weighted GCI",value:jX((kt==null?void 0:kt.weightedGCI)||0),hint:"GCI adjusted by each deal's win probability"},{label:"Weighted Net",value:jX((kt==null?void 0:kt.weightedNet)||0),hint:"Net to agent adjusted by each deal's win probability"},{label:"YTD Closed Net",value:jX((kt==null?void 0:kt.ytdWonNet)||0),subtitle:`${(kt==null?void 0:kt.ytdWonDeals)||0} deals`,hint:"Net commission from deals closed this year"},{label:"Projected Annual",value:jX((kt==null?void 0:kt.projectedAnnualNet)||0),hint:"YTD closed net + weighted active net"}],Rs=[...V!=="all"?[{key:"type",label:`Type: ${V}`,onClear:()=>G("all")}]:[],...ae!=="all"?[{key:"year",label:`Year: ${ae}`,onClear:()=>le("all")}]:[],...Y!=="all"?[{key:"tag",label:`Tag: ${Y}`,onClear:()=>X("all")}]:[],...U?[{key:"search",label:`"${U}"`,onClear:()=>W("")}]:[],...ne?[{key:"attention",label:"Needs attention",onClear:()=>te(null)}]:[]],jr=()=>{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(car,{summary:`${(kt==null?void 0:kt.activeDeals)||0} active deals • ${jX((kt==null?void 0:kt.weightedNet)||0)} weighted net`,stats:hn==="portals"?[]:hr,search:U,onSearchChange:W,onAddDeal:()=>wt(),onRefresh:()=>i(),onTeam:Ae&&!Ce?()=>he(!0):void 0,showSearch:hn!=="portals",activeFilters:Rs,onClearAll:jr,resultLabel:Rs.length>0?`${Ft.length} of ${gt.length} deals`:null,viewControls:s?null:e.jsx(bk,{children:e.jsx("div",{className:"hub-glass flex items-center gap-0.5 rounded-full p-1",children:[{mode:"board",icon:Qf,label:"Board",hint:"Kanban board view"},{mode:"list",icon:T0,label:"List",hint:"Grouped list view"},{mode:"table",icon:nV,label:"Table",hint:"Sortable table view"},{mode:"portals",icon:Nn,label:"Portals",hint:"Client portal management"}].map(({mode:$n,icon:kn,label:Fn,hint:bn})=>e.jsxs(iy,{children:[e.jsx(oy,{asChild:!0,children:e.jsxs("button",{onClick:()=>h($n),className:Pt("inline-flex items-center gap-1.5 rounded-full px-3 py-1.5 text-xs font-medium transition-colors",u===$n?"bg-background text-foreground shadow-sm":"opacity-80 hover:opacity-100"),children:[e.jsx(kn,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:Fn})]})}),e.jsx(jx,{children:bn})]},$n))})}),filters:hn!=="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"}),as.map($n=>e.jsx(Ge,{value:$n,children:$n},$n))]})]}),e.jsxs(ms,{value:Y,onValueChange:X,children:[e.jsxs(us,{className:"hub-glass h-10 w-[150px] rounded-full border-0 text-sm",children:[e.jsx(Ap,{className:"mr-1.5 h-3.5 w-3.5 opacity-70"}),e.jsx(fs,{placeholder:"All Tags"})]}),e.jsxs(hs,{className:"max-h-[300px]",children:[e.jsx(Ge,{value:"all",children:"All Tags"}),ts.length===0&&e.jsx("div",{className:"px-2 py-1.5 text-xs text-muted-foreground",children:"No tags yet"}),ts.map($n=>e.jsx(Ge,{value:$n,children:$n},$n))]})]})]}):null}),e.jsx(par,{}),hn!=="portals"&&e.jsx(uar,{items:Bt,active:ne,onToggle:$n=>te(kn=>kn===$n?null:$n)})]}),e.jsxs("div",{className:"flex-1 min-h-0 flex",children:[Ce&&!s&&Ve.length>0&&e.jsx(jQn,{members:Ve,enabledMembers:Ee,onToggleMember:at,isOpen:ue,onToggleOpen:()=>ve($n=>!$n),showOwnDeals:Le,onToggleOwnDeals:()=>Fe($n=>!$n)}),e.jsx("div",{className:"flex-1 min-w-0 min-h-0 p-4 md:p-6 pt-4",children:Ut?e.jsx("div",{className:"flex gap-4 h-full",children:[1,2,3,4].map($n=>e.jsx("div",{className:"min-w-[280px] max-w-[320px] flex-shrink-0",children:e.jsx(xn,{className:"h-full rounded-xl"})},$n))}):hn==="board"?e.jsxs(uo,{className:"h-full -mx-4 md:-mx-6 px-4 md:px-6",children:[e.jsx("div",{className:"flex gap-4 h-full pb-4",children:t==null?void 0:t.map($n=>e.jsx(EQn,{stage:$n,deals:Js($n.id),onDealClick:Ks,onAddDeal:wt,onDragStart:Is,onDragOver:Xs,onDrop:ds,isDragOver:E===$n.id,isWonStage:$n.is_won_stage,isLostStage:$n.is_lost_stage,getOwnerInfo:Xe,tagsByDeal:Yt,overdueTasksByDeal:ss},$n.id))}),e.jsx(Rae,{orientation:"horizontal"})]}):hn==="table"?e.jsx(uo,{className:"h-full",children:e.jsx(Grr,{deals:Ft,stages:t||[],onDealClick:Ks,onStageChange:yn})}):hn==="portals"?e.jsx(Kis,{}):e.jsx(uo,{className:"h-full",children:e.jsxs("div",{className:"space-y-6",children:[t==null?void 0:t.map($n=>{const kn=Js($n.id);return kn.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:$n.color}}),e.jsx("h3",{className:"font-semibold",children:$n.name}),e.jsxs("span",{className:"text-muted-foreground text-sm",children:["(",kn.length,")"]})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3",children:kn.map(Fn=>e.jsx(Urs,{deal:Fn,onClick:()=>Ks(Fn),stages:t,onStageChange:yn,showStagePicker:!0,isWonStage:$n.is_won_stage,isLostStage:$n.is_lost_stage,ownerInfo:Xe(Fn),tags:Yt[Fn.id]||[],overdueTaskCount:ss[Fn.id]||0},Fn.id))})]},$n.id)}),(r==null?void 0:r.length)===0&&e.jsxs("div",{className:"text-center py-16",children:[e.jsx("div",{className:"w-16 h-16 mx-auto mb-4 bg-muted rounded-full flex items-center justify-center",children:e.jsx(Qf,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx("h3",{className:"font-semibold text-lg mb-2",children:"No deals yet"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Start tracking your opportunities by adding your first deal"}),e.jsxs($,{onClick:()=>wt(),children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Add Your First Deal"]})]}),((r==null?void 0:r.length)||0)>0&&Ft.length===0&&e.jsxs("div",{className:"text-center py-16",children:[e.jsx("div",{className:"w-16 h-16 mx-auto mb-4 bg-muted rounded-full flex items-center justify-center",children:e.jsx(Zr,{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:jr,children:"Clear Filters"})]})]})})})]})]}),e.jsx(zQn,{open:m,onOpenChange:f,deal:y,defaultStageId:b}),e.jsx(qrr,{deal:y,open:g,onOpenChange:ks,onEdit:gs,isWonStage:y?(kr=t==null?void 0:t.find($n=>$n.id===y.stage_id))==null?void 0:kr.is_won_stage:!1,onAddToScorecard:$n=>{O($n),R(!0),x(!1)}}),e.jsx(Vrr,{open:P,onOpenChange:R,deal:D,onComplete:()=>{i(),O(null)}}),Be&&e.jsx(nar,{open:!!Be,onOpenChange:$n=>{$n||Ne(null)},dealId:Be.dealId,dealName:Be.dealName,fromStageName:Be.fromStageName,toStageName:Be.toStageName,toStageId:Be.toStageId,onConfirm:Ss}),e.jsx(_Qn,{open:_e,onOpenChange:he})]})}function yar(){return e.jsx(gar,{children:e.jsx(xar,{})})}function RPe({open:s,onOpenChange:t,templateId:n,templateName:r,brokerageId:a,onUploaded:i}){const l=!!n,o=j.useRef(null),[c,d]=j.useState(null),[u,h]=j.useState(""),[m,f]=j.useState(""),[g,x]=j.useState("other"),[y,v]=j.useState(!1),b=Knr(),w=()=>{d(null),h(""),f(""),x("other"),v(!1),o.current&&(o.current.value="")},S=E=>{if(E){if(E.type!=="application/pdf"&&!E.name.toLowerCase().endsWith(".pdf")){re.error("Only PDF files can be uploaded.");return}if(E.size>Dis){re.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});re.success(E.version.has_acroform?`Found ${E.version.detected_fields.length} fillable fields — map them next.`:"Uploaded. This PDF has no fillable fields yet."),i==null||i(E.templateId,E.version.id),w(),t(!1)}catch(E){re.error((E==null?void 0:E.message)||"Upload failed")}};return e.jsx(zs,{open:s,onOpenChange:E=>{E||w(),t(E)},children:e.jsxs(Os,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:l?`New version of ${r}`:"Upload a form template"}),e.jsxs(Pr,{children:["PDF only, up to 20MB."," ",a?"Brokerage templates stay in draft until you publish them to your agents.":"Templates stay private to your account."]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("input",{ref:o,type:"file",accept:"application/pdf,.pdf",className:"hidden",onChange:E=>{var I;return S((I=E.target.files)==null?void 0:I[0])}}),e.jsx("button",{type:"button",onClick:()=>{var E;return(E=o.current)==null?void 0:E.click()},className:"w-full rounded-lg border border-dashed p-6 text-center transition-colors hover:bg-muted/50",children:c?e.jsxs("div",{className:"flex items-center justify-center gap-3",children:[e.jsx(Jr,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"text-sm font-medium",children:c.name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:klt(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:jlt.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(Ls,{id:"tpl-desc",rows:2,value:m,onChange:E=>f(E.target.value)})]})]}),e.jsxs("label",{className:"flex items-start gap-3 rounded-lg bg-muted/50 p-3 text-xs text-muted-foreground",children:[e.jsx(ai,{checked:y,onCheckedChange:E=>v(!!E),className:"mt-0.5"}),e.jsx("span",{children:"I confirm I am legally permitted to use and store this form. LevelUp does not provide or license association forms."})]})]}),e.jsxs(Sr,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{onClick:A,disabled:!c||!y||b.isPending,children:[b.isPending&&e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}),b.isPending?"Reading PDF…":"Upload"]})]})]})})}function tQe(s){return s.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[^a-zA-Z0-9]+/g," ").toLowerCase().trim()}function XAt(s){return tQe(s).split(" ").filter(Boolean)}function bar(s,t,n){const r=tQe(s),a=new Set(XAt(s));let i=0;const l=[t,...n];for(const o of l){const c=tQe(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=XAt(o),u=d.filter(h=>a.has(h)).length;u>0&&(i=Math.max(i,Math.round(u/d.length*45)))}return i}function _ar(s){if(!s)return null;let t=null;for(const n of SW){const r=bar(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 war=["Deal","Contact","Agent","Other"],rUe="__blank__",aUe="__static__";function Yis({version:s}){const{data:t,isLoading:n}=ooe(s.id),r=srr(),[a,i]=j.useState([]),[l,o]=j.useState("");j.useEffect(()=>{if(n)return;const f=new Map((t||[]).map(g=>[g.pdf_field_name||"",g]));i((s.detected_fields||[]).map(g=>{const x=f.get(g.name),y=_ar(g.name);return{pdf_field_name:g.name,mapping_mode:(x==null?void 0:x.mapping_mode)||"acroform",merge_key:(x==null?void 0:x.merge_key)??null,static_value:(x==null?void 0:x.static_value)??null,suggested:(y==null?void 0:y.mergeKey)??null}}))},[t,n,s.id,s.detected_fields]);const c=j.useMemo(()=>{if(!l.trim())return a;const f=l.toLowerCase();return a.filter(g=>(g.pdf_field_name||"").toLowerCase().includes(f))},[a,l]),d=a.filter(f=>f.merge_key||f.mapping_mode==="static"&&f.static_value).length,u=(f,g)=>{i(x=>x.map(y=>y.pdf_field_name===f?{...y,...g}:y))},h=()=>{let f=0;i(g=>g.map(x=>x.merge_key||!x.suggested?x:(f+=1,{...x,mapping_mode:"acroform",merge_key:x.suggested}))),re.success(f?`Applied ${f} suggestion${f===1?"":"s"}`:"No new suggestions to apply")},m=async()=>{try{await r.mutateAsync({versionId:s.id,hasAcroform:s.has_acroform,mappings:a.map(({suggested:f,...g})=>g)}),re.success("Field mapping saved")}catch(f){re.error((f==null?void 0:f.message)||"Could not save the mapping")}};return s.has_acroform?n?e.jsx("div",{className:"flex justify-center py-10",children:e.jsx(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(Nn,{className:"mr-1.5 h-4 w-4"})," Apply suggestions"]}),e.jsxs($,{size:"sm",onClick:m,disabled:r.isPending,children:[r.isPending?e.jsx(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(Zr,{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"?aUe:f.merge_key?f.merge_key:rUe;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=SW.find(y=>y.key===f.suggested))==null?void 0:x.label]})]}),e.jsxs("div",{className:"flex w-full gap-2 sm:w-[420px]",children:[e.jsxs(ms,{value:g,onValueChange:y=>{y===rUe?u(f.pdf_field_name,{mapping_mode:"blank",merge_key:null,static_value:null}):y===aUe?u(f.pdf_field_name,{mapping_mode:"static",merge_key:null}):u(f.pdf_field_name,{mapping_mode:"acroform",merge_key:y,static_value:null})},children:[e.jsx(us,{className:"flex-1",children:e.jsx(fs,{placeholder:"Leave blank"})}),e.jsxs(hs,{className:"max-h-[320px]",children:[e.jsx(Ge,{value:rUe,children:"Leave blank"}),e.jsx(Ge,{value:aUe,children:"Fixed text…"}),war.map(y=>e.jsxs(HMs,{children:[e.jsx(_zt,{children:y}),SW.filter(v=>v.group===y).map(v=>e.jsx(Ge,{value:v.key,children:v.label},v.key))]},y))]})]}),f.mapping_mode==="static"&&e.jsx(pe,{className:"flex-1",placeholder:"Fixed text",value:f.static_value||"",onChange:y=>u(f.pdf_field_name,{static_value:y.target.value})})]})]},f.pdf_field_name)}),c.length===0&&e.jsx("p",{className:"py-8 text-center text-sm text-muted-foreground",children:"No fields match that search."})]})]}):e.jsx(je,{children:e.jsxs(Ie,{className:"p-6 text-center space-y-2",children:[e.jsx("p",{className:"font-medium",children:"Needs field placement"}),e.jsx("p",{className:"text-sm text-muted-foreground max-w-md mx-auto",children:"This PDF has no fillable form fields, so there is nothing to map yet. Visual field placement for flat PDFs is coming next — for now, upload a fillable (AcroForm) version of this form to use it from a deal."})]})})}Bot.workerSrc=$ot;const wAe={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"}},iUe=["signature","initials","date_signed","printed_name","text"],QAt=12,jar={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"},Xue=s=>Math.min(1,Math.max(0,s));function Zis({version:s,templateName:t,open:n,onOpenChange:r}){const a=Wt(),{data:i=[],isLoading:l}=ooe(n?s.id:void 0),[o,c]=j.useState(null),[d,u]=j.useState(null),[h,m]=j.useState([]),[f,g]=j.useState("select"),[x,y]=j.useState(null),[v,b]=j.useState(!1),[w,S]=j.useState(!1),A=j.useRef(null),E=j.useRef([]),I=j.useRef(null),P=Math.min(s.page_count||1,QAt);j.useEffect(()=>{if(!n)return;let X=!1;return c(null),u(null),iFe(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 ne=await o.arrayBuffer(),te=await yPe({data:ne}).promise;if(X)return;ae.innerHTML="",E.current=[];const J=Math.min(ae.clientWidth-32||720,860);for(let ce=1;ce<=te.numPages;ce++){const _e=await te.getPage(ce);if(X)return;const he=_e.getViewport({scale:1}),ue=J/he.width,ve=_e.getViewport({scale:ue*(window.devicePixelRatio||1)}),Ee=document.createElement("div");Ee.className="relative mx-auto shadow-sm",Ee.style.width=`${J}px`,Ee.style.height=`${he.height*ue}px`,Ee.dataset.pageIndex=String(ce-1);const Se=document.createElement("canvas");Se.width=Math.floor(ve.width),Se.height=Math.floor(ve.height),Se.style.width="100%",Se.style.height="100%",Se.className="rounded-md border border-border bg-white",Ee.appendChild(Se),ae.appendChild(Ee),E.current[ce-1]=Ee;const Le=Se.getContext("2d");Le&&await _e.render({canvasContext:Le,viewport:ve}).promise}X||m(ce=>[...ce])}catch(ne){X||u((ne==null?void 0:ne.message)||"Could not render the PDF")}})(),()=>{X=!0})},[o]),j.useEffect(()=>{if(!n||l)return;const X=i.filter(ae=>ae.field_kind!=="data"||ae.mapping_mode==="overlay").filter(ae=>ae.pos_x!=null&&ae.pos_y!=null).map(ae=>({key:ae.id,page_index:ae.page_index??0,x:Number(ae.pos_x),y:Number(ae.pos_y),w:Number(ae.width??.2),h:Number(ae.height??.03),field_kind:ae.field_kind||"data",merge_key:ae.merge_key,static_value:ae.static_value,signer_role:ae.signer_role,label:ae.label,is_required:ae.is_required??!0,font_size:ae.font_size,source:ae.source||"manual"}));m(X),y(null)},[n,l,i]),j.useEffect(()=>{const X=le=>{const ne=I.current;if(!ne)return;const te=(le.clientX-ne.startX)/ne.pageW,J=(le.clientY-ne.startY)/ne.pageH;m(ce=>ce.map(_e=>_e.key!==ne.key?_e:ne.mode==="move"?{..._e,x:Xue(Math.min(ne.orig.x+te,1-_e.w)),y:Xue(Math.min(ne.orig.y+J,1-_e.h))}:{..._e,w:Math.min(Math.max(.04,ne.orig.w+te),1-_e.x),h:Math.min(Math.max(.015,ne.orig.h+J),1-_e.y)}))},ae=()=>{I.current=null};return window.addEventListener("pointermove",X),window.addEventListener("pointerup",ae),()=>{window.removeEventListener("pointermove",X),window.removeEventListener("pointerup",ae)}},[]);const R=(X,ae,le)=>{X.stopPropagation(),X.preventDefault();const ne=E.current[ae.page_index];if(!ne)return;const te=ne.getBoundingClientRect();I.current={key:ae.key,mode:le,startX:X.clientX,startY:X.clientY,orig:ae,pageW:te.width,pageH:te.height},y(ae.key)},D=(X,ae)=>{if(f==="select"){y(null);return}const le=E.current[ae];if(!le)return;const ne=le.getBoundingClientRect(),te=wAe[f],J=Xue((X.clientX-ne.left)/ne.width-te.w/2),ce=Xue((X.clientY-ne.top)/ne.height-te.h/2),_e={key:crypto.randomUUID(),page_index:ae,x:Math.min(J,1-te.w),y:Math.min(ce,1-te.h),w:te.w,h:te.h,field_kind:f,merge_key:null,static_value:null,signer_role:iUe.includes(f)?"buyer_1":null,label:null,is_required:!0,font_size:null};m(he=>[...he,_e]),y(_e.key),g("select")},O=h.find(X=>X.key===x)||null,U=X=>{O&&m(ae=>ae.map(le=>le.key===O.key?{...le,...X}:le))},W=async(X=!1)=>{if(o){S(!0);try{const ae=await o.arrayBuffer(),le=await yPe({data:ae}).promise,ne=Math.min(le.numPages,QAt),te=[];for(let ue=1;ue<=ne;ue++){const ve=await le.getPage(ue),Ee=ve.getViewport({scale:1}),Se=ve.getViewport({scale:Math.min(1e3/Ee.width,1.6)}),Le=document.createElement("canvas");Le.width=Math.floor(Se.width),Le.height=Math.floor(Se.height);const Fe=Le.getContext("2d");Fe&&(Fe.fillStyle="#ffffff",Fe.fillRect(0,0,Le.width,Le.height),await ve.render({canvasContext:Fe,viewport:Se}).promise,te.push({index:ue-1,image:Le.toDataURL("image/jpeg",.7)}))}const{data:J,error:ce}=await q.functions.invoke("forms-autoplace",{body:{version_id:s.id,pages:te,force:X}});if(ce)throw new Error(ce.message||"The field scan failed.");if(J!=null&&J.error)throw new Error(J.error);const _e=(J==null?void 0:J.fields)||[];if(!_e.length){re.info("The scan did not find any blank fields on this form. Place them manually below.");return}const he=_e.map(ue=>({key:crypto.randomUUID(),page_index:ue.page_index,x:ue.x,y:ue.y,w:ue.w,h:ue.h,field_kind:ue.field_kind,merge_key:null,static_value:null,signer_role:ue.signer_role||"buyer_1",label:ue.label,is_required:!0,font_size:null,source:"ai"}));m(ue=>[...ue,...he]),y(null),re.success(`${he.length} field${he.length===1?"":"s"} placed${J!=null&&J.cached?" (from the earlier scan)":""}. Review, nudge, then save.`)}catch(ae){re.error((ae==null?void 0:ae.message)||"Could not scan this document. You can still place fields manually.")}finally{S(!1)}}},V=async()=>{const X=h.filter(ae=>iUe.includes(ae.field_kind));for(const ae of X)if(!ae.signer_role){re.error("Every signer field needs a role (Buyer 1, Seller 1, Agent…)");return}b(!0);try{const{error:ae}=await q.from("form_field_mappings").delete().eq("version_id",s.id).or("field_kind.neq.data,mapping_mode.eq.overlay");if(ae)throw ae;const le=h.map((ce,_e)=>({version_id:s.id,pdf_field_name:null,mapping_mode:(ce.field_kind==="data"&&ce.static_value&&!ce.merge_key,"overlay"),field_kind:ce.field_kind,merge_key:ce.field_kind==="data"?ce.merge_key:null,static_value:ce.field_kind==="data"?ce.static_value:null,signer_role:iUe.includes(ce.field_kind)?ce.signer_role:null,label:ce.label,is_required:ce.is_required,page_index:ce.page_index,pos_x:ce.x,pos_y:ce.y,width:ce.w,height:ce.h,coords_normalized:!0,font_size:ce.font_size,source:ce.source||"manual",sort_order:_e}));if(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;re.success("Placement saved"),a.invalidateQueries({queryKey:["form-field-mappings",s.id]}),a.invalidateQueries({queryKey:["form-templates"]}),r(!1)}catch(ae){re.error((ae==null?void 0:ae.message)||"Could not save placement")}finally{b(!1)}},G=[{tool:"select",label:"Select",icon:$J},{tool:"data",label:"Merge field",icon:sP},{tool:"signature",label:"Signature",icon:_f},{tool:"initials",label:"Initials",icon:oV},{tool:"date_signed",label:"Date signed",icon:Wc},{tool:"printed_name",label:"Printed name",icon:sl},{tool:"text",label:"Text input",icon:iV}],Y=s.page_count||1;return e.jsx(zs,{open:n,onOpenChange:r,children:e.jsxs(Os,{className:"flex h-[94vh] max-w-6xl flex-col overflow-hidden p-0",children:[e.jsxs(Us,{className:"border-b px-5 py-3 text-left",children:[e.jsxs(Bs,{className:"text-base",children:["Place fields — ",t," (v",s.version_number,")"]}),e.jsx("p",{className:"text-xs font-normal text-muted-foreground",children:"Pick a field type on the left, then click on the document where it belongs. Drag to move, pull the corner to resize."})]}),e.jsxs("div",{className:"flex min-h-0 flex-1",children:[e.jsxs("div",{className:"w-36 shrink-0 space-y-1 overflow-y-auto border-r p-3 sm:w-44",children:[e.jsxs($,{size:"sm",variant:"secondary",className:"mb-2 h-auto w-full flex-col items-start gap-0.5 py-2 text-left",disabled:w||!o,onClick:()=>W(!!s.autoplace_ran_at),children:[e.jsxs("span",{className:"flex items-center gap-1.5 text-xs font-semibold",children:[w?e.jsx(Ct,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Nn,{className:"h-3.5 w-3.5"}),w?"Scanning…":s.autoplace_ran_at?"Re-scan with AI":"Find fields with AI"]}),e.jsx("span",{className:"text-[10px] font-normal opacity-70",children:s.autoplace_ran_at?"Runs a fresh scan":`Scan ${P} page${P===1?"":"s"}`})]}),G.map(X=>e.jsxs("button",{onClick:()=>g(X.tool),className:`flex w-full items-center gap-2 rounded-md px-2.5 py-2 text-left text-xs font-medium transition-colors ${f===X.tool?"bg-primary text-primary-foreground":"hover:bg-muted"}`,children:[e.jsx(X.icon,{className:"h-3.5 w-3.5 shrink-0"}),X.label]},X.tool)),e.jsx("div",{className:"pt-3 text-[11px] leading-snug text-muted-foreground",children:"Merge fields fill automatically from the deal. Signature fields are assigned to a signer."})]}),e.jsxs("div",{className:"relative min-w-0 flex-1 overflow-auto bg-muted/40 p-4",children:[(l||!o)&&!d&&e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx(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?wAe[O.field_kind].label:"Field settings"}),e.jsx(uo,{className:"flex-1 p-4",children:O?e.jsxs("div",{className:"space-y-4",children:[O.field_kind==="data"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Merge value"}),e.jsxs(ms,{value:O.merge_key||"",onValueChange:X=>U({merge_key:X||null,static_value:null}),children:[e.jsx(us,{className:"h-8 text-xs",children:e.jsx(fs,{placeholder:"Choose data…"})}),e.jsx(hs,{children:["Deal","Contact","Agent","Other"].map(X=>e.jsxs("div",{children:[e.jsx("div",{className:"px-2 py-1 text-[10px] font-semibold uppercase text-muted-foreground",children:X}),SW.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:Clt.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:wAe[O.field_kind].label,value:O.label||"",onChange:X=>U({label:X.target.value||null})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{className:"text-xs",children:"Required"}),e.jsx(Sn,{checked:O.is_required,onCheckedChange:X=>U({is_required:X})})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Font size (optional)"}),e.jsx(pe,{className:"h-8 text-xs",type:"number",min:6,max:24,value:O.font_size??"",onChange:X=>U({font_size:X.target.value?Number(X.target.value):null})})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[O.page_index+1{const X={...O,key:crypto.randomUUID(),page_index:O.page_index+1};m(ae=>[...ae,X]),y(X.key)},children:[e.jsx(Ha,{className:"mr-1 h-3 w-3"})," Next page"]}),e.jsxs($,{variant:"outline",size:"sm",className:"h-8 flex-1 text-xs text-destructive",onClick:()=>{m(X=>X.filter(ae=>ae.key!==O.key)),y(null)},children:[e.jsx(Hn,{className:"mr-1 h-3 w-3"})," Remove"]})]})]}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"Select a box on the document to edit what it fills and who signs it."})}),e.jsx("div",{className:"border-t p-4",children:e.jsxs($,{className:"w-full",onClick:V,disabled:v,children:[v?e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(tl,{className:"mr-2 h-4 w-4"}),"Save placement"]})})]})]}),e.jsx(Nar,{boxes:h,pageRefs:E,selectedKey:x,onSelect:y,onDragStart:R})]})})}function Nar({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(kar,{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":jar[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=SW.find(d=>d.key===l.merge_key))==null?void 0:c.label)||l.merge_key:l.static_value||"Data":`${l.label||wAe[l.field_kind].label} · ${oFe(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 kar({target:s,children:t}){return vv.createPortal(t,s)}function Sar({templates:s}){const{data:t=[],isLoading:n}=Uis(),r=crr(),a=drr(),[i,l]=j.useState(null),[o,c]=j.useState(""),[d,u]=j.useState(""),[h,m]=j.useState([]);j.useEffect(()=>{i&&(i==="new"?(c(""),u(""),m([])):(c(i.name),u(i.description||""),m([...i.items||[]].sort((v,b)=>v.sort_order-b.sort_order).map(v=>v.template_id))))},[i]);const f=s.filter(v=>{var b;return((b=wx(v))==null?void 0:b.mapping_status)==="mapped"}),g=v=>m(b=>b.includes(v)?b.filter(w=>w!==v):[...b,v]),x=(v,b)=>m(w=>{const S=[...w],A=v+b;return A<0||A>=S.length?w:([S[v],S[A]]=[S[A],S[v]],S)}),y=async()=>{if(!o.trim())return re.error("Give the packet a name");if(!h.length)return re.error("Add at least one form to the packet");try{await r.mutateAsync({id:i==="new"?void 0:i.id,name:o.trim(),description:d.trim()||null,templateIds:h}),re.success(i==="new"?"Packet created":"Packet updated"),l(null)}catch(v){re.error((v==null?void 0:v.message)||"Could not save the packet")}};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"flex items-center gap-2 text-lg font-semibold tracking-tight",children:[e.jsx(M4,{className:"h-4 w-4 text-primary"})," Form packets"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Bundle the forms you always send together. Signers sign the whole packet in one session."})]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>l("new"),disabled:f.length===0,children:[e.jsx(dn,{className:"mr-2 h-4 w-4"})," New packet"]})]}),n?e.jsx("div",{className:"flex justify-center py-6",children:e.jsx(Ct,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):t.length===0?e.jsx(je,{className:"border-dashed",children:e.jsx(Ie,{className:"p-6 text-center text-sm text-muted-foreground",children:f.length===0?"Once at least one template is ready to send, you can bundle templates into a packet.":"No packets yet — build a “New Buyer Packet” or “Listing Agreement Bundle” and send it in one click."})}):e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:t.map(v=>{const b=Alt(v,s);return e.jsx(je,{children:e.jsxs(Ie,{className:"space-y-3 p-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-primary/10",children:e.jsx(M4,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate font-medium",children:v.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[b.length," form",b.length===1?"":"s"]})]})]}),e.jsx("ol",{className:"ml-4 list-decimal space-y-0.5 text-xs text-muted-foreground",children:b.map(w=>e.jsx("li",{className:"truncate",children:w.name},w.id))}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx($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(v),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 fo(`Delete the "${v.name}" packet? The forms themselves are kept.`)&&(await a.mutateAsync(v.id),re.success("Packet deleted"))},children:e.jsx(Hn,{className:"h-3 w-3"})})]})]})]})},v.id)})}),e.jsx(zs,{open:!!i,onOpenChange:v=>!v&&l(null),children:e.jsxs(Os,{className:"flex max-h-[88vh] max-w-lg flex-col overflow-hidden",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:i==="new"?"New form packet":"Edit packet"}),e.jsx(Pr,{children:"Pick the forms and the order signers see them in. Only templates that are ready to send can be added."})]}),e.jsxs("div",{className:"space-y-4 overflow-y-auto",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Packet name"}),e.jsx(pe,{value:o,onChange:v=>c(v.target.value),placeholder:"New Buyer Packet"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Description (optional)"}),e.jsx(Ls,{rows:2,value:d,onChange:v=>u(v.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Forms in this packet"}),e.jsx(uo,{className:"max-h-56 rounded-lg border",children:e.jsx("div",{className:"divide-y",children:f.map(v=>e.jsxs("label",{className:"flex cursor-pointer items-center gap-3 p-2.5 text-sm hover:bg-muted/50",children:[e.jsx(ai,{checked:h.includes(v.id),onCheckedChange:()=>g(v.id)}),e.jsx("span",{className:"min-w-0 flex-1 truncate",children:v.name})]},v.id))})})]}),h.length>0&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Signing order"}),e.jsx("div",{className:"space-y-1 rounded-lg border p-2",children:h.map((v,b)=>{const w=s.find(S=>S.id===v);return e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsxs("span",{className:"w-4 text-muted-foreground",children:[b+1,"."]}),e.jsx("span",{className:"min-w-0 flex-1 truncate",children:(w==null?void 0:w.name)||"Removed template"}),e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>x(b,-1),children:e.jsx(Zf,{className:"h-3 w-3"})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>x(b,1),children:e.jsx(Dg,{className:"h-3 w-3"})})]},v)})})]})]}),e.jsxs(Sr,{children:[e.jsx($,{variant:"outline",onClick:()=>l(null),children:"Cancel"}),e.jsxs($,{onClick:y,disabled:r.isPending,children:[r.isPending&&e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}),"Save packet"]})]})]})})]})}function Car(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 Ris(s.templateBytes,t,s.values),r=n.bytes.buffer.slice(n.bytes.byteOffset,n.bytes.byteOffset+n.bytes.byteLength),a=await t3.load(r,{updateMetadata:!1}),i=await a.embedFont(kW.Helvetica),l=a.getPages(),o=[...n.skipped];for(const d of s.signerBoxes){const u=s.entries[d.id],h=l[d.page_index??0];if(!h||d.pos_x==null||d.pos_y==null)continue;if(!u||!u.png&&!((c=u.text)!=null&&c.trim())){o.push(d.static_value||d.field_kind||"signature");continue}const{width:m,height:f}=h.getSize(),g=d.coords_normalized!==!1,x=Number(d.pos_x)*(g?m:1),y=Number(d.width??(g?.2:140))*(g?m:1),v=Number(d.height??(g?.04:24))*(g?f:1),b=Number(d.pos_y)*(g?f:1),w=g?f-b-v:b;if(u.png){const S=Car(u.png);if(!S){o.push("signature");continue}const A=await a.embedPng(S),E=Math.min(y/A.width,v/A.height),I=A.width*E,P=A.height*E;h.drawImage(A,{x:x+(y-I)/2,y:w+(v-P)/2,width:I,height:P})}else{const S=u.text.trim(),A=Math.min(11,Math.max(7,v*.6));h.drawText(S,{x:x+1,y:w+Math.max(2,(v-A)/2),size:A,font:i,color:Sh(0,0,0),maxWidth:Math.max(10,y-2)})}}return{bytes:await a.save(),skipped:o}}const Xis='"Segoe Script","Brush Script MT",cursive';function Ear(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 ${Xis}`,n.fillText(s,t.width/2,t.height/2+24),t.toDataURL("image/png")}function Tar({label:s,onAdopt:t}){const n=j.useRef(null),r=j.useRef(!1),[a,i]=j.useState(""),[l,o]=j.useState(!1),c=m=>{const f=n.current,g=f.getBoundingClientRect();return{x:(m.clientX-g.left)/g.width*f.width,y:(m.clientY-g.top)/g.height*f.height}},d=m=>{const f=n.current;if(!f)return;r.current=!0,f.setPointerCapture(m.pointerId);const g=f.getContext("2d");g.lineWidth=3,g.lineCap="round",g.strokeStyle="#12233f";const x=c(m);g.beginPath(),g.moveTo(x.x,x.y)},u=m=>{if(!r.current)return;const f=n.current.getContext("2d"),g=c(m);f.lineTo(g.x,g.y),f.stroke(),o(!0)},h=()=>{r.current=!1};return e.jsxs(ha,{defaultValue:"draw",className:"w-full",children:[e.jsxs(ma,{className:"grid w-full grid-cols-2",children:[e.jsx(Zt,{value:"draw",children:"Draw"}),e.jsx(Zt,{value:"type",children:"Type"})]}),e.jsxs(Xt,{value:"draw",className:"space-y-3 pt-3",children:[e.jsx("canvas",{ref:n,width:640,height:200,className:"h-36 w-full touch-none rounded-lg border bg-white",onPointerDown:d,onPointerMove:u,onPointerUp:h,onPointerLeave:h}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:()=>{var f;const m=n.current;(f=m==null?void 0:m.getContext("2d"))==null||f.clearRect(0,0,m.width,m.height),o(!1)},children:[e.jsx(Tq,{className:"mr-1 h-3.5 w-3.5"})," Clear"]}),e.jsxs($,{type:"button",size:"sm",className:"flex-1",disabled:!l,onClick:()=>{const m=n.current;m&&t(m.toDataURL("image/png"))},children:["Use this ",s]})]})]}),e.jsxs(Xt,{value:"type",className:"space-y-3 pt-3",children:[e.jsx(pe,{value:a,onChange:m=>i(m.target.value),placeholder:"Type your name"}),e.jsx("div",{className:"flex h-24 items-center justify-center rounded-lg border bg-white",children:e.jsx("span",{className:"text-3xl text-[#12233f]",style:{fontFamily:Xis},children:a||" "})}),e.jsxs($,{type:"button",size:"sm",className:"w-full",disabled:!a.trim(),onClick:()=>t(Ear(a.trim())),children:["Use this ",s]})]})]})}const Mar=["signature","initials","date_signed","printed_name","text"],Par={signature:"Signature",initials:"Initials",date_signed:"Date signed",printed_name:"Printed name",text:"Text"};function Iar({open:s,onOpenChange:t,template:n,version:r}){const a=Sa(),{data:i=[],isLoading:l}=ooe(s?r.id:void 0),{data:o=[]}=eY(),[c,d]=j.useState(""),{data:u}=Slt(s&&c?c:void 0),[h,m]=j.useState({}),[f,g]=j.useState({}),[x,y]=j.useState(null),[v,b]=j.useState(!1),w=j.useMemo(()=>i.filter(R=>(R.field_kind==null||R.field_kind==="data")&&R.mapping_mode!=="blank"&&(R.merge_key||R.pdf_field_name||R.static_value)),[i]),S=j.useMemo(()=>i.filter(R=>R.field_kind&&Mar.includes(R.field_kind)),[i]);j.useEffect(()=>{u&&m(R=>{const D={...R};for(const[O,U]of Object.entries(u.values))U&&!D[O]&&(D[O]=U);return D})},[u]),j.useEffect(()=>{s||(m({}),g({}),y(null),d(""))},[s]);const A=R=>R.merge_key||R.pdf_field_name||R.id,E=R=>{y(R),g(D=>{var U;const O={...D};for(const W of S)(W.field_kind==="signature"||W.field_kind==="initials")&&(O[W.id]={png:R}),W.field_kind==="date_signed"&&!((U=O[W.id])!=null&&U.text)&&(O[W.id]={text:new Date().toLocaleDateString("en-US")});return O}),re.success("Signature applied to the document")},I=S.filter(R=>{var D,O,U;return((D=f[R.id])==null?void 0:D.png)||((U=(O=f[R.id])==null?void 0:O.text)==null?void 0:U.trim())}).length,P=async()=>{b(!0);try{const R=await iFe(r.storage_path),D={...h},{bytes:O}=await Aar({templateBytes:R,mappings:i,values:D,signerBoxes:S,entries:f}),W=`${n.name.replace(/[^a-zA-Z0-9-_ ]/g,"").trim()||"Form"} - signed.pdf`,V=O.buffer.slice(O.byteOffset,O.byteOffset+O.byteLength),G=new Blob([V],{type:"application/pdf"}),Y=URL.createObjectURL(G),X=document.createElement("a");if(X.href=Y,X.download=W,X.click(),URL.revokeObjectURL(Y),c&&a){const ae=`${a}/${c}/${crypto.randomUUID()}.pdf`,{error:le}=await q.storage.from("deal-files").upload(ae,G,{contentType:"application/pdf"});if(le)throw le;const{error:ne}=await q.from("deal_files").insert({deal_id:c,owner_user_id:a,file_name:W,file_size:G.size,file_type:"application/pdf",storage_path:ae});if(ne)throw ne;await q.from("deal_activities").insert({deal_id:c,activity_type:"document",title:`Filled and signed ${n.name}`,description:`${W} was completed in LevelUp (v${r.version_number}).`,metadata:{template_id:n.id,version_id:r.id}}),re.success("Saved to the deal and downloaded")}else re.success("Your signed PDF is downloading");t(!1)}catch(R){re.error(wlt(R))}finally{b(!1)}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"flex max-h-[90vh] max-w-2xl flex-col overflow-hidden",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{children:["Fill & sign — ",n.name]}),e.jsx(Pr,{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=zis.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:()=>y(null),children:"Redo"})]}):e.jsx(Tar,{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:[Par[R.field_kind||"text"]," · page ",(R.page_index??0)+1,R.signer_role?` · ${oFe(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(Sr,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),disabled:v,children:"Cancel"}),e.jsxs($,{onClick:P,disabled:v||l,children:[v?e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(xi,{className:"mr-2 h-4 w-4"}),"Finish & download"]})]})]})})}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(){var X,ae;const{data:s=[],isLoading:t,error:n}=Nlt(),{data:r=[]}=eY(),a=Fis(),i=Ois(),l=Ynr(),[o,c]=j.useState(!1),[d,u]=j.useState(null),[h,m]=j.useState(null),[f,g]=j.useState(""),[x,y]=j.useState(null),[v,b]=j.useState(""),[w,S]=j.useState(null),[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,ne)=>(le.scope==="brokerage"?1:0)-(ne.scope==="brokerage"?1:0)),W=async le=>{try{await l.mutateAsync(le),re.success(`"${le.name}" copied to your forms`)}catch(ne){re.error((ne==null?void 0:ne.message)||"Could not copy that form")}},V=h?s.find(le=>le.id===h.id)||h:null,G=wx(V),Y=async le=>{if(await fo(`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),re.success("Template deleted")}catch(ne){re.error((ne==null?void 0:ne.message)||"Could not delete the template")}};return e.jsxs(Vs,{children:[e.jsxs("div",{className:"mx-auto w-full max-w-6xl space-y-6 px-4 py-6 sm:px-6",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Forms Library"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Upload blank PDF forms you are permitted to use, map their fields once, then fill them from any deal."})]}),e.jsxs($,{onClick:()=>c(!0),children:[e.jsx(dn,{className:"mr-2 h-4 w-4"})," Upload template"]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("div",{className:"relative w-full max-w-sm",children:[e.jsx(Zr,{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,ne])=>e.jsx($,{size:"sm",variant:R===le?"secondary":"ghost",className:"h-7 text-xs",onClick:()=>D(le),children:ne},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(Ie,{className:"p-6 text-center text-sm text-destructive",children:"Could not load your templates. Please refresh and try again."})}),!t&&!n&&s.length===0&&e.jsx(je,{className:"border-dashed",children:e.jsxs(Ie,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx("div",{className:"flex h-12 w-12 items-center justify-center rounded-full bg-muted",children:e.jsx(Jr,{className:"h-6 w-6 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"No form templates yet"}),e.jsx("p",{className:"mx-auto max-w-sm text-sm text-muted-foreground",children:"Upload a blank PDF form you are legally permitted to use. LevelUp reads its fillable fields so you can map them to your deal, contact and agent data."})]}),e.jsxs($,{onClick:()=>c(!0),children:[e.jsx(ni,{className:"mr-2 h-4 w-4"})," Upload your first template"]})]})}),!t&&!n&&s.length>0&&e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:[U.map(le=>{var J;const ne=wx(le),te=le.scope==="brokerage";return e.jsx(je,{className:"transition-shadow hover:shadow-md",children:e.jsxs(Ie,{className:"space-y-3 p-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-primary/10",children:e.jsx(Jr,{className:"h-5 w-5 text-primary"})}),e.jsxs("button",{className:"min-w-0 flex-1 text-left",onClick:()=>m(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(ji,{className:"h-3 w-3"})," Brokerage form"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(J=jlt.find(ce=>ce.value===le.category))==null?void 0:J.label," · v",(ne==null?void 0:ne.version_number)??1,ne?` · ${ne.page_count} page${ne.page_count===1?"":"s"}`:""]})]}),e.jsxs($u,{children:[e.jsx(Uu,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(Jx,{className:"h-4 w-4"})})}),e.jsx(Au,{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(Ha,{className:"mr-2 h-4 w-4"})," Copy to my forms"]}),e.jsxs(ja,{disabled:(ne==null?void 0:ne.mapping_status)!=="mapped",onClick:()=>P(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(Qf,{className:"mr-2 h-4 w-4"})," Place fields & signatures"]}),e.jsxs(ja,{disabled:(ne==null?void 0:ne.mapping_status)!=="mapped",onClick:()=>{E("sign"),y(le),b("")},children:[e.jsx(_f,{className:"mr-2 h-4 w-4"})," Send for signature"]}),e.jsxs(ja,{disabled:(ne==null?void 0:ne.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(jv,{className:"mr-2 h-4 w-4"})," Archive"]}),e.jsxs(ja,{className:"text-destructive",onClick:()=>Y(le),children:[e.jsx(Hn,{className:"mr-2 h-4 w-4"})," Delete"]})]})})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Lar,{status:ne==null?void 0:ne.mapping_status}),e.jsxs("div",{className:"flex gap-1",children:[e.jsxs($,{variant:"ghost",size:"sm",disabled:(ne==null?void 0:ne.mapping_status)!=="mapped",onClick:()=>P(le),children:[e.jsx(_f,{className:"mr-1.5 h-4 w-4"})," Fill & sign"]}),e.jsxs($,{variant:"ghost",size:"sm",disabled:(ne==null?void 0:ne.mapping_status)!=="mapped",onClick:()=>{E("sign"),y(le),b("")},children:[e.jsx(_f,{className:"mr-1.5 h-4 w-4"})," Send"]}),e.jsxs($,{variant:"ghost",size:"sm",disabled:(ne==null?void 0:ne.mapping_status)!=="mapped",onClick:()=>{E("generate"),y(le),b("")},children:[e.jsx(Mq,{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(Sar,{templates:s})})]}),e.jsx(Gy,{open:!!V,onOpenChange:le=>!le&&m(null),children:e.jsxs(my,{side:"right",className:"w-full overflow-y-auto sm:max-w-2xl",children:[e.jsxs(L0,{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(R0,{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," · ",klt(G.file_size)," · uploaded ",en(new Date(G.created_at),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"mt-5 space-y-4",children:[(V==null?void 0:V.description)&&e.jsx("p",{className:"text-sm text-muted-foreground",children:V.description}),G?e.jsx(e.Fragment,{children:(V==null?void 0:V.scope)==="brokerage"?e.jsxs("div",{className:"rounded-lg border bg-muted/40 p-4 text-sm text-muted-foreground",children:[e.jsxs("p",{className:"flex items-center gap-2 font-medium text-foreground",children:[e.jsx(ji,{className:"h-4 w-4"})," Managed by your brokerage"]}),e.jsx("p",{className:"mt-1",children:"Fields on this form are set up by your brokerage. You can fill it from any deal or send it for signature. Need your own version? Use “Copy to my forms”."}),e.jsxs($,{variant:"outline",className:"mt-3 w-full",disabled:l.isPending,onClick:()=>V&&W(V),children:[e.jsx(Ha,{className:"mr-2 h-4 w-4"})," Copy to my forms"]})]}):e.jsxs(e.Fragment,{children:[e.jsxs($,{variant:"outline",className:"w-full",onClick:()=>V&&S(V),children:[e.jsx(Qf,{className:"mr-2 h-4 w-4"})," Place fields & signatures on the document"]}),e.jsx(Yis,{version:G})]})}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"This template has no uploaded version yet."})]})]})}),e.jsx(RPe,{open:o,onOpenChange:c}),e.jsx(RPe,{open:!!d,onOpenChange:le=>!le&&u(null),templateId:d==null?void 0:d.id,templateName:d==null?void 0:d.name}),e.jsx(Gy,{open:!!x&&!v,onOpenChange:le=>!le&&y(null),children:e.jsxs(my,{side:"bottom",className:"space-y-4",children:[e.jsx(L0,{className:"text-left",children:e.jsx(R0,{children:"Choose a deal"})}),r.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"You don’t have any deals yet."}):e.jsxs(ms,{value:v,onValueChange:b,children:[e.jsx(us,{className:"max-w-md",children:e.jsx(fs,{placeholder:"Select a deal"})}),e.jsx(hs,{children:r.map(le=>e.jsx(Ge,{value:le.id,children:le.deal_name},le.id))})]})]})}),x&&v&&A==="generate"&&e.jsx(Bis,{open:!0,onOpenChange:le=>{le||(y(null),b(""))},dealId:v,dealName:(X=r.find(le=>le.id===v))==null?void 0:X.deal_name,initialTemplateId:x.id}),x&&v&&A==="sign"&&e.jsx(qis,{open:!0,onOpenChange:le=>{le||(y(null),b(""))},dealId:v,dealName:(ae=r.find(le=>le.id===v))==null?void 0:ae.deal_name,initialTemplateId:x.id}),w&&wx(w)&&e.jsx(Zis,{open:!0,onOpenChange:le=>!le&&S(null),version:wx(w),templateName:w.name}),I&&wx(I)&&e.jsx(Iar,{open:!0,onOpenChange:le=>!le&&P(null),template:I,version:wx(I)})]})}function Qis({open:s,onOpenChange:t,editTask:n,defaultDealId:r,defaultStageId:a}){var W;const i=Krr(),l=Yrr(),{data:o}=eY(),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"),[y,v]=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"),v(n.contact_id||"none"),w(n.priority),A(n.status),I(n.due_date?gv(n.due_date):void 0)):(h(""),f(""),x(r||"none"),v("none"),w("medium"),A("todo"),I(void 0))},[n,s,r]);const U=async()=>{if(!u.trim()){re.error("Task title is required");return}try{const V={title:u.trim(),description:m.trim()||null,deal_id:g==="none"?null:g,contact_id:y==="none"?null:y,stage_id:a||null,priority:b,status:S,due_date:E?en(E,"yyyy-MM-dd"):null};n?(await l.mutateAsync({id:n.id,...V}),re.success("Task updated")):(await i.mutateAsync(V),re.success("Task created")),t(!1)}catch{re.error("Failed to save task")}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-[480px]",children:[e.jsx(Us,{children:e.jsx(Bs,{children:n?"Edit Task":"New Task"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Title *"}),e.jsx(pe,{value:u,onChange:V=>h(V.target.value),placeholder:"e.g., Send inspection report"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Description"}),e.jsx(Ls,{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(Kd,{children:[e.jsx(Yd,{asChild:!0,children:e.jsxs($,{variant:"outline",className:Pt("w-full justify-start text-left font-normal",!E&&"text-muted-foreground"),children:[e.jsx(Ta,{className:"mr-2 h-4 w-4"}),E?en(E,"PPP"):"Pick a date"]})}),e.jsx(Od,{className:"w-auto p-0",align:"start",children:e.jsx(T2,{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(Kd,{open:P,onOpenChange:R,children:[e.jsx(Yd,{asChild:!0,children:e.jsxs($,{variant:"outline",role:"combobox",className:"w-full justify-between font-normal",children:[e.jsxs("span",{className:"flex items-center gap-2 truncate",children:[e.jsx(ji,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),g!=="none"?((W=o==null?void 0:o.find(V=>V.id===g))==null?void 0:W.deal_name)||"Select deal":"No Deal"]}),e.jsx(Sw,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Od,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(S2,{children:[e.jsx(C2,{placeholder:"Search deals..."}),e.jsxs(A2,{children:[e.jsx(E2,{children:"No deals found."}),e.jsxs(Dw,{children:[e.jsxs(m1,{value:"no-deal",onSelect:()=>{x("none"),R(!1)},children:[e.jsx(ca,{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(m1,{value:V.deal_name,onSelect:()=>{x(V.id),R(!1)},children:[e.jsx(ca,{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(Kd,{open:D,onOpenChange:O,children:[e.jsx(Yd,{asChild:!0,children:e.jsxs($,{variant:"outline",role:"combobox",className:"w-full justify-between font-normal",children:[e.jsxs("span",{className:"flex items-center gap-2 truncate",children:[e.jsx(sl,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),y!=="none"?(()=>{const V=d==null?void 0:d.find(G=>G.id===y);return V?`${V.first_name} ${V.last_name}`:"Select contact"})():"No Contact"]}),e.jsx(Sw,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Od,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(S2,{children:[e.jsx(C2,{placeholder:"Search contacts..."}),e.jsxs(A2,{children:[e.jsx(E2,{children:"No contacts found."}),e.jsxs(Dw,{children:[e.jsxs(m1,{value:"no-contact",onSelect:()=>{v("none"),O(!1)},children:[e.jsx(ca,{className:Pt("mr-2 h-4 w-4",y==="none"?"opacity-100":"opacity-0")}),"No Contact"]}),d==null?void 0:d.map(V=>e.jsxs(m1,{value:`${V.first_name} ${V.last_name}`,onSelect:()=>{v(V.id),O(!1)},children:[e.jsx(ca,{className:Pt("mr-2 h-4 w-4",y===V.id?"opacity-100":"opacity-0")}),V.first_name," ",V.last_name]},V.id))]})]})]})})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx($,{onClick:U,disabled:i.isPending||l.isPending,children:n?"Save Changes":"Create Task"})]})]})]})})}const Dar={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 Far({tasks:s}){const t=lFe(),n=Zrr(),r=Xn(),[a,i]=j.useState(null),l=async u=>{const h=u.status==="done"?"todo":"done";try{await t.mutateAsync({id:u.id,status:h})}catch{re.error("Failed to update task")}},o=async u=>{try{await n.mutateAsync(u),re.success("Task deleted")}catch{re.error("Failed to delete task")}};if(s.length===0)return e.jsxs("div",{className:"flex flex-col items-center justify-center py-20 text-center",children:[e.jsx(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(JAt,{task:u,onToggle:l,onDelete:o,onEdit:i,onNavigateDeal:h=>r(`/mission-control/pipeline?deal=${h}`)},u.id))]}),Array.from(c.entries()).map(([u,h])=>e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("button",{onClick:()=>r(`/mission-control/pipeline?deal=${u}`),className:"w-full bg-muted/30 px-4 py-2 border-b flex items-center gap-2 hover:bg-muted/50 transition-colors text-left",children:[e.jsx(ji,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("h3",{className:"font-medium text-sm",children:h.dealName}),e.jsxs($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(JAt,{task:m,onToggle:l,onDelete:o,onEdit:i,onNavigateDeal:f=>r(`/mission-control/pipeline?deal=${f}`)},m.id))]},u)),a&&e.jsx(Qis,{open:!!a,onOpenChange:()=>i(null),editTask:a})]})}function JAt({task:s,onToggle:t,onDelete:n,onEdit:r,onNavigateDeal:a}){const i=s.status==="done",l=!i&&s.due_date&&D4(gv(s.due_date))&&!_v(gv(s.due_date)),o=!i&&s.due_date&&_v(gv(s.due_date)),c=Dar[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(Og,{className:"h-5 w-5 text-muted-foreground hover:text-primary transition-colors"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:Pt("text-sm font-medium truncate",i&&"line-through text-muted-foreground"),children:s.title}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5 flex-wrap",children:[s.stage&&e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full font-medium",style:{backgroundColor:s.stage.color+"20",color:s.stage.color},children:s.stage.name}),s.contact&&e.jsxs("span",{className:"text-[10px] text-muted-foreground flex items-center gap-0.5",children:[e.jsx(sl,{className:"h-2.5 w-2.5"}),s.contact.first_name," ",s.contact.last_name]})]})]}),e.jsxs($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(da,{className:"h-3 w-3"}),en(gv(s.due_date),"MMM d")]}),e.jsxs("div",{className:"flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity",children:[e.jsx("button",{onClick:()=>r(s),className:"p-1 hover:bg-muted rounded",children:e.jsx(_p,{className:"h-3.5 w-3.5 text-muted-foreground"})}),e.jsx("button",{onClick:()=>n(s.id),className:"p-1 hover:bg-destructive/10 rounded",children:e.jsx(Hn,{className:"h-3.5 w-3.5 text-destructive"})})]})]})}const Oar=[{status:"todo",label:"To Do",icon:Og,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"}],zar={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function Bar({tasks:s}){const t=lFe(),n=j.useMemo(()=>{const i={todo:[],in_progress:[],done:[]};return s.forEach(l=>i[l.status].push(l)),i},[s]),r=(i,l)=>{i.dataTransfer.setData("taskId",l)},a=async(i,l)=>{i.preventDefault();const o=i.dataTransfer.getData("taskId");if(!o)return;const c=s.find(d=>d.id===o);if(!(!c||c.status===l))try{await t.mutateAsync({id:o,status:l})}catch{re.error("Failed to move task")}};return e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:Oar.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($ar,{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 $ar({task:s,onDragStart:t}){const n=s.status==="done",r=!n&&s.due_date&&D4(gv(s.due_date))&&!_v(gv(s.due_date)),a=!n&&s.due_date&&_v(gv(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:zar[s.priority]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:Pt("text-sm font-medium",n&&"line-through text-muted-foreground"),children:s.title}),e.jsxs("div",{className:"flex items-center gap-2 mt-1.5 flex-wrap",children:[s.deal&&e.jsxs("span",{className:"text-[10px] text-muted-foreground flex items-center gap-0.5",children:[e.jsx(ji,{className:"h-2.5 w-2.5"}),s.deal.deal_name]}),s.contact&&e.jsxs("span",{className:"text-[10px] text-muted-foreground flex items-center gap-0.5",children:[e.jsx(sl,{className:"h-2.5 w-2.5"}),s.contact.first_name," ",s.contact.last_name]})]}),s.due_date&&e.jsxs("div",{className:Pt("text-[10px] mt-1.5 flex items-center gap-1",r&&"text-destructive font-medium",a&&"text-amber-600 font-medium",!r&&!a&&"text-muted-foreground"),children:[e.jsx(da,{className:"h-2.5 w-2.5"}),r?"Overdue — ":a?"Due today — ":"",en(gv(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 eEt={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function Uar({tasks:s}){const[t,n]=j.useState(new Date),r=lFe(),a=Zm(t),i=hw(t),l=j1(a),o=PLe(i),c=cPs({start:l,end:o}),d=j.useMemo(()=>{const m=new Map;return s.forEach(f=>{if(!f.due_date)return;const g=f.due_date,x=m.get(g)||[];x.push(f),m.set(g,x)}),m},[s]),u=j.useMemo(()=>s.filter(m=>!m.due_date),[s]),h=async m=>{const f=m.status==="done"?"todo":"done";try{await r.mutateAsync({id:m.id,status:f})}catch{re.error("Failed to update task")}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>n(i8(t,1)),children:e.jsx(kd,{className:"h-4 w-4"})}),e.jsx("h3",{className:"font-semibold",children:en(t,"MMMM yyyy")}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>n(Ev(t,1)),children:e.jsx(Di,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"grid grid-cols-7 text-center",children:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"].map(m=>e.jsx("div",{className:"text-xs font-medium text-muted-foreground py-2",children:m},m))}),e.jsx("div",{className:"grid grid-cols-7 border-l border-t",children:c.map(m=>{const f=en(m,"yyyy-MM-dd"),g=d.get(f)||[],x=Oae(m,t),y=_v(m);return e.jsxs("div",{className:Pt("border-r border-b min-h-[100px] p-1",!x&&"bg-muted/30",y&&"bg-primary/5"),children:[e.jsx("div",{className:Pt("text-xs font-medium mb-1 text-right px-1",!x&&"text-muted-foreground/40",y&&"text-primary font-bold"),children:en(m,"d")}),e.jsxs("div",{className:"space-y-0.5",children:[g.slice(0,3).map(v=>e.jsxs("button",{onClick:()=>h(v),className:Pt("w-full text-left text-[10px] px-1 py-0.5 rounded truncate flex items-center gap-0.5 hover:bg-muted transition-colors",v.status==="done"?"text-muted-foreground line-through":"text-foreground"),children:[v.status==="done"?e.jsx(Vr,{className:"h-2.5 w-2.5 text-emerald-500 shrink-0"}):e.jsx(Og,{className:"h-2.5 w-2.5 shrink-0"}),e.jsxs("span",{className:"truncate",children:[eEt[v.priority]," ",v.title]})]},v.id)),g.length>3&&e.jsxs("p",{className:"text-[9px] text-muted-foreground text-center",children:["+",g.length-3," more"]})]})]},f)})}),u.length>0&&e.jsxs("div",{className:"border rounded-lg p-3",children:[e.jsxs("h4",{className:"text-sm font-medium text-muted-foreground mb-2",children:["No Due Date (",u.length,")"]}),e.jsx("div",{className:"space-y-1",children:u.map(m=>e.jsxs("button",{onClick:()=>h(m),className:Pt("w-full text-left text-xs px-2 py-1.5 rounded flex items-center gap-2 hover:bg-muted transition-colors",m.status==="done"&&"opacity-50 line-through"),children:[m.status==="done"?e.jsx(Vr,{className:"h-3.5 w-3.5 text-emerald-500 shrink-0"}):e.jsx(Og,{className:"h-3.5 w-3.5 shrink-0"}),e.jsxs("span",{className:"truncate",children:[eEt[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 qar={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function Var({open:s,onOpenChange:t,stages:n}){var v;const[r,a]=j.useState(((v=n[0])==null?void 0:v.id)||""),{data:i,isLoading:l}=Qrr(r||void 0),o=Jrr(),c=ear(),[d,u]=j.useState(""),[h,m]=j.useState("medium"),[f,g]=j.useState(""),x=async()=>{if(!(!d.trim()||!r))try{await o.mutateAsync({stage_id:r,title:d.trim(),priority:h,default_due_offset_days:f?parseInt(f):null,sort_order:((i==null?void 0:i.length)||0)+1}),u(""),g(""),re.success("Template added")}catch{re.error("Failed to add template")}},y=async b=>{try{await c.mutateAsync(b),re.success("Template deleted")}catch{re.error("Failed to delete template")}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-[560px]",children:[e.jsx(Us,{children:e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(bJ,{className:"h-5 w-5"}),"Task Templates by Stage"]})}),e.jsx("p",{className:"text-sm text-muted-foreground -mt-2",children:"Create default tasks that auto-populate when a deal enters a stage."}),e.jsxs("div",{children:[e.jsx(ee,{children:"Pipeline Stage"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:n.filter(b=>!b.is_won_stage&&!b.is_lost_stage).map(b=>e.jsx("button",{onClick:()=>a(b.id),className:Pt("px-3 py-1.5 rounded-full text-xs font-medium border transition-colors",r===b.id?"border-primary bg-primary/10 text-primary":"border-border hover:bg-muted"),children:b.name},b.id))})]}),e.jsx(uo,{className:"max-h-[250px]",children:e.jsxs("div",{className:"space-y-1.5",children:[i==null?void 0:i.map((b,w)=>e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 border rounded-lg group",children:[e.jsx("span",{className:"text-xs",children:qar[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:()=>y(b.id),className:"opacity-0 group-hover:opacity-100 p-1 hover:bg-destructive/10 rounded transition-opacity",children:e.jsx(Hn,{className:"h-3.5 w-3.5 text-destructive"})})]},b.id)),(i==null?void 0:i.length)===0&&r&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No templates for this stage yet"})]})}),r&&e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(ee,{className:"text-xs text-muted-foreground",children:"Add Template Task"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{placeholder:"Task title...",value:d,onChange:b=>u(b.target.value),className:"flex-1",onKeyDown:b=>b.key==="Enter"&&x()}),e.jsxs(ms,{value:h,onValueChange:b=>m(b),children:[e.jsx(us,{className:"w-[100px]",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"low",children:"🟢 Low"}),e.jsx(Ge,{value:"medium",children:"🟡 Med"}),e.jsx(Ge,{value:"high",children:"🟠 High"}),e.jsx(Ge,{value:"urgent",children:"🔴 Urgent"})]})]})]}),e.jsxs("div",{className:"flex gap-2 items-end",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(ee,{className:"text-xs",children:"Due offset (days from entering stage)"}),e.jsx(pe,{type:"number",placeholder:"e.g., 7",value:f,onChange:b=>g(b.target.value)})]}),e.jsxs($,{onClick:x,disabled:!d.trim()||o.isPending,children:[e.jsx(dn,{className:"h-4 w-4 mr-1"}),"Add"]})]})]})]})})}function Har(){const{data:s,isLoading:t}=Gis(),{data:n}=Yie(),[r,a]=j.useState("list"),[i,l]=j.useState(""),[o,c]=j.useState("active"),[d,u]=j.useState("all"),[h,m]=j.useState("all"),[f,g]=j.useState(!1),[x,y]=j.useState(!1),v=j.useMemo(()=>{if(!s)return[];const S=new Map;return s.forEach(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&&D4(gv(S.due_date))&&!_v(gv(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&&D4(gv(A.due_date))&&!_v(gv(A.due_date))).length,dueToday:S.filter(A=>A.due_date&&_v(gv(A.due_date))).length,dueThisWeek:S.filter(A=>A.due_date&&iLs(gv(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:()=>y(!0),children:[e.jsx(Cw,{className:"h-4 w-4 mr-1"}),"Templates"]}),e.jsxs($,{size:"sm",onClick:()=>g(!0),children:[e.jsx(dn,{className:"h-4 w-4 mr-1"}),"New Task"]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[e.jsxs("button",{onClick:()=>c("active"),className:`p-3 rounded-lg border text-left transition-colors ${o==="active"?"border-primary bg-primary/5":"hover:bg-muted/50"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-xs font-medium",children:[e.jsx(T0,{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(da,{className:"h-3.5 w-3.5"}),"Due Today"]}),e.jsx("p",{className:"text-xl font-bold mt-1",children:w.dueToday})]}),e.jsxs("button",{onClick:()=>{c("active")},className:"p-3 rounded-lg border text-left hover:bg-muted/50 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2 text-blue-600 text-xs font-medium",children:[e.jsx(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(Zr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search tasks...",value:i,onChange:S=>l(S.target.value),className:"pl-9"})]}),e.jsxs(ms,{value:d,onValueChange:u,children:[e.jsx(us,{className:"w-[130px]",children:e.jsx(fs,{placeholder:"Priority"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Priorities"}),e.jsx(Ge,{value:"urgent",children:"🔴 Urgent"}),e.jsx(Ge,{value:"high",children:"🟠 High"}),e.jsx(Ge,{value:"medium",children:"🟡 Medium"}),e.jsx(Ge,{value:"low",children:"🟢 Low"})]})]}),e.jsxs(ms,{value:h,onValueChange:m,children:[e.jsx(us,{className:"w-[160px]",children:e.jsx(fs,{placeholder:"Deal"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All Deals"}),e.jsx(Ge,{value:"no_deal",children:"No Deal"}),v.map(S=>e.jsx(Ge,{value:S.id,children:S.name},S.id))]})]}),e.jsxs("div",{className:"flex items-center border rounded-lg p-0.5 ml-auto",children:[e.jsx("button",{onClick:()=>a("list"),className:`p-1.5 rounded-md transition-colors ${r==="list"?"bg-primary text-primary-foreground":"text-muted-foreground hover:text-foreground"}`,children:e.jsx(T0,{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(l2,{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(Far,{tasks:b}),r==="kanban"&&e.jsx(Bar,{tasks:b}),r==="calendar"&&e.jsx(Uar,{tasks:b})]}),e.jsx(Qis,{open:f,onOpenChange:g}),e.jsx(Var,{open:x,onOpenChange:y,stages:n||[]})]})})}function Gar(s){const t=Ilt(s);return t?t.toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric"}):""}function War({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 Que({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 Kar(){const s=Xn(),{data:t,isLoading:n}=Arr(),r=lFe(),[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=>{WQ.forEach(S=>{const A=w[S.key],E=S5(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=S5(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=S5(E.target_close_date);return I!==null&&I>=0&&I<=7}).length,S=b.reduce((E,I)=>E+I.tasks.filter(P=>{const R=S5(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}`),y=async b=>{try{await r.mutateAsync({id:b,status:"done"}),re.success("Task completed")}catch{re.error("Could not update task")}},v=({title:b,items:w,tone:S})=>{if(w.length===0)return null;const 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:()=>y(E.id),"aria-label":`Complete ${E.label}`}):e.jsx(Cu,{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," · ",Gar(E.date)]})]}),e.jsx("span",{className:Pt("text-[11px] font-semibold shrink-0 tabular-nums",E.days<0?"text-destructive":E.days<=3?"text-amber-600":"text-muted-foreground"),children:E.days<0?`${Math.abs(E.days)}d late`:E.days===0?"Today":`${E.days}d`})]},E.id))]})};return e.jsxs(Vs,{children:[e.jsxs("div",{className:"p-4 sm:p-6 space-y-6 max-w-[1400px] mx-auto",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Transaction Coordinator"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Every deadline, every checklist, one screen. Nothing slips."})]}),e.jsxs($,{onClick:()=>o(!0),className:"gap-2 shrink-0",children:[e.jsx(Xf,{className:"h-4 w-4"}),"Playbooks"]})]}),e.jsxs("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-3",children:[e.jsx(Que,{icon:zg,label:"Active transactions",value:f.active}),e.jsx(Que,{icon:sh,label:"Closing within 7 days",value:f.closingSoon,tone:"warn"}),e.jsx(Que,{icon:Al,label:"Overdue tasks",value:f.overdueTasks,tone:f.overdueTasks>0?"danger":"good"}),e.jsx(Que,{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(Zr,{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(Cu,{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(v,{title:"Overdue",items:m.overdue,tone:"danger"}),e.jsx(v,{title:"Today",items:m.today,tone:"warn"}),e.jsx(v,{title:"This week",items:m.week,tone:"warn"}),e.jsx(v,{title:"Coming up",items:m.later,tone:"default"})]})]})}),e.jsx("div",{className:"lg:col-span-3 space-y-3",children:u.length===0?e.jsxs("div",{className:"rounded-xl border border-dashed p-12 text-center",children:[e.jsx(va,{className:"h-8 w-8 text-muted-foreground mx-auto mb-3"}),e.jsx("p",{className:"font-medium",children:"No active transactions"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Deals in progress will appear here with their full deadline chain."}),e.jsx($,{variant:"outline",className:"mt-4",onClick:()=>s("/mission-control/pipeline"),children:"Go to Deal Pipeline"})]}):u.map(b=>{const w=g(b),S=S5(b.target_close_date),A=b.tasks.filter(P=>P.status!=="done"),E=A.filter(P=>{const R=S5(P.due_date);return R!==null&&R<0}),I=A.filter(P=>P.due_date).sort((P,R)=>(S5(P.due_date)??0)-(S5(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(War,{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(His,{open:l,onOpenChange:o})]})}function Jis(){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 Yar(){const s=Wt();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 Zar(){const s=Wt();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 Xar=s=>new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(s)),oUe=[{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"}],Qar={buying:"Buying",selling:"Selling",both:"Buying & Selling",unsure:"Not sure yet"};function eos(){const{data:s=[],isLoading:t}=Jis(),n=Yar(),r=Zar(),[a,i]=j.useState("all"),[l,o]=j.useState({}),c=j.useMemo(()=>a==="all"?s:s.filter(f=>f.status===a),[s,a]),d=j.useMemo(()=>({total:s.length,new:s.filter(f=>f.status==="new").length,converted:s.filter(f=>f.status==="converted").length}),[s]),u=(f,g)=>{n.mutate({id:f.id,status:g}),re.success("Status updated")},h=f=>{const g=l[f.id];n.mutate({id:f.id,agent_notes:g}),o(x=>{const{[f.id]:y,...v}=x;return v}),re.success("Notes saved")},m=async f=>{await fo(`Delete referral for ${f.friend_name}?`)&&r.mutate(f.id)};return e.jsxs("div",{className:"container max-w-5xl py-6 px-4",children:[e.jsx(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(ul,{className:"h-6 w-6 text-primary"}),"Portal Referrals"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Referrals sent in by happy clients via their post-close portal."})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsxs("div",{className:"bg-card border rounded-lg px-4 py-2 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:d.total}),e.jsx("div",{className:"text-[10px] uppercase tracking-wide text-muted-foreground",children:"Total"})]}),e.jsxs("div",{className:"bg-card border rounded-lg px-4 py-2 text-center",children:[e.jsx("div",{className:"text-2xl font-bold text-blue-600",children:d.new}),e.jsx("div",{className:"text-[10px] uppercase tracking-wide text-muted-foreground",children:"New"})]}),e.jsxs("div",{className:"bg-card border rounded-lg px-4 py-2 text-center",children:[e.jsx("div",{className:"text-2xl font-bold text-emerald-600",children:d.converted}),e.jsx("div",{className:"text-[10px] uppercase tracking-wide text-muted-foreground",children:"Closed"})]})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2 mb-4",children:[{v:"all",l:"All"},...oUe.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(Ie,{className:"py-12 text-center",children:[e.jsx(ul,{className:"h-10 w-10 text-muted-foreground/40 mx-auto mb-3"}),e.jsx("p",{className:"text-sm font-medium",children:"No referrals yet"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Once your closed clients refer friends from their portal, they'll show up here."})]})}):e.jsx("div",{className:"space-y-3",children:c.map(f=>{var v,b;const g=oUe.find(w=>w.value===f.status),x=(v=f.client_portals)==null?void 0:v.slug,y=f.referrer_name||((b=f.client_portals)==null?void 0:b.client_name)||"Anonymous client";return e.jsxs(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(Ta,{className:"h-3 w-3"}),"Referred by ",e.jsx("span",{className:"font-medium text-foreground",children:y})," ·"," ",Xar(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:oUe.map(w=>e.jsx(Ge,{value:w.value,className:"text-xs",children:w.label},w.value))})]})]})]})}),e.jsxs(Ie,{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[f.friend_interest&&e.jsx($e,{variant:"secondary",className:"text-xs",children:Qar[f.friend_interest]||f.friend_interest}),f.friend_email&&e.jsxs("a",{href:`mailto:${f.friend_email}`,className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(mn,{className:"h-3 w-3"}),f.friend_email]}),f.friend_phone&&e.jsxs(e.Fragment,{children:[e.jsxs("a",{href:`tel:${f.friend_phone}`,className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(Da,{className:"h-3 w-3"}),f.friend_phone]}),e.jsxs("a",{href:`sms:${f.friend_phone}`,className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(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(Ls,{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(Fr,{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(Hn,{className:"h-3.5 w-3.5"})})]})]})]},f.id)})})]})}function tos({vendor:s,onEdit:t,onDelete:n,onToggleVisible:r,isVisible:a,showOwnerBadge:i,clickCount:l}){var c;const o=((c=iK.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(pc,{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(mn,{className:"w-3 h-3"}),e.jsx("span",{className:"truncate",children:s.email})]}),s.website&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(dl,{className:"w-3 h-3"}),e.jsx("span",{className:"truncate",children:s.website})]}),s.booking_url&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Ta,{className:"w-3 h-3"}),e.jsx("span",{className:"truncate",children:"Booking link"})]}),s.address&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ci,{className:"w-3 h-3"}),e.jsx("span",{className:"truncate",children:s.address})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-2 border-t",children:[r&&e.jsxs($,{size:"sm",variant:a?"default":"outline",onClick:()=>r(!a),disabled:s.is_required&&!a,className:"flex-1",children:[a?e.jsx(Ca,{className:"w-3.5 h-3.5 mr-1.5"}):e.jsx($g,{className:"w-3.5 h-3.5 mr-1.5"}),a?"Showing in portals":"Hidden"]}),t&&e.jsx($,{size:"sm",variant:"ghost",onClick:t,children:e.jsx(_p,{className:"w-3.5 h-3.5"})}),n&&e.jsx($,{size:"sm",variant:"ghost",onClick:n,className:"text-destructive",children:e.jsx(Hn,{className:"w-3.5 h-3.5"})})]})]})}function sos({open:s,onOpenChange:t,vendor:n,ownerType:r,brokerageId:a,agentUserId:i,showBrokerageOnlyFields:l}){const o=g9s(),[c,d]=j.useState({}),[u,h]=j.useState(!1),m=j.useRef(null),f=async y=>{if(!y.type.startsWith("image/")){re.error("Please select an image");return}if(y.size>5*1024*1024){re.error("Image must be under 5MB");return}h(!0);try{const v=y.name.split(".").pop()||"png",b=`${r}/${a||i||"misc"}/${Date.now()}.${v}`,{error:w}=await q.storage.from("vendor-logos").upload(b,y,{upsert:!0,contentType:y.type});if(w)throw w;const{data:S}=q.storage.from("vendor-logos").getPublicUrl(b);d(A=>({...A,logo_url:S.publicUrl})),re.success("Logo uploaded")}catch(v){re.error(v.message||"Upload failed")}finally{h(!1)}};j.useEffect(()=>{s&&d(n||{owner_type:r,owner_brokerage_id:r==="brokerage"&&a||null,owner_user_id:r==="agent"&&i||null,category:"other",action_type:"call",is_active:!0,is_featured:!1,is_required:!1})},[s,n,r,a,i]);const g=(y,v)=>d(b=>({...b,[y]:v})),x=async()=>{var y;if(!((y=c.name)!=null&&y.trim())){re.error("Name is required");return}try{await o.mutateAsync(c),re.success(n?"Vendor updated":"Vendor added"),t(!1)}catch(v){re.error(v.message||"Failed to save vendor")}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(Bs,{children:n?"Edit Vendor":"Add Vendor"})}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(ee,{children:"Contact Name *"}),e.jsx(pe,{value:c.name||"",onChange:y=>g("name",y.target.value),placeholder:"Bob Smith"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Company"}),e.jsx(pe,{value:c.company||"",onChange:y=>g("company",y.target.value),placeholder:"Smith Inspections"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Category"}),e.jsxs(ms,{value:c.category,onValueChange:y=>g("category",y),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:iK.map(y=>e.jsx(Ge,{value:y.value,children:y.label},y.value))})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Phone"}),e.jsx(pe,{value:c.phone||"",onChange:y=>g("phone",y.target.value),placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Email"}),e.jsx(pe,{type:"email",value:c.email||"",onChange:y=>g("email",y.target.value),placeholder:"bob@smithinsp.com"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Website"}),e.jsx(pe,{value:c.website||"",onChange:y=>g("website",y.target.value),placeholder:"https://..."})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Logo"}),e.jsx("input",{ref:m,type:"file",accept:"image/*",className:"hidden",onChange:y=>{var b;const v=(b=y.target.files)==null?void 0:b[0];v&&f(v),y.target.value=""}}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[c.logo_url?e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:c.logo_url,alt:"Vendor logo",className:"h-14 w-14 rounded-md object-cover border"}),e.jsx("button",{type:"button",onClick:()=>g("logo_url",""),className:"absolute -top-2 -right-2 bg-background border rounded-full p-0.5 shadow","aria-label":"Remove logo",children:e.jsx(pr,{className:"h-3 w-3"})})]}):e.jsx("div",{className:"h-14 w-14 rounded-md border border-dashed flex items-center justify-center text-muted-foreground",children:e.jsx(ni,{className:"h-5 w-5"})}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:()=>{var y;return(y=m.current)==null?void 0:y.click()},disabled:u,children:[u?e.jsx(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:y=>g("address",y.target.value)})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(ee,{children:"Description"}),e.jsx(Ls,{rows:3,value:c.description||"",onChange:y=>g("description",y.target.value),placeholder:"Why your clients should use this vendor..."})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Primary Action"}),e.jsxs(ms,{value:c.action_type,onValueChange:y=>g("action_type",y),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:m9s.map(y=>e.jsx(Ge,{value:y.value,children:y.label},y.value))})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Booking URL (Calendly etc.)"}),e.jsx(pe,{value:c.booking_url||"",onChange:y=>g("booking_url",y.target.value),placeholder:"https://calendly.com/..."})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(ee,{children:"Compliance Disclosure (optional)"}),e.jsx(Ls,{rows:2,value:c.disclosure_text||"",onChange:y=>g("disclosure_text",y.target.value),placeholder:"e.g. Agent receives no compensation for this referral."})]}),e.jsxs("div",{className:"flex items-center justify-between md:col-span-2 border rounded-lg p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"font-medium",children:"Active"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show this vendor in client portals"})]}),e.jsx(Sn,{checked:!!c.is_active,onCheckedChange:y=>g("is_active",y)})]}),l&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between border rounded-lg p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"font-medium",children:"Featured"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Highlight in agent library"})]}),e.jsx(Sn,{checked:!!c.is_featured,onCheckedChange:y=>g("is_featured",y)})]}),e.jsxs("div",{className:"flex items-center justify-between border rounded-lg p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"font-medium",children:"Required"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Agents cannot hide"})]}),e.jsx(Sn,{checked:!!c.is_required,onCheckedChange:y=>g("is_required",y)})]})]})]}),e.jsxs(Sr,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx($,{onClick:x,disabled:o.isPending,children:o.isPending?"Saving...":"Save Vendor"})]})]})})}function nos({embedded:s=!1}={}){const t=Sa(),{brokerageId:n}=bs(),{data:r,isLoading:a}=p9s(),{data:i={}}=G9t("agent",t),l=V9t(),o=x9s(),[c,d]=j.useState(null),[u,h]=j.useState(!1),[m,f]=j.useState(""),[g,x]=j.useState("all"),y=(r==null?void 0:r.vendors)||[],v=(r==null?void 0:r.selections)||[],b=j.useMemo(()=>{const D=new Map;return v.forEach(O=>D.set(O.vendor_id,O.is_visible)),D},[v]),w=j.useMemo(()=>y.filter(D=>!(g!=="all"&&D.category!==g||m&&!`${D.name} ${D.company||""}`.toLowerCase().includes(m.toLowerCase()))),[y,m,g]),S=w.filter(D=>D.owner_type==="agent"),A=w.filter(D=>D.owner_type==="brokerage"),E=async D=>{if(await fo("Delete this vendor?"))try{await l.mutateAsync(D),re.success("Vendor deleted")}catch(O){re.error(O.message)}},I=async(D,O)=>{try{await o.mutateAsync({vendorId:D,isVisible:O})}catch(U){re.error(U.message)}},P=D=>D.is_required?!0:b.get(D.id)??D.owner_type==="agent",R=e.jsxs("div",{className:s?"space-y-6":"max-w-6xl mx-auto p-4 md:p-8 space-y-6",children:[e.jsxs("div",{className:"flex items-start justify-between flex-wrap gap-4",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl font-bold flex items-center gap-2",children:[e.jsx(kx,{className:"w-6 h-6 text-primary"}),"My Vendor Library"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Curate trusted partners that show up in your client portals — inspector, lender, movers and more."})]}),e.jsxs($,{onClick:()=>{d(null),h(!0)},children:[e.jsx(dn,{className:"w-4 h-4 mr-2"})," Add Personal Vendor"]})]}),e.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[e.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[e.jsx(Zr,{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"}),iK.map(D=>e.jsx("option",{value:D.value,children:D.label},D.value))]})]}),a?e.jsx("div",{className:"text-center text-muted-foreground py-12",children:"Loading vendors..."}):e.jsxs(ha,{defaultValue:n?"all":"personal",children:[e.jsxs(ma,{children:[e.jsxs(Zt,{value:"all",children:["All (",w.length,")"]}),n&&e.jsxs(Zt,{value:"brokerage",children:["From Brokerage (",A.length,")"]}),e.jsxs(Zt,{value:"personal",children:["My Personal (",S.length,")"]})]}),e.jsx(Xt,{value:"all",className:"mt-4",children:e.jsx(lUe,{vendors:w,isVisibleInPortals:P,onToggle:I,onEdit:D=>{d(D),h(!0)},onDelete:E,userId:t,clicks:i})}),n&&e.jsx(Xt,{value:"brokerage",className:"mt-4",children:A.length===0?e.jsx(tEt,{icon:e.jsx(Nn,{className:"w-12 h-12"}),title:"No brokerage vendors yet",desc:"Your brokerage hasn't added any vendors. Ask your manager to set them up."}):e.jsx(lUe,{vendors:A,isVisibleInPortals:P,onToggle:I,userId:t,clicks:i})}),e.jsx(Xt,{value:"personal",className:"mt-4",children:S.length===0?e.jsx(tEt,{icon:e.jsx(kx,{className:"w-12 h-12"}),title:"No personal vendors yet",desc:"Add your trusted inspector, lender, mover — they'll show in every client portal you create.",action:e.jsxs($,{onClick:()=>{d(null),h(!0)},children:[e.jsx(dn,{className:"w-4 h-4 mr-2"})," Add Your First Vendor"]})}):e.jsx(lUe,{vendors:S,isVisibleInPortals:P,onToggle:I,onEdit:D=>{d(D),h(!0)},onDelete:E,userId:t,clicks:i})})]}),e.jsx(sos,{open:u,onOpenChange:h,vendor:c,ownerType:"agent",agentUserId:t})]});return s?R:e.jsx(Vs,{children:R})}function lUe({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(tos,{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 tEt({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 Jar(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 eir(s){const t=Wt(),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 tir({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 sir(){const{brokerageId:s,isBrokerageManager:t,isAdmin:n,loading:r}=bs(),{data:a=[],isLoading:i}=Wnr(s),l=Fis(),o=Ois(),[c,d]=j.useState(!1),[u,h]=j.useState(null),[m,f]=j.useState(null),[g,x]=j.useState(null),[y,v]=j.useState(""),[b,w]=j.useState("all"),{data:S=[]}=Jar(s),{createFolder:A,deleteFolder:E,moveTemplate:I}=eir(s),P=async()=>{var G;const V=(G=window.prompt("Folder name (for example: Onboarding, Listing paperwork)"))==null?void 0:G.trim();if(V)try{const Y=await A.mutateAsync(V);w(Y.id),re.success("Folder created")}catch(Y){re.error((Y==null?void 0:Y.message)||"Could not create the folder")}};if(r)return e.jsx(Vs,{children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!t&&!n)return e.jsx(Vs,{children:e.jsx("div",{className:"p-8 text-center",children:e.jsx("h2",{className:"text-xl font-semibold",children:"Brokerage managers only"})})});const R=a.filter(V=>V.name.toLowerCase().includes(y.trim().toLowerCase())).filter(V=>b==="all"?!0:b==="unfiled"?!V.folder_id:V.folder_id===b),D=m?a.find(V=>V.id===m.id)||m:null,O=wx(D),U=async(V,G)=>{const Y=wx(V);if(G&&(Y==null?void 0:Y.mapping_status)!=="mapped"){re.error("Map and place the fields before publishing this form to your agents.");return}try{await l.mutateAsync({id:V.id,patch:{is_published:G}}),re.success(G?"Published to your agents":"Unpublished — agents can no longer use it")}catch(X){re.error((X==null?void 0:X.message)||"Could not update the form")}},W=async V=>{if(await fo(`Delete "${V.name}"? Agents will lose access. Forms already generated stay on their deals.`))try{await o.mutateAsync(V),(m==null?void 0:m.id)===V.id&&f(null),re.success("Form deleted")}catch(G){re.error((G==null?void 0:G.message)||"Could not delete the form")}};return e.jsxs(Vs,{children:[e.jsxs("div",{className:"mx-auto w-full max-w-6xl space-y-6 px-4 py-6 sm:px-6",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Brokerage Forms"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Build the official set of forms your agents can pick from. Map the fields once, publish, and every agent can fill them straight from a deal."})]}),e.jsxs($,{onClick:()=>d(!0),children:[e.jsx(dn,{className:"mr-2 h-4 w-4"})," Upload form"]})]}),e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center",children:[e.jsxs("div",{className:"relative max-w-sm flex-1",children:[e.jsx(Zr,{className:"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(pe,{className:"pl-9",placeholder:"Search forms…",value:y,onChange:V=>v(V.target.value)})]}),e.jsxs($,{variant:"outline",size:"sm",onClick:P,children:[e.jsx(NJ,{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(Iq,{className:"mr-2 h-4 w-4"}),V.name]}),e.jsx($,{size:"sm",variant:b===V.id?"default":"outline",className:"rounded-l-none border-l-0 px-2","aria-label":`Delete ${V.name} folder`,onClick:async()=>{await fo(`Delete the "${V.name}" folder? The forms inside stay in your library.`)&&(await E.mutateAsync(V.id),b===V.id&&w("all"))},children:e.jsx(Hn,{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(Ie,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx("div",{className:"flex h-12 w-12 items-center justify-center rounded-full bg-muted",children:e.jsx(ji,{className:"h-6 w-6 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"No brokerage forms yet"}),e.jsx("p",{className:"mx-auto max-w-sm text-sm text-muted-foreground",children:"Upload the blank PDFs your office uses. Once you map their fields and publish, your agents can pick them from their Forms library and Deal → Forms tab."})]}),e.jsxs($,{onClick:()=>d(!0),children:[e.jsx(ni,{className:"mr-2 h-4 w-4"})," Upload your first form"]})]})}),!i&&a.length>0&&e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:[R.map(V=>{var Y;const G=wx(V);return e.jsx(je,{className:"transition-shadow hover:shadow-md",children:e.jsxs(Ie,{className:"space-y-3 p-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-primary/10",children:e.jsx(Jr,{className:"h-5 w-5 text-primary"})}),e.jsxs("button",{className:"min-w-0 flex-1 text-left",onClick:()=>f(V),children:[e.jsx("p",{className:"truncate font-medium",children:V.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(Y=jlt.find(X=>X.value===V.category))==null?void 0:Y.label," · v",(G==null?void 0:G.version_number)??1,G?` · ${G.page_count} page${G.page_count===1?"":"s"}`:""]})]}),e.jsxs($u,{children:[e.jsx(Uu,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(Jx,{className:"h-4 w-4"})})}),e.jsxs(Au,{align:"end",children:[e.jsx(ja,{onClick:()=>f(V),children:"Open & map fields"}),e.jsxs(ja,{onClick:()=>x(V),children:[e.jsx(Qf,{className:"mr-2 h-4 w-4"})," Place fields & signatures"]}),e.jsxs(ja,{onClick:()=>h(V),children:[e.jsx(ni,{className:"mr-2 h-4 w-4"})," Upload new version"]}),S.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(I0,{}),e.jsx(jL,{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(Iq,{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(I0,{})]}),e.jsxs(ja,{onClick:()=>l.mutate({id:V.id,patch:{is_archived:!0,is_published:!1}}),children:[e.jsx(jv,{className:"mr-2 h-4 w-4"})," Archive"]}),e.jsxs(ja,{className:"text-destructive",onClick:()=>W(V),children:[e.jsx(Hn,{className:"mr-2 h-4 w-4"})," Delete"]})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(tir,{status:G==null?void 0:G.mapping_status}),e.jsxs("label",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[V.is_published?"Published":"Draft",e.jsx(Sn,{checked:!!V.is_published,onCheckedChange:X=>U(V,X)})]})]})]})},V.id)}),R.length===0&&e.jsx("p",{className:"col-span-full py-10 text-center text-sm text-muted-foreground",children:"No forms match that search."})]})]}),e.jsx(Gy,{open:!!D,onOpenChange:V=>!V&&f(null),children:e.jsxs(my,{side:"right",className:"w-full overflow-y-auto sm:max-w-2xl",children:[e.jsxs(L0,{className:"space-y-1 text-left",children:[e.jsx(R0,{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," ·"," ",klt(O.file_size)," · uploaded"," ",en(new Date(O.created_at),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"mt-5 space-y-4",children:[(D==null?void 0:D.description)&&e.jsx("p",{className:"text-sm text-muted-foreground",children:D.description}),O?e.jsxs(e.Fragment,{children:[e.jsxs($,{variant:"outline",className:"w-full",onClick:()=>D&&x(D),children:[e.jsx(Qf,{className:"mr-2 h-4 w-4"})," Place fields & signatures on the document"]}),e.jsx(Yis,{version:O})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"This form has no uploaded version yet."})]})]})}),e.jsx(RPe,{open:c,onOpenChange:d,brokerageId:s}),e.jsx(RPe,{open:!!u,onOpenChange:V=>!V&&h(null),templateId:u==null?void 0:u.id,templateName:u==null?void 0:u.name,brokerageId:s}),g&&wx(g)&&e.jsx(Zis,{open:!0,onOpenChange:V=>!V&&x(null),version:wx(g),templateName:g.name})]})}function nir(){const{brokerageId:s,isBrokerageManager:t,isAdmin:n,loading:r}=bs(),{data:a=[],isLoading:i}=f9s(s),{data:l={}}=G9t("brokerage",s),o=V9t(),[c,d]=j.useState(null),[u,h]=j.useState(!1),[m,f]=j.useState(""),[g,x]=j.useState("all");if(r)return e.jsx(Vs,{children:e.jsx("div",{className:"p-8",children:"Loading..."})});if(!t&&!n)return e.jsx(Vs,{children:e.jsx("div",{className:"p-8 text-center",children:e.jsx("h2",{className:"text-xl font-semibold",children:"Brokerage managers only"})})});const y=a.filter(b=>!(g!=="all"&&b.category!==g||m&&!`${b.name} ${b.company||""}`.toLowerCase().includes(m.toLowerCase()))),v=async b=>{if(await fo("Delete this vendor? This will remove it from all agent libraries."))try{await o.mutateAsync(b),re.success("Vendor deleted")}catch(w){re.error(w.message)}};return e.jsx(Vs,{children:e.jsxs("div",{className:"max-w-6xl mx-auto p-4 md:p-8 space-y-6",children:[e.jsxs("div",{className:"flex items-start justify-between flex-wrap gap-4",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl font-bold flex items-center gap-2",children:[e.jsx(ji,{className:"w-6 h-6 text-primary"}),"Brokerage Vendor Library"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Manage preferred vendors that all agents in your brokerage can offer to their clients."})]}),e.jsxs($,{onClick:()=>{d(null),h(!0)},children:[e.jsx(dn,{className:"w-4 h-4 mr-2"})," Add Vendor"]})]}),e.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[e.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[e.jsx(Zr,{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"}),iK.map(b=>e.jsx("option",{value:b.value,children:b.label},b.value))]})]}),i?e.jsx("div",{className:"text-center text-muted-foreground py-12",children:"Loading vendors..."}):y.length===0?e.jsxs("div",{className:"text-center py-16 border-2 border-dashed rounded-xl",children:[e.jsx(ji,{className:"w-12 h-12 text-muted-foreground mx-auto mb-3"}),e.jsx("h3",{className:"font-semibold",children:"No vendors yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 mb-4",children:"Add preferred lenders, inspectors, title companies, and more."}),e.jsxs($,{onClick:()=>{d(null),h(!0)},children:[e.jsx(dn,{className:"w-4 h-4 mr-2"})," Add Your First Vendor"]})]}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:y.map(b=>e.jsx(tos,{vendor:b,onEdit:()=>{d(b),h(!0)},onDelete:()=>v(b.id),clickCount:l[b.id]},b.id))}),e.jsx(sos,{open:u,onOpenChange:h,vendor:c,ownerType:"brokerage",brokerageId:s,showBrokerageOnlyFields:!0})]})})}function ros({portalId:s,portalSlug:t,clientName:n,agentName:r}){const{data:a,isLoading:i}=Y9t(s),l=Z9t(),o=b9s(),[c,d]=j.useState(""),u=j.useRef(null),h=(a||[]).filter(f=>f.sender_type==="client"&&!f.read_at).length;j.useEffect(()=>{h>0&&o.mutate(s)},[h,s]),j.useEffect(()=>{var f;(f=u.current)==null||f.scrollIntoView({block:"nearest"})},[a==null?void 0:a.length]);const m=async()=>{const f=c.trim();if(f)try{await l.mutateAsync({portalId:s,senderType:"agent",senderName:r||null,body:f,portalUrl:t?`https://clients.relevelup.com/${t}`:void 0}),d(""),re.success("Message sent — your client was emailed")}catch(g){re.error((g==null?void 0:g.message)||"Could not send message")}};return e.jsx(je,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("h3",{className:"font-semibold",children:["Conversation with ",n||"your client"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Both sides get an email for every message"})]}),e.jsxs("div",{className:"space-y-3 max-h-[420px] overflow-y-auto pr-1",children:[i&&e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(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"," ·"," ",en(new Date(f.created_at),"MMM d, h:mm a")]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:f.body})]})},f.id)}),e.jsx("div",{ref:u})]}),e.jsxs("div",{className:"mt-4 space-y-2",children:[e.jsx(Ls,{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(Kr,{className:"w-4 h-4 mr-1.5"}),"Send & notify"]})})]})]})})}function rir({selectedPortalId:s,onSelectPortal:t}){const{data:n,isLoading:r}=X9t(),[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(Ie,{className:"p-10 text-center",children:[e.jsx(eo,{className:"w-6 h-6 mx-auto text-muted-foreground mb-3"}),e.jsx("p",{className:"font-medium",children:"No client portals yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Create a portal from a deal and your conversations will appear here."})]})}):e.jsxs("div",{className:"grid gap-4 md:grid-cols-[320px_1fr]",children:[e.jsx("div",{className:`${f?"hidden md:block":"block"}`,children:e.jsxs(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(Zr,{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(ros,{portalId:f.portalId,portalSlug:f.slug,clientName:f.clientName})]}):e.jsx(je,{children:e.jsx(Ie,{className:"p-10 text-center text-sm text-muted-foreground",children:"Pick a client to see the conversation."})})})]})}const air=[{value:"overview",label:"Portals",icon:Qf},{value:"messages",label:"Messages",icon:eo},{value:"vendors",label:"Vendors",icon:vb},{value:"referrals",label:"Referrals",icon:ul},{value:"branding",label:"Branding",icon:yd},{value:"questions",label:"Onboarding",icon:Cv}];function iir(){const[s,t]=gc(),n=s.get("tab")||"overview",[r,a]=j.useState(n),[i,l]=j.useState(!1),[o,c]=j.useState(!1),d=s.get("portal"),{data:u}=X9t(),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(Nn,{className:"w-6 h-6 text-primary"}),"Client Portals"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 max-w-2xl",children:"Your central hub for everything client-facing — manage active portals, curate trusted vendors, tune branding, and inbox referrals from happy clients."})]})}),e.jsx("div",{className:"border rounded-xl p-5 bg-card",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"rounded-lg bg-primary/10 p-3",children:e.jsx(a7,{className:"w-5 h-5 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h2",{className:"text-base font-semibold",children:"Create portals from Deal Pipeline"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 max-w-3xl",children:"This page is for managing portals after they’ve been created. To create a new client portal, open the deal inside Deal Pipeline and enable the portal from that deal."})]}),e.jsx($,{asChild:!0,variant:"outline",size:"sm",className:"shrink-0",children:e.jsx(wr,{to:"/mission-control/pipeline",children:"Open Deal Pipeline"})})]})}),e.jsxs(ha,{value:r,onValueChange:a,className:"w-full",children:[e.jsx(ma,{className:"w-full justify-start overflow-x-auto h-auto flex-wrap",children:air.map(m=>e.jsxs(Zt,{value:m.value,className:"gap-2",children:[e.jsx(m.icon,{className:"w-4 h-4"}),m.label,m.value==="messages"&&h>0&&e.jsx($e,{className:"ml-1 h-5 px-1.5",children:h})]},m.value))}),e.jsx(Xt,{value:"overview",className:"mt-6",children:e.jsx(Kis,{})}),e.jsx(Xt,{value:"messages",className:"mt-6",children:e.jsx(rir,{selectedPortalId:d,onSelectPortal:m=>t(f=>{const g=new URLSearchParams(f);return g.set("tab","messages"),m?g.set("portal",m):g.delete("portal"),g},{replace:!0})})}),e.jsx(Xt,{value:"vendors",className:"mt-6",children:e.jsx(oir,{})}),e.jsx(Xt,{value:"referrals",className:"mt-6",children:e.jsx(lir,{})}),e.jsx(Xt,{value:"branding",className:"mt-6",children:e.jsx("div",{className:"border rounded-xl p-8 bg-card",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"rounded-lg bg-primary/10 p-3",children:e.jsx(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(Xt,{value:"questions",className:"mt-6",children:e.jsx("div",{className:"border rounded-xl p-8 bg-card",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"rounded-lg bg-primary/10 p-3",children:e.jsx(Cv,{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(Wis,{open:i,onOpenChange:l}),e.jsx(Vis,{open:o,onOpenChange:c})]})}function oir(){return e.jsx(nos,{embedded:!0})}function lir(){return e.jsx(eos,{})}const X$=s=>new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(s));function cir(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 dir(){const{portalId:s}=Wi(),t=Xn(),n=Sa(),{data:r,isLoading:a}=cir(s),{data:i=[]}=rUn(s),{data:l=[]}=Jis(),o=OK(),c=YQt(),d=ZQt(),u=XQt(),[h,m]=j.useState(!1),[f,g]=j.useState(!1),[x,y]=j.useState(!1),[v,b]=j.useState(!1),w=(r==null?void 0:r.portal)??null,S=(r==null?void 0:r.deal)??null,A=j.useMemo(()=>w?l.filter(Y=>Y.portal_id===w.id):[],[l,w==null?void 0:w.id]);if(a)return e.jsx(Vs,{children:e.jsx("div",{className:"flex items-center justify-center py-24",children:e.jsx(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(wr,{to:"/mission-control/client-portals",children:[e.jsx(Va,{className:"w-4 h-4 mr-2"}),"Back to Portals"]})})]})});const E=lC(w.slug),I=(S==null?void 0:S.deal_name)||"Untitled deal",P=S==null?void 0:S.contact,R=P?`${P.first_name||""} ${P.last_name||""}`.trim():"",D=!!w.archived_at,O=()=>{navigator.clipboard.writeText(E),re.success("Portal link copied!")},U=async Y=>{try{await o.mutateAsync({id:w.id,is_enabled:Y}),re.success(Y?"Portal enabled":"Portal disabled")}catch{re.error("Failed to update")}},W=async()=>{try{await c.mutateAsync(w.id),re.success("Portal archived")}catch{re.error("Failed to archive")}},V=async()=>{try{await d.mutateAsync(w.id),re.success("Portal restored")}catch{re.error("Failed to restore")}},G=async()=>{try{await u.mutateAsync({id:w.id,dealId:w.deal_id}),re.success("Portal deleted"),t("/mission-control/client-portals")}catch{re.error("Failed to delete")}};return e.jsxs(Vs,{children:[e.jsx(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(wr,{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(Nn,{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(mn,{className:"w-3.5 h-3.5"}),e.jsx("span",{className:"truncate",children:P.email})]}),(P==null?void 0:P.phone)&&e.jsxs(e.Fragment,{children:["· ",e.jsx(Da,{className:"w-3.5 h-3.5"}),P.phone]})]}),e.jsx("div",{className:"mt-3 flex items-center gap-2 bg-background/60 border rounded-md px-3 py-1.5 max-w-full",children:e.jsx("code",{className:"text-xs font-mono text-muted-foreground truncate flex-1",children:E})})]}),!D&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Live"}),e.jsx(Sn,{checked:w.is_enabled,onCheckedChange:U})]})]}),e.jsxs("div",{className:"mt-5 flex items-center gap-2 flex-wrap",children:[e.jsxs($,{onClick:O,variant:"outline",size:"sm",children:[e.jsx(Ha,{className:"w-4 h-4 mr-1.5"})," Copy Link"]}),e.jsxs($,{onClick:()=>window.open(E,"_blank"),variant:"outline",size:"sm",children:[e.jsx(Fr,{className:"w-4 h-4 mr-1.5"})," Preview"]}),e.jsxs($,{onClick:()=>y(!0),size:"sm",children:[e.jsx(Kr,{className:"w-4 h-4 mr-1.5"})," Invite Client"]}),e.jsxs($,{onClick:()=>g(!0),variant:"outline",size:"sm",children:[e.jsx(m4,{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(zI,{className:"w-4 h-4 mr-1.5"})," Restore"]}):e.jsxs($,{onClick:W,variant:"ghost",size:"sm",children:[e.jsx(jv,{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(Hn,{className:"w-4 h-4"})})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(Jue,{icon:m4,label:"Updates Posted",value:i.length}),e.jsx(Jue,{icon:ul,label:"Referrals",value:A.length}),e.jsx(Jue,{icon:Ta,label:"Inspection",value:w.inspection_date?X$(w.inspection_date):"—"}),e.jsx(Jue,{icon:Ta,label:"Appraisal",value:w.appraisal_date?X$(w.appraisal_date):"—"})]}),e.jsxs(ha,{defaultValue:"updates",className:"w-full",children:[e.jsxs(ma,{children:[e.jsxs(Zt,{value:"updates",children:["Updates (",i.length,")"]}),e.jsx(Zt,{value:"messages",children:"Messages"}),e.jsxs(Zt,{value:"referrals",children:["Referrals (",A.length,")"]}),e.jsx(Zt,{value:"branding",children:"Branding"}),e.jsx(Zt,{value:"details",children:"Details"})]}),e.jsx(Xt,{value:"messages",className:"mt-4",children:e.jsx(ros,{portalId:w.id,portalSlug:w.slug,clientName:w.client_name})}),e.jsx(Xt,{value:"updates",className:"mt-4",children:e.jsx(je,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"font-semibold",children:"Portal Update Feed"}),e.jsxs($,{size:"sm",onClick:()=>g(!0),children:[e.jsx(m4,{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(m4,{className:"w-10 h-10 text-muted-foreground/40 mx-auto mb-3"}),e.jsx("p",{className:"text-sm font-medium",children:"No updates posted yet"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Keep your client in the loop — post your first update."})]}):e.jsx("div",{className:"space-y-3",children:i.map(Y=>e.jsx("div",{className:"border rounded-lg p-4",children:e.jsx("div",{className:"flex items-start justify-between gap-2",children:e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("h4",{className:"font-medium text-sm",children:Y.title}),Y.is_stage_change&&e.jsx($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:X$(Y.created_at)}),Y.content&&e.jsx("p",{className:"text-sm text-muted-foreground mt-2 whitespace-pre-wrap",children:Y.content}),Y.video_url&&e.jsxs("a",{href:Y.video_url,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-xs text-primary hover:underline mt-2",children:[e.jsx(ua,{className:"w-3 h-3"})," View video"]})]})})},Y.id))})]})})}),e.jsx(Xt,{value:"referrals",className:"mt-4",children:e.jsx(je,{children:e.jsxs(Ie,{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(ul,{className:"w-10 h-10 text-muted-foreground/40 mx-auto mb-3"}),e.jsx("p",{className:"text-sm font-medium",children:"No referrals yet"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"When your client refers a friend, they'll show up here."})]}):e.jsx("div",{className:"space-y-2",children:A.map(Y=>e.jsx(wr,{to:"/mission-control/client-portals?tab=referrals",className:"block border rounded-lg p-3 hover:bg-muted/50 transition-colors",children:e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:Y.friend_name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Y.friend_email||Y.friend_phone||"No contact info"," · ",X$(Y.created_at)]})]}),e.jsx($e,{variant:"outline",className:"text-xs capitalize",children:Y.status})]})},Y.id))})]})})}),e.jsx(Xt,{value:"branding",className:"mt-4",children:e.jsx(je,{children:e.jsx(Ie,{className:"p-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"rounded-lg bg-primary/10 p-3",children:e.jsx(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(Xt,{value:"details",className:"mt-4",children:e.jsx(je,{children:e.jsxs(Ie,{className:"p-6 space-y-4",children:[e.jsx(PM,{label:"Visibility",value:w.visibility}),e.jsx(PM,{label:"Onboarding Required",value:w.require_onboarding?"Yes":"No"}),e.jsx(PM,{label:"Allow Spouse",value:w.allow_spouse?"Yes":"No"}),e.jsx(PM,{label:"Notify Client on Updates",value:w.notify_client?"Yes":"No"}),e.jsx(PM,{label:"Show Post-Close Tips",value:w.show_post_close_tips?"Yes":"No"}),e.jsx(PM,{label:"Slug",value:w.slug,mono:!0}),e.jsx(PM,{label:"Created",value:X$(w.created_at)}),e.jsx(PM,{label:"Last Updated",value:X$(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(Tlt,{open:h,onOpenChange:m,portal:w,dealOwnerId:n||""}),e.jsx(Mlt,{open:f,onOpenChange:g,portalId:w.id,portalSlug:w.slug,notifyClient:w.notify_client}),e.jsx(Plt,{open:x,onOpenChange:y,portal:w,dealName:I}),e.jsx(fc,{open:v,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 Jue({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 PM({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 sQe=[{value:"video_intro",label:"Video Intro",icon:ua,description:"Add an intro video"},{value:"testimonials",label:"Testimonials",icon:PE,description:"Client testimonials carousel"},{value:"specialties",label:"Specialties",icon:Ap,description:"Tags for your specialties"},{value:"custom_links",label:"Custom Links",icon:Wd,description:"Custom CTA buttons"},{value:"social_media",label:"Social Media",icon:Fd,description:"Links to your social profiles"}],uir=["First-Time Buyers","Luxury Homes","Investment Properties","Relocation","New Construction","Condos & Townhomes","Waterfront","Commercial","Land & Lots","Senior Living","Military/VA","Short Sales & Foreclosures"],hir={video_intro:{video_url:""},testimonials:{testimonials:[{name:"",quote:"",role:""}]},specialties:{tags:[]},custom_links:{links:[{label:"",url:""}]},social_media:{platforms:[]}};function aos({cardId:s}){const{data:t,isLoading:n}=RDs(s),r=DDs(),a=FDs(),i=ODs(),[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:hir[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 fo("Remove this block from this card?")&&i.mutate(b.id)},y=(b,w)=>{a.mutate({id:b.id,config:w},{onSuccess:()=>h(null)})},v=b=>sQe.find(w=>w.value===b);return e.jsxs("div",{className:"space-y-3",children:[!t||t.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx("p",{className:"text-muted-foreground mb-4 text-sm",children:"No blocks yet. Add a block to customize this card."}),e.jsxs($,{size:"sm",onClick:()=>o(!0),children:[e.jsx(dn,{className:"h-4 w-4 mr-1"})," Add Block"]})]}):e.jsxs(e.Fragment,{children:[t.map((b,w)=>{const S=v(b.block_type),A=(S==null?void 0:S.icon)||Ap;return e.jsx(je,{className:b.is_visible?"":"opacity-50",children:e.jsx(Ie,{className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ug,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsx(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:mir(b)})]}),e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>g(b,"up"),disabled:w===0,children:e.jsx(Zf,{className:"h-3 w-3"})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>g(b,"down"),disabled:w===t.length-1,children:e.jsx(Dg,{className:"h-3 w-3"})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>f(b),children:b.is_visible?e.jsx(Ca,{className:"h-3 w-3"}):e.jsx($g,{className:"h-3 w-3"})}),e.jsx($,{variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>h(b),children:"Edit"}),e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7 text-destructive",onClick:()=>x(b),children:e.jsx(Hn,{className:"h-3 w-3"})})]})]})})},b.id)}),e.jsxs($,{variant:"outline",size:"sm",className:"w-full",onClick:()=>o(!0),children:[e.jsx(dn,{className:"h-4 w-4 mr-1"})," Add Block"]})]}),e.jsx(zs,{open:l,onOpenChange:o,children:e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Add Block"})}),e.jsx("div",{className:"grid gap-3",children:sQe.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(Sr,{children:[e.jsx($,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx($,{onClick:m,disabled:!c||r.isPending,children:"Add Block"})]})]})}),u&&e.jsx(fir,{block:u,onSave:b=>y(u,b),onClose:()=>h(null)})]})}function mir(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 fir({block:s,onSave:t,onClose:n}){const[r,a]=j.useState(s.config),i=sQe.find(l=>l.value===s.block_type);return e.jsx(zs,{open:!0,onOpenChange:n,children:e.jsxs(Os,{className:"max-w-lg max-h-[80vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsxs(Bs,{children:["Edit ",i==null?void 0:i.label]})}),s.block_type==="video_intro"&&e.jsx(pir,{config:r,onChange:a,cardId:s.card_id}),s.block_type==="testimonials"&&e.jsx(gir,{config:r,onChange:a}),s.block_type==="specialties"&&e.jsx(xir,{config:r,onChange:a}),s.block_type==="custom_links"&&e.jsx(yir,{config:r,onChange:a}),s.block_type==="social_media"&&e.jsx(vir,{config:r,onChange:a}),e.jsxs(Sr,{children:[e.jsx($,{variant:"outline",onClick:n,children:"Cancel"}),e.jsx($,{onClick:()=>t(r),children:"Save"})]})]})})}function pir({config:s,onChange:t,cardId:n}){var f,g;const[r,a]=j.useState(""),[i,l]=j.useState((f=s.video_url)!=null&&f.includes("youtube")||(g=s.video_url)!=null&&g.includes("youtu.be")?"youtube":"library"),{data:o}=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:y}=await q.from("agent_videos").select("id, title, bunny_video_id, thumbnail_url, playback_url, created_at").eq("owner_user_id",o).eq("is_deleted",!1).eq("status","ready").order("created_at",{ascending:!1});if(y)throw y;return x||[]},enabled:!!o}),u=(c==null?void 0:c.filter(x=>!r||(x.title||"").toLowerCase().includes(r.toLowerCase())))||[],h=s.bunny_video_id,m=x=>{var w;const y=(w=x.playback_url)==null?void 0:w.match(/\/(?:play|embed)\/(\d+)\//),b=`https://iframe.mediadelivery.net/embed/${y?y[1]:"570924"}/${x.bunny_video_id}?autoplay=false&responsive=true`;t({...s,video_url:b,bunny_video_id:x.bunny_video_id,video_source:"library"})};return e.jsx("div",{className:"space-y-4",children:e.jsxs(ha,{value:i,onValueChange:l,children:[e.jsxs(ma,{className:"w-full",children:[e.jsx(Zt,{value:"library",className:"flex-1",children:"Video Library"}),e.jsx(Zt,{value:"youtube",className:"flex-1",children:"YouTube URL"})]}),e.jsxs(Xt,{value:"library",className:"space-y-3 mt-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Zr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search videos...",value:r,onChange:x=>a(x.target.value),className:"pl-9"})]}),e.jsx(uo,{className:"h-[240px]",children:d?e.jsxs("div",{className:"space-y-2",children:[e.jsx(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:y=>{var v;y.currentTarget.style.display="none",(v=y.currentTarget.nextElementSibling)==null||v.classList.remove("hidden")}}):null,e.jsx("div",{className:`h-10 w-16 rounded bg-muted flex items-center justify-center flex-shrink-0 ${x.thumbnail_url?"hidden":""}`,children:e.jsx(ua,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"text-sm font-medium truncate flex-1",children:x.title||"Untitled Video"}),h===x.bunny_video_id&&e.jsx(ca,{className:"h-4 w-4 text-primary flex-shrink-0"})]},x.id))})})]}),e.jsx(Xt,{value:"youtube",className:"space-y-3 mt-3",children:e.jsxs("div",{children:[e.jsx(ee,{children:"YouTube URL"}),e.jsx(pe,{placeholder:"https://www.youtube.com/watch?v=...",value:s.video_source==="youtube"&&s.video_url||"",onChange:x=>t({...s,video_url:x.target.value,bunny_video_id:null,video_source:"youtube"})}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Paste a YouTube video link"})]})})]})})}function gir({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(Ie,{className:"p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(ee,{className:"text-xs font-medium",children:["Testimonial ",o+1]}),n.length>1&&e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6 text-destructive",onClick:()=>i(o),children:e.jsx(Hn,{className:"h-3 w-3"})})]}),e.jsx(pe,{placeholder:"Client name",value:l.name,onChange:c=>r(o,"name",c.target.value)}),e.jsx(pe,{placeholder:"Role/title (optional)",value:l.role||"",onChange:c=>r(o,"role",c.target.value)}),e.jsx("textarea",{className:"w-full min-h-[60px] rounded-md border border-input bg-background px-3 py-2 text-sm",placeholder:"Their testimonial quote...",value:l.quote,onChange:c=>r(o,"quote",c.target.value)})]})},o)),e.jsxs($,{variant:"outline",size:"sm",onClick:a,className:"w-full",children:[e.jsx(dn,{className:"h-4 w-4 mr-1"})," Add Testimonial"]})]})}function xir({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:uir.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 yir({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(Hn,{className:"h-3 w-3"})})]},o)),e.jsxs($,{variant:"outline",size:"sm",onClick:a,className:"w-full",children:[e.jsx(dn,{className:"h-4 w-4 mr-1"})," Add Link"]})]})}const sEt=[{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 vir({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=sEt.filter(c=>!n.find(d=>d.platform===c.value)),o=c=>{const d=nGe[c],u=sEt.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(Hn,{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=nGe[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 bir({slug:s,agentName:t}){const n=j.useRef(null),r=`https://cards.relevelup.com/${s}`,a=j.useCallback(()=>{var h;const i=(h=n.current)==null?void 0:h.querySelector("svg");if(!i)return;const l=document.createElement("canvas"),o=1024;l.width=o,l.height=o;const c=l.getContext("2d");if(!c)return;const d=new XMLSerializer().serializeToString(i),u=new Image;u.onload=()=>{c.fillStyle="#ffffff",c.fillRect(0,0,o,o),c.drawImage(u,0,0,o,o);const m=document.createElement("a");m.download=`${s}-qr-code.png`,m.href=l.toDataURL("image/png"),m.click(),re.success("QR code downloaded!")},u.src="data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent(d)))},[s]);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(ee,{className:"text-sm font-medium",children:"QR Code"}),e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{ref:n,className:"bg-white p-3 rounded-lg border shadow-sm shrink-0",children:e.jsx(uk,{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(xi,{className:"h-3.5 w-3.5"}),"Download PNG"]})]})]})]})}function cUe(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 _ir(){const{user:s}=bs(),{data:t,isLoading:n}=PDs(s==null?void 0:s.id),r=FK(),[a,i]=j.useState(null),l=j.useMemo(()=>a||(t?cUe(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(jir,{userId:s==null?void 0:s.id})});const o=l||cUe(t),c=d=>{i(u=>{const h=u||cUe(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(Air,{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(XN,{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(wir,{card:t,form:o})})]})})]})})}function wir({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(Jtt,{card:r})})}function jir({userId:s}){var c;const[t,n]=j.useState(""),r=U7t(),{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){re.error("Please enter a URL slug for your card");return}r.mutate({user_id:s,slug:d,is_published:!0},{onSuccess:()=>re.success("Your digital card has been created!")})},o=[{icon:dl,title:"Shareable Link",desc:"One link that works everywhere"},{icon:eg,title:"Lead Capture",desc:"Collect leads automatically"},{icon: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(Nn,{className:"h-3.5 w-3.5"}),"New Feature"]}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold mb-3 tracking-tight",children:"Your Digital Business Card"}),e.jsx("p",{className:"text-primary-foreground/80 text-lg max-w-md leading-relaxed",children:"Ditch the paper. Share a beautiful, interactive card that captures leads and makes a lasting impression."})]})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3 mb-8",children:o.map(d=>e.jsxs("div",{className:"flex items-start gap-3 p-4 rounded-xl border bg-card hover:shadow-md transition-shadow",children:[e.jsx("div",{className:"mt-0.5 p-2 rounded-lg bg-primary/10 shrink-0",children:e.jsx(d.icon,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-sm",children:d.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:d.desc})]})]},d.title))}),e.jsxs(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(Gn,{children:"Choose a URL slug — this is the link you'll share with clients"})]}),e.jsxs(Ie,{className:"p-6 pt-2 space-y-5",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm font-medium",children:"Your Card URL"}),e.jsxs("div",{className:"flex items-center gap-0 mt-1.5",children:[e.jsx("span",{className:"inline-flex items-center px-3 h-10 rounded-l-md border border-r-0 bg-muted text-sm text-muted-foreground whitespace-nowrap",children:"cards.relevelup.com/"}),e.jsx(pe,{value:t||i,onChange:d=>n(d.target.value),placeholder:"your-name",className:"rounded-l-none"})]})]}),e.jsxs($,{onClick:l,disabled:r.isPending,className:"w-full h-11 text-base font-semibold",size:"lg",children:[e.jsx(Nn,{className:"h-4 w-4 mr-2"}),r.isPending?"Creating...":"Create My Card"]})]})]})]})}function Nir({card:s}){const n=`https://cards.relevelup.com/${s.slug}`,r=()=>{navigator.clipboard.writeText(n),re.success("Card link copied!")};return e.jsx("div",{className:"rounded-xl border bg-card p-5",children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h1",{className:"text-xl font-bold",children:"My Digital Card"}),e.jsx($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(dl,{className:"h-3.5 w-3.5"}),"cards.relevelup.com/",s.slug]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{variant:"outline",size:"sm",onClick:r,className:"gap-1.5",children:[e.jsx(Ha,{className:"h-3.5 w-3.5"})," Copy Link"]}),e.jsx($,{size:"sm",asChild:!0,className:"gap-1.5",children:e.jsxs("a",{href:n,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Fr,{className:"h-3.5 w-3.5"})," Preview"]})})]})]})})}function kir({userId:s}){const t=Wt(),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,y]=j.useState(!1),v=d??(o==null?void 0:o.name)??"",b=h??(o==null?void 0:o.phone)??"",w=f??(o==null?void 0:o.email)??"",S=o==null?void 0:o.avatar_url,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"]}),re.success("Profile updated!")},onError:()=>re.error("Failed to update profile")}),P=()=>{const O={};if(d!==null&&d!==(o==null?void 0:o.name)&&(O.name=d),h!==null&&h!==(o==null?void 0:o.phone)&&(O.phone=h||null),f!==null&&f!==(o==null?void 0:o.email)&&(O.email=f),Object.keys(O).length===0){re.info("No changes to save");return}I.mutate(O)},R=O=>{var V;const U=(V=O.target.files)==null?void 0:V[0];if(!U)return;if(!U.type.startsWith("image/")){re.error("Please select an image file");return}const W=new FileReader;W.onloadend=()=>{l(W.result),a(!0)},W.readAsDataURL(U),O.target.value=""},D=async O=>{y(!0);try{const{data:U}=await q.storage.from("avatars").list(`${s}`);U&&U.length>0&&await q.storage.from("avatars").remove(U.map(X=>`${s}/${X.name}`));const W=`${s}/avatar.jpg`,{error:V}=await q.storage.from("avatars").upload(W,O,{upsert:!0,contentType:"image/jpeg"});if(V)throw V;const{data:G}=q.storage.from("avatars").getPublicUrl(W),Y=G.publicUrl+"?t="+Date.now();await q.from("profiles").update({avatar_url:Y}).eq("id",s),t.invalidateQueries({queryKey:["card-editor-profile",s]}),t.invalidateQueries({queryKey:["card-preview-profile",s]}),t.invalidateQueries({queryKey:["agent-card-user"]}),re.success("Photo updated!")}catch{re.error("Failed to upload photo")}finally{y(!1)}};return c?e.jsx(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(Ie,{className:"p-5 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(ee,{className:"text-sm font-semibold",children:"Profile Info"}),E&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-amber-600 dark:text-amber-400 font-medium",children:[e.jsx(ll,{className:"h-3 w-3"}),"Missing info — complete below so your card looks great"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground -mt-3",children:"This info shows on your digital card and updates your profile everywhere."}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"relative group cursor-pointer",onClick:()=>{var O;return(O=n.current)==null?void 0:O.click()},children:[e.jsxs(Oa,{className:"h-16 w-16 ring-2 ring-muted",children:[e.jsx(Ii,{src:S||void 0,alt:v}),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(Sx,{className:"h-5 w-5 text-white"})}),e.jsx("input",{ref:n,type:"file",accept:"image/*",className:"hidden",onChange:R})]}),e.jsxs("div",{className:"flex-1 space-y-0.5",children:[e.jsx("p",{className:"text-sm font-medium",children:x?"Uploading...":S?"Tap to change photo":"Add a profile photo"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This photo appears on your card, profile, and community posts"})]})]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs font-medium text-muted-foreground",children:"Full Name"}),e.jsx(pe,{value:v,onChange:O=>u(O.target.value),placeholder:"Your full name",className:"h-10"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs font-medium text-muted-foreground",children:"Phone Number"}),e.jsx(pe,{value:b,onChange:O=>m(O.target.value),placeholder:"(555) 123-4567",className:"h-10",type:"tel"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs font-medium text-muted-foreground",children:"Email"}),e.jsx(pe,{value:w,onChange:O=>g(O.target.value),placeholder:"you@example.com",className:"h-10",type:"email"})]})]})]}),e.jsx($,{variant:"outline",size:"sm",onClick:P,disabled:I.isPending,className:"w-full",children:I.isPending?"Saving...":"Update Profile Info"})]})}),e.jsx(Xnt,{open:r,onClose:()=>a(!1),imageSrc:i,onCropComplete:D,aspectRatio:1})]})}function Sir({form:s,setForm:t,userId:n}){const[r,a]=j.useState(null),[i,l]=j.useState(s.brokerage_logo_url?"logo":"name"),[o,c]=j.useState(s.team_logo_url?"logo":"name"),d=f=>{l(f),t(f==="name"?g=>({...g,brokerage_logo_url:""}):g=>({...g,brokerage_display_name:""}))},u=f=>{c(f),t(f==="name"?g=>({...g,team_logo_url:""}):g=>({...g,team_name:""}))},h=async(f,g)=>{var y;const x=(y=f.target.files)==null?void 0:y[0];if(x){if(!x.type.startsWith("image/")){re.error("Please select an image file");return}a(g);try{const v=x.name.split(".").pop()||"png",w=`${n}/${g==="brokerage_logo_url"?"brokerage-logo":"team-logo"}.${v}`,{error:S}=await q.storage.from("card-logos").upload(w,x,{upsert:!0});if(S)throw S;const{data: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:""})),re.success("Logo uploaded!")}catch{re.error("Failed to upload logo")}finally{a(null),f.target.value=""}}},m=f=>{t(g=>({...g,[f]:""}))};return e.jsx(je,{children:e.jsxs(Ie,{className:"p-5 space-y-5",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm font-semibold",children:"Brokerage & Team Branding"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Choose either a name or a logo for each — not both."})]}),e.jsxs("div",{className:"space-y-3 p-3 rounded-lg bg-muted/30 border",children:[e.jsx(ee,{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Brokerage"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{type:"button",variant:i==="name"?"default":"outline",size:"sm",className:"text-xs",onClick:()=>d("name"),children:"Use Name"}),e.jsx($,{type:"button",variant:i==="logo"?"default":"outline",size:"sm",className:"text-xs",onClick:()=>d("logo"),children:"Use Logo"})]}),i==="name"?e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs font-medium text-muted-foreground",children:"Brokerage Name"}),e.jsx(pe,{value:s.brokerage_display_name,onChange:f=>t(g=>({...g,brokerage_display_name:f.target.value})),placeholder:"e.g. Keller Williams Realty",className:"h-10"})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsx(ee,{className:"text-xs font-medium text-muted-foreground",children:"Brokerage Logo"}),e.jsxs("div",{className:"flex items-center gap-3",children:[s.brokerage_logo_url?e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:s.brokerage_logo_url,alt:"Brokerage logo",style:{height:`${s.brokerage_logo_size||56}px`},className:"max-w-[200px] object-contain rounded border bg-white p-1"}),e.jsx("button",{onClick:()=>m("brokerage_logo_url"),className:"absolute -top-1.5 -right-1.5 h-5 w-5 rounded-full bg-destructive text-destructive-foreground text-xs flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity",children:"×"})]}):null,e.jsxs("label",{className:"cursor-pointer",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-md border text-xs font-medium hover:bg-muted transition-colors",children:[e.jsx(Sx,{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(Nx,{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(Sx,{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(Nx,{value:[s.team_logo_size||56],onValueChange:([f])=>t(g=>({...g,team_logo_size:f})),min:24,max:120,step:4})]})]})]})]})})}function Cir({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 Air({card:s,form:t,setForm:n}){var x;const r=q7t(),a=Wt(),{data:i}=V7t(s.id),[l,o]=j.useState(s.slug),[c,d]=j.useState(!1),[u,h]=j.useState("idle"),m=j.useRef(JSON.stringify(t)),f=j.useRef(null);j.useEffect(()=>{const y=JSON.stringify(t);if(y!==m.current)return f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{h("saving"),r.mutate({id:s.id,...t,is_published:!0,title:t.title||null,positioning_statement:t.positioning_statement||null,bio:t.bio||null,review_snippet:t.review_snippet||null,review_source_url:t.review_source_url||null,booking_url:t.booking_url||null,custom_cta_label:t.custom_cta_label||null,brokerage_display_name:t.brokerage_display_name||null,brokerage_logo_url:t.brokerage_logo_url||null,brokerage_logo_size:t.brokerage_logo_size,team_name:t.team_name||null,team_logo_url:t.team_logo_url||null,team_logo_size:t.team_logo_size,bold_theme_colors:t.bold_theme_colors||null,display_email:t.display_email||null},{onSuccess:()=>{m.current=y,h("saved"),setTimeout(()=>h("idle"),2e3)},onError:()=>h("idle")})},1500),()=>{f.current&&clearTimeout(f.current)}},[t]);const g=async()=>{const y=l.trim().toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/(^-|-$)/g,"");if(!y){re.error("Please enter a valid URL");return}if(y===s.slug){re.info("No changes to save");return}d(!0);try{const{data:v}=await q.from("agent_cards").select("id").eq("slug",y).neq("id",s.id).maybeSingle();if(v){re.error("This URL is already taken. Try another one.");return}const{error:b}=await q.from("agent_cards").update({slug:y}).eq("id",s.id);if(b)throw b;o(y),a.invalidateQueries({queryKey:["agent-card"]}),re.success("Card address updated!")}catch{re.error("Failed to update card address")}finally{d(!1)}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs(ha,{defaultValue:"content",children:[e.jsxs(ma,{className:"w-full h-11 p-1",children:[e.jsxs(Zt,{value:"content",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(Nv,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Content"]}),e.jsxs(Zt,{value:"sections",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(Ca,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Sections"]}),e.jsxs(Zt,{value:"blocks",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(eg,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Blocks"]}),e.jsxs(Zt,{value:"qrcode",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(Jp,{className:"h-3.5 w-3.5 hidden sm:inline"}),"QR Code"]}),e.jsxs(Zt,{value:"analytics",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(Pm,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Analytics"]})]}),e.jsxs(Xt,{value:"content",className:"mt-4 space-y-4",children:[e.jsx(kir,{userId:s.user_id}),e.jsx(Sir,{form:t,setForm:n,userId:s.user_id}),e.jsx(je,{children:e.jsxs(Ie,{className:"p-5 space-y-5",children:[e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg bg-muted/50",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm font-semibold",children:"Card Status"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Toggle your card on or off"})]}),e.jsx(Sn,{checked:t.is_published,onCheckedChange:y=>n(v=>({...v,is_published:y}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-sm font-medium",children:"Card Address"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"flex flex-1",children:[e.jsx("span",{className:"inline-flex items-center px-3 rounded-l-md border border-r-0 bg-muted text-muted-foreground text-xs whitespace-nowrap",children:"cards.relevelup.com/"}),e.jsx(pe,{value:l,onChange:y=>o(y.target.value.toLowerCase().replace(/[^a-z0-9-]/g,"-")),placeholder:"your-name",className:"rounded-l-none h-10"})]}),e.jsx($,{variant:"outline",size:"sm",onClick:g,disabled:c||l===s.slug,className:"shrink-0",children:c?"Saving...":"Update"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This is your unique card URL. Only letters, numbers, and dashes allowed."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-sm font-medium",children:"Card Email (Override)"}),e.jsx(pe,{value:t.display_email,onChange:y=>n(v=>({...v,display_email:y.target.value})),placeholder:"you@yourbusiness.com",className:"h-11",type:"email"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Optional — use a different email on your card instead of your sign-in email."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-sm font-medium",children:"Theme"}),e.jsxs(ms,{value:t.theme,onValueChange:y=>n(v=>({...v,theme:y})),children:[e.jsx(us,{className:"h-11",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"standard",children:"✨ Standard — Modern & Clean"}),e.jsx(Ge,{value:"luxury",children:"🌙 Luxury — Dark & Gold"}),e.jsx(Ge,{value:"bold",children:"🔥 Bold — Vibrant & Punchy"}),e.jsx(Ge,{value:"classic",children:"📋 Classic — Professional"})]})]})]}),t.theme==="bold"&&e.jsx(Cir,{form:t,setForm:n}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-sm font-medium",children:"Title / Tagline"}),e.jsx(pe,{value:t.title,onChange:y=>n(v=>({...v,title:y.target.value})),placeholder:"e.g. Luxury Real Estate Specialist",className:"h-11"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Shown below your name on the card"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-sm font-medium",children:"Positioning Statement"}),e.jsx(pe,{value:t.positioning_statement,onChange:y=>n(v=>({...v,positioning_statement:y.target.value})),placeholder:"Your home journey, handled with care.",className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-sm font-medium",children:"Bio"}),e.jsx(Ls,{value:t.bio,onChange:y=>n(v=>({...v,bio:y.target.value})),placeholder:"A short intro about you and what makes you different...",rows:3})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-sm font-medium",children:"Review Snippet"}),e.jsx(pe,{value:t.review_snippet,onChange:y=>n(v=>({...v,review_snippet:y.target.value})),placeholder:"Best agent we've ever worked with...",className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-sm font-medium",children:"Review Source URL"}),e.jsx(pe,{value:t.review_source_url,onChange:y=>n(v=>({...v,review_source_url:y.target.value})),placeholder:"https://g.page/your-business/review",className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-sm font-medium",children:"Booking URL"}),e.jsx(pe,{value:t.booking_url,onChange:y=>n(v=>({...v,booking_url:y.target.value})),placeholder:"https://calendly.com/your-link",className:"h-11"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Leave empty to show a built-in lead form instead"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-sm font-medium",children:"Custom CTA Label"}),e.jsx(pe,{value:t.custom_cta_label,onChange:y=>n(v=>({...v,custom_cta_label:y.target.value})),placeholder:"Book a Call",className:"h-11"})]})]})})]}),e.jsx(Xt,{value:"sections",className:"mt-4",children:e.jsx(je,{children:e.jsx(Ie,{className:"p-5 divide-y",children:[{key:"show_photo",label:"Photo",desc:"Uses the photo from your Profile Info above"},{key:"show_bio",label:"Bio Section",desc:"Display your bio on the card"},{key:"show_credentials",label:"Credentials",desc:"Show star rating and reviews"},{key:"show_social_links",label:"Social Links",desc:"Display your social media links"},{key:"show_save_contact",label:"Save Contact",desc:"Let visitors save you as a contact"},{key:"show_leave_review",label:"Leave Review",desc:"Link to your review page"},{key:"show_refer_friend",label:"Refer a Friend",desc:"Enable referral submissions"}].map(({key:y,label:v,desc:b})=>e.jsxs("div",{className:"flex items-center justify-between py-4 first:pt-0 last:pb-0",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(ee,{className:"text-sm font-medium",children:v}),e.jsx("p",{className:"text-xs text-muted-foreground",children:b})]}),e.jsx(Sn,{checked:t[y],onCheckedChange:w=>n(S=>({...S,[y]:w}))})]},y))})})}),e.jsx(Xt,{value:"blocks",className:"mt-4",children:e.jsx(aos,{cardId:s.id})}),e.jsx(Xt,{value:"analytics",className:"mt-4",children:e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-3 gap-3",children:[{label:"Views",value:(i==null?void 0:i.views)??0,icon:Ca,color:"text-blue-600 bg-blue-100 dark:text-blue-400 dark:bg-blue-900/30"},{label:"Clicks",value:(i==null?void 0:i.clicks)??0,icon: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(y=>e.jsx(je,{className:"overflow-hidden",children:e.jsxs(Ie,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("div",{className:`p-1.5 rounded-md ${y.color}`,children:e.jsx(y.icon,{className:"h-3.5 w-3.5"})}),e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:y.label})]}),e.jsx("div",{className:"text-2xl font-bold",children:y.value})]})},y.label))}),i&&i.leads.length>0&&e.jsxs(je,{children:[e.jsx(St,{className:"pb-3",children:e.jsx(Et,{className:"text-base",children:"Recent Leads"})}),e.jsx(Ie,{className:"pt-0 space-y-2",children:i.leads.slice(0,5).map(y=>e.jsxs("div",{className:"flex items-center justify-between text-sm p-3 rounded-lg bg-muted/50",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:y.name}),y.phone&&e.jsx("span",{className:"text-muted-foreground ml-2",children:y.phone})]}),y.intent&&e.jsx($e,{variant:"secondary",className:"text-xs",children:y.intent})]},y.id))})]}),(!i||i.leads.length===0)&&e.jsx(je,{children:e.jsxs(Ie,{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(Xt,{value:"qrcode",className:"mt-4 space-y-4",children:e.jsx(je,{children:e.jsx(Ie,{className:"p-6",children:e.jsx(bir,{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 Eir(){const s=Wt(),[t,n]=j.useState(""),[r,a]=j.useState(!1),[i,l]=j.useState(!1),[o,c]=j.useState(null),[d,u]=j.useState(!1),[h,m]=j.useState(!1),[f,g]=j.useState(null),[x,y]=j.useState(null),[v,b]=j.useState(0),[w,S]=j.useState(""),[A,E]=j.useState(!1),{data:I,isLoading:P}=st({queryKey:["boldtrail-status"],queryFn:async()=>{const{data:le,error:ne}=await q.functions.invoke("boldtrail-sync",{body:{action:"status"}});if(ne)throw ne;return le}}),R=mt({mutationFn:async le=>{const{data:ne,error:te}=await q.functions.invoke("boldtrail-sync",{body:{action:"save_token",api_token:le}});if(te)throw te;if(ne!=null&&ne.error)throw new Error(ne.error);return ne},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),n(""),re.success("BoldTrail connected successfully!")},onError:le=>{re.error(le.message||"Failed to connect BoldTrail")}}),D=mt({mutationFn:async()=>{const{data:le,error:ne}=await q.functions.invoke("boldtrail-sync",{body:{action:"disconnect"}});if(ne)throw ne;return le},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),re.success("BoldTrail disconnected")},onError:()=>re.error("Failed to disconnect")}),O=mt({mutationFn:async le=>{const{data:ne,error:te}=await q.functions.invoke("boldtrail-sync",{body:{action:"save_direction",sync_direction:le}});if(te)throw te;if(ne!=null&&ne.error)throw new Error(ne.error);return ne},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),re.success("Sync direction saved")},onError:le=>{re.error(le.message||"Failed to save sync direction")}}),U=mt({mutationFn:async()=>{const{data:le,error:ne}=await q.functions.invoke("boldtrail-sync",{body:{action:"detect_owner"}});if(ne)throw ne;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 ne=le.detected_name||le.detected_email||`ID ${le.kvcore_user_id}`;re.success(`Detected your BoldTrail account: ${ne}`)}else if(le.candidates&&le.candidates.length>0){const ne=le.candidates.slice(0,5).map(te=>`${te.id} (${te.count} contacts)`).join(", ");re.warning(`Couldn't auto-detect your ID. Owner IDs found in your contacts: ${ne}. Pick yours and enter it below.`,{duration:12e3}),E(!0)}else re.warning("Couldn't auto-detect your BoldTrail user ID. Please find it in BoldTrail (My Profile URL) and enter it manually."),E(!0)},onError:le=>re.error(le.message||"Detection failed")}),W=mt({mutationFn:async le=>{const{data:ne,error:te}=await q.functions.invoke("boldtrail-sync",{body:{action:"save_owner_settings",...le}});if(te)throw te;if(ne!=null&&ne.error)throw new Error(ne.error);return ne},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),re.success("Settings saved"),E(!1)},onError:le=>re.error(le.message||"Failed to save settings")}),V=mt({mutationFn:async()=>{const{data:le,error:ne}=await q.functions.invoke("boldtrail-sync",{body:{action:"sync_preview"}});if(ne)throw ne;if(le!=null&&le.error)throw new Error(le.error);return le},onSuccess:le=>{g(null),c(le),a(!0)},onError:le=>{re.error(le.message||"Failed to generate sync preview")}}),G=mt({mutationFn:async()=>{y("Initializing sync..."),b(5);const{data:le,error:ne}=await q.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"init",sync_direction:ae}});if(ne)throw ne;if(le!=null&&le.error)throw new Error(le.error);const te=le;let J=te.sync_log_id,ce=te.next_phase,_e=te.next_offset,he=te.push_total||0,ue=te.pull_total||0,ve=0,Ee=0;for(;ce!=="finalize";){const Fe=he+ue;ce==="fetch_bt"?y("Fetching BoldTrail contacts..."):ce==="analyze"?(y("Analyzing contacts..."),b(15)):ce==="push"?(y(`Pushing contacts to BoldTrail... (${ve}/${he})`),b(Fe>0?ve/Fe*100:0)):ce==="pull"&&(y(`Pulling contacts from BoldTrail... (${Ee}/${ue})`),b(Fe>0?(he+Ee)/Fe*100:0));const{data:ke,error:Be}=await q.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:ce,offset:_e,sync_log_id:J,sync_direction:ae}});if(Be)throw Be;if(ke!=null&&ke.error)throw new Error(ke.error);const Ne=ke;ve+=Ne.chunk_pushed||0,Ee+=Ne.chunk_pulled||0,Ne.push_total!==void 0&&(he=Ne.push_total||0),Ne.pull_total!==void 0&&(ue=Ne.pull_total||0),Ne.progress&&y(Ne.progress),ce==="pull"&&ue>0?b(Math.min(95,Ee/ue*100)):ce==="push"&&he>0&&b(Math.min(95,ve/he*100)),ce=Ne.next_phase,_e=Ne.next_offset}y("Finalizing sync..."),b(95);const{data:Se,error:Le}=await q.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"finalize",sync_log_id:J,sync_direction:ae}});if(Le)throw Le;return b(100),Se},onSuccess:le=>{y(null),b(0),a(!1),s.invalidateQueries({queryKey:["boldtrail-status"]}),s.invalidateQueries({queryKey:["contacts"]}),s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),s.invalidateQueries({queryKey:["contacts-last-touch"]}),re.success(`Sync complete! Pushed ${le.contacts_pushed||0}, pulled ${le.contacts_pulled||0}, skipped ${le.contacts_skipped||0} duplicates.`)},onError:le=>{y(null),b(0),re.error(le.message||"Sync failed")}}),Y=I==null?void 0:I.connected,X=(I==null?void 0:I.sync_direction)||"bidirectional",ae=f??X;return e.jsxs(e.Fragment,{children:[e.jsxs(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(zy,{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",Y&&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(Gn,{children:"Sync contacts bidirectionally between Agent OS and your BoldTrail (kvCORE) CRM."})]})]})}),e.jsx(Ie,{children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-2 text-sm text-muted-foreground",children:[e.jsx(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"})]}),Y?e.jsxs("div",{className:"space-y-3 mt-4",children:[e.jsx("div",{className:"rounded-lg border p-3 space-y-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:"BoldTrail Connected"}),(I==null?void 0:I.last_sync_at)&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Last sync: ",new Date(I.last_sync_at).toLocaleString(),I.last_sync_status&&e.jsx($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(Tg,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Hn,{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(m2,{className:"h-4 w-4 mt-0.5 text-emerald-600 shrink-0"}),e.jsxs("div",{className:"flex-1 space-y-1",children:[e.jsx("p",{className:"text-sm font-medium",children:"Include contacts without an email address"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Phone or name-only leads come across too. Turn this off to sync only contacts that have an email address."})]}),e.jsx(Sn,{checked:(I==null?void 0:I.sync_include_no_email)!==!1,onCheckedChange: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(m2,{className:"h-4 w-4 mt-0.5 text-emerald-600 shrink-0"}),e.jsxs("div",{className:"flex-1 space-y-1",children:[e.jsx("p",{className:"text-sm font-medium",children:"Only sync contacts I own in BoldTrail"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"If your token has access to the whole brokerage's contacts, turn this on to sync just the contacts assigned to you."})]}),e.jsx(Sn,{checked:!!(I!=null&&I.sync_only_owned),onCheckedChange: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(ro,{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(ZMe,{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(ro,{className:"h-4 w-4 animate-spin"}):e.jsx(Ca,{className:"h-4 w-4"}),"Preview Sync"]})})]}):e.jsxs("div",{className:"mt-4 space-y-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{type:"password",placeholder:"Paste your BoldTrail API token",value:t,onChange: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(ro,{className:"h-4 w-4 animate-spin mr-2"}):null,"Connect"]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Find your API token in BoldTrail → Lead Engine → Lead Dropbox → My API Tokens. Generate a ",e.jsx("strong",{children:"Contacts"})," scope token."]})]})]})})]}),e.jsx(zs,{open:r,onOpenChange:le=>{G.isPending||a(le)},children:e.jsxs(Os,{className:"sm:max-w-lg",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(zy,{className:"h-5 w-5 text-emerald-600"}),"Sync Preview"]}),e.jsx(Pr,{children:"Review what will happen when you sync your contacts."})]}),o&&(()=>{const le=ae==="pull_only"?0:o.to_push,ne=ae==="push_only"?0:o.to_pull;return e.jsxs("div",{className:"space-y-4",children:[e.jsx(ZMe,{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(m2,{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:ne}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(Dg,{className:"h-3 w-3"})," Pull to Agent OS"]})]}),e.jsxs("div",{className:"rounded-lg border p-3 text-center",children:[e.jsx("p",{className:"text-2xl font-bold text-muted-foreground",children:o.already_synced}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(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:v||10,className:"h-2"}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:x||"Sync in progress..."})]}),le>0&&e.jsxs(v1,{open:d,onOpenChange:u,children:[e.jsx(b1,{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(_1,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[o.push_preview.map((te,J)=>e.jsxs("div",{className:"px-3 py-1.5 text-xs flex justify-between",children:[e.jsx("span",{className:"font-medium",children:te.name||"No name"}),e.jsx("span",{className:"text-muted-foreground",children:te.email})]},J)),o.to_push>20&&e.jsxs("div",{className:"px-3 py-1.5 text-xs text-muted-foreground text-center",children:["...and ",o.to_push-20," more"]})]})})]}),ne>0&&e.jsxs(v1,{open:h,onOpenChange:m,children:[e.jsx(b1,{asChild:!0,children:e.jsxs($,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Dg,{className:"h-3 w-3 text-blue-600"}),ne," contacts to pull from BoldTrail"]}),e.jsx(wl,{className:`h-3 w-3 transition-transform ${h?"rotate-180":""}`})]})}),e.jsx(_1,{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&&ne===0&&e.jsx("div",{className:"text-center py-4 text-sm text-muted-foreground",children:"✅ Everything is already in sync! No contacts to transfer."}),e.jsxs("div",{className:"flex gap-2 justify-end pt-2",children:[e.jsx($,{variant:"outline",onClick:()=>a(!1),disabled:G.isPending,children:"Cancel"}),e.jsxs($,{onClick:()=>G.mutate(),disabled:G.isPending||le===0&&ne===0,className:"gap-2",children:[G.isPending?e.jsx(ro,{className:"h-4 w-4 animate-spin"}):e.jsx(zy,{className:"h-4 w-4"}),G.isPending?"Syncing...":"Sync Now"]})]})]})})()]})}),e.jsx(zs,{open:i,onOpenChange:l,children:e.jsxs(Os,{className:"sm:max-w-2xl p-0 overflow-hidden",children:[e.jsx(Us,{className:"p-6 pb-0",children:e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(zy,{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 Q$=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 Tir(){const s=Wt(),[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 Q$({action:"status"})}),x=()=>s.invalidateQueries({queryKey:["lofty-status"]}),y=mt({mutationFn:async()=>Q$({action:"save_token",api_token:t.trim()}),onSuccess:E=>{re.success(E!=null&&E.contact_count?`Connected to Lofty — ${E.contact_count} contacts found`:"Connected to Lofty"),n(""),x()},onError:E=>re.error(E.message)}),v=mt({mutationFn:async()=>Q$({action:"disconnect"}),onSuccess:()=>{re.success("Lofty disconnected"),x()},onError:E=>re.error(E.message)}),b=mt({mutationFn:async E=>Q$({action:"save_settings",...E}),onSuccess:()=>x(),onError:E=>re.error(E.message)}),w=mt({mutationFn:async()=>Q$({action:"detect_owner"}),onSuccess:E=>{const I=(E==null?void 0:E.candidates)||[];m(I),I.length===0?re.info("No assigned-agent IDs found on your Lofty contacts."):I.length===1?(b.mutate({lofty_user_id:I[0].id}),re.success(`Using Lofty agent ID ${I[0].id}`)):re.success("Pick which Lofty agent ID is yours below.")},onError:E=>re.error(E.message)}),S=async()=>{l(!0),c(2),u("Starting Lofty sync…");try{let E="start",I=0,P=null,R=0;for(;E&&R<400;){R++;const D=await Q$({action:"sync",phase:E,offset:I,sync_log_id:P});P=D.sync_log_id||P,D.progress&&u(D.progress),c(O=>Math.min(95,O+4)),E=D.next_phase,I=D.next_offset||0,E||(c(100),u(D.message||"Sync complete"),re.success(D.message||"Lofty sync complete"))}}catch(E){re.error(E.message||"Lofty sync failed"),u(null)}finally{l(!1),setTimeout(()=>c(0),2500),x()}},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(Gn,{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(Tg,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon","aria-label":"Disconnect Lofty",children:e.jsx(Hn,{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:()=>v.mutate(),children:"Disconnect"})]})]})]})]})}),e.jsx(Ie,{className:"space-y-5",children:g?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Ct,{className:"h-4 w-4 animate-spin"})," Loading…"]}):A?e.jsxs("div",{className:"space-y-5",children:[e.jsx(ZMe,{value:(f==null?void 0:f.sync_direction)||"pull_only",onChange:E=>b.mutate({sync_direction:E}),size:"sm"}),e.jsxs("div",{className:"space-y-3 rounded-lg border p-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Only my contacts"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Skip team/brokerage contacts assigned to other Lofty agents."})]}),e.jsx(Sn,{checked:!!(f!=null&&f.sync_only_owned),onCheckedChange:E=>b.mutate({sync_only_owned:E})})]}),(f==null?void 0:f.sync_only_owned)&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{size:"sm",variant:"outline",onClick:()=>w.mutate(),disabled:w.isPending,children:[w.isPending?e.jsx(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(Sn,{checked:!!(f!=null&&f.import_notes),onCheckedChange:E=>b.mutate({import_notes:E})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"lofty-tags",className:"text-sm",children:"Tag filter (optional)"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{id:"lofty-tags",placeholder:((f==null?void 0:f.pull_tag_filter)||[]).join(", ")||"e.g. Sphere, Buyer",value:r,onChange:E=>a(E.target.value)}),e.jsx($,{variant:"outline",onClick:()=>b.mutate({pull_tag_filter:r.split(",").map(E=>E.trim()).filter(Boolean)}),children:"Save"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Leave empty to import every contact. Comma-separated Lofty tags."})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs($,{onClick:S,disabled:i,children:[i?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(ro,{className:"h-4 w-4"}),i?"Syncing…":"Sync Now"]}),(f==null?void 0:f.last_sync_at)&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Last sync ",new Date(f.last_sync_at).toLocaleString("en-US",{timeZone:"America/New_York"})]})]}),(i||o>0)&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(Yi,{value:o}),d&&e.jsx("p",{className:"text-xs text-muted-foreground",children:d})]}),(f==null?void 0:f.last_sync_message)&&!i&&e.jsx("p",{className:"text-xs text-muted-foreground",children:f.last_sync_message})]}),((f==null?void 0:f.logs)||[]).length>0&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"text-sm font-medium",children:"Recent syncs"}),e.jsx("div",{className:"space-y-1",children:f.logs.map(E=>e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 rounded-md border px-3 py-2 text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:new Date(E.created_at).toLocaleString("en-US",{timeZone:"America/New_York"})}),e.jsxs("span",{children:[E.contacts_pulled," imported · ",E.contacts_pushed," pushed ·"," ",E.contacts_skipped," skipped"]}),e.jsx($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:()=>y.mutate(),disabled:t.trim().length<10||y.isPending,children:[y.isPending?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(JN,{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(Fr,{className:"ml-1 h-3 w-3"})]})})]})]})})]})}function Mir(){const s=Wt(),[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:y}=await q.functions.invoke("followupboss-sync",{body:{action:"status"}});if(y)throw y;return x}}),h=mt({mutationFn:async x=>{const{data:y,error:v}=await q.functions.invoke("followupboss-sync",{body:{action:"save_token",api_key:x}});if(v)throw v;if(y!=null&&y.error)throw new Error(y.error);return y},onSuccess:()=>{re.success("Connected to Follow Up Boss"),n(""),s.invalidateQueries({queryKey:["fub-status"]})},onError:x=>re.error(x.message)}),m=mt({mutationFn:async()=>{const{error:x}=await q.functions.invoke("followupboss-sync",{body:{action:"disconnect"}});if(x)throw x},onSuccess:()=>{re.success("Disconnected"),s.invalidateQueries({queryKey:["fub-status"]})}}),f=mt({mutationFn:async x=>{const{error:y}=await q.functions.invoke("followupboss-sync",{body:{action:"set_direction",sync_direction:x}});if(y)throw y},onSuccess:()=>s.invalidateQueries({queryKey:["fub-status"]})}),g=async()=>{a(!0),l(0),c("Pulling from FUB…");let x=0,y=0,v=0,b=0;try{for(;;){const{data:E,error:I}=await q.functions.invoke("followupboss-sync",{body:{action:"sync",offset:x}});if(I)throw I;if(E!=null&&E.error)throw new Error(E.error);y+=E.chunk_created||0,v+=E.chunk_updated||0,b+=E.chunk_skipped||0,x=E.next_offset;const P=E.total?Math.min(100,Math.round(x/E.total*100)):100;if(l(P),c(`Pulling · ${x} / ${E.total||"?"}`),E.done)break;await new Promise(R=>setTimeout(R,400))}let w=0,S=0;if((d==null?void 0:d.sync_direction)==="bidirectional"){let E=0;for(l(0),c("Pushing to FUB…");;){const{data:I,error:P}=await q.functions.invoke("followupboss-sync",{body:{action:"push",offset:E}});if(P)throw P;if(I!=null&&I.error)throw new Error(I.error);w+=I.chunk_pushed||0,S+=I.chunk_failed||0,E=I.next_offset;const R=I.total?Math.min(100,Math.round(E/I.total*100)):100;if(l(R),c(`Pushing · ${E} / ${I.total||"?"}`),I.done)break;await new Promise(D=>setTimeout(D,400))}}const A=w||S?` · pushed ${w}${S?`, ${S} failed`:""}`:"";re.success(`Sync complete · ${y} new, ${v} updated${b?`, ${b} skipped`:""}${A}`),s.invalidateQueries({queryKey:["fub-status"]})}catch(w){re.error(w.message||"Sync failed")}finally{a(!1),setTimeout(()=>{l(0),c(null)},2500)}};return e.jsxs(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(JN,{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(Gn,{children:"Sync your Follow Up Boss contacts into Agent OS."})]})})}),e.jsx(Ie,{className:"space-y-4",children:u?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading…"}):d!=null&&d.connected?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Last sync"}),e.jsx("p",{className:"font-medium",children:d.last_sync_at?new Date(d.last_sync_at).toLocaleString():"Never"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"FUB contacts"}),e.jsx("p",{className:"font-medium",children:d.fub_contact_count??"—"})]})]}),d.last_sync_status==="error"&&e.jsx("p",{className:"text-sm text-destructive",children:d.last_sync_message}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border px-3 py-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Two-way sync"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Off = pull from FUB only. On = also push new Agent OS contacts to FUB."})]}),e.jsx(Sn,{checked:d.sync_direction==="bidirectional",onCheckedChange:x=>f.mutate(x?"bidirectional":"pull_only"),disabled:r||f.isPending})]}),o&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(Yi,{value:i}),e.jsx("p",{className:"text-xs text-muted-foreground",children:o})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs($,{onClick:g,disabled:r,children:[e.jsx(ro,{className:`h-4 w-4 mr-2 ${r?"animate-spin":""}`}),r?"Syncing…":"Sync Now"]}),e.jsxs(fc,{children:[e.jsx(Tg,{asChild:!0,children:e.jsxs($,{variant:"outline",disabled:r,children:[e.jsx(Hn,{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(Fr,{className:"h-3 w-3"})]})]})]}),e.jsx($,{onClick:()=>h.mutate(t),disabled:!t.trim()||h.isPending,children:h.isPending?"Connecting…":"Connect"})]})})]})}function Pir(){var V;const s=Wt(),[t,n]=j.useState(""),[r,a]=j.useState(""),[i,l]=j.useState(!1),[o,c]=j.useState(0),[d,u]=j.useState(null),[h,m]=j.useState(!1),[f,g]=j.useState(null),[x,y]=j.useState(!1),[v,b]=j.useState(new Set),{data:w,isLoading:S}=st({queryKey:["cloze-status"],queryFn:async()=>{const{data:G,error:Y}=await q.functions.invoke("cloze-sync",{body:{action:"status"}});if(Y)throw Y;return G}}),A=mt({mutationFn:async()=>{const{data:G,error:Y}=await q.functions.invoke("cloze-sync",{body:{action:"save_token",api_key:t.trim(),account_email:r.trim()}});if(Y)throw Y;if(G!=null&&G.error)throw new Error(G.error);return G},onSuccess:()=>{re.success("Connected to Cloze"),n(""),a(""),s.invalidateQueries({queryKey:["cloze-status"]})},onError:G=>re.error(G.message)}),E=mt({mutationFn:async()=>{const{error:G}=await q.functions.invoke("cloze-sync",{body:{action:"disconnect"}});if(G)throw G},onSuccess:()=>{re.success("Cloze disconnected"),s.invalidateQueries({queryKey:["cloze-status"]})}}),I=mt({mutationFn:async G=>{const{error:Y}=await q.functions.invoke("cloze-sync",{body:{action:"set_direction",sync_direction:G}});if(Y)throw Y},onSuccess:()=>s.invalidateQueries({queryKey:["cloze-status"]})}),P=mt({mutationFn:async G=>{const{error:Y}=await q.functions.invoke("cloze-sync",{body:{action:"set_scope",...G}});if(Y)throw Y},onSuccess:()=>s.invalidateQueries({queryKey:["cloze-status"]})}),R=async()=>{y(!0);try{const{data:G,error:Y}=await q.functions.invoke("cloze-sync",{body:{action:"list_segments"}});if(Y)throw Y;if(G!=null&&G.error)throw new Error(G.error);g(G.segments||[]),b(new Set((w==null?void 0:w.selected_segments)||[])),m(!0)}catch(G){re.error(G.message||"Failed to load segments")}finally{y(!1)}},D=async()=>{const G=Array.from(v);await P.mutateAsync({sync_scope:"segments",selected_segments:G}),re.success(`Saved · ${G.length} segment(s) selected`),m(!1)},O=async()=>{const G=(w==null?void 0:w.sync_direction)||"pull_only";l(!0),c(0);try{if(G==="pull_only"||G==="bidirectional"){u("Pulling from Cloze…");let Y=0,X=0,ae=0;for(;;){const{data:le,error:ne}=await q.functions.invoke("cloze-sync",{body:{action:"sync",offset:Y}});if(ne)throw ne;if(le!=null&&le.error)throw new Error(le.error);if(X+=le.chunk_created||0,ae+=le.chunk_updated||0,Y=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))}re.success(`Pulled · ${X} new, ${ae} updated`)}if(G==="push_only"||G==="bidirectional"){c(0),u("Pushing to Cloze…");let Y=0,X=0,ae=0;for(;;){const{data:le,error:ne}=await q.functions.invoke("cloze-sync",{body:{action:"push",offset:Y}});if(ne)throw ne;if(le!=null&&le.error)throw new Error(le.error);X+=le.chunk_pushed||0,ae+=le.chunk_failed||0,Y=le.next_offset;const te=le.total?Math.min(100,Math.round(Y/le.total*100)):100;if(c(te),u(`Pushing · ${Y} / ${le.total||"?"}`),le.done)break;await new Promise(J=>setTimeout(J,300))}re.success(`Pushed · ${X}${ae?`, ${ae} failed`:""}`)}s.invalidateQueries({queryKey:["cloze-status"]})}catch(Y){re.error(Y.message||"Sync failed")}finally{l(!1),setTimeout(()=>{c(0),u(null)},2e3)}},U=(w==null?void 0:w.sync_scope)||"all",W=((V=w==null?void 0:w.selected_segments)==null?void 0:V.length)||0;return e.jsxs(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(JN,{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(Gn,{children:"Sync contacts between Cloze and Agent OS using your personal Cloze API key."})]})})}),e.jsx(Ie,{className:"space-y-4",children:S?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading…"}):w!=null&&w.connected?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Account"}),e.jsx("p",{className:"font-medium break-all",children:w.account_email})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Last sync"}),e.jsx("p",{className:"font-medium",children:w.last_sync_at?new Date(w.last_sync_at).toLocaleString():"Never"})]})]}),w.last_sync_status==="error"&&e.jsx("p",{className:"text-sm text-destructive",children:w.last_sync_message}),e.jsx("div",{className:"rounded-lg border px-3 py-2 space-y-2",children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Sync direction"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Choose which way contacts should flow."})]}),e.jsxs(ms,{value:w.sync_direction||"pull_only",onValueChange:G=>I.mutate(G),disabled:i||I.isPending,children:[e.jsx(us,{className:"w-[180px]",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"pull_only",children:"Pull from Cloze"}),e.jsx(Ge,{value:"push_only",children:"Push to Cloze"}),e.jsx(Ge,{value:"bidirectional",children:"Two-way sync"})]})]})]})}),e.jsxs("div",{className:"rounded-lg border px-3 py-2 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"What to sync"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:U==="all"?"All Cloze contacts.":`${W} segment${W===1?"":"s"} selected.`})]}),e.jsxs(ms,{value:U,onValueChange:G=>{G==="all"?P.mutate({sync_scope:"all",selected_segments:[]}):(P.mutate({sync_scope:"segments",selected_segments:w.selected_segments||[]}),R())},disabled:i||P.isPending,children:[e.jsx(us,{className:"w-[180px]",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All contacts"}),e.jsx(Ge,{value:"segments",children:"Selected segments"})]})]})]}),U==="segments"&&e.jsxs("div",{children:[e.jsxs($,{variant:"outline",size:"sm",onClick:R,disabled:x,children:[e.jsx(eee,{className:"h-4 w-4 mr-2"}),x?"Loading segments…":"Choose segments"]}),h&&f&&e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsxs("div",{className:"max-h-96 overflow-y-auto rounded-md border divide-y",children:[f.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground p-3",children:"No segments found in your Cloze account."}),f.map(G=>{const Y=v.has(G.id);return e.jsxs("label",{className:"flex items-center gap-3 p-2 cursor-pointer hover:bg-muted/50",children:[e.jsx(ai,{checked:Y,onCheckedChange:X=>{const ae=new Set(v);X?ae.add(G.id):ae.delete(G.id),b(ae)}}),e.jsx("span",{className:"flex-1 text-sm",children:G.name}),G.count!=null&&e.jsx($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 (",v.size,")"]}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>m(!1),children:"Cancel"})]})]})]})]}),d&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(Yi,{value:o}),e.jsx("p",{className:"text-xs text-muted-foreground",children:d})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(fc,{children:[e.jsx(Tg,{asChild:!0,children:e.jsxs($,{disabled:i,children:[e.jsx(ro,{className:`h-4 w-4 mr-2 ${i?"animate-spin":""}`}),i?"Syncing…":"Sync Now"]})}),e.jsxs(sc,{children:[e.jsxs(nc,{children:[e.jsx(ac,{children:"Preview sync"}),e.jsx(ic,{asChild:!0,children:e.jsx(Iir,{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(Tg,{asChild:!0,children:e.jsxs($,{variant:"outline",disabled:i,children:[e.jsx(Hn,{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(Fr,{className:"h-3 w-3"})]})]})]}),e.jsx($,{onClick:()=>A.mutate(),disabled:!t.trim()||!r.trim()||A.isPending,children:A.isPending?"Connecting…":"Connect Cloze"})]})})]})}function Iir({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 Lir(){const s=Wt(),[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:y}=await q.functions.invoke("boomtown-sync",{body:{action:"status"}});if(y)throw y;return x}}),h=mt({mutationFn:async x=>{const{data:y,error:v}=await q.functions.invoke("boomtown-sync",{body:{action:"save_token",api_key:x}});if(v)throw v;if(y!=null&&y.error)throw new Error(y.error);return y},onSuccess:()=>{re.success("Connected to Boomtown"),n(""),s.invalidateQueries({queryKey:["boomtown-status"]})},onError:x=>re.error(x.message)}),m=mt({mutationFn:async()=>{const{error:x}=await q.functions.invoke("boomtown-sync",{body:{action:"disconnect"}});if(x)throw x},onSuccess:()=>{re.success("Disconnected"),s.invalidateQueries({queryKey:["boomtown-status"]})}}),f=mt({mutationFn:async x=>{const{error:y}=await q.functions.invoke("boomtown-sync",{body:{action:"set_direction",sync_direction:x}});if(y)throw y},onSuccess:()=>s.invalidateQueries({queryKey:["boomtown-status"]})}),g=async()=>{a(!0),l(0),c("Pulling from Boomtown…");let x=0,y=0,v=0,b=0;try{for(;;){const{data:E,error:I}=await q.functions.invoke("boomtown-sync",{body:{action:"sync",offset:x}});if(I)throw I;if(E!=null&&E.error)throw new Error(E.error);y+=E.chunk_created||0,v+=E.chunk_updated||0,b+=E.chunk_skipped||0,x=E.next_offset;const P=E.total?Math.min(100,Math.round(x/E.total*100)):100;if(l(P),c(`Pulling · ${x} / ${E.total||"?"}`),E.done)break;await new Promise(R=>setTimeout(R,400))}let w=0,S=0;if((d==null?void 0:d.sync_direction)==="bidirectional"){let E=0;for(l(0),c("Pushing to Boomtown…");;){const{data:I,error:P}=await q.functions.invoke("boomtown-sync",{body:{action:"push",offset:E}});if(P)throw P;if(I!=null&&I.error)throw new Error(I.error);w+=I.chunk_pushed||0,S+=I.chunk_failed||0,E=I.next_offset;const R=I.total?Math.min(100,Math.round(E/I.total*100)):100;if(l(R),c(`Pushing · ${E} / ${I.total||"?"}`),I.done)break;await new Promise(D=>setTimeout(D,400))}}const A=w||S?` · pushed ${w}${S?`, ${S} failed`:""}`:"";re.success(`Sync complete · ${y} new, ${v} updated${b?`, ${b} skipped`:""}${A}`),s.invalidateQueries({queryKey:["boomtown-status"]})}catch(w){re.error(w.message||"Sync failed")}finally{a(!1),setTimeout(()=>{l(0),c(null)},2500)}};return e.jsxs(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(JN,{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(Gn,{children:"Sync your Boomtown contacts into Agent OS."})]})})}),e.jsx(Ie,{className:"space-y-4",children:u?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading…"}):d!=null&&d.connected?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Last sync"}),e.jsx("p",{className:"font-medium",children:d.last_sync_at?new Date(d.last_sync_at).toLocaleString():"Never"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Boomtown contacts"}),e.jsx("p",{className:"font-medium",children:d.boomtown_contact_count??"—"})]})]}),d.last_sync_status==="error"&&e.jsx("p",{className:"text-sm text-destructive",children:d.last_sync_message}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border px-3 py-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Two-way sync"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Off = pull from Boomtown only. On = also push new Agent OS contacts to Boomtown."})]}),e.jsx(Sn,{checked:d.sync_direction==="bidirectional",onCheckedChange:x=>f.mutate(x?"bidirectional":"pull_only"),disabled:r||f.isPending})]}),o&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(Yi,{value:i}),e.jsx("p",{className:"text-xs text-muted-foreground",children:o})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs($,{onClick:g,disabled:r,children:[e.jsx(ro,{className:`h-4 w-4 mr-2 ${r?"animate-spin":""}`}),r?"Syncing…":"Sync Now"]}),e.jsxs(fc,{children:[e.jsx(Tg,{asChild:!0,children:e.jsxs($,{variant:"outline",disabled:r,children:[e.jsx(Hn,{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(Fr,{className:"h-3 w-3"})]})]}),e.jsx($,{onClick:()=>h.mutate(t),disabled:!t.trim()||h.isPending,children:h.isPending?"Connecting…":"Connect"})]})})]})}function ios(){const s=Xn(),[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 une();return(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ses-send-campaign",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${f}`},body:JSON.stringify({action:"check_config"})})).json()}}),h=async()=>{if(!t||!r){re.error("Please fill in From and To email addresses");return}c(!0);try{const f=await une(),x=await(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ses-send-campaign",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${f}`},body:JSON.stringify({action:"test_send",to:t,from_email:r,subject:i,body_html:"

Test Email

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

If you received this, SES is configured correctly! 🎉

"})})).json();x.success?re.success(`Test email sent! Message ID: ${x.messageId}`):re.error(x.error||"Failed to send test email")}catch(f){re.error(f.message||"Failed to send test email")}finally{c(!1)}},m=(d==null?void 0:d.configured)===!0;return e.jsxs(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(mn,{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(Gn,{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(ll,{className:"h-3 w-3"})," Not Configured"]})})]})}),m&&e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-lg border p-4 space-y-3",children:[e.jsx("h4",{className:"font-medium text-sm",children:"Send Test Email"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:'Verify your SES setup by sending a test email. The "From" address must be verified in SES or belong to a verified domain.'}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(ee,{className:"text-xs",children:"From Email"}),e.jsx(pe,{placeholder:"notifications@mail.relevelup.com",value:r,onChange:f=>a(f.target.value),className:"text-sm"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ee,{className:"text-xs",children:"To Email"}),e.jsx(pe,{placeholder:"your@email.com",value:t,onChange:f=>n(f.target.value),className:"text-sm"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ee,{className:"text-xs",children:"Subject"}),e.jsx(pe,{value:i,onChange:f=>l(f.target.value),className:"text-sm"})]})]}),e.jsxs($,{onClick:h,disabled:o,size:"sm",children:[o?e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Kr,{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(Ie,{children:e.jsxs("p",{className:"text-sm text-muted-foreground",children:["AWS SES credentials are not configured. Add ",e.jsx("code",{children:"AWS_SES_ACCESS_KEY_ID"}),", ",e.jsx("code",{children:"AWS_SES_SECRET_ACCESS_KEY"}),", and ",e.jsx("code",{children:"AWS_SES_REGION"})," as secrets to enable."]})})]})}async function dUe(s){const t=await une(),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 Rir({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(da,{className:"h-3 w-3 mr-1"})," Pending — check inbox"]}):s==="failed"||s==="temporary_failure"?e.jsxs($e,{variant:"destructive",children:[e.jsx(ll,{className:"h-3 w-3 mr-1"})," Failed"]}):e.jsxs($e,{variant:"outline",children:[e.jsx(ll,{className:"h-3 w-3 mr-1"})," Not started"]})}function oos({brokerageId:s,onVerifiedSelect:t}){const n=Wt(),[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()=>dUe({action:"request_verification",brokerage_id:s,email:r,display_name:i||void 0}),onSuccess:()=>{n.invalidateQueries({queryKey:["brokerage-verified-senders",s]}),re.success("Verification email sent",{description:`Check ${r} and click the AWS verification link.`}),a(""),l(""),c(!1)},onError:b=>re.error(b.message)}),y=async b=>{var w,S;u(b.id);try{const A=await dUe({action:"check_status",sender_id:b.id});n.invalidateQueries({queryKey:["brokerage-verified-senders",s]}),((w=A.sender)==null?void 0:w.status)==="verified"?re.success(`${b.email} is verified! 🎉`):re.info(`Status: ${((S=A.sender)==null?void 0:S.status)||"unknown"}`)}catch(A){re.error(A.message)}finally{u(null)}},v=mt({mutationFn:async b=>dUe({action:"delete",sender_id:b}),onSuccess:()=>{n.invalidateQueries({queryKey:["brokerage-verified-senders",s]}),re.success("Sender removed"),m(null)},onError:b=>re.error(b.message)});return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium mb-1",children:"Verified Sender Addresses"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Verify any email address (yours or your brokerage's) so recruiting emails can be sent from that address. Anyone managing this brokerage can use these senders."})]}),g?e.jsx("div",{className:"text-xs text-muted-foreground py-3",children:"Loading…"}):f&&f.length>0?e.jsx("div",{className:"space-y-2",children:f.map(b=>e.jsxs("div",{className:"flex items-center justify-between gap-3 p-3 rounded-lg border bg-card",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[e.jsx("div",{className:"h-9 w-9 rounded-full bg-muted flex items-center justify-center shrink-0",children:e.jsx(mn,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-sm font-medium truncate",children:b.email}),e.jsx(Rir,{status:b.status})]}),b.display_name&&e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:['"',b.display_name,'"']})]})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[b.status==="verified"&&t&&e.jsx($,{size:"sm",variant:"outline",onClick:()=>t(b.email),children:"Use"}),b.status!=="verified"&&e.jsx($,{size:"sm",variant:"ghost",onClick:()=>y(b),disabled:d===b.id,title:"Refresh status from AWS",children:d===b.id?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(ro,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>m(b),className:"text-destructive hover:text-destructive",children:e.jsx(Hn,{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(mn,{className:"h-4 w-4 mr-2"}),"Send Verification Email"]}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>{c(!1),a(""),l("")},children:"Cancel"})]})]}):e.jsxs($,{size:"sm",variant:"outline",onClick:()=>c(!0),children:[e.jsx(dn,{className:"h-4 w-4 mr-1"})," Add Sender Address"]}),e.jsx(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&&v.mutate(h.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})})]})}async function uUe(s){const t=await une(),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 Dir({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(da,{className:"h-3 w-3 mr-1"})," Pending — check inbox"]}):s==="failed"||s==="temporary_failure"?e.jsxs($e,{variant:"destructive",children:[e.jsx(ll,{className:"h-3 w-3 mr-1"})," Failed"]}):e.jsxs($e,{variant:"outline",children:[e.jsx(ll,{className:"h-3 w-3 mr-1"})," Not started"]})}function Fir({userId:s,onVerifiedSelect:t}){const n=Wt(),[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()=>uUe({action:"request_verification",scope:"user",email:r,display_name:i||void 0}),onSuccess:b=>{n.invalidateQueries({queryKey:["user-verified-senders",s]}),re.success("Verification email sent",{description:`Check ${r} and click the AWS verification link.`}),b!=null&&b.domain_warning&&re.warning("Heads up about this address",{description:b.domain_warning,duration:15e3}),a(""),l(""),c(!1)},onError:b=>re.error(b.message)}),y=async b=>{var w,S;u(b.id);try{const A=await uUe({action:"check_status",sender_id:b.id});n.invalidateQueries({queryKey:["user-verified-senders",s]}),((w=A.sender)==null?void 0:w.status)==="verified"?re.success(`${b.email} is verified! 🎉`):re.info(`Status: ${((S=A.sender)==null?void 0:S.status)||"unknown"}`)}catch(A){re.error(A.message)}finally{u(null)}},v=mt({mutationFn:async b=>uUe({action:"delete",sender_id:b}),onSuccess:()=>{n.invalidateQueries({queryKey:["user-verified-senders",s]}),re.success("Sender removed"),m(null)},onError:b=>re.error(b.message)});return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium mb-1",children:"Your Verified Sender Addresses"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Verify your email address with Amazon so mass emails can be sent ",e.jsx("em",{children:"from"})," you. Add an address, then click the verification link Amazon sends to that inbox."]})]}),g?e.jsx("div",{className:"text-xs text-muted-foreground py-3",children:"Loading…"}):f&&f.length>0?e.jsx("div",{className:"space-y-2",children:f.map(b=>e.jsxs("div",{className:"flex items-center justify-between gap-3 p-3 rounded-lg border bg-card",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[e.jsx("div",{className:"h-9 w-9 rounded-full bg-muted flex items-center justify-center shrink-0",children:e.jsx(mn,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-sm font-medium truncate",children:b.email}),e.jsx(Dir,{status:b.status})]}),b.display_name&&e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:['"',b.display_name,'"']})]})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[b.status==="verified"&&t&&e.jsx($,{size:"sm",variant:"outline",onClick:()=>t(b.email),children:"Use"}),b.status!=="verified"&&e.jsx($,{size:"sm",variant:"ghost",onClick:()=>y(b),disabled:d===b.id,title:"Refresh status from AWS",children:d===b.id?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(ro,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>m(b),className:"text-destructive hover:text-destructive",children:e.jsx(Hn,{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(mn,{className:"h-4 w-4 mr-2"}),"Send Verification Email"]}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>{c(!1),a(""),l("")},children:"Cancel"})]})]}):e.jsxs($,{size:"sm",variant:"outline",onClick:()=>c(!0),children:[e.jsx(dn,{className:"h-4 w-4 mr-1"})," Add Sender Address"]}),e.jsx(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&&v.mutate(h.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})})]})}function Oir(){var S,A,E,I,P;const{user:s,isBrokerageManager:t,isAdmin:n,managedBrokerages:r,selectedBrokerageId:a}=bs(),i=a||((S=r==null?void 0:r[0])==null?void 0:S.id)||null,l=(t||n)&&!!i,o=Wt(),[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}}),y=((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())||"",v=((I=g==null?void 0:g.display_name)==null?void 0:I.trim())||((P=x==null?void 0:x.name)==null?void 0:P.trim())||"";j.useEffect(()=>{c||(h(y),f(v))},[c,y,v]);const b=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]}),re.success("Reply-to email saved!"),d(!1)},onError:R=>re.error(R.message)}),w=!!y;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(Kr,{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(Gn,{children:"Set the email address where replies from your campaigns will be sent. If you haven't customized it yet, we'll use your profile email."})]})]})}),e.jsxs(Ie,{className:"space-y-3",children:[w&&!c?e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:v||"No display name"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:y})]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>d(!0),children:[e.jsx(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(y),f(v)},children:[e.jsx(pr,{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(Fir,{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(oos,{brokerageId:i})]})]})]})]})}function zir({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 Bir=[{id:"all",label:"All tools",icon:Qf},{id:"crm",label:"Real estate CRMs",icon:y0},{id:"social",label:"Social media",icon:Fd},{id:"communication",label:"Communication",icon:mn},{id:"marketing",label:"AI & marketing",icon:Nn}],$ir={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 Uir({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 bj({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(Uir,{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 qir(){const s=Xn(),{isAdmin:t,user:n}=bs(),{actingAsAgent:r,effectiveUserId:a}=Aae(),i=Wt(),[l,o]=j.useState(!1),[c,d]=j.useState(!1),[u,h]=j.useState(!1),[m,f]=j.useState(!1),[g,x]=j.useState("all"),[y,v]=j.useState(null),{scopeUserId:b,isDelegated:w}=zir({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:Ne}=await q.from("gmail_integrations").select("*").eq("user_id",b).maybeSingle();if(Ne)throw Ne;return Be}}),{data:E}=st({queryKey:["social-accounts",b],enabled:!!b&&!w,queryFn:async()=>{const{data:Be,error:Ne}=await q.from("social_accounts").select("*").eq("user_id",b).order("created_at",{ascending:!1});if(Ne)throw Ne;return Be}}),{data:I}=st({queryKey:["google-business-status",b],enabled:!!b&&!w,queryFn:async()=>{const{data:Be,error:Ne}=await q.functions.invoke("google-business-oauth",{body:{action:"get_status"}});if(Ne)throw Ne;return Be}}),P=mt({mutationFn:async Be=>{const{error:Ne}=await q.functions.invoke("google-business-oauth",{body:{action:"set_primary_location",locationId:Be}});if(Ne)throw Ne},onSuccess:()=>{re.success("Business updated"),i.invalidateQueries({queryKey:["google-business-status",b]}),i.invalidateQueries({queryKey:["social-accounts",b]})},onError:()=>re.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]}),re.success("Google Business disconnected")},onError:()=>re.error("Could not disconnect Google Business")}),D=mt({mutationFn:async()=>{const{data:Be,error:Ne}=await q.functions.invoke("google-business-oauth",{body:{action:"rescan_locations"}});if(Ne)throw Ne;return Be},onSuccess:Be=>{i.invalidateQueries({queryKey:["google-business-status",b]}),Be!=null&&Be.success&&Be.locationsCount?re.success(Be.message??"Locations updated"):re.error((Be==null?void 0:Be.message)??"No business locations were found on this Google account.")},onError:()=>re.error("Could not check Google for your business")}),O=async()=>{if(w){re.error("Account connections must be made by the agent from their own login.");return}f(!0);try{const{data:Be,error:Ne}=await q.functions.invoke("google-business-oauth",{body:{action:"get_auth_url",returnPath:"/mission-control/integrations"}});if(Ne)throw Ne;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),re.error("Failed to start Google connection. Please try again."),f(!1)}},U=async()=>{if(w){re.error("Account connections must be made by the agent from their own login.");return}o(!0);try{const{data:Be,error:Ne}=await q.functions.invoke("gmail-oauth",{body:{action:"get_auth_url"}});if(Ne)throw Ne;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),re.error("Failed to start Gmail connection"),o(!1)}},W=async Be=>{if(w){re.error("Account connections must be made by the agent from their own login.");return}d(!0);try{sessionStorage.setItem("social-connect-return-to",window.location.pathname);const{data:Ne,error:Ae}=await q.functions.invoke("meta-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/callback",authMode:Be}});if(Ae)throw Ae;if(Ne!=null&&Ne.authUrl)window.location.href=Ne.authUrl;else throw new Error("Failed to get authorization URL")}catch(Ne){console.error("Meta OAuth error:",Ne),re.error("Failed to start connection. Make sure Meta App credentials are configured."),d(!1)}},V=async()=>{if(w){re.error("Account connections must be made by the agent from their own login.");return}h(!0);try{const{data:Be,error:Ne}=await q.functions.invoke("linkedin-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/linkedin-callback"}});if(Ne)throw Ne;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),re.error("Failed to start LinkedIn connection. Please try again."),h(!1)}},G=mt({mutationFn:async Be=>{const{error:Ne}=await q.from("gmail_integrations").delete().eq("id",Be).eq("user_id",b);if(Ne)throw Ne},onSuccess:()=>{i.invalidateQueries({queryKey:["gmail-integration",b]}),re.success("Gmail disconnected")},onError:()=>{re.error("Failed to disconnect Gmail")}}),Y=mt({mutationFn:async Be=>{const{error:Ne}=await q.from("social_accounts").delete().eq("id",Be).eq("user_id",b);if(Ne)throw Ne},onSuccess:()=>{i.invalidateQueries({queryKey:["social-accounts",b]}),re.success("Account disconnected")},onError:()=>{re.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"))||[],ne=(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:Ne}=await q.from("mass_email_settings").select("reply_to_email").eq("user_id",n==null?void 0:n.id).maybeSingle();if(Ne)throw Ne;return Be}}),ce=(Be,Ne)=>({queryKey:[Be],queryFn:async()=>{const{data:Ae,error:Ce}=await q.functions.invoke(Ne,{body:{action:"status"}});if(Ce)throw Ce;return Ae},staleTime:6e4}),{data:_e}=st(ce("boldtrail-status","boldtrail-sync")),{data:he}=st(ce("lofty-status","lofty-sync")),{data:ue}=st(ce("fub-status","followupboss-sync")),{data:ve}=st(ce("cloze-status","cloze-sync")),{data:Ee}=st(ce("boomtown-status","boomtown-sync")),Se=[X,!!(J!=null&&J.reply_to_email),ae.length>0,le.length>0,ne.length>0,!!(_e!=null&&_e.connected),!!(he!=null&&he.connected),!!(ue!=null&&ue.connected),!!(ve!=null&&ve.connected),!!(Ee!=null&&Ee.connected)].filter(Boolean).length,Le=Be=>{v(Ne=>Ne===Be?null:Be)},Fe=Be=>{const Ne=Be==="facebook"?ae:Be==="instagram"?le:ne,Ae=Be==="facebook"?Qp:Be==="instagram"?Ef:dy,Ce=Be==="facebook"?"Facebook":Be==="instagram"?"Instagram":"LinkedIn",Ve=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(Gn,{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(Ie,{className:"space-y-3",children:[Ne.map(qe=>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:qe.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:qe.page_name||qe.platform_username||`${Ce} account`}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connected"})]})]}),e.jsxs(fc,{children:[e.jsx(Tg,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive","aria-label":`Disconnect ${Ce}`,children:e.jsx(Hn,{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:()=>Y.mutate(qe.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},qe.id)),e.jsxs($,{variant:"outline",onClick:Ve,disabled:ze||w,children:[ze?e.jsx(ro,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(dn,{className:"mr-2 h-4 w-4"}),Ne.length?`Add another ${Ce} account`:`Connect ${Ce}`]})]})]})},ke=(()=>{var Be,Ne,Ae;switch(y){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(Gn,{children:"Send personalized emails from contact pages and automatically record the activity."})]}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsx("div",{className:"grid gap-2 sm:grid-cols-3",children:["Send from your Gmail account","Log email touchpoints","Compose from any contact"].map(ze=>e.jsxs("div",{className:"flex items-start gap-2 rounded-md bg-muted/25 p-3 text-sm",children:[e.jsx(ca,{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(Tg,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:"text-destructive",children:[e.jsx(Hn,{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(ro,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(mn,{className:"mr-2 h-4 w-4"}),"Connect Gmail"]})]})]});case"mass-email":return e.jsx(Oir,{});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,Ve=((Be=I==null?void 0:I.locations)==null?void 0:Be.find(ze=>ze.is_primary))??((Ne=I==null?void 0:I.locations)==null?void 0:Ne[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(Gn,{children:"Post updates and manage reviews from your Google Business Profile."})]}),e.jsxs(Ie,{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:(Ve==null?void 0:Ve.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(Tg,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive","aria-label":"Disconnect Google Business",children:e.jsx(Hn,{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(ro,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(ro,{className:"mr-2 h-4 w-4"}),"Check again"]})]}),e.jsxs($,{variant:Ce&&!(I!=null&&I.needsReconnect)?"outline":"default",onClick:O,disabled:m||w,children:[m?e.jsx(ro,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(dn,{className:"mr-2 h-4 w-4"}),Ce?"Reconnect Google Business":"Connect Google Business"]})]})]});case"boldtrail":return e.jsx(Eir,{});case"lofty":return e.jsx(Tir,{});case"followupboss":return e.jsx(Mir,{});case"cloze":return e.jsx(Pir,{});case"boomtown":return e.jsx(Lir,{});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(Gn,{children:"Connect ChatGPT to LevelUp so it can use LevelUp tools on your behalf."})]}),e.jsx(Ie,{children:e.jsxs($,{variant:"outline",onClick:()=>s("/connect-chatgpt"),children:["View connection instructions ",e.jsx(Qa,{className:"ml-2 h-4 w-4"})]})})]});case"ses":return t?e.jsx(ios,{}):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"}),Se," 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(pc,{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(Gn,{children:["You're working on behalf of ",r==null?void 0:r.name,". Email and social account connections are private to each agent and can only be viewed or changed from their own login."]})]})]})}),e.jsxs("div",{className:"mt-6 grid gap-6 lg:grid-cols-[220px_minmax(0,1fr)]",children:[e.jsx("nav",{"aria-label":"Integration categories",className:"min-w-0",children:e.jsx("div",{className:"flex gap-2 overflow-x-auto pb-2 lg:sticky lg:top-5 lg:flex-col lg:overflow-visible",children:Bir.map(Be=>{const Ne=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),v(null)},children:[e.jsx(Ne,{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(bj,{title:"Gmail",description:"Send personal emails and automatically log each touchpoint.",icon:e.jsx(mn,{className:"h-5 w-5"}),connected:X,selected:y==="gmail",onClick:()=>Le("gmail"),badge:"Priority"}),e.jsx(bj,{title:"Mass Email",description:"Send polished campaigns from a verified sender address.",icon:e.jsx(Kr,{className:"h-5 w-5"}),connected:!!(J!=null&&J.reply_to_email),statusLabel:"Setup required",selected:y==="mass-email",onClick:()=>Le("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(bj,{title:"BoldTrail",description:"Sync contacts, ownership, tags, notes, and lead details.",icon:e.jsx(y0,{className:"h-5 w-5"}),connected:_e==null?void 0:_e.connected,selected:y==="boldtrail",onClick:()=>Le("boldtrail")}),e.jsx(bj,{title:"Lofty",description:"Connect Lofty contacts and control sync direction.",icon:e.jsx(y0,{className:"h-5 w-5"}),connected:he==null?void 0:he.connected,selected:y==="lofty",onClick:()=>Le("lofty")}),e.jsx(bj,{title:"Follow Up Boss",description:"Keep Follow Up Boss contacts aligned with LevelUp.",icon:e.jsx(y0,{className:"h-5 w-5"}),connected:ue==null?void 0:ue.connected,selected:y==="followupboss",onClick:()=>Le("followupboss")}),e.jsx(bj,{title:"Cloze",description:"Sync contacts from your Cloze account or selected segments.",icon:e.jsx(y0,{className:"h-5 w-5"}),connected:ve==null?void 0:ve.connected,selected:y==="cloze",onClick:()=>Le("cloze")}),e.jsx(bj,{title:"BoomTown",description:"Import and synchronize your BoomTown contact database.",icon:e.jsx(y0,{className:"h-5 w-5"}),connected:Ee==null?void 0:Ee.connected,selected:y==="boomtown",onClick:()=>Le("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(bj,{title:"Facebook",description:"Publish to your connected Facebook Pages.",icon:e.jsx(Qp,{className:"h-5 w-5"}),connected:ae.length>0,selected:y==="facebook",onClick:()=>Le("facebook")}),e.jsx(bj,{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:y==="instagram",onClick:()=>Le("instagram")}),e.jsx(bj,{title:"LinkedIn",description:"Share content with your professional network.",icon:e.jsx(dy,{className:"h-5 w-5"}),connected:ne.length>0,selected:y==="linkedin",onClick:()=>Le("linkedin")}),e.jsx(bj,{title:"Google Business",description:"Post updates and manage reviews on your Google Business Profile.",icon:e.jsx(ji,{className:"h-5 w-5"}),connected:te.length>0&&!(I!=null&&I.needsReconnect),statusLabel:I!=null&&I.needsReconnect?"Reconnect":void 0,selected:y==="google-business",onClick:()=>Le("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(bj,{title:"ChatGPT",description:"Use your LevelUp tools directly from ChatGPT.",icon:e.jsx(E4,{className:"h-5 w-5"}),statusLabel:"View setup",selected:y==="chatgpt",onClick:()=>Le("chatgpt")}),t&&e.jsx(bj,{title:"Amazon SES",description:"Manage the platform-level mass email delivery service.",icon:e.jsx(eC,{className:"h-5 w-5"}),statusLabel:"Admin only",badge:"Admin",selected:y==="ses",onClick:()=>Le("ses")})]})]})]})]}),e.jsx(Gy,{open:y!==null,onOpenChange:Be=>{Be||v(null)},children:e.jsxs(my,{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(L0,{className:"sticky top-0 z-10 border-b bg-background px-5 py-5 pr-12 text-left sm:px-7",children:[e.jsxs(R0,{className:"font-display text-xl",children:[y?$ir[y]:"Integration"," settings"]}),e.jsx(DB,{children:"Review the connection and update its settings here."})]}),e.jsx("div",{className:"p-4 sm:p-7",children:ke})]})})]})})}const Vir="https://chromewebstore.google.com/detail/levelup-companion/lppakdeaencigddecnkcifdcemlfpkkk";function Hir(){const[s,t]=j.useState(null),[n,r]=j.useState(!1),[a,i]=j.useState(0),[l,o]=j.useState(!1),c="/levelup-extension.zip",d="https://tile-portal.lovable.app/levelup-extension.zip",u=window.location.hostname.startsWith("id-preview--"),h=async y=>{const v=new Uint8Array(await y.slice(0,4).arrayBuffer());return v[0]===80&&v[1]===75&&v[2]===3&&v[3]===4||v[0]===80&&v[1]===75&&v[2]===5&&v[3]===6||v[0]===80&&v[1]===75&&v[2]===7&&v[3]===8},m=y=>{const v=document.createElement("a");v.href=y,v.download="levelup-extension.zip",v.rel="noopener noreferrer",v.target="_blank",document.body.appendChild(v),v.click(),v.remove()},f=async()=>{o(!0);try{if(u){m(`${d}?v=${Date.now()}`);return}const y=await fetch(`${c}?v=${Date.now()}`,{cache:"no-store"});if(!y.ok)throw new Error(`Download failed (${y.status})`);const v=await y.blob();if(!await h(v)){m(`${d}?v=${Date.now()}`);return}const b=new Blob([v],{type:"application/zip"}),w=URL.createObjectURL(b),S=document.createElement("a");S.href=w,S.download="levelup-extension.zip",document.body.appendChild(S),S.click(),S.remove(),setTimeout(()=>URL.revokeObjectURL(w),1e3)}catch(y){re.error(y.message||"Download failed")}finally{o(!1)}},g=async()=>{r(!0);try{await q.auth.refreshSession();const{data:y}=await q.auth.getSession();if(!y.session){re.error("Your session has expired. Please sign in again.");return}const{data:v,error:b}=await q.functions.invoke("extension-pair-start",{headers:{Authorization:`Bearer ${y.session.access_token}`}});if(b)throw b;t(v.code),i(v.expires_in||300);const w=setInterval(()=>{i(S=>S<=1?(clearInterval(w),t(null),0):S-1)},1e3)}catch(y){console.error("generateCode error",y),re.error("We couldn't generate a pairing code",{description:"Please refresh the page and try again. If it still fails, sign out and sign back in, then click Generate pairing code.",duration:8e3})}finally{r(!1)}},x=()=>{s&&(navigator.clipboard.writeText(s),re.success("Copied"))};return e.jsx(Vs,{title:"Browser Extension",children:e.jsxs("div",{className:"container max-w-3xl mx-auto py-8 px-4 space-y-6",children:[e.jsxs(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(Fz,{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(Vir,"_blank","noopener,noreferrer"),children:[e.jsx(Fz,{className:"w-4 h-4 mr-2"}),"Add to Chrome",e.jsx(Fr,{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(Ha,{className:"w-4 h-4 mr-2"})," Copy"]}),e.jsxs($,{onClick:g,variant:"outline",className:"flex-1",children:[e.jsx(ro,{className:"w-4 h-4 mr-2"})," New code"]})]}),e.jsxs("div",{className:"flex items-start gap-2 text-sm text-muted-foreground bg-muted/50 rounded-lg p-3",children:[e.jsx(ca,{className:"w-4 h-4 mt-0.5 text-primary"}),e.jsx("span",{children:"Click the LevelUp icon in your browser toolbar and paste this code. You only need to do this once per browser."})]})]}):e.jsx($,{onClick:g,disabled:n,size:"lg",className:"w-full",children:n?e.jsxs(e.Fragment,{children:[e.jsx(ro,{className:"w-4 h-4 mr-2 animate-spin"}),"Generating…"]}):"Generate pairing code"})]}),e.jsxs(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 Gir(){const[s]=gc(),t=Xn(),[n,r]=j.useState("loading"),[a,i]=j.useState("Connecting your Gmail account...");return j.useEffect(()=>{(async()=>{const o=s.get("code"),c=s.get("error"),d=s.get("error_description"),u=s.get("state");if(c){r("error"),i(d||"Authorization was denied"),re.error("Connection failed: "+(d||c));return}if(!o){r("error"),i("No authorization code received"),re.error("No authorization code received");return}try{const{data:h,error:m}=await q.functions.invoke("gmail-oauth",{body:{action:"exchange_code",code:o,state:u}});if(m)throw m;if(h!=null&&h.success)r("success"),i(h.message||"Gmail connected successfully!"),re.success("Gmail connected!");else throw new Error((h==null?void 0:h.error)||"Unknown error")}catch(h){console.error("Gmail OAuth callback error:",h),r("error"),i(h instanceof Error?h.message:"Failed to connect Gmail"),re.error("Failed to connect: "+(h instanceof Error?h.message:"Unknown error"))}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(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(Nu,{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(Gn,{children:a})]}),e.jsx(Ie,{className:"flex justify-center",children:n!=="loading"&&e.jsx($,{onClick:()=>t("/mission-control/integrations"),children:n==="success"?"Back to Integrations":"Try Again"})})]})})}function Wir(){const s=Xn();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 Kir(){const[s]=gc(),t=Xn(),[n,r]=j.useState("loading"),a=j.useRef(!1),[i,l]=j.useState("Processing your connection...");return j.useEffect(()=>{if(a.current)return;a.current=!0,(async()=>{var m;const c=s.get("code"),d=s.get("error"),u=s.get("error_description"),h=s.get("state");if(d){r("error"),l(u||"Authorization was denied"),re.error("Connection failed: "+(u||d));return}if(!c){r("error"),l("No authorization code received"),re.error("No authorization code received");return}try{const{data:f,error:g}=await q.functions.invoke("meta-oauth",{body:{action:"exchange_code",code:c,state:h,callbackPath:"/mission-control/integrations/meta/callback"}});if(f&&f.success===!1)throw new Error(f.error||"Failed to connect accounts");if(g){let x=g.message||"Failed to connect accounts";try{const y=g.context;if(y&&typeof y.json=="function"){const v=await y.json();v!=null&&v.error&&(x=v.error)}}catch{}throw new Error(x)}if(f!=null&&f.success)r("success"),l(`Successfully connected ${((m=f.accounts)==null?void 0:m.length)||0} account(s)!`),re.success("Social accounts connected successfully!");else throw new Error((f==null?void 0:f.error)||"Unknown error")}catch(f){console.error("OAuth callback error:",f),r("error"),l(f instanceof Error?f.message:"Failed to connect accounts"),re.error("Failed to connect: "+(f instanceof Error?f.message:"Unknown error"))}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(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(Nu,{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(Gn,{children:i})]}),e.jsx(Ie,{className:"flex justify-center",children:n!=="loading"&&e.jsx($,{onClick:()=>t("/mission-control/integrations"),children:n==="success"?"View Integrations":"Try Again"})})]})})}const los=new Date().getFullYear(),Yir=Array.from({length:5},(s,t)=>los-t);function Zir(){const[s,t]=j.useState(los),n=Xn(),{data:r,isLoading:a}=DWs();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:Yir.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(Ie,{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(Ie,{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(Gn,{children:"Click to view individual agent scorecards"})]}),e.jsx(Ie,{children:!r||r.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(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(En,{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(En,{children:[e.jsx(_t,{className:"font-medium",children:i.name}),e.jsx(_t,{className:"text-muted-foreground",children:i.email}),e.jsx(_t,{className:"text-right",children:e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>n(`/admin/scorecard/${i.id}`),children:[e.jsx(Ca,{className:"h-4 w-4 mr-2"}),"View Scorecard"]})})]},i.id))})]})})]})]})})}const Xir="00000000-0000-0000-0000-000000000000",Qir=s=>{if(!s)return"—";const[t,n,r]=s.split(/[-/T]/);return`${n}/${r}/${t}`};function Jir(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 eor={never_started:"Never started",signed_in_empty:"Signed in, empty",started:"Started, gone quiet",active:"Active"};function tor(){const s=Wt(),[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??Xir).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"]}),re.success("Setting saved")},onError:()=>re.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:()=>re.error("Preview failed")}),y=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=>re.success(`Test email sent to ${S.sent_to}`),onError:S=>re.error(S.message||"Test send failed")}),v=c.filter(S=>S.brokerage_name.toLowerCase().includes(r.toLowerCase())),b=u!=null&&u.sent?Math.round(u.opened/u.sent*100):0,w=u!=null&&u.sent?Math.round(u.clicked/u.sent*100):0;return e.jsx(Vs,{title:"Agent Activation",children:e.jsxs("div",{className:"container mx-auto py-6 space-y-6 max-w-7xl",children:[t?e.jsxs("div",{className:"space-y-4",children:[e.jsxs($,{variant:"ghost",size:"sm",className:"gap-2 text-muted-foreground hover:text-foreground",onClick:()=>n(null),children:[e.jsx(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(Ie,{className:"pt-5",children:[e.jsx("div",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:S.label}),e.jsx("div",{className:"text-2xl font-bold",children:S.value.toLocaleString()}),e.jsx("div",{className:"text-xs text-muted-foreground",children:S.hint})]})},S.label))}),e.jsx(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(Gn,{children:m?"Activation emails are LIVE for brokerages you enable below.":"OFF worldwide. No activation emails can be sent to anyone."})]}),e.jsx(Sn,{checked:m,onCheckedChange:S=>g.mutate({brokerageId:null,enabled:S})})]})})}),e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsxs(Et,{className:"text-lg flex items-center gap-2",children:[e.jsx(mn,{className:"h-5 w-5"})," The sequence"]}),e.jsx(Gn,{children:"Five emails, all sent from LevelUp. Preview any step or send a test to yourself."})]}),e.jsx(Ie,{className:"flex flex-wrap gap-2",children:[1,2,3,4,5].map(S=>e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs($,{variant:"outline",size:"sm",onClick:()=>x.mutate(S),disabled:x.isPending,children:[e.jsx(Ca,{className:"h-3.5 w-3.5 mr-1"})," Step ",S]}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>y.mutate(S),disabled:y.isPending,title:"Send test to my email",children:e.jsx(Kr,{className:"h-3.5 w-3.5"})})]},S))})]}),t?e.jsx(sor,{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(Gn,{children:"Select a brokerage to manage agents and enable the sequence."})]}),e.jsx(pe,{placeholder:"Search brokerages…",value:r,onChange:S=>a(S.target.value),className:"max-w-xs"})]})}),e.jsx(Ie,{children:d?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Brokerage"}),e.jsx(Dt,{children:"Health"}),e.jsx(Dt,{className:"text-right",children:"Agents"}),e.jsx(Dt,{className:"text-right",children:"Never in"}),e.jsx(Dt,{className:"text-right",children:"Active 90d"}),e.jsx(Dt,{className:"text-right",children:"With data"}),e.jsx(Dt,{className:"text-right",children:"Activation"})]})}),e.jsx(fi,{children:v.map(S=>{var I;const A=Jir(S),E=!!((I=f(S.brokerage_id))!=null&&I.enabled);return e.jsxs(En,{className:"cursor-pointer",onClick:()=>n(S),children:[e.jsx(_t,{className:"font-medium",children:S.brokerage_name}),e.jsx(_t,{children:e.jsx($e,{variant:"secondary",className:A.className,children:A.label})}),e.jsx(_t,{className:"text-right",children:S.total_agents}),e.jsx(_t,{className:"text-right",children:S.never_logged_in}),e.jsx(_t,{className:"text-right",children:S.active_90d}),e.jsx(_t,{className:"text-right",children:S.with_contacts+S.with_deals>0?`${S.with_contacts}`:0}),e.jsx(_t,{className:"text-right",children:e.jsx($e,{variant:E?"default":"outline",children:E?"On":"Off"})})]},S.brokerage_id)})})]})})]}),e.jsx(zs,{open:!!i,onOpenChange:()=>l(null),children:e.jsxs(Os,{className:"max-w-3xl max-h-[85vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:i==null?void 0:i.subject}),e.jsx(Pr,{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 sor({brokerage:s,settings:t,masterOn:n,onBack:r,onToggle:a}){const i=Wt(),[l,o]=j.useState(""),{data:c=[],isLoading:d}=st({queryKey:["brokerage-agent-activation",s.brokerage_id],queryFn:async()=>{const{data:x,error:y}=await q.rpc("get_brokerage_agent_activation",{_brokerage_id:s.brokerage_id});if(y)throw y;return x}}),u=mt({mutationFn:async({userId:x,skip:y})=>{if(y){const{error:v}=await q.from("agent_activation_state").upsert({user_id:x,brokerage_id:s.brokerage_id,exited_at:new Date().toISOString(),exit_reason:"manual_skip",updated_at:new Date().toISOString()},{onConflict:"user_id"});if(v)throw v}else{const{error:v}=await q.from("agent_activation_state").update({exited_at:null,exit_reason:null,updated_at:new Date().toISOString()}).eq("user_id",x);if(v)throw v}},onSuccess:()=>{i.invalidateQueries({queryKey:["brokerage-agent-activation",s.brokerage_id]}),re.success("Agent updated")},onError:()=>re.error("Update failed")}),h=mt({mutationFn:async x=>{const{data:y,error:v}=await q.functions.invoke("agent-activation-run",{body:{action:"send_now",user_id:x,brokerage_id:s.brokerage_id}});if(v)throw v;if(y!=null&&y.error)throw new Error(y.error);return y},onSuccess:()=>{i.invalidateQueries({queryKey:["brokerage-agent-activation",s.brokerage_id]}),re.success("Email sent")},onError:x=>re.error(x.message||"Send failed")}),m=!!(t!=null&&t.enabled),f=m&&n,g=c.filter(x=>(x.name||"").toLowerCase().includes(l.toLowerCase())||(x.email||"").toLowerCase().includes(l.toLowerCase()));return e.jsxs(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(Gn,{children:[s.total_agents," agents · ",s.never_logged_in," never logged in ·"," ",s.active_90d," active in 90 days"]})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:f?"Sequence LIVE for this brokerage":n?"Off for this brokerage":"Master switch is off"}),e.jsx(Sn,{checked:m,onCheckedChange:a})]})]}),e.jsx("div",{className:"pt-2",children:e.jsx(pe,{placeholder:"Search agents…",value:l,onChange:x=>o(x.target.value),className:"max-w-xs"})})]}),e.jsx(Ie,{children:d?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(Ct,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Agent"}),e.jsx(Dt,{children:"Stage"}),e.jsx(Dt,{className:"text-right",children:"Logins"}),e.jsx(Dt,{children:"Last login"}),e.jsx(Dt,{className:"text-right",children:"Contacts"}),e.jsx(Dt,{className:"text-right",children:"Deals"}),e.jsx(Dt,{className:"text-right",children:"Step"}),e.jsx(Dt,{className:"text-right",children:"Emails"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(fi,{children:g.map(x=>{const y=x.exit_reason==="manual_skip";return e.jsxs(En,{children:[e.jsxs(_t,{children:[e.jsx("div",{className:"font-medium",children:x.name||"—"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:x.email})]}),e.jsx(_t,{children:e.jsx($e,{variant:x.stage==="active"?"default":"secondary",children:y?"Skipped":eor[x.stage]})}),e.jsx(_t,{className:"text-right",children:x.login_count}),e.jsx(_t,{children:Qir(x.last_login)}),e.jsx(_t,{className:"text-right",children:x.contact_count}),e.jsx(_t,{className:"text-right",children:x.deal_count}),e.jsxs(_t,{className:"text-right",children:[x.step,"/5"]}),e.jsx(_t,{className:"text-right",children:e.jsxs("span",{className:"inline-flex items-center gap-1",children:[x.last_opened_at?e.jsx(Vz,{className:"h-3.5 w-3.5 text-emerald-600"}):e.jsx(mn,{className:"h-3.5 w-3.5 text-muted-foreground"}),x.emails_sent]})}),e.jsx(_t,{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(Kr,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>u.mutate({userId:x.user_id,skip:!y}),title:y?"Include in sequence":"Skip this agent",children:e.jsx(uV,{className:`h-3.5 w-3.5 ${y?"text-red-500":""}`})})]})})]},x.user_id)})})]})})]})}const cos=new Date().getFullYear(),nor=Array.from({length:10},(s,t)=>cos-t);function nEt(){var g;const{userId:s}=Wi(),t=Xn(),r=mu().pathname.startsWith("/mission-control"),[a,i]=j.useState(cos),{data:l,isLoading:o}=st({queryKey:["agent-profile",s],queryFn:async()=>{const{data:x,error:y}=await q.from("profiles").select("id, name, email").eq("id",s).single();if(y)throw y;return x},enabled:!!s}),{data:c,isLoading:d}=lnt(a,s),{yearStats:u,lifetimeStats:h,showCommission:m}=XUt(a,s),{data:f}=ZUt(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:nor.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(Ie,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(va,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Transactions"})]}),e.jsx("p",{className:"text-2xl font-bold",children:u.totalTransactions}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[h.totalTransactions," lifetime"]})]})}),e.jsx(je,{children:e.jsxs(Ie,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(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(Ie,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(nu,{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(Ie,{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(Ie,{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(Nrs,{goals:f,stats:u,year:a,showCommission:m}),e.jsxs(ha,{defaultValue:"transactions",className:"space-y-4",children:[e.jsxs(ma,{children:[e.jsx(Zt,{value:"transactions",children:"Transactions"}),e.jsx(Zt,{value:"charts",children:"Charts"}),e.jsxs(Zt,{value:"map",children:[e.jsx(ci,{className:"h-4 w-4 mr-1"}),"Map"]})]}),e.jsx(Xt,{value:"transactions",children:e.jsx(Uot,{transactions:c||[],showCommission:m,isLoading:d})}),e.jsx(Xt,{value:"charts",children:e.jsx(qot,{stats:u,year:a})}),e.jsx(Xt,{value:"map",children:e.jsx(Vot,{transactions:c||[],isLoading:d})})]})]})})}function ror(){const s=Wt(),[t,n]=j.useState(""),[r,a]=j.useState("all"),[i,l]=j.useState(null);Tae();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&&re.success("Submitted to Google for indexing")}catch(U){console.error("Google indexing submission failed:",U)}},y=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){re.error("Google Indexing API not configured. Add the GOOGLE_INDEXING_SERVICE_ACCOUNT secret.");return}re.success(`Submitted ${(R==null?void 0:R.succeeded)||0} URLs to Google (${(R==null?void 0:R.failed)||0} failed)`)},onError:R=>{re.error("Failed to submit to Google"),console.error(R)}}),v=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"]}),re.success(R.approved?"Listing approved":"Listing unapproved"),R.approved?x(R.id,R.slug||null,"submit_url"):x(R.id,R.slug||null,"remove_url")}}),b=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"]}),re.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"]}),re.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(),re.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:()=>y.mutate(),disabled:y.isPending,className:"gap-2",children:[y.isPending?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(dl,{className:"h-4 w-4"}),"Submit All to Google"]}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Feature visible to agents"}),e.jsx(Sn,{checked: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(Ie,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ji,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Total Listings"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:(h==null?void 0:h.total)||0})]})}),e.jsx(je,{children:e.jsxs(Ie,{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(Ie,{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(Ie,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ca,{className:"h-4 w-4 text-blue-500"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Total Views"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:(h==null?void 0:h.totalViews)||0})]})}),e.jsx(je,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fd,{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(Ie,{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(Ie,{className:"p-4",children:e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Zr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search by city, address, or agent...",value:t,onChange:R=>n(R.target.value),className:"pl-9"})]}),e.jsx(ha,{value:r,onValueChange:R=>a(R),children:e.jsxs(ma,{children:[e.jsx(Zt,{value:"all",children:"All"}),e.jsx(Zt,{value:"pending",children:"Pending"}),e.jsx(Zt,{value:"approved",children:"Approved"})]})})]})})}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsxs(Et,{children:["Listings (",(E==null?void 0:E.length)||0,")"]})}),e.jsx(Ie,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Property"}),e.jsx(Dt,{children:"Agent"}),e.jsx(Dt,{children:"Price"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"text-center",children:"Approved"}),e.jsx(Dt,{className:"text-center",children:"Featured"}),e.jsx(Dt,{children:"Views"}),e.jsx(Dt,{children:"Shares"}),e.jsx(Dt,{children:"Leads"}),e.jsx(Dt,{children:"Date"}),e.jsx(Dt,{})]})}),e.jsx(fi,{children:u?e.jsx(En,{children:e.jsx(_t,{colSpan:11,className:"text-center py-8 text-muted-foreground",children:"Loading..."})}):(E==null?void 0:E.length)===0?e.jsx(En,{children:e.jsx(_t,{colSpan:11,className:"text-center py-8 text-muted-foreground",children:"No listings found"})}):E==null?void 0:E.map(R=>{var D,O,U,W,V;return e.jsxs(En,{children:[e.jsx(_t,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[(O=(D=R.photos)==null?void 0:D[0])!=null&&O.photo_url?e.jsx("img",{src:R.photos[0].photo_url,alt:"",className:"w-12 h-12 object-cover rounded"}):e.jsx("div",{className:"w-12 h-12 bg-muted rounded flex items-center justify-center",children:e.jsx(ji,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:R.property_address||`${R.city}, ${R.state}`}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(U=R.property_type)==null?void 0:U.replace("_"," ")})]})]})}),e.jsx(_t,{children:e.jsx("p",{className:"text-sm",children:((W=R.agent)==null?void 0:W.name)||"Unknown"})}),e.jsx(_t,{className:"font-medium",children:I(R.price)}),e.jsx(_t,{children:e.jsx($e,{variant:"outline",className:P(R.status),children:(V=R.status)==null?void 0:V.replace("_"," ")})}),e.jsx(_t,{className:"text-center",children:e.jsx(Sn,{checked:R.is_approved??!1,onCheckedChange:G=>v.mutate({id:R.id,approved:G,slug:R.slug})})}),e.jsx(_t,{className:"text-center",children:e.jsx(Sn,{checked:R.is_featured??!1,onCheckedChange:G=>b.mutate({id:R.id,featured:G})})}),e.jsx(_t,{children:R.view_count||0}),e.jsx(_t,{children:R.share_count||0}),e.jsx(_t,{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(_t,{className:"text-sm text-muted-foreground",children:en(new Date(R.created_at),"MMM d, yyyy")}),e.jsx(_t,{children:e.jsxs($u,{children:[e.jsx(Uu,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",children:e.jsx(l_,{className:"h-4 w-4"})})}),e.jsxs(Au,{align:"end",children:[e.jsxs(ja,{onClick:()=>window.open(`/mission-control/listings/${R.id}`,"_blank"),children:[e.jsx(Ca,{className:"h-4 w-4 mr-2"}),"View Listing"]}),e.jsxs(ja,{onClick:()=>b.mutate({id:R.id,featured:!R.is_featured}),children:[e.jsx(ei,{className:"h-4 w-4 mr-2"}),R.is_featured?"Unfeature":"Feature"]}),e.jsxs(ja,{className:"text-destructive",onClick:async()=>{await fo("Are you sure you want to delete this listing?")&&w.mutate(R.id)},children:[e.jsx(pr,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})})]},R.id)})})]})})})]})]}),e.jsx(zs,{open:!!i,onOpenChange:R=>!R&&l(null),children:e.jsxs(Os,{className:"max-w-3xl max-h-[80vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Leads from listing"}),e.jsx(Pr,{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(En,{children:[e.jsx(Dt,{children:"Name"}),e.jsx(Dt,{children:"Email"}),e.jsx(Dt,{children:"Phone"}),e.jsx(Dt,{children:"Type"}),e.jsx(Dt,{children:"Captured"})]})}),e.jsx(fi,{children:f.map(R=>{var D;return e.jsxs(En,{children:[e.jsx(_t,{className:"font-medium",children:[R.first_name,R.last_name].filter(Boolean).join(" ")||"—"}),e.jsx(_t,{children:R.email}),e.jsx(_t,{children:R.phone||"—"}),e.jsx(_t,{children:e.jsx($e,{variant:"outline",children:(D=R.lead_type)==null?void 0:D.replace("_"," ")})}),e.jsx(_t,{className:"text-sm text-muted-foreground",children:en(new Date(R.created_at),"MMM d, yyyy h:mm a")})]},R.id)})})]})]})})]})}function aor(s){return s?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s):"—"}function ior(){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,y,v,b,w,S;return h&&new Date(f.created_at).getTime(){const h=c.length,m=c.filter(x=>x.lead_type==="showing_request").length,f=new Set(c.map(x=>x.agent_id)).size,g=new Set(c.map(x=>x.listing_id)).size;return{total:h,showings:m,uniqueAgents:f,uniqueListings:g}},[c]),u=()=>{const m=[["Date","Name","Email","Phone","Type","Showing Date","Property","City","Price","Assigned Agent","Agent Email","Referred By","Message"],...c.map(y=>{var v,b,w,S,A,E;return[en(new Date(y.created_at),"yyyy-MM-dd HH:mm"),`${y.first_name||""} ${y.last_name||""}`.trim(),y.email,y.phone||"",y.lead_type,y.preferred_date?`${y.preferred_date} ${y.preferred_time||""}`:"",((v=y.listing)==null?void 0:v.property_address)||"",((b=y.listing)==null?void 0:b.city)||"",(w=y.listing)!=null&&w.price?String(y.listing.price):"",((S=y.agent)==null?void 0:S.name)||"",((A=y.agent)==null?void 0:A.email)||"",((E=y.referrer)==null?void 0:E.name)||"",(y.message||"").replace(/[\r\n]+/g," ")]})].map(y=>y.map(v=>`"${String(v).replace(/"/g,'""')}"`).join(",")).join(` `),f=new Blob([m],{type:"text/csv"}),g=URL.createObjectURL(f),x=document.createElement("a");x.href=g,x.download=`listing-leads-${en(new Date,"yyyy-MM-dd")}.csv`,x.click(),URL.revokeObjectURL(g)};return e.jsx(Vs,{title:"Listing Leads",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Listing Leads"}),e.jsx("p",{className:"text-muted-foreground",children:"All leads submitted through the public listings site"})]}),e.jsxs($,{variant:"outline",onClick:u,disabled:!c.length,className:"gap-2",children:[e.jsx(xi,{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(Ie,{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(Ie,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ta,{className:"h-4 w-4 text-purple-600"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Showing Requests"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:d.showings})]})}),e.jsx(je,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(va,{className:"h-4 w-4 text-blue-600"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Properties"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:d.uniqueListings})]})}),e.jsx(je,{children:e.jsxs(Ie,{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(Ie,{className:"p-4",children:e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Zr,{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(Ie,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Date"}),e.jsx(Dt,{children:"Lead"}),e.jsx(Dt,{children:"Contact"}),e.jsx(Dt,{children:"Property"}),e.jsx(Dt,{children:"Type"}),e.jsx(Dt,{children:"Assigned To"}),e.jsx(Dt,{children:"Referred By"}),e.jsx(Dt,{children:"Message"})]})}),e.jsx(fi,{children:o?e.jsx(En,{children:e.jsx(_t,{colSpan:8,className:"text-center py-8 text-muted-foreground",children:"Loading..."})}):c.length===0?e.jsx(En,{children:e.jsx(_t,{colSpan:8,className:"text-center py-8 text-muted-foreground",children:"No leads found"})}):c.map(h=>{var m,f;return e.jsxs(En,{children:[e.jsxs(_t,{className:"whitespace-nowrap text-sm",children:[en(new Date(h.created_at),"MMM d, yyyy"),e.jsx("div",{className:"text-xs text-muted-foreground",children:en(new Date(h.created_at),"h:mm a")})]}),e.jsx(_t,{children:e.jsx("div",{className:"font-medium",children:`${h.first_name||""} ${h.last_name||""}`.trim()||"—"})}),e.jsx(_t,{children:e.jsxs("div",{className:"flex flex-col gap-1 text-sm",children:[e.jsxs("a",{href:`mailto:${h.email}`,className:"flex items-center gap-1 hover:underline",children:[e.jsx(mn,{className:"h-3 w-3"}),h.email]}),h.phone&&e.jsxs("a",{href:`tel:${h.phone}`,className:"flex items-center gap-1 text-muted-foreground hover:underline",children:[e.jsx(Da,{className:"h-3 w-3"}),h.phone]})]})}),e.jsx(_t,{children:h.listing?e.jsxs(wr,{to:`/public/listing/${h.listing.slug||h.listing.id}`,target:"_blank",className:"group",children:[e.jsxs("div",{className:"font-medium text-sm group-hover:underline flex items-center gap-1",children:[h.listing.property_address||"Untitled",e.jsx(Fr,{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(", ")," · ",aor(h.listing.price)]})]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsxs(_t,{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(_t,{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(_t,{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(_t,{className:"max-w-xs",children:h.message?e.jsxs("div",{className:"text-xs text-muted-foreground line-clamp-3 flex items-start gap-1",children:[e.jsx(eo,{className:"h-3 w-3 mt-0.5 shrink-0"}),h.message]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})})]},h.id)})})]})})})]})]})})}const J$={new_listing_alerts:{label:"New Listing Alerts",icon:Uy,color:"bg-amber-100 text-amber-800"},exit_intent:{label:"Exit Intent",icon:qz,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:Zr,color:"bg-blue-100 text-blue-800"},buyer_guide:{label:"Buyer's Guide",icon:Xf,color:"bg-emerald-100 text-emerald-800"}},rEt=[{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 aEt(s){return new Date(s).toLocaleString("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"})}function oor(){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=rEt.find(b=>b.key===a);if(x&&x.days>0){const b=new Date(Date.now()-x.days*864e5).toISOString();g=g.gte("created_at",b)}const{data:y,error:v}=await g;f||(v?(console.error(v),t([])):t(y||[]),r(!1))})(),()=>{f=!0}},[a]);const u=j.useMemo(()=>s.filter(f=>{if(l!=="all"&&f.lead_type!==l)return!1;if(c){const g=c.toLowerCase();if(![f.email,f.first_name,f.last_name,f.phone,f.source_page,f.referrer].filter(Boolean).join(" ").toLowerCase().includes(g))return!1}return!0}),[s,l,c]),h=j.useMemo(()=>{const f=u.length,g=new Set(u.map(y=>y.email.toLowerCase())).size,x={};return u.forEach(y=>{x[y.lead_type]=(x[y.lead_type]||0)+1}),{total:f,uniqueEmails:g,byType:x}},[u]),m=()=>{const g=[["Date (ET)","Type","Email","First","Last","Phone","Listing ID","Source Page","Referrer","Criteria"].join(",")];u.forEach(b=>{var S;const w=[aEt(b.created_at),((S=J$[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"}),y=URL.createObjectURL(x),v=document.createElement("a");v.href=y,v.download=`public-site-leads-${new Date().toISOString().slice(0,10)}.csv`,v.click(),URL.revokeObjectURL(y)};return e.jsxs("div",{className:"min-h-screen bg-slate-50",children:[e.jsx(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(wr,{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(xi,{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(Ie,{className:"p-4",children:[e.jsx("div",{className:"text-xs text-slate-500 uppercase tracking-wide",children:"Total Leads"}),e.jsx("div",{className:"text-2xl font-bold mt-1",children:h.total}),e.jsxs("div",{className:"text-xs text-slate-500 mt-1",children:[h.uniqueEmails," unique"]})]})}),Object.keys(J$).map(f=>{const g=J$[f],x=g.icon;return e.jsx(je,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-slate-500 uppercase tracking-wide",children:[e.jsx(x,{className:"h-3.5 w-3.5"}),g.label]}),e.jsx("div",{className:"text-2xl font-bold mt-1",children:h.byType[f]||0})]})},f)})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(ms,{value:a,onValueChange:f=>i(f),children:[e.jsx(us,{className:"w-[160px] bg-white",children:e.jsx(fs,{})}),e.jsx(hs,{children:rEt.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(J$).map(f=>e.jsx(Ge,{value:f,children:J$[f].label},f))]})]}),e.jsxs("div",{className:"relative flex-1 min-w-[200px] max-w-md",children:[e.jsx(Zr,{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=J$[f.lead_type],x=g==null?void 0:g.icon,y=[f.first_name,f.last_name].filter(Boolean).join(" ")||"—";return e.jsxs("tr",{className:"border-b hover:bg-slate-50/60",children:[e.jsx("td",{className:"px-4 py-3 whitespace-nowrap text-slate-600 text-xs",children:aEt(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:y}),e.jsxs("a",{href:`mailto:${f.email}`,className:"text-xs text-blue-600 hover:underline inline-flex items-center gap-1",children:[e.jsx(mn,{className:"h-3 w-3"}),f.email]})]}),e.jsx("td",{className:"px-4 py-3 whitespace-nowrap",children:f.phone?e.jsxs("a",{href:`tel:${f.phone}`,className:"text-xs text-blue-600 hover:underline inline-flex items-center gap-1",children:[e.jsx(Da,{className:"h-3 w-3"}),f.phone]}):e.jsx("span",{className:"text-slate-400 text-xs",children:"—"})}),e.jsxs("td",{className:"px-4 py-3 text-xs text-slate-600 max-w-xs",children:[f.listing_id&&e.jsxs("div",{className:"mb-0.5",children:["Listing: ",e.jsxs("span",{className:"font-mono text-[10px]",children:[f.listing_id.slice(0,8),"…"]})]}),f.criteria&&Object.keys(f.criteria).length>0&&e.jsx("div",{className:"text-slate-500 line-clamp-2",children:Object.entries(f.criteria).map(([v,b])=>`${v}: ${b}`).join(" · ")})]}),e.jsxs("td",{className:"px-4 py-3 text-xs text-slate-500 max-w-xs truncate",children:[f.source_page&&e.jsxs("div",{className:"inline-flex items-center gap-1",children:[e.jsx(Fr,{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 lor=()=>{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:y}=await q.from("profiles").select("id, name, email").in("id",x);return f==null?void 0:f.map(b=>({...b,profiles:(y==null?void 0:y.find(w=>w.id===b.user_id))||null}))}}),l=a==null?void 0:a.filter(f=>{var x,y,v,b,w;const g=s.toLowerCase();return((y=(x=f.profiles)==null?void 0:x.name)==null?void 0:y.toLowerCase().includes(g))||((b=(v=f.profiles)==null?void 0:v.email)==null?void 0:b.toLowerCase().includes(g))||((w=f.review_text)==null?void 0:w.toLowerCase().includes(g))}),o=a!=null&&a.length?(a.reduce((f,g)=>f+g.rating,0)/a.length).toFixed(1):"0.0",c=a==null?void 0:a.reduce((f,g)=>(f[g.rating]=(f[g.rating]||0)+1,f),{}),d=(a==null?void 0:a.filter(f=>f.posted_to_google).length)||0,u=f=>e.jsx("div",{className:"flex gap-0.5",children:[1,2,3,4,5].map(g=>e.jsx(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(Gn,{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(Gn,{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(Gn,{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(Gn,{children:"Posted to Google"}),e.jsxs(Et,{className:"flex items-center gap-2 text-3xl",children:[d,e.jsx(Fr,{className:"h-5 w-5 text-muted-foreground"})]})]})})]}),e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(Zr,{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(Ie,{className:"p-0",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Member"}),e.jsx(Dt,{children:"Rating"}),e.jsx(Dt,{className:"hidden md:table-cell",children:"Review"}),e.jsx(Dt,{children:"Google"}),e.jsx(Dt,{children:"Date"})]})}),e.jsx(fi,{children:i?e.jsx(En,{children:e.jsx(_t,{colSpan:5,className:"text-center py-8",children:"Loading reviews..."})}):(l==null?void 0:l.length)===0?e.jsx(En,{children:e.jsx(_t,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No reviews found"})}):l==null?void 0:l.map(f=>{var g,x;return e.jsxs(En,{className:"cursor-pointer hover:bg-muted/50",onClick:()=>r(f),children:[e.jsx(_t,{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(_t,{children:u(f.rating)}),e.jsx(_t,{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(_t,{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(_t,{className:"text-sm text-muted-foreground",children:en(new Date(f.created_at),"MMM d, yyyy")})]},f.id)})})]})})}),e.jsx(zs,{open:!!n,onOpenChange:()=>r(null),children:e.jsxs(Os,{className:"max-w-lg",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Review Details"})}),n&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-4 p-4 bg-muted/50 rounded-lg",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-semibold text-lg",children:((h=n.profiles)==null?void 0:h.name)||"Unknown Member"}),((m=n.profiles)==null?void 0:m.email)&&e.jsxs("a",{href:`mailto:${n.profiles.email}`,className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-primary",children:[e.jsx(mn,{className:"h-3 w-3"}),n.profiles.email]})]}),e.jsxs("div",{className:"text-right",children:[u(n.rating),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[n.rating," out of 5 stars"]})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-medium mb-2",children:"Review"}),e.jsx("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap",children:n.review_text||"No written review provided."})]}),e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Ta,{className:"h-4 w-4"}),en(new Date(n.created_at),"MMMM d, yyyy 'at' h:mm a")]}),n.posted_to_google?e.jsxs($e,{variant:"secondary",className:"bg-green-100 text-green-800",children:[e.jsx(Fr,{className:"h-3 w-3 mr-1"}),"Posted to Google"]}):e.jsx($e,{variant:"outline",children:"Not posted to Google"})]})]})]})})]})})},iEt={agent_card:"Agent Card",listing:"Listing",lead_site:"Lead Site",guest_book:"Guest Book",landing_page:"Landing Page",connect_page:"Connect Page",booking:"Booking"},cor={sent:"bg-green-100 text-green-800",backfilled:"bg-blue-100 text-blue-800",failed:"bg-red-100 text-red-800",pending:"bg-yellow-100 text-yellow-800"};function dor(){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(y=>y.status==="sent"||y.status==="backfilled").length,g=u.filter(y=>y.status==="failed").length,x=new Set(u.map(y=>y.agent_user_id).filter(Boolean)).size;return{total:m,sent:f,failed:g,agents:x}},[u]);return e.jsx(Vs,{children:e.jsxs("div",{className:"container mx-auto py-6 space-y-6",children:[e.jsx(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(Ie,{className:"p-4",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:"Total"}),e.jsx("div",{className:"text-2xl font-bold",children:h.total})]})}),e.jsx(je,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:"Sent"}),e.jsx("div",{className:"text-2xl font-bold text-green-600",children:h.sent})]})}),e.jsx(je,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:"Failed"}),e.jsx("div",{className:"text-2xl font-bold text-red-600",children:h.failed})]})}),e.jsx(je,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:"Unique Agents"}),e.jsx("div",{className:"text-2xl font-bold",children:h.agents})]})})]}),e.jsxs("div",{className:"flex flex-col md:flex-row gap-3",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Zr,{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(iEt).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(Ie,{className:"p-0",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"When"}),e.jsx(Dt,{children:"Source"}),e.jsx(Dt,{children:"Agent"}),e.jsx(Dt,{children:"Lead"}),e.jsx(Dt,{children:"Status"})]})}),e.jsx(fi,{children:d?e.jsx(En,{children:e.jsx(_t,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"Loading…"})}):u.length===0?e.jsx(En,{children:e.jsx(_t,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No notifications match the current filters."})}):u.map(m=>e.jsxs(En,{children:[e.jsx(_t,{className:"whitespace-nowrap text-sm",children:en(new Date(m.created_at),"MMM d, yyyy h:mm a")}),e.jsx(_t,{children:e.jsx($e,{variant:"secondary",children:iEt[m.source]||m.source})}),e.jsxs(_t,{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(_t,{children:[e.jsx("div",{className:"font-medium",children:m.lead_name||"—"}),e.jsxs("div",{className:"text-xs text-muted-foreground flex flex-wrap gap-x-3 gap-y-1",children:[m.lead_email&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(mn,{className:"h-3 w-3"}),m.lead_email]}),m.lead_phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Da,{className:"h-3 w-3"}),m.lead_phone]})]})]}),e.jsxs(_t,{children:[e.jsx($e,{className:cor[m.status]||"",children:m.status}),m.error_message&&e.jsx("div",{className:"text-xs text-red-600 mt-1 max-w-[220px] truncate",title:m.error_message,children:m.error_message})]})]},m.id))})]})})}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Historical entries (before this feature was enabled) are marked as ",e.jsx("em",{children:"backfilled"})," and reconstructed from the underlying lead records. New leads are logged automatically going forward."]})]})})}const uor=[{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"}],hor=Array.from({length:24},(s,t)=>({value:String(t),label:t===0?"12:00 AM":t<12?`${t}:00 AM`:t===12?"12:00 PM":`${t-12}:00 PM`}));function mor(){const s=Wt(),{user:t}=bs(),[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}}),y=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"]}),re.success("Settings updated")},onError:P=>{re.error("Failed to update settings: "+P.message)}}),v=async()=>{r(!0);try{const{data:P,error:R}=await q.functions.invoke("send-weekly-digest",{body:{manual:!0}});if(R)throw R;P.queued?re.success(`${P.queued.toLocaleString()} emails queued! They'll be sent automatically (~80/minute).`):P.sent!==void 0&&re.success(`Digest sent! ${P.sent} emails delivered, ${P.failed} failed`),g(),s.invalidateQueries({queryKey:["weekly-digest-logs"]})}catch(P){re.error("Failed to send digest: "+P.message)}finally{r(!1)}},b=async()=>{var P,R,D,O,U,W;if(!(t!=null&&t.email)){re.error("No email found for your account");return}i(!0);try{const{data:V,error:G}=await q.functions.invoke("send-weekly-digest",{body:{preview:!0,previewEmail:t.email}});if(G)throw G;const Y=V==null?void 0:V.resendId,X=V==null?void 0:V.resendDetails,ae=X==null?void 0:X.status,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),ne=((U=(O=X==null?void 0:X.body)==null?void 0:O.error)==null?void 0:U.message)||((W=X==null?void 0:X.body)==null?void 0:W.message);re.success(Y?`Preview accepted by email provider (id: ${Y})${ae?`, status check: ${ae}`:""}${le?`, provider: ${le}`:""}${ne?` (${ne})`:""}. Check spam/promotions—delivery can take a few minutes.`:"Preview accepted by email provider. Check spam/promotions—delivery can take a few minutes.")}catch(V){re.error("Failed to send preview: "+V.message)}finally{i(!1)}},w=async()=>{o(!0);try{const{data:P,error:R}=await q.functions.invoke("send-weekly-digest",{body:{retryFailed:!0}});if(R)throw R;P.queued===0||P.sent===0&&P.failed===0&&!P.queued?re.info("No failed emails to retry"):P.queued?re.success(`${P.queued} emails queued for retry!`):re.success(`Retry complete! ${P.sent} emails delivered, ${P.failed} failed`),g(),s.invalidateQueries({queryKey:["weekly-digest-logs"]}),s.invalidateQueries({queryKey:["digest-today-failed-count"]}),s.invalidateQueries({queryKey:["digest-today-missing-count"]})}catch(P){re.error("Failed to retry: "+P.message)}finally{o(!1)}},S=f!=null&&f.total?Math.round((f.sent+f.failed)/f.total*100):0,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(ha,{defaultValue:"settings",className:"space-y-6",children:[e.jsxs(ma,{children:[e.jsxs(Zt,{value:"settings",className:"flex items-center gap-2",children:[e.jsx(Nd,{className:"h-4 w-4"}),"Settings"]}),e.jsxs(Zt,{value:"stats",className:"flex items-center gap-2",children:[e.jsx(Gl,{className:"h-4 w-4"}),"Delivery Stats"]})]}),e.jsxs(Xt,{value:"settings",className:"space-y-6",children:[A&&f&&e.jsx(je,{className:"border-primary/50 bg-primary/5",children:e.jsxs(Ie,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-4 mb-4",children:[e.jsx(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(Ie,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"p-3 rounded-full bg-primary/10",children:e.jsx(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(Ie,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"p-3 rounded-full bg-emerald-500/10",children:e.jsx(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(Ie,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"p-3 rounded-full bg-destructive/10",children:e.jsx(Nu,{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(Ie,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"p-3 rounded-full bg-primary/10",children:e.jsx(da,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:I.lastSent?en(new Date(I.lastSent),"MMM d"):"Never"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Last Sent"})]})]})})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(da,{className:"h-5 w-5"}),"Schedule"]}),e.jsx(Gn,{children:"Configure when the digest is sent"})]}),e.jsxs(Ie,{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Enable Weekly Digest"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Send automated weekly emails to members"})]}),e.jsx(Sn,{checked:c==null?void 0:c.is_enabled,onCheckedChange:P=>y.mutate({is_enabled:P})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Cron Frequency"}),e.jsxs(ms,{value:(c==null?void 0:c.cron_frequency)||"daily",onValueChange:P=>y.mutate({cron_frequency:P}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"daily",children:"Daily (runs once at selected time)"}),e.jsx(Ge,{value:"hourly",children:"Hourly (checks every hour)"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(c==null?void 0:c.cron_frequency)==="hourly"?"Cron runs every hour; digest sends when day & hour match.":"Cron runs once daily at the selected hour (UTC)."})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Day of Week"}),e.jsxs(ms,{value:String(c==null?void 0:c.send_day),onValueChange:P=>y.mutate({send_day:parseInt(P)}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:uor.map(P=>e.jsx(Ge,{value:P.value,children:P.label},P.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Time (UTC)"}),e.jsxs(ms,{value:String(c==null?void 0:c.send_hour),onValueChange:P=>y.mutate({send_hour:parseInt(P)}),disabled:(c==null?void 0:c.cron_frequency)==="daily",children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:hor.map(P=>e.jsx(Ge,{value:P.value,children:P.label},P.value))})]})]})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{onClick:b,disabled:a,variant:"outline",className:"flex-1",children:[e.jsx(Ca,{className:"h-4 w-4 mr-2"}),a?"Sending...":"Send Preview to Me"]}),e.jsxs($,{onClick:v,disabled:n,className:"flex-1",children:[e.jsx(Kr,{className:"h-4 w-4 mr-2"}),n?"Sending...":"Send to All"]})]}),x>0&&e.jsxs($,{onClick:w,disabled:l,variant:"outline",className:"w-full",children:[e.jsx(ro,{className:`h-4 w-4 mr-2 ${l?"animate-spin":""}`}),l?"Retrying...":`Retry ${x} Failed`]})]})]})]}),e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(Jr,{className:"h-5 w-5"}),"Content Sections"]}),e.jsx(Gn,{children:"Choose what to include in the digest"})]}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Jr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ee,{children:"New Resources"})]}),e.jsx(Sn,{checked:c==null?void 0:c.include_new_resources,onCheckedChange:P=>y.mutate({include_new_resources:P})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Yn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ee,{children:"Community Highlights"})]}),e.jsx(Sn,{checked:c==null?void 0:c.include_community_posts,onCheckedChange:P=>y.mutate({include_community_posts:P})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Gl,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ee,{children:"Agent OS Stats"})]}),e.jsx(Sn,{checked:c==null?void 0:c.include_agent_os_stats,onCheckedChange:P=>y.mutate({include_agent_os_stats:P})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ta,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ee,{children:"Upcoming Events"})]}),e.jsx(Sn,{checked:c==null?void 0:c.include_upcoming_events,onCheckedChange:P=>y.mutate({include_upcoming_events:P})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(nh,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ee,{children:"Goals Progress"})]}),e.jsx(Sn,{checked:c==null?void 0:c.include_goals_progress,onCheckedChange:P=>y.mutate({include_goals_progress:P})})]})]})]})]}),e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{children:"Custom Introduction"}),e.jsx(Gn,{children:"Personalize the intro message (optional)"})]}),e.jsx(Ie,{children:e.jsx(Ls,{placeholder:"Here's what's new this week to help you grow your business...",value:(c==null?void 0:c.custom_intro_text)||"",onChange:P=>y.mutate({custom_intro_text:P.target.value||null}),rows:3})})]})]}),e.jsx(Xt,{value:"stats",children:e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(mn,{className:"h-5 w-5"}),"Delivery History"]}),e.jsx(Gn,{children:"Recent digest emails sent to members"})]}),e.jsx(Ie,{children:h?e.jsx("div",{className:"animate-pulse space-y-2",children:[1,2,3,4,5].map(P=>e.jsx("div",{className:"h-12 bg-muted rounded"},P))}):u&&u.length>0?e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Email"}),e.jsx(Dt,{children:"Sent At"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{children:"Resources"}),e.jsx(Dt,{children:"Agent OS"})]})}),e.jsx(fi,{children:u.map(P=>e.jsxs(En,{children:[e.jsx(_t,{className:"font-medium",children:P.email_sent_to}),e.jsx(_t,{children:en(new Date(P.sent_at),"MMM d, yyyy h:mm a")}),e.jsx(_t,{children:e.jsx($e,{variant:P.delivery_status==="sent"?"default":"destructive",children:P.delivery_status})}),e.jsx(_t,{children:P.resources_count}),e.jsx(_t,{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(mn,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No digests sent yet"}),e.jsx("p",{className:"text-sm",children:"Send your first digest to see delivery stats"})]})})]})})]})})}const por={first_event:"bg-emerald-100 text-emerald-800 dark:bg-emerald-900 dark:text-emerald-200",streak_3:"bg-orange-100 text-orange-800 dark:bg-orange-900 dark:text-orange-200",streak_5:"bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200",events_5:"bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200",events_10:"bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-200",events_25:"bg-amber-100 text-amber-800 dark:bg-amber-900 dark:text-amber-200"};function gor(){var J,ce,_e;const s=Wt(),[t,n]=j.useState(""),[r,a]=j.useState(null),[i,l]=j.useState(!1),[o,c]=j.useState(!1),[d,u]=j.useState(""),[h,m]=j.useState(""),[f,g]=j.useState(!0),[x,y]=j.useState(!1),[v,b]=j.useState(""),[w,S]=j.useState(null),{data:A,isLoading:E}=st({queryKey:["admin-agent-points"],queryFn:async()=>{const{data:he,error:ue}=await q.from("agent_attendance_stats").select("*").order("total_points",{ascending:!1});if(ue)throw ue;const ve=(he==null?void 0:he.map(Le=>Le.user_id))||[],{data:Ee}=await q.from("profiles").select("id, name, email").in("id",ve),Se=new Map((Ee==null?void 0:Ee.map(Le=>[Le.id,{name:Le.name,email:Le.email}]))||[]);return he==null?void 0:he.map(Le=>({...Le,profile:Se.get(Le.user_id)||null}))}}),{data:I}=st({queryKey:["all-profiles-for-points",A],queryFn:async()=>{const ue=[];let ve=0;for(;;){const{data:Ee,error:Se}=await q.from("profiles").select("id, name, email").order("name").range(ve,ve+1e3-1);if(Se)throw Se;if(ue.push(...Ee),!Ee||Ee.length<1e3)break;ve+=1e3}return ue}}),R=((I==null?void 0:I.filter(he=>!(A!=null&&A.some(ue=>ue.user_id===he.id))))||[]).filter(he=>{var ve,Ee;if(!v)return!0;const ue=v.toLowerCase();return((ve=he.name)==null?void 0:ve.toLowerCase().includes(ue))||((Ee=he.email)==null?void 0:Ee.toLowerCase().includes(ue))}),{data:D,isLoading:O}=st({queryKey:["agent-point-history",r==null?void 0:r.user_id],queryFn:async()=>{if(!(r!=null&&r.user_id))return[];const{data:he,error:ue}=await q.from("agent_points").select("*").eq("user_id",r.user_id).order("created_at",{ascending:!1});if(ue)throw ue;return he},enabled:!!(r!=null&&r.user_id)&&o}),{data:U}=st({queryKey:["agent-badges",r==null?void 0:r.user_id],queryFn:async()=>{if(!(r!=null&&r.user_id))return[];const{data:he,error:ue}=await q.from("agent_badges").select("*").eq("user_id",r.user_id).order("earned_at",{ascending:!1});if(ue)throw ue;return he},enabled:!!(r!=null&&r.user_id)}),W=mt({mutationFn:async({userId:he,points:ue,reason:ve})=>{const{error:Ee}=await q.from("agent_points").insert({user_id:he,points:ue,reason:ve});if(Ee)throw Ee;const{data:Se}=await q.from("agent_attendance_stats").select("total_points, spendable_points").eq("user_id",he).maybeSingle(),Le=((Se==null?void 0:Se.total_points)||0)+ue,Fe=((Se==null?void 0:Se.spendable_points)||0)+ue,{error:ke}=await q.from("agent_attendance_stats").upsert({user_id:he,total_points:Math.max(0,Le),spendable_points:Math.max(0,Fe),updated_at:new Date().toISOString()},{onConflict:"user_id"});if(ke)throw ke},onSuccess:()=>{s.invalidateQueries({queryKey:["admin-agent-points"]}),s.invalidateQueries({queryKey:["agent-point-history"]}),l(!1),u(""),m(""),re.success(f?"Points awarded successfully!":"Points deducted successfully!")},onError:he=>{console.error("Error modifying points:",he),re.error("Failed to modify points")}}),V=()=>{if(!r||!d||!h){re.error("Please fill in all fields");return}const he=parseInt(d);if(isNaN(he)||he<=0){re.error("Please enter a valid positive number");return}W.mutate({userId:r.user_id,points:f?he:-he,reason:h})},G=()=>{if(!w||!d||!h){re.error("Please fill in all fields");return}const he=parseInt(d);if(isNaN(he)||he<=0){re.error("Please enter a valid positive number");return}W.mutate({userId:w.id,points:he,reason:h},{onSuccess:()=>{y(!1),S(null),b("")}})},Y=(he,ue)=>{a(he),g(ue),l(!0)},X=he=>{a(he),c(!0)},ae=A==null?void 0:A.filter(he=>{var Se,Le,Fe,ke;const ue=((Le=(Se=he.profile)==null?void 0:Se.name)==null?void 0:Le.toLowerCase())||"",ve=((ke=(Fe=he.profile)==null?void 0:Fe.email)==null?void 0:ke.toLowerCase())||"",Ee=t.toLowerCase();return ue.includes(Ee)||ve.includes(Ee)}),le=(A==null?void 0:A.reduce((he,ue)=>he+ue.total_points,0))||0,ne=(A==null?void 0:A.length)||0,te=ne>0?Math.round(le/ne):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(he=>e.jsx(xn,{className:"h-24"},he))}),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(Ie,{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:ne}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"with points tracked"})]})}),e.jsx(je,{children:e.jsxs(Ie,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Kl,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Total Points"})]}),e.jsx("p",{className:"text-2xl font-bold",children:le.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"awarded across all agents"})]})}),e.jsx(je,{children:e.jsxs(Ie,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(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(Zr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search agents...",value:t,onChange:he=>n(he.target.value),className:"pl-10"})]}),e.jsxs($,{onClick:()=>y(!0),children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Award Points to New Agent"]})]}),e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{children:"Agent Leaderboard"}),e.jsx(Gn,{children:"All agents with their points, events, and streaks"})]}),e.jsx(Ie,{children:!ae||ae.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Kl,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No agents with points yet"})]}):e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{children:[e.jsx(Dt,{className:"w-12",children:"#"}),e.jsx(Dt,{children:"Agent"}),e.jsx(Dt,{className:"text-center",children:"Total Points"}),e.jsx(Dt,{className:"text-center",children:"Spendable"}),e.jsx(Dt,{className:"text-center",children:"Events"}),e.jsx(Dt,{className:"text-center",children:"Streak"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(fi,{children:ae.map((he,ue)=>{var ve,Ee,Se,Le;return e.jsxs(En,{children:[e.jsx(_t,{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(_t,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Oa,{className:"h-8 w-8",children:e.jsx(za,{children:((Ee=(ve=he.profile)==null?void 0:ve.name)==null?void 0:Ee.charAt(0))||"?"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((Se=he.profile)==null?void 0:Se.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(Le=he.profile)==null?void 0:Le.email})]})]})}),e.jsx(_t,{className:"text-center",children:e.jsxs($e,{variant:"secondary",className:"font-bold",children:[e.jsx(ei,{className:"h-3 w-3 mr-1"}),he.total_points]})}),e.jsx(_t,{className:"text-center",children:e.jsxs($e,{variant:"outline",className:"font-bold text-primary",children:[e.jsx(ul,{className:"h-3 w-3 mr-1"}),he.spendable_points||0]})}),e.jsx(_t,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(Ta,{className:"h-3 w-3 text-muted-foreground"}),he.total_events_attended]})}),e.jsx(_t,{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"}),he.current_streak]})}),e.jsx(_t,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx($,{variant:"ghost",size:"sm",onClick:()=>Y(he,!0),title:"Award points",children:e.jsx(dn,{className:"h-4 w-4 text-green-600"})}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>Y(he,!1),title:"Deduct points",children:e.jsx(ZN,{className:"h-4 w-4 text-red-600"})}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>X(he),title:"View history",children:e.jsx(Aw,{className:"h-4 w-4"})})]})})]},he.user_id)})})]})})]}),e.jsx(zs,{open:i,onOpenChange:l,children:e.jsxs(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:f?"Award Points":"Deduct Points"}),e.jsxs(Pr,{children:[f?"Award":"Deduct"," points ",f?"to":"from"," ",((J=r==null?void 0:r.profile)==null?void 0:J.name)||"this agent"]})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"points",children:"Points Amount"}),e.jsx(pe,{id:"points",type:"number",min:"1",placeholder:"Enter points...",value:d,onChange:he=>u(he.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"reason",children:"Reason"}),e.jsx(Ls,{id:"reason",placeholder:"Enter reason for this adjustment...",value:h,onChange:he=>m(he.target.value)})]})]}),e.jsxs(Sr,{children:[e.jsx($,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx($,{onClick:V,disabled:W.isPending,className:f?"bg-green-600 hover:bg-green-700":"bg-red-600 hover:bg-red-700",children:W.isPending?"Saving...":f?"Award Points":"Deduct Points"})]})]})}),e.jsx(zs,{open:o,onOpenChange:c,children:e.jsxs(Os,{className:"max-w-2xl",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{children:["Point History: ",(ce=r==null?void 0:r.profile)==null?void 0:ce.name]}),e.jsx(Pr,{children:"View all point transactions and badges for this agent"})]}),e.jsxs(ha,{defaultValue:"history",className:"w-full",children:[e.jsxs(ma,{className:"grid w-full grid-cols-2",children:[e.jsx(Zt,{value:"history",children:"Point History"}),e.jsx(Zt,{value:"badges",children:"Badges"})]}),e.jsx(Xt,{value:"history",className:"mt-4",children:O?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(he=>e.jsx(xn,{className:"h-12"},he))}):!D||D.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Aw,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"No point history yet"})]}):e.jsx("div",{className:"max-h-80 overflow-y-auto space-y-2",children:D.map(he=>e.jsxs("div",{className:"flex items-center justify-between p-3 border rounded-lg",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-medium",children:he.reason}),e.jsx("p",{className:"text-xs text-muted-foreground",children:en(new Date(he.created_at),"MMM d, yyyy h:mm a")})]}),e.jsxs($e,{variant:he.points>=0?"default":"destructive",className:he.points>=0?"bg-green-100 text-green-800":"",children:[he.points>=0?"+":"",he.points]})]},he.id))})}),e.jsx(Xt,{value:"badges",className:"mt-4",children:!U||U.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(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(he=>e.jsxs("div",{className:`p-3 rounded-lg ${por[he.badge_type]||"bg-gray-100"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Im,{className:"h-5 w-5"}),e.jsx("span",{className:"font-medium",children:he.badge_name})]}),he.badge_description&&e.jsx("p",{className:"text-xs mt-1 opacity-80",children:he.badge_description}),e.jsxs("p",{className:"text-xs mt-1 opacity-60",children:["Earned ",en(new Date(he.earned_at),"MMM d, yyyy")]})]},he.id))})})]})]})}),e.jsx(zs,{open:x,onOpenChange:he=>{y(he),he||(S(null),b(""),u(""),m(""))},children:e.jsxs(Os,{className:"max-w-md",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Award Points to New Agent"}),e.jsx(Pr,{children:"Select an agent who doesn't have points yet and award them points"})]}),e.jsx("div",{className:"space-y-4 py-4",children:w?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-muted/50 rounded-lg",children:[e.jsx(Oa,{className:"h-10 w-10",children:e.jsx(za,{children:((_e=w.name)==null?void 0:_e.charAt(0))||"?"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-medium",children:w.name||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:w.email})]}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>S(null),children:"Change"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"new-points",children:"Points Amount"}),e.jsx(pe,{id:"new-points",type:"number",min:"1",placeholder:"Enter points...",value:d,onChange:he=>u(he.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"new-reason",children:"Reason"}),e.jsx(Ls,{id:"new-reason",placeholder:"Enter reason for awarding points...",value:h,onChange:he=>m(he.target.value)})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Search Agent"}),e.jsxs("div",{className:"relative",children:[e.jsx(Zr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search by name or email...",value:v,onChange:he=>b(he.target.value),className:"pl-10"})]})]}),e.jsx("div",{className:"max-h-60 overflow-y-auto border rounded-lg",children:R.length===0?e.jsxs("div",{className:"text-center py-4 text-muted-foreground",children:[e.jsx(Yn,{className:"h-6 w-6 mx-auto mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:v?"No matching agents found":"All agents already have points"})]}):R.slice(0,20).map(he=>{var ue;return e.jsxs("button",{onClick:()=>S(he),className:"w-full flex items-center gap-3 p-3 hover:bg-muted/50 transition-colors border-b last:border-b-0 text-left",children:[e.jsx(Oa,{className:"h-8 w-8",children:e.jsx(za,{children:((ue=he.name)==null?void 0:ue.charAt(0))||"?"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:he.name||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:he.email})]})]},he.id)})})]})}),e.jsxs(Sr,{children:[e.jsx($,{variant:"outline",onClick:()=>y(!1),children:"Cancel"}),w&&e.jsxs($,{onClick:G,disabled:W.isPending,className:"bg-green-600 hover:bg-green-700",children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Award Points"]})]})]})})]})})}function xor(){const{data:s,isLoading:t}=MDs(),[n,r]=j.useState(null),[a,i]=j.useState(!1),[l,o]=j.useState(""),[c,d]=j.useState("all"),[u,h]=j.useState("newest"),[m,f]=j.useState("table"),g=j.useMemo(()=>(s==null?void 0:s.map(w=>w.user_id))||[],[s]),x=j.useMemo(()=>(s==null?void 0:s.map(w=>w.id))||[],[s]),{data:y}=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:v}=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=y==null?void 0:y[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=y==null?void 0:y[S.user_id])==null?void 0:E.name)||"").localeCompare(((I=y==null?void 0:y[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=v==null?void 0:v[A.id])==null?void 0:E.views)||0)-(((I=v==null?void 0:v[S.id])==null?void 0:I.views)||0)}):u==="views_asc"?w.sort((S,A)=>{var E,I;return(((E=v==null?void 0:v[S.id])==null?void 0:E.views)||0)-(((I=v==null?void 0:v[A.id])==null?void 0:I.views)||0)}):u==="leads_desc"?w.sort((S,A)=>{var E,I;return(((E=v==null?void 0:v[A.id])==null?void 0:E.leads)||0)-(((I=v==null?void 0:v[S.id])==null?void 0:I.leads)||0)}):u==="leads_asc"&&w.sort((S,A)=>{var E,I;return(((E=v==null?void 0:v[S.id])==null?void 0:E.leads)||0)-(((I=v==null?void 0:v[A.id])==null?void 0:I.leads)||0)}),w},[s,c,l,u,y]);return e.jsxs(Vs,{title:"Digital Agent Cards",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Digital Agent Cards"}),e.jsx("p",{className:"text-muted-foreground",children:"Create and manage agent digital business cards"})]}),e.jsxs($,{onClick:()=>i(!0),children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Create Card"]})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Zr,{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(nV,{className:"h-4 w-4"})}),e.jsx($,{variant:m==="grid"?"default":"ghost",size:"sm",onClick:()=>f("grid"),className:"rounded-l-none",children:e.jsx(Qf,{className:"h-4 w-4"})})]})]}),!t&&s&&s.length>0&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Showing ",b.length," of ",s.length," cards"]}),t?e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(w=>e.jsx(xn,{className:"h-48"},w))}):b.length>0?m==="table"?e.jsx(yor,{cards:b,cardProfiles:y,cardStats:v,onEdit:r,sortBy:u,setSortBy:h}):e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:b.map(w=>e.jsx(vor,{card:w,onEdit:()=>r(w),stats:v==null?void 0:v[w.id]},w.id))}):s&&s.length>0?e.jsx(je,{children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center py-12",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 matching cards"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Try adjusting your search or filters"})]})}):e.jsx(je,{children:e.jsxs(Ie,{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(dn,{className:"h-4 w-4 mr-2"}),"Create Card"]})]})})]}),e.jsx(bor,{open:a,onOpenChange:i}),n&&e.jsx(_or,{card:n,open:!!n,onOpenChange:w=>!w&&r(null)})]})}function yor({cards:s,cardProfiles:t,cardStats:n,onEdit:r,sortBy:a,setSortBy:i}){const l=c=>{a===`${c}_desc`?i(`${c}_asc`):i(`${c}_desc`)},o=({field:c})=>a===`${c}_desc`?e.jsx(Dg,{className:"h-3 w-3"}):a===`${c}_asc`?e.jsx(Zf,{className:"h-3 w-3"}):e.jsx(zy,{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),re.success("Link copied!")},children:e.jsx(Ha,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",asChild:!0,children:e.jsx("a",{href:h,target:"_blank",rel:"noopener noreferrer",children:e.jsx(Fr,{className:"h-3.5 w-3.5"})})})]})})]},c.id)})})]})})})}function vor({card:s,onEdit:t,stats:n}){const[r,a]=j.useState(null);j.useEffect(()=>{(async()=>{const{data:c}=await q.from("profiles").select("name").eq("id",s.user_id).single();let d=null;try{const{data:u}=await q.storage.from("avatars").list(`${s.user_id}`);if(u&&u.length>0){const{data:h}=q.storage.from("avatars").getPublicUrl(`${s.user_id}/${u[0].name}`);d=h.publicUrl}}catch{}a({name:(c==null?void 0:c.name)||"Unknown",avatar_url:d})})()},[s.user_id]);const i=`https://cards.relevelup.com/${s.slug}`,l=()=>{navigator.clipboard.writeText(i),re.success("Link copied!")};return e.jsx(je,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start gap-3 mb-3",children:[e.jsxs(Oa,{className:"h-10 w-10",children:[e.jsx(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(Ca,{className:"h-3.5 w-3.5"}),(n==null?void 0:n.views)??0," views"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(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(Ha,{className:"h-3 w-3"})}),e.jsx($,{variant:"outline",size:"sm",asChild:!0,children:e.jsx("a",{href:i,target:"_blank",rel:"noopener noreferrer",children:e.jsx(Fr,{className:"h-3 w-3"})})})]})]})})}function bor({open:s,onOpenChange:t}){const[n,r]=j.useState(""),[a,i]=j.useState(""),[l,o]=j.useState(""),[c,d]=j.useState(!1),u=U7t(),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,y=()=>{if(!n||!a.trim()){re.error("Select an agent and enter a slug");return}u.mutate({user_id:n,slug:a.trim().toLowerCase().replace(/[^a-z0-9-]/g,"-"),is_published:!0},{onSuccess:()=>{t(!1),r(""),i(""),o("")}})},v=b=>{var S;r(b),d(!1);const w=m==null?void 0:m.find(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(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Create Agent Card"}),e.jsx(Pr,{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(Kd,{open:c,onOpenChange:d,children:[e.jsx(Yd,{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(Sw,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Od,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(S2,{shouldFilter:!1,children:[e.jsx(C2,{placeholder:"Search by name or email...",value:l,onValueChange:o}),e.jsxs(A2,{children:[e.jsx(E2,{children:"No agents found."}),e.jsx(Dw,{children:(m||[]).map(b=>e.jsxs(m1,{value:b.id,onSelect:v,children:[e.jsx(ca,{className:Pt("mr-2 h-4 w-4",n===b.id?"opacity-100":"opacity-0")}),b.name," (",b.email,")"]},b.id))})]})]})})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"URL Slug"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"/card/"}),e.jsx(pe,{value:a,onChange:b=>i(b.target.value),placeholder:"john-doe"})]})]}),e.jsx($,{onClick:y,disabled:u.isPending,className:"w-full",children:u.isPending?"Creating...":"Create Card"})]})]})})}function _or({card:s,open:t,onOpenChange:n}){const r=q7t(),{data:a}=V7t(s.id),i=Wt(),[l,o]=j.useState(null),[c,d]=j.useState(!1),[u,h]=j.useState(!1),[m,f]=j.useState(""),[g,x]=j.useState(s.slug),[y,v]=j.useState(!1),[b,w]=j.useState({is_published:s.is_published,theme:s.theme,title:s.title||"",positioning_statement:s.positioning_statement||"",bio:s.bio||"",review_snippet:s.review_snippet||"",review_source_url:s.review_source_url||"",booking_url:s.booking_url||"",custom_cta_label:s.custom_cta_label||"",custom_cta_url:s.custom_cta_url||"",show_photo:s.show_photo,show_bio:s.show_bio,show_credentials:s.show_credentials,show_social_links:s.show_social_links,show_save_contact:s.show_save_contact,show_leave_review:s.show_leave_review,show_refer_friend:s.show_refer_friend,brokerage_display_name:s.brokerage_display_name||"",brokerage_logo_url:s.brokerage_logo_url||"",brokerage_logo_size:s.brokerage_logo_size||56,team_name:s.team_name||"",team_logo_url:s.team_logo_url||"",team_logo_size:s.team_logo_size||56});j.useEffect(()=>{t&&(async()=>{try{const{data:D}=await q.storage.from("avatars").list(`${s.user_id}`);if(D&&D.length>0){const{data:O}=q.storage.from("avatars").getPublicUrl(`${s.user_id}/${D[0].name}`);o(`${O.publicUrl}?t=${Date.now()}`)}}catch{}})()},[s.user_id,t]);const S=R=>{var U;const D=(U=R.target.files)==null?void 0:U[0];if(!D)return;if(!D.type.startsWith("image/")){re.error("Please select an image file");return}if(D.size>5*1024*1024){re.error("Image must be under 5MB");return}const O=new FileReader;O.onloadend=()=>{f(O.result),h(!0)},O.readAsDataURL(D),R.target.value=""},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"]}),re.success("Photo updated!")}catch(D){re.error(D.message||"Upload failed")}finally{d(!1)}},E=async()=>{const R=g.trim().toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/(^-|-$)/g,"");if(!R){re.error("Please enter a valid URL");return}if(R===s.slug){re.info("No changes to save");return}v(!0);try{const{data:D}=await q.from("agent_cards").select("id").eq("slug",R).neq("id",s.id).maybeSingle();if(D){re.error("This URL is already taken. Try another one.");return}const{error:O}=await q.from("agent_cards").update({slug:R}).eq("id",s.id);if(O)throw O;x(R),i.invalidateQueries({queryKey:["agent-cards-admin"]}),re.success("Card address updated!")}catch{re.error("Failed to update card address")}finally{v(!1)}},I=async(R,D)=>{var U;const O=(U=R.target.files)==null?void 0:U[0];if(O){if(!O.type.startsWith("image/")){re.error("Please select an image file");return}try{const W=O.name.split(".").pop()||"png",V=D==="brokerage_logo_url"?"brokerage-logo":"team-logo",G=`${s.user_id}/${V}.${W}`,{error:Y}=await q.storage.from("card-logos").upload(G,O,{upsert:!0});if(Y)throw Y;const{data:X}=q.storage.from("card-logos").getPublicUrl(G),ae=X.publicUrl+"?t="+Date.now();w(D==="brokerage_logo_url"?le=>({...le,[D]:ae,brokerage_display_name:""}):le=>({...le,[D]:ae,team_name:""})),re.success("Logo uploaded!")}catch{re.error("Failed to upload logo")}finally{R.target.value=""}}},P=()=>{r.mutate({id:s.id,...b,title:b.title||null,positioning_statement:b.positioning_statement||null,bio:b.bio||null,review_snippet:b.review_snippet||null,review_source_url:b.review_source_url||null,booking_url:b.booking_url||null,custom_cta_label:b.custom_cta_label||null,custom_cta_url:b.custom_cta_url||null,brokerage_display_name:b.brokerage_display_name||null,brokerage_logo_url:b.brokerage_logo_url||null,brokerage_logo_size:b.brokerage_logo_size,team_name:b.team_name||null,team_logo_url:b.team_logo_url||null,team_logo_size:b.team_logo_size},{onSuccess:()=>n(!1)})};return e.jsxs(e.Fragment,{children:[e.jsx(zs,{open:t,onOpenChange:n,children:e.jsxs(Os,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Edit Agent Card"}),e.jsxs(Pr,{children:["/card/",s.slug]})]}),e.jsxs(ha,{defaultValue:"content",children:[e.jsxs(ma,{className:"w-full",children:[e.jsx(Zt,{value:"content",className:"flex-1",children:"Content"}),e.jsx(Zt,{value:"sections",className:"flex-1",children:"Sections"}),e.jsx(Zt,{value:"blocks",className:"flex-1",children:"Blocks"}),e.jsx(Zt,{value:"analytics",className:"flex-1",children:"Analytics"})]}),e.jsxs(Xt,{value:"content",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{children:"Published"}),e.jsx(Sn,{checked:b.is_published,onCheckedChange:R=>w(D=>({...D,is_published:R}))})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Agent Photo"}),e.jsxs("div",{className:"flex items-center gap-4 mt-1",children:[e.jsxs(Oa,{className:"h-16 w-16",children:[e.jsx(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:y||g===s.slug,className:"shrink-0",children:y?"Saving...":"Update"})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Theme"}),e.jsxs(ms,{value:b.theme,onValueChange:R=>w(D=>({...D,theme:R})),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"standard",children:"✨ Standard (Modern Clean)"}),e.jsx(Ge,{value:"luxury",children:"🌙 Luxury (Dark & Gold)"}),e.jsx(Ge,{value:"bold",children:"🔥 Bold (Vibrant & Punchy)"}),e.jsx(Ge,{value:"classic",children:"📋 Classic (Professional)"})]})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Title / Tagline"}),e.jsx(pe,{value:b.title,onChange:R=>w(D=>({...D,title:R.target.value})),placeholder:"e.g. Luxury Real Estate Specialist"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Shown below the agent's name on the card"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Positioning Statement"}),e.jsx(pe,{value:b.positioning_statement,onChange:R=>w(D=>({...D,positioning_statement:R.target.value})),placeholder:"Your home journey, handled with care."})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Bio"}),e.jsx(Ls,{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(Nx,{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(Nx,{value:[b.team_logo_size||56],onValueChange:([R])=>w(D=>({...D,team_logo_size:R})),min:24,max:120,step:4})]})]})]})]}),e.jsx(Xt,{value:"sections",className:"space-y-4 mt-4",children:[{key:"show_photo",label:"Show Photo",hint:"Photo is pulled from the agent's profile."},{key:"show_bio",label:"Show Bio"},{key:"show_credentials",label:"Show Credentials"},{key:"show_social_links",label:"Show Social Links"},{key:"show_save_contact",label:"Save Contact Button"},{key:"show_leave_review",label:"Leave Review Button"},{key:"show_refer_friend",label:"Refer a Friend Button"}].map(({key:R,label:D,hint:O})=>e.jsxs("div",{className:"flex items-center justify-between py-2",children:[e.jsxs("div",{children:[e.jsx(ee,{children:D}),O&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[O," ",R==="show_photo"&&e.jsx("a",{href:"/profile",target:"_blank",rel:"noopener noreferrer",className:"text-primary underline hover:no-underline",children:"Update Profile"})]})]}),e.jsx(Sn,{checked:b[R],onCheckedChange:U=>w(W=>({...W,[R]:U}))})]},R))}),e.jsx(Xt,{value:"blocks",className:"mt-4",children:e.jsx(aos,{cardId:s.id})}),e.jsx(Xt,{value:"analytics",className:"mt-4",children:a?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsx(je,{children:e.jsxs(Ie,{className:"p-4 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:a.views}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Views"})]})}),e.jsx(je,{children:e.jsxs(Ie,{className:"p-4 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:a.clicks}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Clicks"})]})}),e.jsx(je,{children:e.jsxs(Ie,{className:"p-4 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:a.leads.length}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Leads"})]})})]}),a.leads.length>0&&e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold mb-2",children:"Recent Leads"}),e.jsx("div",{className:"space-y-2",children:a.leads.slice(0,5).map(R=>e.jsxs("div",{className:"text-sm p-2 bg-muted/50 rounded-lg",children:[e.jsx("span",{className:"font-medium",children:R.name}),R.phone&&e.jsxs("span",{className:"text-muted-foreground",children:[" · ",R.phone]}),R.intent&&e.jsx($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(Xnt,{open:u,onClose:()=>h(!1),imageSrc:m,onCropComplete:A,aspectRatio:1})]})}const HV={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"},Llt={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 Rlt(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 wor(){const s=Wt();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"]}),re.success("Category created successfully")},onError:t=>{re.error("Failed to create category: "+t.message)}})}function jor(){const s=Wt();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"]}),re.success("Category updated successfully")},onError:t=>{re.error("Failed to update category: "+t.message)}})}function Nor(){const s=Wt();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"]}),re.success("Category deleted successfully")},onError:t=>{re.error("Failed to delete category: "+t.message)}})}function dos(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 kor(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 Sor(){const s=Wt();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"]}),re.success("Product created successfully")},onError:t=>{re.error("Failed to create product: "+t.message)}})}function Cor(){const s=Wt();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]}),re.success("Product updated successfully")},onError:t=>{re.error("Failed to update product: "+t.message)}})}function Aor(){const s=Wt();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"]}),re.success("Product deleted successfully")},onError:t=>{re.error("Failed to delete product: "+t.message)}})}function Eor(){const s=Wt();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 Tor(){const s=Wt();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]}),re.success("Image deleted successfully")},onError:t=>{re.error("Failed to delete image: "+t.message)}})}function Mor(){const s=Wt();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]}),re.success("Primary image updated")},onError:t=>{re.error("Failed to set primary image: "+t.message)}})}function Por(){const s=Wt();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]}),re.success("Variant added successfully")}})}function Ior(){const s=Wt();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]}),re.success("Variant deleted successfully")}})}function Lor(){const s=Wt();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]}),re.success("Video updated successfully")}})}function Ror(s){const{isAdmin:t}=bs();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 Dor(){const{user:s}=bs();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 For(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 Oor(){const s=Wt(),{user:t}=bs();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"]}),re.success("Order status updated")},onError:n=>{re.error("Failed to update order: "+n.message)}})}function zor(){const s=Wt();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"]}),re.success("Proof uploaded & customer notified")}})}function Bor(){const s=Wt();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"]}),re.success("Proof approved")}})}function $or(){const s=Wt();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"]}),re.success("Proof rejected - please upload a new proof")}})}function Uor(){const{data:s,isLoading:t}=Rlt(!1),n=wor(),r=jor(),a=Nor(),[i,l]=j.useState(!1),[o,c]=j.useState(null),[d,u]=j.useState({name:"",description:"",image_url:"",sort_order:0,is_active:!0}),h=()=>{u({name:"",description:"",image_url:"",sort_order:0,is_active:!0}),c(null)},m=x=>{c(x),u({name:x.name,description:x.description||"",image_url:x.image_url||"",sort_order:x.sort_order,is_active:x.is_active}),l(!0)},f=async x=>{x.preventDefault(),o?await r.mutateAsync({id:o.id,...d}):await n.mutateAsync(d),l(!1),h()},g=async x=>{await fo("Are you sure you want to delete this category?")&&await a.mutateAsync(x)};return t?e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(xn,{className:"h-8 w-48"})}),e.jsx(Ie,{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(zs,{open:i,onOpenChange:x=>{l(x),x||h()},children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Add Category"]})}),e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsx(Bs,{children:o?"Edit Category":"Add Category"})}),e.jsxs("form",{onSubmit:f,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"name",children:"Name"}),e.jsx(pe,{id:"name",value:d.name,onChange:x=>u({...d,name:x.target.value}),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"description",children:"Description"}),e.jsx(Ls,{id:"description",value:d.description,onChange:x=>u({...d,description:x.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"image_url",children:"Image URL"}),e.jsx(pe,{id:"image_url",value:d.image_url,onChange:x=>u({...d,image_url:x.target.value}),placeholder:"https://..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"sort_order",children:"Sort Order"}),e.jsx(pe,{id:"sort_order",type:"number",value:d.sort_order,onChange:x=>u({...d,sort_order:parseInt(x.target.value)||0})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sn,{id:"is_active",checked:d.is_active,onCheckedChange:x=>u({...d,is_active:x})}),e.jsx(ee,{htmlFor:"is_active",children:"Active"})]}),e.jsx($,{type:"submit",className:"w-full",disabled:n.isPending||r.isPending,children:o?"Update Category":"Create Category"})]})]})]})]}),e.jsx(Ie,{children:s&&s.length>0?e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Name"}),e.jsx(Dt,{children:"Description"}),e.jsx(Dt,{children:"Sort Order"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(fi,{children:s.map(x=>e.jsxs(En,{children:[e.jsx(_t,{className:"font-medium",children:x.name}),e.jsx(_t,{className:"max-w-xs truncate",children:x.description}),e.jsx(_t,{children:x.sort_order}),e.jsx(_t,{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(_t,{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(Hn,{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 qor(){var te,J;const{data:s,isLoading:t}=dos(void 0,!1),{data:n}=Rlt(!1),r=Sor(),a=Cor(),i=Aor(),l=Eor(),o=Tor(),c=Mor(),d=Por(),u=Ior(),h=Lor(),[m,f]=j.useState(!1),[g,x]=j.useState(!1),[y,v]=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)},Y=async ce=>{ce.preventDefault();const _e={...P,category_id:P.category_id||null};b?await a.mutateAsync({id:b.id,..._e}):await r.mutateAsync(_e),f(!1),V()},X=async ce=>{await fo("Are you sure you want to delete this product?")&&await i.mutateAsync(ce)},ae=async ce=>{if(!S||!ce.target.files||ce.target.files.length===0)return;I(!0);const _e=ce.target.files[0],he=_e.name.split(".").pop(),ue=`products/${S.id}/${Date.now()}.${he}`;try{const{error:ve}=await q.storage.from("marketplace").upload(ue,_e);if(ve)throw ve;const{data:{publicUrl:Ee}}=q.storage.from("marketplace").getPublicUrl(ue);await l.mutateAsync({product_id:S.id,image_url:Ee,is_primary:!S.images||S.images.length===0}),re.success("Image uploaded successfully")}catch(ve){re.error("Failed to upload image: "+ve.message)}finally{I(!1)}},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}))},ne=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(Ie,{children:e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(ce=>e.jsx(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(zs,{open:m,onOpenChange:ce=>{f(ce),ce||V()},children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Add Product"]})}),e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(Bs,{children:b?"Edit Product":"Add Product"})}),e.jsxs("form",{onSubmit:Y,className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"name",children:"Product Name"}),e.jsx(pe,{id:"name",value:P.name,onChange:ce=>R({...P,name:ce.target.value}),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"category",children:"Category"}),e.jsxs(ms,{value:P.category_id,onValueChange:ce=>R({...P,category_id:ce}),children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Select category"})}),e.jsx(hs,{children:n==null?void 0:n.map(ce=>e.jsx(Ge,{value:ce.id,children:ce.name},ce.id))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"description",children:"Description"}),e.jsx(Ls,{id:"description",value:P.description,onChange:ce=>R({...P,description:ce.target.value}),rows:4})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"base_price",children:"Base Price ($)"}),e.jsx(pe,{id:"base_price",type:"number",step:"0.01",min:"0",value:P.base_price,onChange:ce=>R({...P,base_price:parseFloat(ce.target.value)||0}),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"shipping_fee",children:"Shipping Fee ($)"}),e.jsx(pe,{id:"shipping_fee",type:"number",step:"0.01",min:"0",value:P.shipping_fee,onChange:ce=>R({...P,shipping_fee:parseFloat(ce.target.value)||0})})]})]}),e.jsx("div",{className:"grid grid-cols-2 gap-4",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"sort_order",children:"Sort Order"}),e.jsx(pe,{id:"sort_order",type:"number",value:P.sort_order,onChange:ce=>R({...P,sort_order:parseInt(ce.target.value)||0})})]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sn,{id:"allow_artwork_upload",checked:P.allow_artwork_upload,onCheckedChange:ce=>R({...P,allow_artwork_upload:ce})}),e.jsx(ee,{htmlFor:"allow_artwork_upload",children:"Allow customer to upload artwork"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sn,{id:"requires_proof_approval",checked:P.requires_proof_approval,onCheckedChange:ce=>R({...P,requires_proof_approval:ce})}),e.jsx(ee,{htmlFor:"requires_proof_approval",children:"Requires proof approval"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sn,{id:"is_active",checked:P.is_active,onCheckedChange:ce=>R({...P,is_active:ce})}),e.jsx(ee,{htmlFor:"is_active",children:"Active"})]})]}),e.jsx($,{type:"submit",className:"w-full",disabled:r.isPending||a.isPending,children:b?"Update Product":"Create Product"})]})]})]})]}),e.jsx(Ie,{children:s&&s.length>0?e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:s.map(ce=>{var _e,he;return e.jsxs(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:((_e=ce.images.find(ue=>ue.is_primary))==null?void 0:_e.image_url)||ce.images[0].image_url,alt:ce.name,className:"w-full h-full object-cover"}):e.jsx("div",{className:"flex items-center justify-center h-full text-muted-foreground",children:"No image"}),!ce.is_active&&e.jsx($e,{variant:"secondary",className:"absolute top-2 right-2",children:"Inactive"})]}),e.jsxs(Ie,{className:"p-4",children:[e.jsx("h3",{className:"font-semibold mb-1",children:ce.name}),e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:((he=ce.category)==null?void 0:he.name)||"No category"}),e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("span",{className:"font-bold",children:["$",Number(ce.base_price).toFixed(2)]}),Number(ce.shipping_fee)>0&&e.jsxs("span",{className:"text-sm text-muted-foreground",children:["+$",Number(ce.shipping_fee).toFixed(2)," shipping"]})]}),e.jsxs("div",{className:"flex flex-wrap gap-1 mb-3",children:[ce.allow_artwork_upload&&e.jsx($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(Sv,{className:"h-3 w-3 mr-1"}),"Images"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>{A(ce),v(!0)},children:[e.jsx(Ap,{className:"h-3 w-3 mr-1"}),"Variants"]}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>X(ce.id),children:e.jsx(Hn,{className:"h-3 w-3 text-destructive"})})]})]})]},ce.id)})}):e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No products yet. Create your first product to get started."})})]}),e.jsx(zs,{open:g,onOpenChange:x,children:e.jsxs(Os,{className:"max-w-2xl",children:[e.jsx(Us,{children:e.jsxs(Bs,{children:["Manage Images - ",S==null?void 0:S.name]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-3 gap-4",children:(te=S==null?void 0:S.images)==null?void 0:te.map(ce=>e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:ce.image_url,alt:"",className:"w-full aspect-square object-cover rounded-lg"}),ce.is_primary&&e.jsx($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 _e;await c.mutateAsync({imageId:ce.id,productId:S.id}),A({...S,images:(_e=S.images)==null?void 0:_e.map(he=>({...he,is_primary:he.id===ce.id}))})},disabled:c.isPending,title:"Set as primary",children:e.jsx(ei,{className:"h-4 w-4"})}),e.jsx($,{variant:"destructive",size:"icon",onClick:async()=>{var he;await o.mutateAsync({id:ce.id,productId:S.id});const _e=s==null?void 0:s.find(ue=>ue.id===S.id);_e&&A({..._e,images:(he=_e.images)==null?void 0:he.filter(ue=>ue.id!==ce.id)})},disabled:o.isPending,children:e.jsx(Hn,{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(Sv,{className:"h-8 w-8 mx-auto mb-2 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:E?"Uploading...":"Click to upload an image"})]})]}),e.jsxs("div",{className:"border-t pt-4 mt-4",children:[e.jsx(ee,{children:"Product Video (optional)"}),e.jsxs("div",{className:"flex gap-2 mt-2",children:[e.jsx(pe,{placeholder:"Enter video URL (YouTube, Vimeo, etc.)",value:U,onChange:ce=>W(ce.target.value)}),e.jsxs($,{onClick:ne,disabled:!U,children:[e.jsx(ua,{className:"h-4 w-4 mr-2"}),"Set Video"]})]}),(S==null?void 0:S.video)&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-2",children:["Current video: ",S.video.video_url]})]})]})]})}),e.jsx(zs,{open:y,onOpenChange:v,children:e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsxs(Bs,{children:["Manage Variants - ",S==null?void 0:S.name]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("form",{onSubmit: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(Hn,{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 Vor=["pending_payment","order_submitted","awaiting_proof_approval","proof_approved","processing","in_production","shipped","completed","cancelled","refunded"];function Hor(){var x,y,v;const{data:s,isLoading:t}=Ror(),n=Oor(),r=zor(),[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}),re.success("Proof uploaded successfully")}catch(I){re.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(Ie,{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(Ie,{children:s&&s.length>0?e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Order #"}),e.jsx(Dt,{children:"Customer"}),e.jsx(Dt,{children:"Date"}),e.jsx(Dt,{children:"Total"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(fi,{children:s.map(b=>{var w,S;return e.jsxs(En,{children:[e.jsx(_t,{className:"font-mono",children:b.order_number}),e.jsx(_t,{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(_t,{children:en(new Date(b.created_at),"MMM d, yyyy")}),e.jsxs(_t,{className:"font-bold",children:["$",Number(b.total).toFixed(2)]}),e.jsx(_t,{children:e.jsx($e,{className:Llt[b.status],children:HV[b.status]})}),e.jsx(_t,{className:"text-right",children:e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>m(b),children:[e.jsx(Ca,{className:"h-4 w-4 mr-1"}),"View"]})})]},b.id)})})]}):e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No orders yet."})})]}),e.jsx(zs,{open:l,onOpenChange:o,children:e.jsxs(Os,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsxs(Bs,{children:["Order ",a==null?void 0:a.order_number]})}),a&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-2",children:"Customer"}),e.jsx("p",{children:(x=a.user)==null?void 0:x.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(y=a.user)==null?void 0:y.email})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-2",children:"Shipping Address"}),e.jsx("p",{children:a.shipping_name}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[a.shipping_address,e.jsx("br",{}),a.shipping_city,", ",a.shipping_state," ",a.shipping_zip]})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-2",children:"Order Items"}),e.jsx("div",{className:"space-y-3",children:(v=a.items)==null?void 0:v.map(b=>e.jsxs("div",{className:"border rounded-lg p-4",children:[e.jsxs("div",{className:"flex justify-between items-start mb-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:b.product_name}),b.variant_name&&e.jsx("p",{className:"text-sm text-muted-foreground",children:b.variant_name})]}),e.jsxs("p",{className:"font-bold",children:["$",Number(b.unit_price).toFixed(2)," x ",b.quantity]})]}),b.artwork_url&&e.jsxs("div",{className:"mt-2",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-1",children:"Customer Artwork:"}),e.jsx("a",{href:b.artwork_url,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline text-sm",children:"View Artwork"})]}),e.jsx("div",{className:"mt-3 pt-3 border-t",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Proof Status: "}),e.jsx($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:Vor.map(b=>e.jsx(Ge,{value:b,children:HV[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(Ls,{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:HV[b.status]}),b.notes&&e.jsx("p",{className:"text-muted-foreground mt-1",children:b.notes})]}),e.jsx("span",{className:"text-muted-foreground",children:en(new Date(b.created_at),"MMM d, h:mm a")})]},b.id))})]})]})]})})]})}function Gor(){const[s,t]=j.useState("products"),n=Xn();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(Fr,{className:"h-4 w-4 mr-2"}),"View Store"]})]}),e.jsxs(ha,{value:s,onValueChange:t,children:[e.jsxs(ma,{className:"grid w-full grid-cols-3",children:[e.jsxs(Zt,{value:"products",className:"flex items-center gap-2",children:[e.jsx(ym,{className:"h-4 w-4"}),"Products"]}),e.jsxs(Zt,{value:"categories",className:"flex items-center gap-2",children:[e.jsx(kv,{className:"h-4 w-4"}),"Categories"]}),e.jsxs(Zt,{value:"orders",className:"flex items-center gap-2",children:[e.jsx(tC,{className:"h-4 w-4"}),"Orders"]})]}),e.jsx(Xt,{value:"products",children:e.jsx(qor,{})}),e.jsx(Xt,{value:"categories",children:e.jsx(Uor,{})}),e.jsx(Xt,{value:"orders",children:e.jsx(Hor,{})})]})]})})}function uos(){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 Wor(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 Kor(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 Yor(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 Zor(){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 Xor(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 Qor(){const s=Wt();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 Jor(){const s=Wt();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 elr(){const s=Wt();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 tlr(){const s=Wt();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 slr(){const s=Wt();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 nlr(){const s=Wt();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 rlr(){const s=Wt();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 alr(s){const t=s.match(/\/storage\/v1\/object\/public\/([^/]+)\/(.+)$/);return t?{bucket:t[1],path:t[2]}:null}async function hUe(s,t){const n=alr(s);if(n)try{const{data:r,error:a}=await q.storage.from(n.bucket).download(n.path);if(a){console.error("Error downloading file:",a),re.error("Failed to download file");return}const i=URL.createObjectURL(r),l=document.createElement("a");l.href=i,l.download=t||n.path.split("/").pop()||"download",document.body.appendChild(l),l.click(),document.body.removeChild(l),setTimeout(()=>URL.revokeObjectURL(i),100)}catch(r){console.error("Download error:",r),re.error("Failed to download file")}else try{const a=await(await fetch(s)).blob(),i=URL.createObjectURL(a),l=document.createElement("a");l.href=i,l.download=t||s.split("/").pop()||"download",document.body.appendChild(l),l.click(),document.body.removeChild(l),setTimeout(()=>URL.revokeObjectURL(i),100)}catch(r){console.error("External download error:",r),re.error("Failed to download file")}}function hos(){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 ilr(){const s=Wt();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 olr(){const{user:s}=bs(),[t,n]=j.useState("items"),[r,a]=j.useState(!1),[i,l]=j.useState(null),[o,c]=j.useState(""),[d,u]=j.useState(""),[h,m]=j.useState(""),[f,g]=j.useState(null),[x,y]=j.useState(!1),[v,b]=j.useState(null),[w,S]=j.useState(""),[A,E]=j.useState(""),[I,P]=j.useState(null),[R,D]=j.useState(""),[O,U]=j.useState("file"),[W,V]=j.useState(""),[G,Y]=j.useState(""),[X,ae]=j.useState(""),[le,ne]=j.useState(!0),[te,J]=j.useState(null),[ce,_e]=j.useState(!1),[he,ue]=j.useState(!1),ve=j.useRef(null),Ee=j.useRef(null),{data:Se,isLoading:Le}=uos(),{data:Fe,isLoading:ke}=Wor(),{data:Be,isLoading:Ne}=Zor(),{data:Ae,isLoading:Ce}=hos(),Ve=Jor(),ze=elr(),qe=tlr(),dt=slr(),Xe=nlr(),at=rlr(),rt=ilr(),[Ke,Je]=j.useState({}),pt=kt=>{kt?(l(kt),c(kt.name),u(kt.description||""),m(kt.icon||"")):(l(null),c(""),u(""),m("")),a(!0)},gt=async()=>{if(!o.trim()){re.error("Please enter a category name");return}try{i?(await ze.mutateAsync({id:i.id,name:o,description:d||null,icon:h||null}),re.success("Category updated successfully")):(await Ve.mutateAsync({name:o,description:d||null,icon:h||null,sort_order:((Se==null?void 0:Se.length)||0)+1}),re.success("Category created successfully")),a(!1)}catch(kt){console.error("Error saving category:",kt),re.error("Failed to save category")}},ss=async()=>{if(f)try{await qe.mutateAsync(f),re.success("Category deleted successfully"),g(null)}catch(kt){console.error("Error deleting category:",kt),re.error("Failed to delete category")}},Yt=kt=>{var Ks;kt?(b(kt),S(kt.name),E(kt.description||""),P(kt.category_id),D(kt.points_cost.toString()),U(kt.item_type),V(kt.file_url||""),Y(kt.preview_image_url||""),ae(((Ks=kt.max_quantity)==null?void 0:Ks.toString())||""),ne(kt.is_active)):(b(null),S(""),E(""),P(null),D(""),U("file"),V(""),Y(""),ae(""),ne(!0)),y(!0)},ts=async(kt,Ks)=>{Ks==="file"?_e(!0):ue(!0);try{const wt=kt.name.split(".").pop(),gs=`${Date.now()}-${Math.random().toString(36).substring(7)}.${wt}`,ks=`${Ks==="file"?"items":"previews"}/${gs}`,{error:Is}=await q.storage.from("reward-store").upload(ks,kt);if(Is)throw Is;const{data:{publicUrl:Xs}}=q.storage.from("reward-store").getPublicUrl(ks);Ks==="file"?V(Xs):Y(Xs),re.success("File uploaded successfully")}catch(wt){console.error("Error uploading file:",wt),re.error("Failed to upload file")}finally{Ks==="file"?_e(!1):ue(!1)}},ys=async()=>{if(!w.trim()){re.error("Please enter an item name");return}if(!R||parseInt(R)<0){re.error("Please enter a valid points cost");return}try{const kt={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};v?(await Xe.mutateAsync({id:v.id,...kt,current_quantity:v.max_quantity!==(X?parseInt(X):null)?X?parseInt(X):null:v.current_quantity}),re.success("Item updated successfully")):(await dt.mutateAsync(kt),re.success("Item created successfully")),y(!1)}catch(kt){console.error("Error saving item:",kt),re.error("Failed to save item")}},Bt=async()=>{if(te)try{await at.mutateAsync(te),re.success("Item deleted successfully"),J(null)}catch(kt){console.error("Error deleting item:",kt),re.error("Failed to delete item")}},Ft=async(kt,Ks)=>{const wt=Ke[kt];if(wt===void 0||wt===Ks.toString())return;const gs=parseInt(wt);if(isNaN(gs)||gs<0){re.error("Please enter a valid positive number");return}try{await rt.mutateAsync({id:kt,points:gs}),re.success("Points updated successfully"),Je(ks=>{const Is={...ks};return delete Is[kt],Is})}catch(ks){console.error("Error updating points:",ks),re.error("Failed to update points")}};return Le||ke||Ne||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(Ie,{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(kt=>kt.is_active).length)||0," active"]})]})}),e.jsx(je,{children:e.jsxs(Ie,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(kv,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Categories"})]}),e.jsx("p",{className:"text-2xl font-bold",children:(Se==null?void 0:Se.length)||0})]})}),e.jsx(je,{children:e.jsxs(Ie,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(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((kt,Ks)=>kt+Ks.points_cost,0)/Fe.length):0," pts"]})]})})]}),e.jsxs(ha,{value:t,onValueChange:n,children:[e.jsxs(ma,{children:[e.jsx(Zt,{value:"items",children:"Items"}),e.jsx(Zt,{value:"categories",children:"Categories"}),e.jsx(Zt,{value:"purchases",children:"Purchases"}),e.jsx(Zt,{value:"point-settings",children:"Point Settings"})]}),e.jsx(Xt,{value:"items",className:"mt-4",children:e.jsxs(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(Gn,{children:"Manage rewards that agents can purchase"})]}),e.jsxs($,{onClick:()=>Yt(),children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Add Item"]})]}),e.jsx(Ie,{children:!Fe||Fe.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(ul,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No items yet. Add your first reward item!"})]}):e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Item"}),e.jsx(Dt,{children:"Category"}),e.jsx(Dt,{className:"text-center",children:"Cost"}),e.jsx(Dt,{className:"text-center",children:"Type"}),e.jsx(Dt,{className:"text-center",children:"Quantity"}),e.jsx(Dt,{className:"text-center",children:"Status"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(fi,{children:Fe.map(kt=>e.jsxs(En,{children:[e.jsx(_t,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[kt.preview_image_url?e.jsx("img",{src:kt.preview_image_url,alt:kt.name,className:"h-10 w-10 rounded object-cover"}):e.jsx("div",{className:"h-10 w-10 rounded bg-muted flex items-center justify-center",children:e.jsx(ul,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:kt.name}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1",children:kt.description||"No description"})]})]})}),e.jsx(_t,{children:kt.category?e.jsx($e,{variant:"outline",children:kt.category.name}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(_t,{className:"text-center",children:e.jsxs($e,{variant:"secondary",className:"font-bold",children:[e.jsx(ei,{className:"h-3 w-3 mr-1"}),kt.points_cost]})}),e.jsx(_t,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[kt.item_type==="file"?e.jsx(Jr,{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:kt.item_type})]})}),e.jsx(_t,{className:"text-center",children:kt.max_quantity!==null?e.jsxs("span",{className:kt.current_quantity===0?"text-red-500":"",children:[kt.current_quantity,"/",kt.max_quantity]}):e.jsx("span",{className:"text-muted-foreground",children:"Unlimited"})}),e.jsx(_t,{className:"text-center",children:e.jsx($e,{variant:kt.is_active?"default":"secondary",children:kt.is_active?"Active":"Inactive"})}),e.jsx(_t,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx($,{variant:"ghost",size:"sm",onClick:()=>Yt(kt),children:e.jsx(pi,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>J(kt.id),children:e.jsx(Hn,{className:"h-4 w-4 text-destructive"})})]})})]},kt.id))})]})})]})}),e.jsx(Xt,{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(Gn,{children:"Organize your store items into categories"})]}),e.jsxs($,{onClick:()=>pt(),children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Add Category"]})]}),e.jsx(Ie,{children:!Se||Se.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(kv,{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(En,{children:[e.jsx(Dt,{children:"Name"}),e.jsx(Dt,{children:"Description"}),e.jsx(Dt,{className:"text-center",children:"Items"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(fi,{children:Se.map(kt=>e.jsxs(En,{children:[e.jsxs(_t,{className:"font-medium",children:[kt.icon&&e.jsx("span",{className:"mr-2",children:kt.icon}),kt.name]}),e.jsx(_t,{className:"text-muted-foreground",children:kt.description||"—"}),e.jsx(_t,{className:"text-center",children:(Fe==null?void 0:Fe.filter(Ks=>Ks.category_id===kt.id).length)||0}),e.jsx(_t,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx($,{variant:"ghost",size:"sm",onClick:()=>pt(kt),children:e.jsx(pi,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>g(kt.id),children:e.jsx(Hn,{className:"h-4 w-4 text-destructive"})})]})})]},kt.id))})]})})]})}),e.jsx(Xt,{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(tC,{className:"h-5 w-5"}),"Purchase History"]}),e.jsx(Gn,{children:"View all reward redemptions by agents"})]}),e.jsx(Ie,{children:!Be||Be.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(tC,{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(En,{children:[e.jsx(Dt,{children:"Date"}),e.jsx(Dt,{children:"Agent"}),e.jsx(Dt,{children:"Item"}),e.jsx(Dt,{className:"text-center",children:"Points Spent"})]})}),e.jsx(fi,{children:Be.map(kt=>{var Ks,wt,gs,ks;return e.jsxs(En,{children:[e.jsx(_t,{className:"text-muted-foreground",children:en(new Date(kt.purchased_at),"MMM d, yyyy 'at' h:mm a")}),e.jsx(_t,{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:((Ks=kt.user)==null?void 0:Ks.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:((wt=kt.user)==null?void 0:wt.email)||"—"})]})]})}),e.jsx(_t,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[(gs=kt.item)!=null&&gs.preview_image_url?e.jsx("img",{src:kt.item.preview_image_url,alt:kt.item.name,className:"h-8 w-8 rounded object-cover"}):e.jsx("div",{className:"h-8 w-8 rounded bg-muted flex items-center justify-center",children:e.jsx(ul,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{children:((ks=kt.item)==null?void 0:ks.name)||"Deleted item"})]})}),e.jsx(_t,{className:"text-center",children:e.jsxs($e,{variant:"secondary",className:"font-bold",children:[e.jsx(ei,{className:"h-3 w-3 mr-1"}),kt.points_spent]})})]},kt.id)})})]})})]})})]})]}),e.jsx(zs,{open:r,onOpenChange:a,children:e.jsxs(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:i?"Edit Category":"Add Category"}),e.jsx(Pr,{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:kt=>c(kt.target.value),placeholder:"e.g., Templates, Resources"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"categoryDescription",children:"Description"}),e.jsx(Ls,{id:"categoryDescription",value:d,onChange:kt=>u(kt.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:kt=>m(kt.target.value),placeholder:"e.g., 📄, 🎁"})]})]}),e.jsxs(Sr,{children:[e.jsx($,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx($,{onClick:gt,disabled:Ve.isPending||ze.isPending,children:Ve.isPending||ze.isPending?"Saving...":"Save"})]})]})}),e.jsx(zs,{open:x,onOpenChange:y,children:e.jsxs(Os,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:v?"Edit Item":"Add Item"}),e.jsx(Pr,{children:v?"Update the item details":"Create a new reward item for agents to purchase"})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"itemName",children:"Name *"}),e.jsx(pe,{id:"itemName",value:w,onChange:kt=>S(kt.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(Ls,{id:"itemDescription",value:A,onChange:kt=>E(kt.target.value),placeholder:"Describe the item..."})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"itemCategory",children:"Category"}),e.jsxs(ms,{value:I||"none",onValueChange:kt=>P(kt==="none"?null:kt),children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Select category"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"none",children:"No category"}),Se==null?void 0:Se.map(kt=>e.jsxs(Ge,{value:kt.id,children:[kt.icon&&`${kt.icon} `,kt.name]},kt.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:kt=>D(kt.target.value),placeholder:"e.g., 100"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(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:kt=>ae(kt.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:kt=>V(kt.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 kt;return(kt=ve.current)==null?void 0:kt.click()},disabled:ce,children:e.jsx(ni,{className:"h-4 w-4"})}),e.jsx("input",{ref:ve,type:"file",className:"hidden",onChange:kt=>{var wt;const Ks=(wt=kt.target.files)==null?void 0:wt[0];Ks&&ts(Ks,"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:kt=>Y(kt.target.value),placeholder:"Upload an image or paste URL"}),e.jsx($,{type:"button",variant:"outline",size:"icon",onClick:()=>{var kt;return(kt=Ee.current)==null?void 0:kt.click()},disabled:he,children:e.jsx(Hc,{className:"h-4 w-4"})}),e.jsx("input",{ref:Ee,type:"file",accept:"image/*",className:"hidden",onChange:kt=>{var wt;const Ks=(wt=kt.target.files)==null?void 0:wt[0];Ks&&ts(Ks,"preview")}})]}),G&&e.jsx("img",{src:G,alt:"Preview",className:"mt-2 h-24 rounded object-cover"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sn,{id:"itemIsActive",checked:le,onCheckedChange:ne}),e.jsx(ee,{htmlFor:"itemIsActive",children:"Active (visible to agents)"})]})]}),e.jsxs(Sr,{children:[e.jsx($,{variant:"outline",onClick:()=>y(!1),children:"Cancel"}),e.jsx($,{onClick:ys,disabled:dt.isPending||Xe.isPending,children:dt.isPending||Xe.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:ss,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:Bt,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(Gn,{children:"Configure how many points agents earn for various actions. Adjust these values to run double-points promotions."})]})]})}),e.jsx(Ie,{children:!Ae||Ae.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(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(En,{children:[e.jsx(Dt,{children:"Action"}),e.jsx(Dt,{children:"Description"}),e.jsx(Dt,{className:"text-center w-32",children:"Points"}),e.jsx(Dt,{className:"text-right w-24",children:"Save"})]})}),e.jsx(fi,{children:Ae.map(kt=>e.jsxs(En,{children:[e.jsx(_t,{children:e.jsx("p",{className:"font-medium",children:kt.action_name})}),e.jsx(_t,{children:e.jsx("p",{className:"text-sm text-muted-foreground",children:kt.description})}),e.jsx(_t,{className:"text-center",children:e.jsx(pe,{type:"number",min:"0",className:"w-20 mx-auto text-center",value:Ke[kt.id]??kt.points.toString(),onChange:Ks=>Je(wt=>({...wt,[kt.id]:Ks.target.value}))})}),e.jsx(_t,{className:"text-right",children:e.jsx($,{size:"sm",variant:"outline",disabled:Ke[kt.id]===void 0||Ke[kt.id]===kt.points.toString()||rt.isPending,onClick:()=>Ft(kt.id,kt.points),children:e.jsx(tl,{className:"h-4 w-4"})})})]},kt.id))})]})})]})]})}const oEt=()=>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"})]}),lEt=[{value:"template",label:"Templates"},{value:"brand",label:"Brand Assets"},{value:"listing",label:"Listing Assets"},{value:"social",label:"Social Media"},{value:"general",label:"General"}];function llr(){const s=Wt(),[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){re.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),re.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),re.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")?re.error("Canva app credentials not configured yet."):re.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"]}),re.success("Canva disconnected")},onError:b=>{re.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"]}),re.success("Folder added"),l(!1),c({brokerage_id:"",folder_id:"",folder_name:"",folder_type:"template",description:""})},onError:()=>re.error("Failed to add folder")}),y=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"]}),re.success("Folder removed")},onError:()=>re.error("Failed to remove folder")}),v=!!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(oEt,{})}),e.jsxs("div",{children:[e.jsxs(Et,{className:"text-lg flex items-center gap-2",children:["Canva Connect",v&&e.jsx($e,{variant:"default",className:"text-xs",children:"Connected"}),e.jsx($e,{variant:"outline",className:"text-xs",children:"Admin Only"})]}),e.jsx(Gn,{children:"Auto-share brokerage asset folders with agents when they connect their Canva accounts."})]})]})})}),e.jsx(Ie,{children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-2 text-sm text-muted-foreground",children:[e.jsx(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"})]}),v?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(Tg,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Hn,{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(kv,{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(yb,{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=lEt.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:()=>y.mutate(b.id),children:e.jsx(pr,{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(dn,{className:"h-3.5 w-3.5"}),"Add Folder Mapping"]})]})]})]}):e.jsxs($,{className:"mt-4",onClick:f,disabled:t||u,children:[t?e.jsx(ro,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx("div",{className:"mr-2",children:e.jsx(oEt,{})}),"Connect Canva",e.jsx(Qa,{className:"h-4 w-4 ml-2"})]})]})})]}),e.jsx(zs,{open:i,onOpenChange:l,children:e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsx(Bs,{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:lEt.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(Sr,{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(ro,{className:"h-4 w-4 mr-2 animate-spin"}):null,"Add Folder"]})]})]})})]})}function clr(){const s=Xn();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(Fd,{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(llr,{}),e.jsx(ios,{})]})})}const cEt=s=>{const t="h-4 w-4";return s==="facebook"?e.jsx(Qp,{className:t}):s==="instagram"?e.jsx(Ef,{className:t}):s==="linkedin"?e.jsx(dy,{className:t}):s==="google"?e.jsx(mn,{className:t}):null},dlr=s=>s?new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",year:"numeric",month:"short",day:"numeric"}).format(new Date(s)):"—";function ulr(){const[s,t]=j.useState([]),[n,r]=j.useState(!0),[a,i]=j.useState(""),[l,o]=j.useState("all");j.useEffect(()=>{(async()=>{r(!0);const{data:m,error:f}=await q.rpc("admin_get_social_connections");if(f){re.error(f.message),r(!1);return}t(m||[]),r(!1)})()},[]);const c=j.useMemo(()=>{const m=a.trim().toLowerCase();return s.filter(f=>l!=="all"&&f.platform!==l?!1:m?(f.user_name||"").toLowerCase().includes(m)||(f.user_email||"").toLowerCase().includes(m)||(f.page_name||"").toLowerCase().includes(m)||(f.platform_username||"").toLowerCase().includes(m):!0)},[s,a,l]),d=j.useMemo(()=>{const m=new Map;return s.forEach(f=>{const g=m.get(f.user_id)||{name:f.user_name,email:f.user_email,platforms:new Set,count:0};g.platforms.add(f.platform),g.count+=1,m.set(f.user_id,g)}),Array.from(m.entries()).map(([f,g])=>({user_id:f,...g}))},[s]),u=j.useMemo(()=>{const m=new Map;return s.forEach(f=>m.set(f.platform,(m.get(f.platform)||0)+1)),{uniqueUsers:d.length,totalConnections:s.length,byPlatform:Array.from(m.entries())}},[s,d]),h=m=>m&&new Date(m).getTime()e.jsxs(je,{className:"p-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground capitalize flex items-center gap-2",children:[cEt(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(En,{children:[e.jsx(Dt,{children:"User"}),e.jsx(Dt,{children:"Platform"}),e.jsx(Dt,{children:"Page / Account"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{children:"Connected"})]})}),e.jsx(fi,{children:c.length===0?e.jsx(En,{children:e.jsx(_t,{colSpan:5,className:"text-center text-muted-foreground py-8",children:"No connections found."})}):c.map(m=>{const f=h(m.token_expires_at);return e.jsxs(En,{children:[e.jsxs(_t,{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(_t,{children:e.jsxs("div",{className:"flex items-center gap-2 capitalize",children:[cEt(m.platform)," ",m.platform]})}),e.jsxs(_t,{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(_t,{children:m.is_active?f?e.jsxs($e,{variant:"destructive",className:"gap-1",children:[e.jsx(ll,{className:"h-3 w-3"})," Expired"]}):e.jsx($e,{children:"Active"}):e.jsx($e,{variant:"secondary",children:"Inactive"})}),e.jsx(_t,{className:"text-sm text-muted-foreground",children:dlr(m.created_at)})]},m.id)})})]})})]})})}const hlr={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 NX(s,t=18,n=10){return s.length<=t+n+3?s:`${s.slice(0,t)}…${s.slice(-n)}`}function mlr(){var O,U,W,V,G;const s=Wt(),[t,n]=j.useState("Test Push"),[r,a]=j.useState("Testing web push notification"),[i,l]=j.useState("/community"),[o,c]=j.useState(!1),[d,u]=j.useState(!1),[h,m]=j.useState({isSupported:typeof window<"u"&&"serviceWorker"in navigator&&"PushManager"in window}),[f,g]=j.useState(null),[x,y]=j.useState(null),{data:v,isLoading:b}=st({queryKey:["push-notification-settings"],queryFn:async()=>{const{data:Y,error:X}=await q.from("push_notification_settings").select("*").order("setting_key");if(X)throw X;return Y}}),{data:w,isLoading:S}=st({queryKey:["push-subscription-stats"],queryFn:async()=>{const{count:Y,error:X}=await q.from("push_subscriptions").select("*",{count:"exact",head:!0});if(X)throw X;return{totalSubscriptions:Y||0}}}),A=mt({mutationFn:async({settingKey:Y,isEnabled:X})=>{const{error:ae}=await q.from("push_notification_settings").update({is_enabled:X}).eq("setting_key",Y);if(ae)throw ae},onSuccess:()=>{s.invalidateQueries({queryKey:["push-notification-settings"]}),re.success("Notification setting updated")},onError:Y=>{re.error("Failed to update setting: "+Y.message)}}),E=j.useMemo(()=>{var Y,X;return h.isSupported?`perm=${h.permission??"unknown"} · controller=${h.controllerPresent?"yes":"no"} · sw=${((Y=h.serviceWorker)==null?void 0:Y.activeState)??"unknown"} · sub=${(X=h.subscription)!=null&&X.endpoint?"yes":"no"}`:"Push not supported in this browser."},[h]);j.useEffect(()=>{let Y=!0;const X=async()=>{var te,J,ce,_e,he,ue,ve;const le="serviceWorker"in navigator&&"PushManager"in window,ne={isSupported:le,permission:typeof Notification<"u"?Notification.permission:void 0,controllerPresent:!!((te=navigator.serviceWorker)!=null&&te.controller)};if(!le){Y&&m(ne);return}try{const{data:Ee,error:Se}=await q.functions.invoke("get-vapid-public-key",{body:{}});if(Se)throw Se;ne.vapidPublicKey=Ee==null?void 0:Ee.vapidPublicKey;const Fe=(await navigator.serviceWorker.getRegistrations()).find(ke=>{var Ne,Ae,Ce;return(((Ne=ke.active)==null?void 0:Ne.scriptURL)||((Ae=ke.waiting)==null?void 0:Ae.scriptURL)||((Ce=ke.installing)==null?void 0:Ce.scriptURL)||"").includes("/sw.js")});if(Fe){ne.pushWorkerScriptUrl=((J=Fe.active)==null?void 0:J.scriptURL)||((ce=Fe.waiting)==null?void 0:ce.scriptURL)||((_e=Fe.installing)==null?void 0:_e.scriptURL),ne.serviceWorker={scope:Fe.scope,activeState:(he=Fe.active)==null?void 0:he.state};const ke=await Fe.pushManager.getSubscription();if(ke){const Be=ke.toJSON();ne.subscription={endpoint:Be.endpoint,p256dh:(ue=Be.keys)==null?void 0:ue.p256dh,auth:(ve=Be.keys)==null?void 0:ve.auth}}}}catch(Ee){ne.error=(Ee==null?void 0:Ee.message)||String(Ee)}Y&&m(ne)};X();const ae=window.setInterval(X,4e3);return()=>{Y=!1,window.clearInterval(ae)}},[]);const I=async()=>{if(typeof Notification>"u"){re.error("Notifications API not available in this browser.");return}try{if(Notification.permission!=="granted"&&await Notification.requestPermission()!=="granted"){re.error("Notification permission not granted.");return}new Notification("Local notification test",{body:"If you see this, OS/browser notifications can display."}),re.success("Triggered a local notification (not push).")}catch(Y){re.error(`Local notification failed: ${(Y==null?void 0:Y.message)||String(Y)}`)}},P=async()=>{c(!0),g(null);try{const{data:Y,error:X}=await q.functions.invoke("send-push-notification",{body:{title:t,body:r,url:i}});if(X)throw X;g({sent:Y==null?void 0:Y.sent,failed:Y==null?void 0:Y.failed,expiredCleaned:Y==null?void 0:Y.expiredCleaned,vapidPublicKey:Y==null?void 0:Y.vapidPublicKey}),(Y==null?void 0:Y.sent)>0?re.success(`Test notification sent to ${Y.sent} subscriber(s)`):(Y==null?void 0:Y.failed)>0?re.warning(`Notification failed for ${Y.failed} subscriber(s). ${Y.expired||0} expired subscriptions cleaned up.`):re.info("No active subscriptions to send to")}catch(Y){console.error("Error sending test notification:",Y),g({error:(Y==null?void 0:Y.message)||String(Y)}),re.error("Failed to send test notification: "+(Y.message||"Unknown error"))}finally{c(!1)}},R=async()=>{u(!0),y(null);try{const{data:Y,error:X}=await q.functions.invoke("generate-vapid-keys",{body:{}});if(X)throw X;const ae=Y==null?void 0:Y.publicKey,le=Y==null?void 0:Y.privateKey;if(!ae||!le)throw new Error("generate-vapid-keys did not return keys");y({publicKey:ae,privateKey:le}),re.success("Generated new VAPID keys. Update backend secrets, then clear + re-subscribe.")}catch(Y){console.error("Error generating VAPID keys:",Y),re.error("Failed to generate VAPID keys: "+((Y==null?void 0:Y.message)||"Unknown error"))}finally{u(!1)}},D=mt({mutationFn:async()=>{const{error:Y}=await q.from("push_subscriptions").delete().neq("id","00000000-0000-0000-0000-000000000000");if(Y)throw Y},onSuccess:()=>{re.success("All subscriptions cleared. Users will need to re-enable notifications."),s.invalidateQueries({queryKey:["push-subscription-stats"]})},onError:Y=>{re.error("Failed to clear subscriptions: "+Y.message)}});return e.jsx(Vs,{title:"Notification Settings",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(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(Gn,{children:"Current active push notification subscriptions"})]}),e.jsx(Ie,{children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"text-4xl font-bold",children:S?"...":(w==null?void 0:w.totalSubscriptions)||0}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"active subscriptions"})]})})]}),e.jsxs(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(Gn,{children:"Control which types of push notifications are sent to users"})]}),e.jsx(Ie,{children:b?e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading settings..."}):e.jsx("div",{className:"space-y-4",children:v==null?void 0:v.map(Y=>{const X=hlr[Y.setting_key]||{label:Y.setting_key,icon:"🔔"};return e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-2xl",children:X.icon}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:X.label}),e.jsx("div",{className:"text-sm text-muted-foreground",children:Y.description})]})]}),e.jsx(Sn,{checked:Y.is_enabled,onCheckedChange:ae=>A.mutate({settingKey:Y.setting_key,isEnabled:ae}),disabled:A.isPending})]},Y.id)})})})]}),e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(Uy,{className:"h-5 w-5"}),"Send Test Notification"]}),e.jsx(Gn,{children:"Send a test push notification to all subscribed users"})]}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-md border bg-muted/30 p-3 text-sm",children:[e.jsx("div",{className:"font-medium",children:"Client push debug"}),e.jsx("div",{className:"mt-1 text-muted-foreground",children:E}),h.error&&e.jsx("div",{className:"mt-2 text-destructive",children:h.error}),e.jsxs("div",{className:"mt-2 grid gap-2 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Backend VAPID public key"}),e.jsx("div",{className:"break-all rounded-md border bg-background p-2 font-mono text-xs",children:h.vapidPublicKey?NX(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?NX(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?NX(h.subscription.endpoint,40,12):"none"]}),e.jsxs("div",{children:["p256dh: ",(V=h.subscription)!=null&&V.p256dh?NX(h.subscription.p256dh,22,10):"none"]}),e.jsxs("div",{children:["auth: ",(G=h.subscription)!=null&&G.auth?NX(h.subscription.auth,22,10):"none"]})]})]})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx($,{variant:"outline",onClick:I,children:"Local notification test"}),e.jsx($,{variant:"outline",onClick:()=>window.location.reload(),children:"Reload page"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"test-title",children:"Notification Title"}),e.jsx(pe,{id:"test-title",value:t,onChange:Y=>n(Y.target.value),placeholder:"Enter notification title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"test-body",children:"Notification Body"}),e.jsx(Ls,{id:"test-body",value:r,onChange:Y=>a(Y.target.value),placeholder:"Enter notification message",rows:3})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"test-url",children:"Click URL (optional)"}),e.jsx(pe,{id:"test-url",value:i,onChange:Y=>l(Y.target.value),placeholder:"/community or full URL"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Where users will be taken when they click the notification"})]}),e.jsxs($,{onClick:P,disabled:o||!t||!r,className:"w-full sm:w-auto",children:[e.jsx(Kr,{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(Hn,{className:"h-5 w-5"}),"Subscription Maintenance"]}),e.jsx(Gn,{children:"Clear all push subscriptions if VAPID keys were changed or subscriptions are invalid"})]}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"If you've recently updated the VAPID keys, existing subscriptions will no longer work. Use this to clear all subscriptions so users can re-subscribe with the new keys."}),e.jsxs($,{variant:"destructive",onClick:()=>D.mutate(),disabled:D.isPending,children:[e.jsx(Hn,{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 flr(){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}=bie("presentation_count","desc"),h=u(t,{name:g=>{var x;return((x=g.name)==null?void 0:x.toLowerCase())||""},presentations:g=>g.presentation_count,views:g=>g.total_views,leads:g=>g.total_leads,cta_clicks:g=>g.total_cta_clicks,conversion:g=>g.total_views>0?g.total_leads/g.total_views*100:0});j.useEffect(()=>{m()},[]);const m=async()=>{try{l(!0);const{data:g,error:x}=await q.rpc("get_admin_presentation_stats");if(x)throw x;if(!g||g.length===0){l(!1);return}const y=g.map(A=>A.owner_user_id),{data:v,error:b}=await q.from("profiles").select("id, name, email, avatar_url").in("id",y);if(b)throw b;const w=new Map((v==null?void 0:v.map(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:bb,color:"text-violet-600"},{label:"Total Views",value:r.totalViews,icon:Ca,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(Ie,{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(Ie,{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(En,{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 y,v;const x=g.total_views>0?(g.total_leads/g.total_views*100).toFixed(1):"0.0";return e.jsxs(En,{children:[e.jsx(_t,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-8 w-8 rounded-full bg-muted flex items-center justify-center overflow-hidden",children:g.avatar_url?e.jsx("img",{src:g.avatar_url,alt:"",className:"h-full w-full object-cover"}):e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:((v=(y=g.name)==null?void 0:y.charAt(0))==null?void 0:v.toUpperCase())||"?"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:g.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:g.email})]})]})}),e.jsx(_t,{className:"text-center font-medium",children:g.presentation_count}),e.jsx(_t,{className:"text-center",children:g.total_views.toLocaleString()}),e.jsx(_t,{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(_t,{className:"text-center",children:g.total_cta_clicks}),e.jsx(_t,{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 mUe=s=>s?new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(s)):"—",plr=s=>s==null?"—":`$${Number(s).toLocaleString("en-US",{maximumFractionDigits:0})}`;function glr(){const{toast:s}=Bi(),[t,n]=j.useState(!0),[r,a]=j.useState([]),[i,l]=j.useState({}),[o,c]=j.useState("");j.useEffect(()=>{(async()=>{try{n(!0);const y=[],v=1e3;for(let S=0;;S+=v){const{data: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+v-1);if(E)throw E;if(y.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(y){console.error(y),s({title:"Error",description:"Failed to load presentation data",variant:"destructive"})}finally{n(!1)}})()},[s]);const d=j.useMemo(()=>{const x=Date.now(),y=x-7*24*60*60*1e3,v=x-30*24*60*60*1e3;return{total:r.length,generated:r.filter(b=>!!b.last_generated_at).length,agents:new Set(r.map(b=>b.owner_user_id)).size,thisWeek:r.filter(b=>new Date(b.created_at).getTime()>=y).length,thisMonth:r.filter(b=>new Date(b.created_at).getTime()>=v).length}},[r]),u=j.useMemo(()=>{const x=new Map;return r.forEach(y=>{const v=i[y.owner_user_id],b=x.get(y.owner_user_id)??{user_id:y.owner_user_id,name:(v==null?void 0:v.name)??"Unknown",email:(v==null?void 0:v.email)??"",total:0,generated:0,last_activity:y.updated_at};b.total+=1,y.last_generated_at&&(b.generated+=1),new Date(y.updated_at)>new Date(b.last_activity)&&(b.last_activity=y.updated_at),x.set(y.owner_user_id,b)}),Array.from(x.values()).sort((y,v)=>v.total-y.total)},[r,i]),h=o.trim().toLowerCase(),m=h?u.filter(x=>x.name.toLowerCase().includes(h)||x.email.toLowerCase().includes(h)):u,f=h?r.filter(x=>{const y=i[x.owner_user_id];return(x.title??"").toLowerCase().includes(h)||(x.property_address_line1??"").toLowerCase().includes(h)||(x.city??"").toLowerCase().includes(h)||((y==null?void 0:y.name)??"").toLowerCase().includes(h)||((y==null?void 0:y.email)??"").toLowerCase().includes(h)}):r,g=[{label:"Total presentations",value:d.total,icon:Jr,sub:"All time"},{label:"Agents using it",value:d.agents,icon:Yn,sub:"Created at least one"},{label:"PDFs generated",value:d.generated,icon:Nn,sub:"Rendered at least once"},{label:"Created last 30 days",value:d.thisMonth,icon:Cu,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(Ie,{children:[e.jsx("div",{className:"text-2xl font-bold",children:x.value}),e.jsx("p",{className:"text-xs text-muted-foreground",children:x.sub})]})]},x.label))}),e.jsxs("div",{className:"relative max-w-md",children:[e.jsx(Zr,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(pe,{className:"pl-9",placeholder:"Search agents, addresses, titles...",value:o,onChange:x=>c(x.target.value)})]}),e.jsxs(ha,{defaultValue:"agents",className:"space-y-4",children:[e.jsxs(ma,{children:[e.jsxs(Zt,{value:"agents",children:["By agent (",m.length,")"]}),e.jsxs(Zt,{value:"all",children:["All presentations (",f.length,")"]})]}),e.jsx(Xt,{value:"agents",children:e.jsx(je,{children:e.jsx(Ie,{className:"p-0",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Agent"}),e.jsx(Dt,{className:"text-right",children:"Presentations"}),e.jsx(Dt,{className:"text-right",children:"Generated"}),e.jsx(Dt,{children:"Last activity"})]})}),e.jsxs(fi,{children:[m.map(x=>e.jsxs(En,{children:[e.jsxs(_t,{children:[e.jsx("div",{className:"font-medium",children:x.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:x.email})]}),e.jsx(_t,{className:"text-right font-semibold",children:x.total}),e.jsx(_t,{className:"text-right",children:x.generated}),e.jsx(_t,{children:mUe(x.last_activity)})]},x.user_id)),!t&&m.length===0&&e.jsx(En,{children:e.jsx(_t,{colSpan:4,className:"py-10 text-center text-muted-foreground",children:"No agents have created a listing presentation yet."})})]})]})})})}),e.jsx(Xt,{value:"all",children:e.jsx(je,{children:e.jsx(Ie,{className:"p-0",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Presentation"}),e.jsx(Dt,{children:"Agent"}),e.jsx(Dt,{children:"Property"}),e.jsx(Dt,{children:"Price"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{children:"Created"}),e.jsx(Dt,{children:"Last generated"})]})}),e.jsxs(fi,{children:[f.slice(0,300).map(x=>{var y,v;return e.jsxs(En,{children:[e.jsx(_t,{className:"font-medium",children:x.title||"Untitled"}),e.jsxs(_t,{children:[e.jsx("div",{children:((y=i[x.owner_user_id])==null?void 0:y.name)??"Unknown"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:((v=i[x.owner_user_id])==null?void 0:v.email)??""})]}),e.jsx(_t,{className:"text-sm",children:[x.property_address_line1,x.city,x.state].filter(Boolean).join(", ")||"—"}),e.jsx(_t,{children:plr(x.list_price)}),e.jsx(_t,{children:e.jsx($e,{variant:x.last_generated_at?"default":"secondary",children:x.last_generated_at?"Generated":x.status||"Draft"})}),e.jsx(_t,{children:mUe(x.created_at)}),e.jsx(_t,{children:mUe(x.last_generated_at)})]},x.id)}),!t&&f.length===0&&e.jsx(En,{children:e.jsx(_t,{colSpan:7,className:"py-10 text-center text-muted-foreground",children:"No presentations found."})})]})]})})})})]})]})})}const mte="listing_revival";function xlr(){const{user:s,loading:t,isAdmin:n}=bs(),{data:r}=st({queryKey:["feature-entitlement",mte,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",mte).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 ylr=s=>s?new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(s)):"—";function vlr(){var u,h;const{user:s}=bs(),t=Wt(),[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:y}=await q.from("feature_entitlements").select("user_id, enabled, tier").eq("feature_key",mte).in("user_id",x.length?x:["00000000-0000-0000-0000-000000000000"]),v=new Map((y??[]).map(b=>[b.user_id,b]));return(f??[]).map(b=>{var w;return{user_id:b.id,name:b.name,email:b.email,enabled:!!((w=v.get(b.id))!=null&&w.enabled)}})}}),l=mt({mutationFn:async({userId:m,enabled:f})=>{const{error:g}=await q.from("feature_entitlements").upsert({user_id:m,feature_key:mte,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:mte,target_user_id:m,action:f?"grant":"revoke",performed_by:s.id})},onSuccess:(m,f)=>{t.invalidateQueries({queryKey:["lr-admin-members"]}),re.success(f.enabled?"Access granted":"Access revoked")},onError:m=>re.error(m.message)}),o=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:Nn},{label:"Seller leads",value:c.leads,icon:qg},{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(Ie,{className:"p-5 flex items-center gap-4",children:[e.jsx("div",{className:"rounded-xl bg-amber-500/15 text-amber-600 p-3",children:e.jsx(m.icon,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold tabular-nums",children:a.isLoading?"—":m.value}),e.jsx("div",{className:"text-xs text-muted-foreground uppercase tracking-wider",children:m.label})]})]})},m.label))}),e.jsxs(ha,{defaultValue:"usage",className:"mt-6",children:[e.jsxs(ma,{children:[e.jsx(Zt,{value:"usage",children:"Agent usage"}),e.jsx(Zt,{value:"access",children:"Access"})]}),e.jsx(Xt,{value:"usage",className:"mt-4",children:e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-base",children:"Usage by agent"})}),e.jsx(Ie,{children:a.isLoading?e.jsx("div",{className:"space-y-2",children:[0,1,2].map(m=>e.jsx(xn,{className:"h-10 w-full"},m))}):(h=a.data)!=null&&h.length?e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Agent"}),e.jsx(Dt,{className:"text-right",children:"Campaigns"}),e.jsx(Dt,{className:"text-right",children:"Live pages"}),e.jsx(Dt,{className:"text-right",children:"Leads"}),e.jsx(Dt,{className:"text-right",children:"Hot"}),e.jsx(Dt,{className:"text-right",children:"Engagement"}),e.jsx(Dt,{className:"text-right",children:"Last activity"})]})}),e.jsx(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(En,{children:[e.jsxs(_t,{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(_t,{className:"text-right tabular-nums",children:m.campaign_count}),e.jsx(_t,{className:"text-right tabular-nums",children:m.published_count}),e.jsx(_t,{className:"text-right tabular-nums",children:m.lead_count}),e.jsx(_t,{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(_t,{className:"text-right tabular-nums",children:m.event_count}),e.jsx(_t,{className:"text-right text-sm text-muted-foreground",children:ylr(m.last_activity)})]},m.owner_user_id)})})]}):e.jsx("p",{className:"text-sm text-muted-foreground py-6",children:"No campaigns have been created yet."})})]})}),e.jsx(Xt,{value:"access",className:"mt-4",children:e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-base",children:"Who can use Listing Revival"})}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(Zr,{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(En,{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(En,{children:[e.jsx(_t,{className:"font-medium",children:m.name??"—"}),e.jsx(_t,{className:"text-muted-foreground",children:m.email??"—"}),e.jsx(_t,{className:"text-right",children:e.jsx(Sn,{checked:m.enabled,onCheckedChange:f=>l.mutate({userId:m.user_id,enabled:f})})})]},m.user_id))})]})]})]})})]})]})}function blr(){const{toast:s}=Bi(),[t,n]=j.useState([]),[r,a]=j.useState({totalOpenHouses:0,totalVisitors:0,totalLeads:0,activeOpenHouses:0,agentsUsing:0}),[i,l]=j.useState(!0);j.useEffect(()=>{o()},[]);const o=async()=>{try{l(!0);const{data:d,error:u}=await q.rpc("get_admin_guest_book_stats");if(u)throw u;if(!d||d.length===0){l(!1);return}const h=d.map(y=>y.agent_id),{data:m,error:f}=await q.from("profiles").select("id, name, email, avatar_url").in("id",h);if(f)throw f;const g=new Map((m==null?void 0:m.map(y=>[y.id,y]))||[]),x=d.map(y=>{const v=g.get(y.agent_id);return{agent_id:y.agent_id,name:(v==null?void 0:v.name)||"Unknown",email:(v==null?void 0:v.email)||"",avatar_url:(v==null?void 0:v.avatar_url)||null,open_house_count:Number(y.open_house_count),total_visitors:Number(y.total_visitors),total_leads:Number(y.total_leads),active_count:Number(y.active_count)}});x.sort((y,v)=>v.total_visitors-y.total_visitors),n(x),a({totalOpenHouses:x.reduce((y,v)=>y+v.open_house_count,0),totalVisitors:x.reduce((y,v)=>y+v.total_visitors,0),totalLeads:x.reduce((y,v)=>y+v.total_leads,0),activeOpenHouses:x.reduce((y,v)=>y+v.active_count,0),agentsUsing:x.length})}catch(d){console.error("Error loading guest book stats:",d),s({title:"Error",description:"Failed to load guest book analytics",variant:"destructive"})}finally{l(!1)}},c=[{label:"Agents Using",value:r.agentsUsing,icon: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:Ca,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(Ie,{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(Ie,{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(En,{children:[e.jsx(Dt,{children:"Agent"}),e.jsx(Dt,{className:"text-center",children:"Open Houses"}),e.jsx(Dt,{className:"text-center",children:"Active"}),e.jsx(Dt,{className:"text-center",children:"Visitors"}),e.jsx(Dt,{className:"text-center",children:"Leads"}),e.jsx(Dt,{className:"text-center",children:"Conversion"})]})}),e.jsx(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(En,{children:[e.jsx(_t,{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(_t,{className:"text-center font-medium",children:d.open_house_count}),e.jsx(_t,{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(_t,{className:"text-center",children:d.total_visitors.toLocaleString()}),e.jsx(_t,{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(_t,{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 _lr(){const[s]=gc(),t=Xn(),[n,r]=j.useState("loading"),a=j.useRef(!1),[i,l]=j.useState("Processing connection...");return j.useEffect(()=>{if(a.current)return;a.current=!0,(async()=>{const c=s.get("code"),d=s.get("error"),u=s.get("error_description"),h=s.get("state");if(d){r("error"),l(u||"Authorization was denied"),re.error("Failed to connect: "+(u||d));return}if(!c){r("error"),l("No authorization code received"),re.error("Failed to connect: No authorization code");return}try{const{data:m,error:f}=await q.functions.invoke("meta-oauth",{body:{action:"exchange_code",code:c,state:h}});if(m&&m.success===!1)throw new Error(m.error||"Failed to connect accounts");if(f){let g=f.message||"Failed to connect accounts";try{const x=f.context;if(x&&typeof x.json=="function"){const y=await x.json();y!=null&&y.error&&(g=y.error)}}catch{}throw new Error(g)}if(m!=null&&m.success)r("success"),l(m.message||"Accounts connected successfully!"),re.success(m.message||"Social accounts connected!");else throw new Error((m==null?void 0:m.error)||"Failed to connect accounts")}catch(m){console.error("Callback error:",m),r("error"),l(m.message||"Failed to complete connection"),re.error(m.message||"Failed to connect accounts")}})()},[s]),e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background p-4",children:e.jsxs(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(Nu,{className:"h-12 w-12 text-destructive"})]}),e.jsxs(Et,{children:[n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(Gn,{children:i})]}),e.jsx(Ie,{className:"flex justify-center",children:e.jsx($,{onClick:()=>t("/admin/integrations"),children:n==="success"?"View Integrations":"Back to Integrations"})})]})})}function wlr(){const s=Wt(),[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"]}),re.success(`${b.sent} email${b.sent>1?"s":""} sent successfully!`),n(""),a(""),l([])},onError:b=>{re.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:()=>{re.success("Test email sent to your inbox!")},onError:b=>{re.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"]}),re.success(`${b.sent} live lead invite${b.sent===1?"":"s"} sent!`)},onError:b=>{re.error("Failed to send live lead invites: "+b.message)}}),x=()=>{if(!t.trim()){re.error("Please enter an email address");return}if(c==null?void 0:c.find(w=>w.email.toLowerCase()===t.trim().toLowerCase())){re.error("This email has already been prospected");return}m.mutate([{email:t.trim(),first_name:r.trim()||void 0}])},y=b=>{var 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],Y=V[1];G&&G.includes("@")&&R.push({email:G,first_name:Y||void 0})}l(R),re.success(`${R.length} entries loaded from CSV`)},S.readAsText(w),o.current&&(o.current.value="")},v=()=>{if(i.length===0){re.error("No entries to send");return}const b=new Set((c==null?void 0:c.map(S=>S.email.toLowerCase()))||[]),w=i.filter(S=>!b.has(S.email.toLowerCase()));if(w.length===0){re.error("All emails have already been prospected");return}w.length0&&e.jsxs(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(_b,{className:"h-5 w-5 text-red-600"}),"Live Event Leads",e.jsx($e,{variant:"secondary",className:"ml-2",children:h.liveLeads})]}),e.jsx(Gn,{children:"These agents registered on a LevelUp Live page but haven't received a free trial invite yet."})]}),e.jsx(Ie,{children:e.jsxs($,{onClick:()=>g.mutate(),disabled:g.isPending,className:"gap-2",children:[g.isPending?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Kr,{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(nh,{className:"h-5 w-5"}),"Send Prospect Email"]}),e.jsxs(Gn,{className:"flex items-center justify-between",children:[e.jsx("span",{children:"Send a beautiful free trial invitation email to potential members"}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>f.mutate(),disabled:f.isPending,className:"gap-2 ml-4 shrink-0",children:[f.isPending?e.jsx(Ct,{className:"h-3 w-3 animate-spin"}):e.jsx(mn,{className:"h-3 w-3"}),"Send Test to Me"]})]})]}),e.jsx(Ie,{children:e.jsxs(ha,{defaultValue:"single",children:[e.jsxs(ma,{className:"mb-4",children:[e.jsxs(Zt,{value:"single",children:[e.jsx(Kr,{className:"h-4 w-4 mr-2"}),"Single Send"]}),e.jsxs(Zt,{value:"bulk",children:[e.jsx(ni,{className:"h-4 w-4 mr-2"}),"Bulk CSV"]})]}),e.jsx(Xt,{value:"single",children:e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(ee,{htmlFor:"prospect-email",className:"sr-only",children:"Email"}),e.jsx(pe,{id:"prospect-email",type:"email",placeholder:"agent@example.com",value:t,onChange:b=>n(b.target.value),onKeyDown:b=>b.key==="Enter"&&x()})]}),e.jsxs("div",{className:"w-full sm:w-48",children:[e.jsx(ee,{htmlFor:"prospect-name",className:"sr-only",children:"First Name"}),e.jsx(pe,{id:"prospect-name",placeholder:"First name (optional)",value:r,onChange:b=>a(b.target.value),onKeyDown:b=>b.key==="Enter"&&x()})]}),e.jsxs($,{onClick:x,disabled:m.isPending,className:"gap-2",children:[m.isPending?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Kr,{className:"h-4 w-4"}),"Send Invite"]})]})}),e.jsx(Xt,{value:"bulk",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("input",{ref:o,type:"file",accept:".csv",onChange:y,className:"hidden"}),e.jsxs($,{variant:"outline",onClick:()=>{var b;return(b=o.current)==null?void 0:b.click()},className:"gap-2",children:[e.jsx(Jr,{className:"h-4 w-4"}),"Upload CSV"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Format: email, first_name (one per line)"})]}),i.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs($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(pr,{className:"h-4 w-4"}),"Clear"]})]}),e.jsxs("div",{className:"max-h-40 overflow-y-auto border rounded-lg p-3 bg-muted/30 text-sm font-mono space-y-1",children:[i.slice(0,20).map((b,w)=>e.jsxs("div",{className:"text-muted-foreground",children:[b.email,b.first_name?` — ${b.first_name}`:""]},w)),i.length>20&&e.jsxs("div",{className:"text-muted-foreground/60",children:["...and ",i.length-20," more"]})]}),e.jsxs($,{onClick:v,disabled:m.isPending,className:"gap-2",children:[m.isPending?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Kr,{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(mn,{className:"h-5 w-5"}),"Prospect Log"]}),e.jsx(Gn,{children:"Track all sent invitations and their conversion status"})]}),e.jsx(Ie,{children:d?e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((b,w)=>e.jsx(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:en(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(_b,{className:"h-3 w-3"}),"Live lead"]}):e.jsxs($e,{variant:"secondary",className:"gap-1",children:[e.jsx(da,{className:"h-3 w-3"}),"Sent"]})}),e.jsx("td",{className:"py-3 px-4 text-sm text-muted-foreground",children:(w=b.utm_source)!=null&&w.startsWith("toolbox:")?e.jsxs($e,{variant:"outline",className:"gap-1 font-normal",children:[e.jsx(Jr,{className:"h-3 w-3"}),b.utm_source.replace("toolbox:","")]}):b.utm_source||"—"}),e.jsx("td",{className:"py-3 px-4 text-sm text-muted-foreground",children:b.converted_at?en(new Date(b.converted_at),"MMM d, yyyy"):"—"})]},b.id)})})]})}):e.jsxs("div",{className:"text-center py-12",children:[e.jsx(nh,{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 _9(s){const t=Wt(),{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 jlr(s){const t=Wt(),{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 dEt=(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 Dlt({open:s,onOpenChange:t,stages:n,defaultStageId:r,onSubmit:a,isSubmitting:i}){const[l,o]=j.useState(dEt(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(dEt(r,n)),t(!1)};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Add Recruit Prospect"})}),e.jsxs("form",{onSubmit:d,className:"space-y-4",children:[e.jsxs(ha,{defaultValue:"basic",className:"w-full",children:[e.jsxs(ma,{className:"grid w-full grid-cols-4",children:[e.jsx(Zt,{value:"basic",children:"Basic Info"}),e.jsx(Zt,{value:"production",children:"Production"}),e.jsx(Zt,{value:"social",children:"Social & Web"}),e.jsx(Zt,{value:"personal",children:"Personal"})]}),e.jsxs(Xt,{value:"basic",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"First Name *"}),e.jsx(pe,{required:!0,value:l.first_name,onChange:c("first_name")})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Last Name"}),e.jsx(pe,{value:l.last_name,onChange:c("last_name")})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Email"}),e.jsx(pe,{type:"email",value:l.email,onChange:c("email")})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Phone"}),e.jsx(pe,{value:l.phone,onChange:c("phone")})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Current Brokerage"}),e.jsx(pe,{value:l.current_brokerage,onChange:c("current_brokerage")})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"License #"}),e.jsx(pe,{value:l.license_number,onChange:c("license_number")})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Experience (years)"}),e.jsx(pe,{type:"number",min:"0",value:l.experience_years,onChange:c("experience_years")})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Address"}),e.jsx(pe,{placeholder:"Street address",value:l.address,onChange:c("address")})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"City"}),e.jsx(pe,{value:l.city,onChange:c("city")})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"State"}),e.jsx(pe,{value:l.state,onChange:c("state")})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Zip"}),e.jsx(pe,{value:l.zip_code,onChange:c("zip_code")})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Pipeline Stage"}),e.jsxs(ms,{value:l.stage_id,onValueChange:u=>o(h=>({...h,stage_id:u})),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:n.map(u=>e.jsx(Ge,{value:u.id,children:u.name},u.id))})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Referred By"}),e.jsx(pe,{placeholder:"Who referred this prospect?",value:l.referred_by,onChange:c("referred_by")})]})]}),e.jsxs(Xt,{value:"production",className:"space-y-4 mt-4",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Annual Production Volume"}),e.jsx(pe,{placeholder:"e.g. $5M, 20 transactions",value:l.annual_production,onChange:c("annual_production")})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Last Year Volume"}),e.jsx(pe,{placeholder:"e.g. $8.2M",value:l.last_year_volume,onChange:c("last_year_volume")})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Last Year Transactions"}),e.jsx(pe,{type:"number",min:"0",placeholder:"e.g. 24",value:l.last_year_transactions,onChange:c("last_year_transactions")})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Avg Sale Price"}),e.jsx(pe,{placeholder:"e.g. $350K",value:l.avg_sale_price,onChange:c("avg_sale_price")})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Specialties / Niche"}),e.jsx(pe,{placeholder:"e.g. Luxury, First-time buyers, Investment",value:l.specialties,onChange:c("specialties")})]})]}),e.jsxs(Xt,{value:"social",className:"space-y-4 mt-4",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"LinkedIn URL"}),e.jsx(pe,{type:"url",placeholder:"https://linkedin.com/in/...",value:l.linkedin_url,onChange:c("linkedin_url")})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Website URL"}),e.jsx(pe,{type:"url",placeholder:"https://...",value:l.website_url,onChange:c("website_url")})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Instagram Handle"}),e.jsx(pe,{placeholder:"@handle",value:l.instagram_handle,onChange:c("instagram_handle")})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Facebook URL"}),e.jsx(pe,{type:"url",placeholder:"https://facebook.com/...",value:l.facebook_url,onChange:c("facebook_url")})]})]}),e.jsxs(Xt,{value:"personal",className:"space-y-4 mt-4",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Birthday"}),e.jsx(pe,{type:"date",value:l.birthday,onChange:c("birthday")})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Spouse / Partner Name"}),e.jsx(pe,{value:l.spouse_name,onChange:c("spouse_name")})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Interests / Hobbies"}),e.jsx(pe,{placeholder:"Golf, travel, community events...",value:l.interests,onChange:c("interests")})]})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Notes"}),e.jsx(Ls,{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 cFe(){const{user:s}=bs();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 Flt({value:s,onChange:t}){const{data:n,isLoading:r}=cFe();return e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Send from"}),e.jsxs(ms,{value:s,onValueChange:a=>t(a),disabled:r,children:[e.jsx(us,{className:"mt-1",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"default",children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(ji,{className:"h-3.5 w-3.5"})," Brokerage default sender"]})}),e.jsx(Ge,{value:"mass_email",disabled:!(n!=null&&n.massEmail),children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Uz,{className:"h-3.5 w-3.5"}),"Mass Email",n!=null&&n.massEmail?` (${n.massEmail.email})`:" — not configured"]})}),e.jsx(Ge,{value:"gmail",disabled:!(n!=null&&n.gmail),children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(mn,{className:"h-3.5 w-3.5"}),"Gmail",n!=null&&n.gmail?` (${n.gmail.email})`:" — not connected"]})})]})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-1",children:"Mass Email and Gmail use your own verified sender. Configure them under Integrations."})]})}function mos({open:s,onOpenChange:t,recruitVideoId:n,brokerageId:r,prospectName:a,prospectEmail:i,videoTitle:l,defaultMessage:o}){const c=(a||"").split(" ")[0]||"there",[d,u]=j.useState(""),[h,m]=j.useState(""),[f,g]=j.useState("default"),[x,y]=j.useState(!1),v=Wt(),{data:b}=cFe();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){re.error("This prospect has no email address on file.");return}y(!0);try{const{data:E,error:I}=await q.functions.invoke("send-recruit-video-email",{body:{recruit_video_ids:[n],brokerage_id:r,subject_override:d.trim()||void 0,message_override:h.trim()||void 0,send_via:f}});if(I)throw I;if(((E==null?void 0:E.sent)??0)>0)re.success(`Email sent to ${i}`),v.invalidateQueries({queryKey:["recruit-videos"]}),v.invalidateQueries({queryKey:["recruit-videos-prospect"]}),t(!1);else{const R=((A=(S=E==null?void 0:E.results)==null?void 0:S[0])==null?void 0:A.error)||"Failed to send";re.error(R)}}catch(E){re.error((E==null?void 0:E.message)||"Failed to send email")}finally{y(!1)}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-lg",children:[e.jsx(Us,{children:e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(mn,{className:"h-5 w-5"})," Email video to ",a]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"To"}),e.jsx(pe,{value:i||"— no email on file —",disabled:!0,className:"mt-1"})]}),e.jsx(Flt,{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(Ls,{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(Sr,{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(Kr,{className:"h-4 w-4 mr-2"}),"Send Email"]})]})]})})}function _4(s){return s?s.share_token?`https://video.relevelup.com/thumb/${s.share_token}`:s.thumbnail_url||s.preview_url||null:null}const nQe=[{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 klr(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 fos(){const s=Wt(),{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 pos(){const s=Wt();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 gos(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 Slr(){const s=Wt(),{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 Clr(){const s=Wt();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 Alr({prospectId:s,prospectName:t,prospectEmail:n,brokerageId:r}){var G;const{data:a=[],isLoading:i}=klr(s),{data:l=[]}=gos(r),o=fos(),c=p3();pos();const[d,u]=j.useState("idle"),[h,m]=j.useState(0),[f,g]=j.useState(0),[x,y]=j.useState(""),[v,b]=j.useState(""),[w,S]=j.useState(!1),[A,E]=j.useState(null),[I,P]=j.useState(null),[R,D]=j.useState(null),O=((G=l.find(Y=>Y.id===x))==null?void 0:G.script_text)||"",U=()=>{u("idle"),m(0),g(0),y(""),b("")},W=j.useCallback(async(Y,X)=>{u("uploading");try{const ae=`Recruiting: ${t}`,{videoId:le,libraryId:ne}=await A6(ae),{uploadUrl:te,apiKey:J}=await E6(le),ce=new XMLHttpRequest;ce.upload.onprogress=Fe=>{Fe.lengthComputable&&m(Fe.loaded/Fe.total*100)},await new Promise((Fe,ke)=>{ce.onload=()=>ce.status>=200&&ce.status<300?Fe():ke(new Error("Upload failed")),ce.onerror=()=>ke(new Error("Upload failed")),ce.open("PUT",te),ce.setRequestHeader("AccessKey",J),ce.send(Y)}),u("processing");let _e=0;const he=Date.now(),ue=9e4,ve=`https://iframe.mediadelivery.net/embed/${ne}/${le}`;for(;_e<4&&(await new Promise(ke=>setTimeout(ke,3e3)),!(Date.now()-he>ue));){const Fe=await mk(le);if(_e=Fe.status,g(Fe.encodeProgress||0),_e===5||_e===6)throw new Error("Video processing failed")}const Ee=await mk(le),Se=(Ee.storageSize||Y.size)/(1024*1024),Le=await c.mutateAsync({bunny_video_id:le,playback_url:Ee.directPlayUrl||ve,thumbnail_url:Ee.thumbnailUrl,preview_url:Ee.previewUrl||null,duration_seconds:Ee.length||X,file_size_mb:Se,title:ae,status:_e>=4?"ready":"processing",touch_type:"recruiting"});await o.mutateAsync({prospect_id:s,video_id:Le.id,brokerage_id:r,message:v||void 0}),u("done"),re.success("Video recorded and linked to prospect!"),setTimeout(()=>{S(!1),U()},1500)}catch(ae){re.error(ae.message||"Failed to upload video"),u("record")}},[s,t,r,v,c,o]),V=Y=>{Y&&(navigator.clipboard.writeText(`${window.location.origin}/recruit-video/${Y}`),re.success("Share link copied"))};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h3",{className:"font-semibold text-sm flex items-center gap-1.5",children:[e.jsx(ua,{className:"h-4 w-4"})," Video Outreach"]}),e.jsxs(zs,{open:w,onOpenChange:Y=>{!Y&&(d==="uploading"||d==="processing")||(S(Y),Y||U())},children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{size:"sm",variant:"outline",onClick:()=>u("script"),children:[e.jsx(dn,{className:"h-3.5 w-3.5 mr-1"})," Record Video"]})}),e.jsxs(Os,{className:"max-w-2xl",children:[e.jsx(Us,{children:e.jsxs(Bs,{children:["Record Video for ",t]})}),d==="script"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Choose a Script (optional)"}),e.jsxs(ms,{value:x,onValueChange:y,children:[e.jsx(us,{className:"mt-1",children:e.jsx(fs,{placeholder:"No script — speak freely"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"none",children:"No script"}),l.map(Y=>{var X;return e.jsx(Ge,{value:Y.id,children:e.jsxs("span",{className:"flex items-center gap-2",children:[Y.title,e.jsx($e,{variant:"outline",className:"text-[9px] ml-1",children:(X=nQe.find(ae=>ae.value===Y.category))==null?void 0:X.label})]})},Y.id)})]})]}),O&&e.jsx("div",{className:"mt-2 p-3 bg-muted/50 rounded-md text-sm max-h-32 overflow-y-auto whitespace-pre-wrap",children:O})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Personal Message (shown on landing page)"}),e.jsx(Ls,{value:v,onChange:Y=>b(Y.target.value),placeholder:`Hi ${t.split(" ")[0]}, I'd love to chat about what we're building here...`,rows:3,className:"mt-1"})]}),e.jsxs($,{onClick:()=>u("record"),className:"w-full",children:[e.jsx(ua,{className:"h-4 w-4 mr-2"})," Start Recording"]})]}),d==="record"&&e.jsx(FT,{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(zu,{className:"h-6 w-6 text-emerald-600"})}),e.jsx("p",{className:"font-medium text-emerald-600",children:"Video ready!"})]})]})]})]}),i?e.jsx("div",{className:"text-center py-4",children:e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-primary border-t-transparent mx-auto"})}):a.length===0?e.jsx("p",{className:"text-xs text-muted-foreground text-center py-3",children:"No videos sent yet"}):e.jsx("div",{className:"space-y-2",children:a.map(Y=>{var X;return e.jsxs("div",{className:"flex items-center gap-3 p-2 rounded-md border text-sm",children:[e.jsx("div",{className:"h-10 w-16 rounded bg-muted overflow-hidden flex-shrink-0",children:_4(Y.video)?e.jsx("img",{src:_4(Y.video),alt:"",className:"h-full w-full object-cover",referrerPolicy:"no-referrer"}):e.jsx("div",{className:"h-full w-full flex items-center justify-center",children:e.jsx(ua,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-xs truncate",children:((X=Y.video)==null?void 0:X.title)||"Untitled"}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[Y.view_count>0?e.jsxs($e,{variant:"secondary",className:"text-[9px] h-4",children:[e.jsx(Ca,{className:"h-2.5 w-2.5 mr-0.5"}),Y.view_count]}):Y.sent_at?e.jsxs($e,{variant:"outline",className:"text-[9px] h-4",children:[e.jsx(Kr,{className:"h-2.5 w-2.5 mr-0.5"}),"Sent"]}):e.jsxs($e,{variant:"outline",className:"text-[9px] h-4",children:[e.jsx(da,{className:"h-2.5 w-2.5 mr-0.5"}),"Draft"]}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:en(new Date(Y.created_at),"MMM d")})]})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>V(Y.share_token),title:"Copy link",children:e.jsx(Ha,{className:"h-3 w-3"})}),e.jsxs($,{variant:Y.sent_at?"ghost":"default",size:"sm",className:"h-7 gap-1",disabled:!n,onClick:()=>{var ae;E(Y.id),P(((ae=Y.video)==null?void 0:ae.title)||null),D(Y.message||null)},title:n?"Email video to prospect":"No email on file",children:[e.jsx(mn,{className:"h-3 w-3"}),e.jsx("span",{className:"text-[10px]",children:Y.sent_at?"Resend":"Email"})]})]})]},Y.id)})}),A&&e.jsx(mos,{open:!!A,onOpenChange:Y=>{Y||E(null)},recruitVideoId:A,brokerageId:r,prospectName:t,prospectEmail:n,videoTitle:I,defaultMessage:R})]})}function Elr({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($u,{children:[e.jsx(Uu,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:"gap-2",type:"button",children:[e.jsx(Jr,{className:"h-4 w-4"}),"Use Template",e.jsx(wl,{className:"h-3.5 w-3.5 opacity-60"})]})}),e.jsx(Au,{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(I0,{}),e.jsx(jL,{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 Tlr({open:s,onOpenChange:t,prospectId:n,brokerageId:r,prospectName:a,prospectEmail:i}){const{user:l}=bs(),o=(a||"").split(" ")[0]||"there",[c,d]=j.useState(""),[u,h]=j.useState(""),[m,f]=j.useState("default"),[g,x]=j.useState(!1),[y,v]=j.useState(null),[b,w]=j.useState(!1),S=Wt(),{data:A}=cFe();j.useEffect(()=>{if(s){d(`Hi ${o}`),h("");const O=A!=null&&A.massEmail?"mass_email":A!=null&&A.gmail?"gmail":"default";f(O),v(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===y)||null,R=async()=>{var O,U;if(!i){re.error("This prospect has no email address on file.");return}if(!c.trim()||!u.trim()){re.error("Subject and message are required.");return}x(!0);try{if(y){const{data:W}=await q.from("recruit_videos").select("id").eq("prospect_id",n).eq("video_id",y).maybeSingle();let V=W==null?void 0:W.id;if(!V){const{data:ae,error:le}=await q.from("recruit_videos").insert({prospect_id:n,video_id:y,brokerage_id:r,message:u.trim(),created_by:l.id}).select("id").single();if(le)throw le;V=ae.id}const{data:G,error:Y}=await q.functions.invoke("send-recruit-video-email",{body:{recruit_video_ids:[V],brokerage_id:r,subject_override:c.trim(),message_override:u.trim(),send_via:m}});if(Y)throw Y;if(((G==null?void 0:G.sent)??0)>0)re.success(`Email sent to ${i}`),S.invalidateQueries({queryKey:["recruit-videos"]}),S.invalidateQueries({queryKey:["recruit-videos-prospect",n]}),S.invalidateQueries({queryKey:["recruit-activities",n]}),S.invalidateQueries({queryKey:["recruit-sent-emails"]}),t(!1);else{const ae=((U=(O=G==null?void 0:G.results)==null?void 0:O[0])==null?void 0:U.error)||"Failed to send";re.error(ae)}}else{const{data:W,error:V}=await q.functions.invoke("send-recruit-prospect-email",{body:{prospect_id:n,brokerage_id:r,subject:c.trim(),message:u.trim(),send_via:m}});if(V)throw V;W!=null&&W.success?(re.success(`Email sent to ${i}`),S.invalidateQueries({queryKey:["recruit-activities",n]}),S.invalidateQueries({queryKey:["recruit-sent-emails"]}),t(!1)):re.error((W==null?void 0:W.error)||"Failed to send")}}catch(W){re.error((W==null?void 0:W.message)||"Failed to send email")}finally{x(!1)}},D=O=>{const U=W=>W.replace(/\[First Name\]/gi,o);d(U(O.subject)),h(U(O.body)),re.success(`Loaded "${O.title}"`)};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(mn,{className:"h-5 w-5"})," Email ",a]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"To"}),e.jsx(pe,{value:i||"— no email on file —",disabled:!0,className:"mt-1"})]}),e.jsx(Flt,{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(Elr,{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(Ls,{value:u,onChange:O=>h(O.target.value),rows:8,placeholder:`Hi ${o}, wanted to reach out…`,className:"mt-1"})]}),e.jsxs("div",{className:"rounded-md border p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(ee,{className:"text-xs flex items-center gap-1.5",children:[e.jsx(ua,{className:"h-3.5 w-3.5"})," Include a video"]}),P?e.jsxs($,{type:"button",variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>{v(null),w(!1)},children:[e.jsx(pr,{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:_4(P)?e.jsx("img",{src:_4(P),alt:"",className:"h-full w-full object-cover",referrerPolicy:"no-referrer"}):e.jsx("div",{className:"h-full w-full flex items-center justify-center",children:e.jsx(ua,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsx("p",{className:"text-xs font-medium truncate flex-1",children:P.title||"Untitled video"})]}),!P&&b&&e.jsx("div",{className:"max-h-56 overflow-y-auto space-y-1 -mx-1 px-1",children:I?e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(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:()=>{v(O.id),w(!1)},className:"w-full flex items-center gap-3 p-2 rounded hover:bg-accent text-left transition-colors",children:[e.jsx("div",{className:"h-10 w-16 rounded bg-muted overflow-hidden flex-shrink-0",children:_4(O)?e.jsx("img",{src:_4(O),alt:"",className:"h-full w-full object-cover",referrerPolicy:"no-referrer"}):e.jsx("div",{className:"h-full w-full flex items-center justify-center",children:e.jsx(ua,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-xs font-medium truncate",children:O.title||"Untitled video"}),O.duration_seconds&&e.jsxs("p",{className:"text-[10px] text-muted-foreground",children:[Math.floor(O.duration_seconds/60),":",String(Math.floor(O.duration_seconds%60)).padStart(2,"0")]})]})]},O.id))}),P&&e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"A tracked share link with thumbnail will be added to the email automatically."})]})]}),e.jsxs(Sr,{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(Kr,{className:"h-4 w-4 mr-2"}),"Send Email"]})]})]})})}function Mlr(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 uEt=[{value:"call",label:"Phone Call",icon:Da},{value:"email",label:"Email",icon:mn},{value:"text",label:"Text Message",icon:eo},{value:"meeting",label:"Meeting",icon:Ta},{value:"note",label:"Note",icon:Jr},{value:"campaign_email",label:"Campaign Email",icon:Kr}];function _j({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 ehe({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(Fr,{className:"h-3 w-3 opacity-50"})]}):null}function xp({label:s,value:t,onChange:n,type:r="text",placeholder:a}){return e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:s}),e.jsx(pe,{type:r,value:t,onChange:i=>n(i.target.value),placeholder:a,className:"mt-1 h-8 text-sm"})]})}function Olt({prospect:s,stages:t,brokerageId:n,open:r,onOpenChange:a,onUpdate:i,onDelete:l}){const{activities:o,addActivity:c}=jlr((s==null?void 0:s.id)||null),{data:d=[]}=Mlr((s==null?void 0:s.id)||null),[u,h]=j.useState({type:"note",title:"",description:""}),[m,f]=j.useState(!1),[g,x]=j.useState(!1),[y,v]=j.useState({}),[b,w]=j.useState(!1);if(!s)return null;const S=()=>{var V,G;v({first_name:s.first_name||"",last_name:s.last_name||"",email:s.email||"",phone:s.phone||"",current_brokerage:s.current_brokerage||"",license_number:s.license_number||"",experience_years:((V=s.experience_years)==null?void 0:V.toString())||"",notes:s.notes||"",source:s.source||"",address:s.address||"",city:s.city||"",state:s.state||"",zip_code:s.zip_code||"",last_year_volume:s.last_year_volume||"",last_year_transactions:((G=s.last_year_transactions)==null?void 0:G.toString())||"",avg_sale_price:s.avg_sale_price||"",specialties:s.specialties||"",annual_production:s.annual_production||"",linkedin_url:s.linkedin_url||"",website_url:s.website_url||"",instagram_handle:s.instagram_handle||"",facebook_url:s.facebook_url||"",birthday:s.birthday||"",spouse_name:s.spouse_name||"",interests:s.interests||"",referred_by:s.referred_by||""}),x(!0)},A=()=>{const V={id:s.id};for(const[G,Y]of Object.entries(y))G==="experience_years"||G==="last_year_transactions"?V[G]=Y?parseInt(Y):null:V[G]=Y||null;i(V),x(!1)},E=()=>x(!1),I=V=>G=>v(Y=>({...Y,[V]:G})),P=()=>{u.title.trim()&&(c.mutate({prospect_id:s.id,activity_type:u.type,title:u.title,description:u.description||null}),h({type:"note",title:"",description:""}),f(!1))},R=t.find(V=>V.id===s.stage_id),D=s.address||s.city||s.state,O=s.last_year_volume||s.last_year_transactions||s.avg_sale_price||s.specialties||s.annual_production,U=s.linkedin_url||s.website_url||s.instagram_handle||s.facebook_url,W=s.birthday||s.spouse_name||s.interests||s.referred_by;return e.jsxs(Gy,{open:r,onOpenChange:V=>{V||x(!1),a(V)},children:[e.jsx(my,{className:"w-full sm:max-w-lg p-0",children:e.jsx(uo,{className:"h-full",children:e.jsxs("div",{className:"p-6 space-y-5",children:[e.jsx(L0,{children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsxs(R0,{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(pr,{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(Tg,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Hn,{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(mn,{className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:s.email})]}),e.jsxs($,{size:"sm",variant:"outline",className:"h-7 gap-1.5 flex-shrink-0",onClick:()=>w(!0),children:[e.jsx(mn,{className:"h-3 w-3"})," Email"]})]}),s.phone&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Da,{className:"h-3.5 w-3.5"})," ",s.phone]}),D&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(ci,{className:"h-3.5 w-3.5"}),[s.address,s.city,s.state,s.zip_code].filter(Boolean).join(", ")]})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs text-muted-foreground",children:"Move to Stage"}),e.jsxs(ms,{value:s.stage_id||"",onValueChange:V=>i({id:s.id,stage_id:V}),children:[e.jsx(us,{className:"mt-1",children:e.jsx(fs,{})}),e.jsx(hs,{children:t.map(V=>e.jsx(Ge,{value:V.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-2.5 w-2.5 rounded-full",style:{backgroundColor:V.color}}),V.name]})},V.id))})]})]}),e.jsxs(ha,{defaultValue:"details",className:"w-full",children:[e.jsxs(ma,{className:"grid w-full grid-cols-4 h-8 text-xs",children:[e.jsx(Zt,{value:"details",className:"text-xs",children:"Details"}),e.jsx(Zt,{value:"production",className:"text-xs",children:"Production"}),e.jsx(Zt,{value:"social",className:"text-xs",children:"Social"}),e.jsx(Zt,{value:"personal",className:"text-xs",children:"Personal"})]}),g?e.jsxs(e.Fragment,{children:[e.jsxs(Xt,{value:"details",className:"mt-3 space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(xp,{label:"First Name",value:y.first_name,onChange:I("first_name")}),e.jsx(xp,{label:"Last Name",value:y.last_name,onChange:I("last_name")})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(xp,{label:"Email",value:y.email,onChange:I("email"),type:"email"}),e.jsx(xp,{label:"Phone",value:y.phone,onChange:I("phone")})]}),e.jsx(xp,{label:"Current Brokerage",value:y.current_brokerage,onChange:I("current_brokerage")}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(xp,{label:"License #",value:y.license_number,onChange:I("license_number")}),e.jsx(xp,{label:"Experience (years)",value:y.experience_years,onChange:I("experience_years"),type:"number"})]}),e.jsx(xp,{label:"Address",value:y.address,onChange:I("address"),placeholder:"Street address"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsx(xp,{label:"City",value:y.city,onChange:I("city")}),e.jsx(xp,{label:"State",value:y.state,onChange:I("state")}),e.jsx(xp,{label:"Zip",value:y.zip_code,onChange:I("zip_code")})]}),e.jsx(xp,{label:"Source",value:y.source,onChange:I("source")}),e.jsx(xp,{label:"Referred By",value:y.referred_by,onChange:I("referred_by")}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Notes"}),e.jsx(Ls,{value:y.notes,onChange:V=>v(G=>({...G,notes:V.target.value})),rows:3,className:"mt-1 text-sm"})]})]}),e.jsxs(Xt,{value:"production",className:"mt-3 space-y-3",children:[e.jsx(xp,{label:"Annual Production",value:y.annual_production,onChange:I("annual_production"),placeholder:"e.g. $5M"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(xp,{label:"Last Year Volume",value:y.last_year_volume,onChange:I("last_year_volume"),placeholder:"e.g. $8.2M"}),e.jsx(xp,{label:"Last Year Transactions",value:y.last_year_transactions,onChange:I("last_year_transactions"),type:"number",placeholder:"e.g. 24"})]}),e.jsx(xp,{label:"Avg Sale Price",value:y.avg_sale_price,onChange:I("avg_sale_price"),placeholder:"e.g. $350K"}),e.jsx(xp,{label:"Specialties / Niche",value:y.specialties,onChange:I("specialties"),placeholder:"e.g. Luxury, Investment"})]}),e.jsxs(Xt,{value:"social",className:"mt-3 space-y-3",children:[e.jsx(xp,{label:"LinkedIn URL",value:y.linkedin_url,onChange:I("linkedin_url"),type:"url",placeholder:"https://linkedin.com/in/..."}),e.jsx(xp,{label:"Website URL",value:y.website_url,onChange:I("website_url"),type:"url",placeholder:"https://..."}),e.jsx(xp,{label:"Instagram Handle",value:y.instagram_handle,onChange:I("instagram_handle"),placeholder:"@handle"}),e.jsx(xp,{label:"Facebook URL",value:y.facebook_url,onChange:I("facebook_url"),type:"url",placeholder:"https://facebook.com/..."})]}),e.jsxs(Xt,{value:"personal",className:"mt-3 space-y-3",children:[e.jsx(xp,{label:"Birthday",value:y.birthday,onChange:I("birthday"),type:"date"}),e.jsx(xp,{label:"Spouse / Partner",value:y.spouse_name,onChange:I("spouse_name")}),e.jsx(xp,{label:"Interests / Hobbies",value:y.interests,onChange:I("interests"),placeholder:"Golf, travel, community events..."})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(Xt,{value:"details",className:"mt-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(_j,{label:"Current Brokerage",value:s.current_brokerage}),e.jsx(_j,{label:"License #",value:s.license_number}),e.jsx(_j,{label:"Experience",value:s.experience_years!=null?`${s.experience_years} years`:null}),e.jsx(_j,{label:"Referred By",value:s.referred_by}),e.jsx(_j,{label:"Source",value:s.source})]}),s.notes&&e.jsxs("div",{className:"mt-3",children:[e.jsx(ee,{className:"text-xs text-muted-foreground",children:"Notes"}),e.jsx("p",{className:"text-sm mt-1 whitespace-pre-wrap",children:s.notes})]})]}),e.jsx(Xt,{value:"production",className:"mt-3",children:O?e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(_j,{label:"Annual Production",value:s.annual_production}),e.jsx(_j,{label:"Last Year Volume",value:s.last_year_volume}),e.jsx(_j,{label:"Last Year Transactions",value:s.last_year_transactions}),e.jsx(_j,{label:"Avg Sale Price",value:s.avg_sale_price}),e.jsx(_j,{label:"Specialties / Niche",value:s.specialties})]}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No production data added yet"})}),e.jsx(Xt,{value:"social",className:"mt-3",children:U?e.jsxs("div",{className:"space-y-2",children:[e.jsx(ehe,{label:"LinkedIn",url:s.linkedin_url,icon:dy}),e.jsx(ehe,{label:"Website",url:s.website_url,icon:dl}),s.instagram_handle&&e.jsx(ehe,{label:s.instagram_handle,url:`https://instagram.com/${s.instagram_handle.replace("@","")}`,icon:Ef}),e.jsx(ehe,{label:"Facebook",url:s.facebook_url,icon:Qp})]}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No social profiles added yet"})}),e.jsx(Xt,{value:"personal",className:"mt-3",children:W?e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(_j,{label:"Birthday",value:s.birthday?en(new Date(s.birthday+"T00:00:00"),"MMMM d, yyyy"):null,icon:ul}),e.jsx(_j,{label:"Spouse / Partner",value:s.spouse_name,icon:Jo}),e.jsx("div",{className:"col-span-2",children:e.jsx(_j,{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(Alr,{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(dn,{className:"h-3.5 w-3.5 mr-1"})," Log Activity"]})]}),m&&e.jsxs("div",{className:"border rounded-lg p-3 mb-4 space-y-3 bg-muted/30",children:[e.jsxs(ms,{value:u.type,onValueChange:V=>h(G=>({...G,type:V})),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:uEt.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(Ls,{placeholder:"Details (optional)",value:u.description,onChange:V=>h(G=>({...G,description:V.target.value})),rows:2}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{size:"sm",variant:"ghost",onClick:()=>f(!1),children:"Cancel"}),e.jsx($,{size:"sm",onClick:P,disabled:!u.title.trim(),children:"Save"})]})]}),e.jsx("div",{className:"space-y-3",children:(()=>{const V=[...o.map(G=>({type:"manual",data:G,date:G.created_at})),...d.map(G=>({type:"campaign_email",data:G,date:G.sent_at||G.created_at}))].sort((G,Y)=>new Date(Y.date).getTime()-new Date(G.date).getTime());return V.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No activity logged yet"}):V.map(G=>{if(G.type==="manual"){const X=G.data,ae=uEt.find(ne=>ne.value===X.activity_type),le=(ae==null?void 0:ae.icon)||Jr;return e.jsxs("div",{className:"flex gap-3 text-sm",children:[e.jsx("div",{className:"mt-0.5",children:e.jsx("div",{className:"h-7 w-7 rounded-full bg-muted flex items-center justify-center",children:e.jsx(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:en(new Date(X.created_at),"MMM d, yyyy h:mm a")})]})]},`activity-${X.id}`)}const Y=G.data;return e.jsxs("div",{className:"flex gap-3 text-sm",children:[e.jsx("div",{className:"mt-0.5",children:e.jsx("div",{className:"h-7 w-7 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx(Kr,{className:"h-3.5 w-3.5 text-primary"})})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:"font-medium",children:["Campaign Email #",Y.email_number]}),e.jsx("p",{className:"text-muted-foreground text-xs mt-0.5",children:Y.subject}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mt-1.5",children:[Y.status==="failed"?e.jsx($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(Kr,{className:"h-2.5 w-2.5 mr-0.5"})," Sent"]}),Y.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(Ca,{className:"h-2.5 w-2.5 mr-0.5"})," Opened ",en(new Date(Y.opened_at),"MMM d, h:mm a")]}):Y.status!=="failed"?e.jsx($e,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 text-muted-foreground",children:"Not opened"}):null,Y.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(cb,{className:"h-2.5 w-2.5 mr-0.5"})," Clicked ",en(new Date(Y.clicked_at),"MMM d, h:mm a")]})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:en(new Date(Y.sent_at||Y.created_at),"MMM d, yyyy h:mm a")})]})]},`send-${Y.id}`)})})()})]})]})})}),e.jsx(Tlr,{open:b,onOpenChange:w,prospectId:s.id,brokerageId:s.brokerage_id,prospectName:`${s.first_name} ${s.last_name??""}`.trim(),prospectEmail:s.email})]})}const Plr=["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 zlt({open:s,onOpenChange:t,brokerageId:n,stages:r}){var D;const{toast:a}=Bi(),i=Wt(),l=j.useRef(null),[o,c]=j.useState([]),[d,u]=j.useState([]),[h,m]=j.useState({}),[f,g]=j.useState(((D=r[0])==null?void 0:D.id)||""),[x,y]=j.useState(!1),[v,b]=j.useState("upload"),[w,S]=j.useState(0),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={},ne=new Set;ae.forEach((ce,_e)=>{const he=ce.toLowerCase().replace(/[^a-z0-9]/g,"");let ue=null;/^firstname$/.test(he)||he==="first"?ue="first_name":/^lastname$/.test(he)||he==="last"?ue="last_name":/^email$/.test(he)||he==="emailaddress"?ue="email":/^mobile$|^phone$|^cellphone$|^mobilephone$/.test(he)?ue="phone":/officename|currentbrokerage|brokerage|company/.test(he)?ue="current_brokerage":/membernumber|licensenumber|license/.test(he)?ue="license_number":/experienceyears|yearsexperience/.test(he)?ue="experience_years":/^totalvolume$|annualproduction/.test(he)?ue="annual_production":/^address$/.test(he)?ue="address":/^city$/.test(he)?ue="city":/^state$/.test(he)?ue="state":/^postalcode$|^zip$|^zipcode$/.test(he)?ue="zip_code":/listsidevolume|lastyearvolume/.test(he)?ue="last_year_volume":/^totalcount$|lastyeartransactions/.test(he)?ue="last_year_transactions":/avgsaleprice|averageprice/.test(he)?ue="avg_sale_price":/linkedin/.test(he)?ue="linkedin_url":/website/.test(he)?ue="website_url":/specialt/.test(he)?ue="specialties":/referr/.test(he)?ue="referred_by":/^notes$|^note$/.test(he)&&(ue="notes"),ue&&!ne.has(ue)&&(le[String(_e)]=ue,ne.add(ue))}),m(le);const te=X.slice(1).map(ce=>{const _e=I(ce),he={};return ae.forEach((ue,ve)=>{he[String(ve)]=_e[ve]||""}),he});c(te),b("map")},W.readAsText(U)},I=O=>{const U=[];let W="",V=!1;for(const G of O)G==='"'?V=!V:G===","&&!V?(U.push(W.trim()),W=""):W+=G;return U.push(W.trim()),U},P=async()=>{y(!0);try{const{data:{user:O}}=await q.auth.getUser();if(!O)throw new Error("Not authenticated");const U=o.map(V=>{const G={brokerage_id:n,created_by:O.id,stage_id:f,source:"csv_import",first_name:"Unknown"},Y=G;return Object.entries(h).forEach(([X,ae])=>{var ne;const le=(ne=V[X])==null?void 0:ne.trim();le&&(ae==="experience_years"||ae==="last_year_transactions"?Y[ae]=parseInt(le.replace(/[^0-9.-]/g,""))||null:ae==="annual_production"||ae==="last_year_volume"||ae==="avg_sale_price"?Y[ae]=le.replace(/[^0-9.$,.-]/g,""):Y[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(zs,{open:s,onOpenChange:O=>{O||A(),t(O)},children:e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Import Prospects from CSV"})}),v==="upload"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-8 text-center",children:[e.jsx(YN,{className:"h-10 w-10 mx-auto text-muted-foreground mb-3"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Upload a CSV file with prospect data"}),e.jsx("input",{ref:l,type:"file",accept:".csv",className:"hidden",onChange:E}),e.jsxs($,{onClick:()=>{var O;return(O=l.current)==null?void 0:O.click()},children:[e.jsx(ni,{className:"h-4 w-4 mr-2"})," Choose File"]})]}),e.jsx($,{variant:"link",className:"text-xs",onClick:R,children:"Download CSV template"})]}),v==="map"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:[o.length," rows found"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm",children:"Import to stage:"}),e.jsxs(ms,{value:f,onValueChange:g,children:[e.jsx(us,{className:"w-[180px]",children:e.jsx(fs,{})}),e.jsx(hs,{children:r.map(O=>e.jsx(Ge,{value:O.id,children:O.name},O.id))})]})]})]}),e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{children:[e.jsx(Dt,{className:"w-[140px]",children:"CSV Column"}),e.jsx(Dt,{className:"w-[160px]",children:"Map To"}),e.jsx(Dt,{children:"Preview"})]})}),e.jsx(fi,{children:d.map((O,U)=>{var W;return e.jsxs(En,{children:[e.jsx(_t,{className:"font-medium text-xs",children:O}),e.jsx(_t,{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 —"}),Plr.map(V=>e.jsx(Ge,{value:V,children:V.replace(/_/g," ")},V))]})]})}),e.jsx(_t,{className:"text-xs text-muted-foreground truncate max-w-[200px]",children:((W=o[0])==null?void 0:W[String(U)])||"—"})]},U)})})]})}),!Object.values(h).includes("first_name")&&e.jsxs("div",{className:"flex items-center gap-2 text-amber-600 text-sm",children:[e.jsx(ll,{className:"h-4 w-4"}),' Map at least "first name" to proceed']}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>{A()},children:"Back"}),e.jsx($,{onClick:P,disabled:x||!Object.values(h).includes("first_name"),children:x?"Importing...":`Import ${o.length} Prospects`})]})]}),v==="done"&&e.jsxs("div",{className:"text-center py-6 space-y-3",children:[e.jsx("div",{className:"h-12 w-12 rounded-full bg-green-500/10 flex items-center justify-center mx-auto",children:e.jsx(ca,{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 xos({brokerageId:s}){const{stages:t,prospects:n,isLoading:r,addProspect:a,updateProspect:i,deleteProspect:l}=_9(s),[o,c]=j.useState(!1),[d,u]=j.useState(),[h,m]=j.useState(null),[f,g]=j.useState(!1),[x,y]=j.useState(!1),[v,b]=j.useState(null),[w,S]=j.useState(""),[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 Y=w.trim().toLowerCase();return(!Y||`${G.first_name} ${G.last_name||""} ${G.current_brokerage||""} ${G.email||""}`.toLowerCase().includes(Y))&&(A==="all"||G.source===A)}),R=G=>P.filter(Y=>Y.stage_id===G),D=(G,Y)=>{b(Y),G.dataTransfer.effectAllowed="move"},O=G=>{G.preventDefault(),G.dataTransfer.dropEffect="move"},U=(G,Y)=>{G.preventDefault(),v&&(i.mutate({id:v,stage_id:Y}),b(null))},W=G=>{u(G),c(!0)},V=G=>{m(G),g(!0)};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col gap-3 rounded-md border bg-card p-3 lg:flex-row lg:items-center lg:justify-between",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-2 sm:flex-row",children:[e.jsxs("div",{className:"relative min-w-0 flex-1 sm:max-w-sm",children:[e.jsx(Zr,{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(Cw,{className:"mr-2 h-3.5 w-3.5"}),e.jsx(fs,{})]}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All sources"}),I.map(G=>e.jsx(Ge,{value:G,children:G.replace(/_/g," ")},G))]})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs($,{variant:"outline",onClick:()=>y(!0),children:[e.jsx(ni,{className:"h-4 w-4 mr-2"})," Import CSV"]}),e.jsxs($,{onClick:()=>{u(void 0),c(!0)},children:[e.jsx(dn,{className:"h-4 w-4 mr-2"})," Add Prospect"]})]})]}),e.jsxs("div",{className:"flex items-center justify-between px-1",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Showing ",P.length," of ",n.length," prospects"]}),(w||A!=="all")&&e.jsx($,{variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>{S(""),E("all")},children:"Clear filters"})]}),e.jsxs(uo,{className:"w-full",children:[e.jsx("div",{className:"flex gap-4 pb-4",style:{minWidth:t.length*300},children:t.map(G=>{const Y=R(G.id);return e.jsxs("div",{className:"w-[280px] flex-shrink-0 flex flex-col",onDragOver:O,onDrop:X=>U(X,G.id),children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between border-b pb-2 px-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-3 w-3 rounded-full",style:{backgroundColor:G.color}}),e.jsx("h3",{className:"font-semibold text-sm",children:G.name}),e.jsx($e,{variant:"secondary",className:"text-xs h-5 px-1.5",children:Y.length})]}),e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>W(G.id),children:e.jsx(dn,{className:"h-3.5 w-3.5"})})]}),e.jsx("div",{className:"min-h-[220px] space-y-2 rounded-md border border-dashed bg-muted/20 p-2",children:Y.map(X=>e.jsx(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(Ug,{className:"mt-0.5 h-4 w-4 cursor-grab text-muted-foreground/40 opacity-40 transition-opacity group-hover:opacity-100"}),e.jsxs("div",{className:"flex-1 min-w-0 space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"truncate text-sm font-semibold",children:[X.first_name," ",X.last_name]}),X.source&&e.jsx($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(ji,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:X.current_brokerage})]}),(X.annual_production||X.last_year_volume||X.specialties)&&e.jsx("p",{className:"truncate text-[11px] font-medium text-primary",children:X.last_year_volume||X.annual_production||X.specialties}),e.jsxs("div",{className:"flex items-center justify-between gap-2 border-t pt-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[X.email&&e.jsx(mn,{className:"h-3 w-3 text-muted-foreground"}),X.phone&&e.jsx(Da,{className:"h-3 w-3 text-muted-foreground"}),!X.email&&!X.phone&&e.jsx("span",{className:"text-[10px] text-amber-700",children:"Contact info needed"})]}),X.experience_years!=null&&e.jsxs($e,{variant:"secondary",className:"text-[10px] h-4 px-1",children:[X.experience_years,"yr"]})]})]})]})},X.id))})]},G.id)})}),e.jsx(Rae,{orientation:"horizontal"})]}),e.jsx(Dlt,{open:o,onOpenChange:c,stages:t,defaultStageId:d,onSubmit:G=>a.mutate(G),isSubmitting:a.isPending}),e.jsx(Olt,{prospect:h,stages:t,brokerageId:s,open:f,onOpenChange:g,onUpdate:G=>{i.mutate(G),m(Y=>Y?{...Y,...G}:null)},onDelete:G=>l.mutate(G)}),e.jsx(zlt,{open:x,onOpenChange:y,brokerageId:s,stages:t})]})}function rQe({brokerageId:s}){const{stages:t,prospects:n,isLoading:r,addProspect:a,updateProspect:i,deleteProspect:l}=_9(s),{user:o}=bs(),c=Wt(),[d,u]=j.useState(!1),[h,m]=j.useState(null),[f,g]=j.useState(!1),[x,y]=j.useState(!1),[v,b]=j.useState(""),[w,S]=j.useState("all"),[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,Y]=j.useState(!1),[X,ae]=j.useState(""),le=j.useMemo(()=>{const ke=new Set;return n.forEach(Be=>{Be.current_brokerage&&ke.add(Be.current_brokerage)}),Array.from(ke).sort()},[n]),{data:ne=[]}=st({queryKey:["recruit-campaigns-list",s],queryFn:async()=>{const{data:ke,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 ke}}),{data:te=[]}=st({queryKey:["recruit-campaign-assignments-lookup",s],queryFn:async()=>{let Be=[],Ne=0;for(;;){const{data:Ae,error:Ce}=await q.from("recruit_campaign_assignments").select("prospect_id, campaign_id, status").eq("brokerage_id",s).range(Ne,Ne+1e3-1);if(Ce)throw Ce;if(Be=Be.concat(Ae??[]),!Ae||Ae.length<1e3)break;Ne+=1e3}return Be}}),J=j.useMemo(()=>{const ke=new Map;return te.forEach(Be=>{ke.has(Be.prospect_id)||ke.set(Be.prospect_id,new Set),ke.get(Be.prospect_id).add(Be.campaign_id)}),ke},[te]),ce=ke=>{R===ke?U(Be=>Be==="asc"?"desc":"asc"):(D(ke),U("asc"))},_e=({column:ke})=>R!==ke?e.jsx(zy,{className:"h-3.5 w-3.5 ml-1 text-muted-foreground/50"}):O==="asc"?e.jsx(Zf,{className:"h-3.5 w-3.5 ml-1 text-primary"}):e.jsx(Dg,{className:"h-3.5 w-3.5 ml-1 text-primary"}),he=ke=>t.find(Be=>Be.id===ke),ue=j.useMemo(()=>{let ke=n.filter(Be=>{var ze,qe,dt;const Ne=!v||`${Be.first_name} ${Be.last_name}`.toLowerCase().includes(v.toLowerCase())||((ze=Be.email)==null?void 0:ze.toLowerCase().includes(v.toLowerCase()))||((qe=Be.current_brokerage)==null?void 0:qe.toLowerCase().includes(v.toLowerCase())),Ae=w==="all"||Be.stage_id===w,Ce=A==="all"||Be.current_brokerage===A;let Ve=!0;return I==="in_campaign"?Ve=J.has(Be.id):I==="not_in_campaign"?Ve=!J.has(Be.id):I!=="all"&&(Ve=((dt=J.get(Be.id))==null?void 0:dt.has(I))??!1),Ne&&Ae&&Ce&&Ve});return R&&(ke=[...ke].sort((Be,Ne)=>{var ze,qe;let Ae=null,Ce=null;switch(R){case"name":Ae=`${Be.first_name} ${Be.last_name||""}`.toLowerCase(),Ce=`${Ne.first_name} ${Ne.last_name||""}`.toLowerCase();break;case"stage":Ae=((ze=he(Be.stage_id))==null?void 0:ze.sort_order)??999,Ce=((qe=he(Ne.stage_id))==null?void 0:qe.sort_order)??999;break;case"brokerage":Ae=(Be.current_brokerage||"").toLowerCase(),Ce=(Ne.current_brokerage||"").toLowerCase();break;case"experience":Ae=Be.experience_years??-1,Ce=Ne.experience_years??-1;break;case"production":Ae=(Be.annual_production||"").toLowerCase(),Ce=(Ne.annual_production||"").toLowerCase();break;case"source":Ae=(Be.source||"").toLowerCase(),Ce=(Ne.source||"").toLowerCase();break;default:return 0}if(Ae===Ce)return 0;if(Ae==null)return 1;if(Ce==null)return-1;const Ve=Ae0&&ue.every(ke=>W.has(ke.id)),Ee=ue.some(ke=>W.has(ke.id)),Se=()=>{V(ve?new Set:new Set(ue.map(ke=>ke.id)))},Le=ke=>{V(Be=>{const Ne=new Set(Be);return Ne.has(ke)?Ne.delete(ke):Ne.add(ke),Ne})},Fe=mt({mutationFn:async()=>{if(!X||!(o!=null&&o.id))throw new Error("Select a campaign");const ke=new Set(te.filter(Ae=>Ae.campaign_id===X).map(Ae=>Ae.prospect_id)),Be=Array.from(W).filter(Ae=>!ke.has(Ae)).map(Ae=>({prospect_id:Ae,campaign_id:X,brokerage_id:s,assigned_by:o.id,status:"active",current_email_number:0}));if(Be.length===0)throw new Error("All selected prospects are already in this campaign");const{error:Ne}=await q.from("recruit_campaign_assignments").insert(Be);if(Ne)throw Ne;return Be.length},onSuccess:ke=>{re.success(`${ke} prospect(s) added to campaign`),Y(!1),V(new Set),ae(""),c.invalidateQueries({queryKey:["recruit-campaign-assignments-lookup"]})},onError:ke=>re.error(ke.message)});return r?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4 flex-wrap",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm min-w-[200px]",children:[e.jsx(Zr,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search prospects...",value:v,onChange:ke=>b(ke.target.value),className:"pl-8"})]}),e.jsxs("div",{className:"flex gap-2",children:[W.size>0&&e.jsxs($,{variant:"secondary",onClick:()=>Y(!0),className:"gap-1.5",children:[e.jsx(Kr,{className:"h-4 w-4"})," Add ",W.size," to Campaign"]}),e.jsxs($,{variant:"outline",onClick:()=>y(!0),children:[e.jsx(ni,{className:"h-4 w-4 mr-2"})," Import CSV"]}),e.jsxs($,{onClick:()=>u(!0),children:[e.jsx(dn,{className:"h-4 w-4 mr-2"})," Add Prospect"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(Cw,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs(ms,{value:w,onValueChange:S,children:[e.jsx(us,{className:"w-[160px] h-8 text-xs",children:e.jsx(fs,{placeholder:"All stages"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All stages"}),t.map(ke=>e.jsx(Ge,{value:ke.id,children:ke.name},ke.id))]})]}),e.jsxs(ms,{value:A,onValueChange:E,children:[e.jsxs(us,{className:"w-[200px] h-8 text-xs",children:[e.jsx(ji,{className:"h-3.5 w-3.5 mr-1.5"}),e.jsx(fs,{placeholder:"All brokerages"})]}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All brokerages"}),le.map(ke=>e.jsx(Ge,{value:ke,children:ke},ke))]})]}),e.jsxs(ms,{value:I,onValueChange:P,children:[e.jsxs(us,{className:"w-[200px] h-8 text-xs",children:[e.jsx(mn,{className:"h-3.5 w-3.5 mr-1.5"}),e.jsx(fs,{placeholder:"Campaign status"})]}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All contacts"}),e.jsx(Ge,{value:"in_campaign",children:"In any campaign"}),e.jsx(Ge,{value:"not_in_campaign",children:"Not in any campaign"}),ne.map(ke=>e.jsxs(Ge,{value:ke.id,children:["In: ",ke.name]},ke.id))]})]}),(w!=="all"||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(En,{children:[e.jsx(Dt,{className:"w-[40px]",children:e.jsx(ai,{checked:ve,onCheckedChange:Se,"aria-label":"Select all",...Ee&&!ve?{"data-state":"indeterminate"}:{}})}),e.jsx(Dt,{className:"cursor-pointer select-none",onClick:()=>ce("name"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Name ",e.jsx(_e,{column:"name"})]})}),e.jsx(Dt,{className:"cursor-pointer select-none",onClick:()=>ce("stage"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Stage ",e.jsx(_e,{column:"stage"})]})}),e.jsx(Dt,{className:"hidden md:table-cell cursor-pointer select-none",onClick:()=>ce("brokerage"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Brokerage ",e.jsx(_e,{column:"brokerage"})]})}),e.jsx(Dt,{className:"hidden md:table-cell",children:"Contact"}),e.jsx(Dt,{className:"hidden lg:table-cell cursor-pointer select-none",onClick:()=>ce("experience"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Experience ",e.jsx(_e,{column:"experience"})]})}),e.jsx(Dt,{className:"hidden lg:table-cell cursor-pointer select-none",onClick:()=>ce("production"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Production ",e.jsx(_e,{column:"production"})]})}),e.jsx(Dt,{className:"hidden lg:table-cell",children:"Campaigns"}),e.jsx(Dt,{className:"w-[50px]"})]})}),e.jsx(fi,{children:ue.length===0?e.jsx(En,{children:e.jsx(_t,{colSpan:9,className:"text-center text-muted-foreground py-8",children:"No prospects found"})}):ue.map(ke=>{const Be=he(ke.stage_id),Ne=J.get(ke.id),Ae=(Ne==null?void 0:Ne.size)??0;return e.jsxs(En,{className:"cursor-pointer",onClick:()=>{m(ke),g(!0)},children:[e.jsx(_t,{onClick:Ce=>Ce.stopPropagation(),children:e.jsx(ai,{checked:W.has(ke.id),onCheckedChange:()=>Le(ke.id),"aria-label":`Select ${ke.first_name}`})}),e.jsxs(_t,{className:"font-medium",children:[ke.first_name," ",ke.last_name]}),e.jsx(_t,{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(_t,{className:"hidden md:table-cell",children:ke.current_brokerage?e.jsxs("div",{className:"flex items-center gap-1.5 text-sm",children:[e.jsx(ji,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate max-w-[150px]",children:ke.current_brokerage})]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(_t,{className:"hidden md:table-cell",children:e.jsxs("div",{className:"flex items-center gap-2",children:[ke.email&&e.jsx(mn,{className:"h-3.5 w-3.5 text-muted-foreground"}),ke.phone&&e.jsx(Da,{className:"h-3.5 w-3.5 text-muted-foreground"}),!ke.email&&!ke.phone&&e.jsx("span",{className:"text-muted-foreground",children:"—"})]})}),e.jsx(_t,{className:"hidden lg:table-cell",children:ke.experience_years!=null?`${ke.experience_years} yr`:"—"}),e.jsx(_t,{className:"hidden lg:table-cell",children:ke.annual_production||"—"}),e.jsx(_t,{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(_t,{children:e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive",onClick:Ce=>{Ce.stopPropagation(),l.mutate(ke.id)},children:e.jsx(Hn,{className:"h-3.5 w-3.5"})})})]},ke.id)})})]})}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[W.size>0&&e.jsxs("span",{className:"font-medium text-foreground",children:[W.size," selected · "]}),ue.length," of ",n.length," prospects"]}),e.jsx(zs,{open:G,onOpenChange:Y,children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Add to Campaign"})}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Add ",e.jsx("span",{className:"font-medium text-foreground",children:W.size})," selected prospect(s) to a recruiting campaign drip."]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Campaign"}),e.jsxs(ms,{value:X,onValueChange:ae,children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Select a campaign..."})}),e.jsx(hs,{children:ne.map(ke=>e.jsxs(Ge,{value:ke.id,children:[ke.name," ",e.jsxs("span",{className:"text-muted-foreground ml-1",children:["(",ke.warmth_level,")"]})]},ke.id))})]})]})]}),e.jsxs(Sr,{children:[e.jsx($,{variant:"outline",onClick:()=>Y(!1),children:"Cancel"}),e.jsx($,{onClick:()=>Fe.mutate(),disabled:!X||Fe.isPending,children:Fe.isPending?"Adding...":"Add to Campaign"})]})]})}),e.jsx(Dlt,{open:d,onOpenChange:u,stages:t,onSubmit:ke=>a.mutate(ke),isSubmitting:a.isPending}),e.jsx(Olt,{prospect:h,stages:t,brokerageId:s,open:f,onOpenChange:g,onUpdate:ke=>{i.mutate(ke),m(Be=>Be?{...Be,...ke}:null)},onDelete:ke=>l.mutate(ke)}),e.jsx(zlt,{open:x,onOpenChange:y,brokerageId:s,stages:t})]})}function yos({brokerageId:s}){const{stages:t,prospects:n,isLoading:r}=_9(s),a=j.useMemo(()=>{if(!t.length||!n.length)return null;const i=n.length,l=t.find(v=>v.name==="Signed"),o=t.find(v=>v.name==="Onboarded"),c=n.filter(v=>v.stage_id===(l==null?void 0:l.id)||v.stage_id===(o==null?void 0:o.id)).length,d=i>0?(c/i*100).toFixed(1):"0",u=new Date,h=i>0?Math.round(n.reduce((v,b)=>v+dk(u,new Date(b.created_at)),0)/i):0,m=t.map(v=>({...v,count:n.filter(b=>b.stage_id===v.id).length})),f={};n.forEach(v=>{const b=v.source||"unknown";f[b]=(f[b]||0)+1});const g=Object.entries(f).sort((v,b)=>b[1]-v[1]),x=new Date;x.setDate(x.getDate()-30);const y=n.filter(v=>new Date(v.created_at)>=x).length;return{total:i,signed:c,conversionRate:d,avgDays:h,byStage:m,bySrc:g,recentCount:y}},[t,n]);return r?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):a?e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(je,{children:e.jsx(Ie,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-blue-500/10 flex items-center justify-center",children:e.jsx(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(Ie,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-green-500/10 flex items-center justify-center",children:e.jsx(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(Ie,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-amber-500/10 flex items-center justify-center",children:e.jsx(da,{className:"h-5 w-5 text-amber-600"})}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-2xl font-bold",children:[a.avgDays,"d"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Avg Days in Pipeline"})]})]})})}),e.jsx(je,{children:e.jsx(Ie,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-violet-500/10 flex items-center justify-center",children:e.jsx(nh,{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(Ie,{className:"space-y-3",children:a.byStage.map(i=>{const l=a.total>0?i.count/a.total*100:0;return e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-2.5 w-2.5 rounded-full",style:{backgroundColor:i.color}}),e.jsx("span",{children:i.name})]}),e.jsx("span",{className:"font-medium",children:i.count})]}),e.jsx("div",{className:"h-2 bg-muted rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${l}%`,backgroundColor:i.color}})})]},i.id)})})]}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-base",children:"Lead Sources"})}),e.jsxs(Ie,{className:"space-y-3",children:[a.bySrc.map(([i,l])=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx($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 Ilr=["Outreach","Follow-up","Interview","Offer","Referral","Other"];function vos({brokerageId:s}){const{toast:t}=Bi(),{user:n}=bs(),r=Wt(),[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"})}),y=(S,A)=>{navigator.clipboard.writeText(S),i(A),t({title:"Copied to clipboard!"}),setTimeout(()=>i(null),2e3)},v=()=>{h({category:"Outreach",title:"",subject:"",body:""}),d(!0)},b=S=>{h(S),d(!0)},w=Array.from(new Set(m.map(S=>S.category)));return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Pre-built and custom recruiting templates. Built-in templates are global; your custom ones are private to this brokerage."}),e.jsxs($,{onClick:v,size:"sm",className:"gap-1.5",children:[e.jsx(dn,{className:"h-4 w-4"})," New Template"]})]}),f?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(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(mn,{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(Ie,{className:"pt-0 space-y-3",children:[e.jsxs("div",{className:"bg-muted/50 rounded-lg p-4",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Subject Line:"}),e.jsx("p",{className:"text-sm mb-3",children: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:()=>y(A.subject,A.id+"-s"),children:[a===A.id+"-s"?e.jsx(ca,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(Ha,{className:"h-3.5 w-3.5 mr-1"}),"Copy Subject"]}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>y(A.body,A.id+"-b"),children:[a===A.id+"-b"?e.jsx(ca,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(Ha,{className:"h-3.5 w-3.5 mr-1"}),"Copy Body"]}),E&&e.jsxs(e.Fragment,{children:[e.jsxs($,{size:"sm",variant:"outline",onClick:()=>b(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 fo("Delete this template?")&&x.mutate(A.id)},children:[e.jsx(Hn,{className:"h-3.5 w-3.5 mr-1"})," Delete"]})]})]})]})]},A.id)})]},S)),e.jsx(zs,{open:c,onOpenChange:d,children:e.jsxs(Os,{className:"max-w-2xl",children:[e.jsx(Us,{children:e.jsx(Bs,{children:u!=null&&u.id?"Edit Template":"New Template"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Title"}),e.jsx(pe,{value:(u==null?void 0:u.title)||"",onChange:S=>h(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:Ilr.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(Ls,{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(Sr,{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 hEt={call:Da,email:mn,text:eo,meeting:Ta,note:Jr};function bos({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=Y4e(new Date,30);return{recruiters:c.map(f=>{var b,w;const g=(l||[]).filter(S=>S.created_by===f),x=g.filter(S=>new Date(S.created_at)>=h),y={};x.forEach(S=>{y[S.activity_type]=(y[S.activity_type]||0)+1});const v=r.filter(S=>S.created_by===f).length;return{id:f,name:((b=u[f])==null?void 0:b.name)||"Unknown",email:((w=u[f])==null?void 0:w.email)||"",totalActivities:g.length,recentActivities:x.length,byType:y,prospectsCreated:v}}).sort((f,g)=>g.recentActivities-f.recentActivities),recentActivities:(l||[]).slice(0,20)}},enabled:!!s});return n?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):t!=null&&t.recruiters.length?e.jsxs("div",{className:"space-y-6",children:[e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-base",children:"Recruiter Leaderboard (Last 30 Days)"})}),e.jsx(Ie,{className:"space-y-4",children:t.recruiters.map((r,a)=>e.jsxs("div",{className:"flex items-center gap-4 p-3 rounded-lg bg-muted/30",children:[e.jsx("div",{className:"flex items-center justify-center h-8 w-8 rounded-full bg-primary/10 text-primary font-bold text-sm",children:a+1}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(sl,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"font-medium text-sm",children:r.name})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:Object.entries(r.byType).map(([i,l])=>{const o=hEt[i]||Jr;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(Ie,{className:"space-y-3",children:t.recentActivities.map(r=>{const a=hEt[r.activity_type]||Jr;return e.jsxs("div",{className:"flex items-start gap-3 text-sm",children:[e.jsx("div",{className:"h-7 w-7 rounded-full bg-muted flex items-center justify-center flex-shrink-0 mt-0.5",children:e.jsx(a,{className:"h-3.5 w-3.5 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium",children:r.title}),r.description&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:r.description}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:en(new Date(r.created_at),"MMM d, h:mm a")})]})]},r.id)})})]})]}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No recruiter activity yet."})}function _os({brokerageId:s}){const{toast:t}=Bi(),n=Wt(),[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:y,error:v}=await q.from("recruit_referrals").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(v)throw v;return y}}),d=[...new Set(o.map(y=>y.referred_by))],{data:u=[]}=st({queryKey:["referral-profiles",d],queryFn:async()=>{if(!d.length)return[];const{data:y}=await q.from("profiles").select("id, name, email").in("id",d);return y||[]},enabled:d.length>0}),h=Object.fromEntries(u.map(y=>[y.id,y])),m=mt({mutationFn:async y=>{const{data:{user:v}}=await q.auth.getUser();if(!v)throw new Error("Not authenticated");const{error:b}=await q.from("recruit_referrals").insert({brokerage_id:s,referred_by:v.id,referee_first_name:y.first_name,referee_last_name:y.last_name||null,referee_email:y.email||null,referee_phone:y.phone||null,referee_current_brokerage:y.current_brokerage||null,notes:y.notes||null});if(b)throw b},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-referrals",s]}),t({title:"Referral submitted!"}),l({first_name:"",last_name:"",email:"",phone:"",current_brokerage:"",notes:""}),a(!1)},onError:y=>t({title:"Error",description:y.message,variant:"destructive"})}),f=mt({mutationFn:async({id:y,status:v,incentive_status:b})=>{const w={updated_at:new Date().toISOString()};v&&(w.status=v),b&&(w.incentive_status=b);const{error:S}=await q.from("recruit_referrals").update(w).eq("id",y);if(S)throw S},onSuccess:()=>n.invalidateQueries({queryKey:["recruit-referrals",s]})}),g=y=>y==="approved"||y==="signed"?e.jsx(ca,{className:"h-3 w-3"}):y==="rejected"?e.jsx(Nu,{className:"h-3 w-3"}):e.jsx(da,{className:"h-3 w-3"}),x=y=>y==="approved"||y==="signed"||y==="paid"?"bg-green-500/10 text-green-600 border-green-200":y==="rejected"?"bg-red-500/10 text-red-600 border-red-200":"bg-amber-500/10 text-amber-600 border-amber-200";return c?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:[o.length," referral",o.length!==1?"s":""]}),e.jsxs($,{onClick:()=>a(!0),children:[e.jsx(dn,{className:"h-4 w-4 mr-2"})," Submit Referral"]})]}),o.length===0?e.jsxs(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(y=>{var v;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:[y.referee_first_name," ",y.referee_last_name]}),e.jsxs($e,{variant:"outline",className:x(y.status),children:[g(y.status)," ",y.status]}),y.incentive_status&&e.jsxs($e,{variant:"outline",className:x(y.incentive_status),children:[e.jsx(ul,{className:"h-3 w-3 mr-1"})," ",y.incentive_status]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground space-y-0.5",children:[y.referee_email&&e.jsx("p",{children:y.referee_email}),y.referee_phone&&e.jsx("p",{children:y.referee_phone}),y.referee_current_brokerage&&e.jsxs("p",{children:["Currently at: ",y.referee_current_brokerage]}),e.jsxs("p",{children:["Referred by: ",((v=h[y.referred_by])==null?void 0:v.name)||"Unknown"," • ",en(new Date(y.created_at),"MMM d, yyyy")]})]}),y.notes&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1 italic",children:y.notes})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsxs(ms,{value:y.status,onValueChange:b=>f.mutate({id:y.id,status:b}),children:[e.jsx(us,{className:"h-7 text-xs w-[110px]",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"pending",children:"Pending"}),e.jsx(Ge,{value:"contacted",children:"Contacted"}),e.jsx(Ge,{value:"approved",children:"Approved"}),e.jsx(Ge,{value:"signed",children:"Signed"}),e.jsx(Ge,{value:"rejected",children:"Rejected"})]})]}),e.jsxs(ms,{value:y.incentive_status||"pending",onValueChange:b=>f.mutate({id:y.id,incentive_status:b}),children:[e.jsx(us,{className:"h-7 text-xs w-[100px]",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"pending",children:"Unpaid"}),e.jsx(Ge,{value:"paid",children:"Paid"}),e.jsx(Ge,{value:"n/a",children:"N/A"})]})]})]})]})},y.id)})}),e.jsx(zs,{open:r,onOpenChange:a,children:e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Submit a Recruit Referral"})}),e.jsxs("form",{onSubmit:y=>{y.preventDefault(),m.mutate(i)},className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"First Name *"}),e.jsx(pe,{required:!0,value:i.first_name,onChange:y=>l(v=>({...v,first_name:y.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Last Name"}),e.jsx(pe,{value:i.last_name,onChange:y=>l(v=>({...v,last_name:y.target.value}))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Email"}),e.jsx(pe,{type:"email",value:i.email,onChange:y=>l(v=>({...v,email:y.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Phone"}),e.jsx(pe,{value:i.phone,onChange:y=>l(v=>({...v,phone:y.target.value}))})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Current Brokerage"}),e.jsx(pe,{value:i.current_brokerage,onChange:y=>l(v=>({...v,current_brokerage:y.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Notes"}),e.jsx(Ls,{value:i.notes,onChange:y=>l(v=>({...v,notes:y.target.value})),rows:2})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx($,{type:"submit",disabled:m.isPending,children:"Submit"})]})]})]})})]})}function wos({brokerageId:s}){const{toast:t}=Bi(),n=Wt(),[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(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Enable Public Form"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Allow agents to express interest in joining via a public link"})]}),e.jsx(Sn,{checked:(i==null?void 0:i.recruit_form_enabled)||!1,onCheckedChange:m=>o.mutate(m)})]}),(i==null?void 0:i.recruit_form_enabled)&&e.jsxs("div",{className:"flex items-center gap-2 p-3 bg-muted/50 rounded-lg",children:[e.jsx("code",{className:"text-xs flex-1 truncate",children:d}),e.jsx($,{size:"sm",variant:"outline",onClick:u,children:r?e.jsx(ca,{className:"h-3.5 w-3.5"}):e.jsx(Ha,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"sm",variant:"outline",asChild:!0,children:e.jsx("a",{href:d,target:"_blank",rel:"noopener noreferrer",children:e.jsx(Fr,{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(Ie,{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(mn,{className:"h-3 w-3"}),m.email]}),m.phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Da,{className:"h-3 w-3"}),m.phone]}),m.current_brokerage&&e.jsxs("span",{children:["From: ",m.current_brokerage]}),m.experience_years&&e.jsxs("span",{children:[m.experience_years,"yr exp"]})]}),m.why_interested&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1 italic",children:['"',m.why_interested,'"']}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:en(new Date(m.created_at),"MMM d, yyyy h:mm a")})]}),e.jsxs(ms,{value:m.status,onValueChange:f=>c.mutate({id:m.id,status:f}),children:[e.jsx(us,{className:"h-7 text-xs w-[110px]",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"new",children:"New"}),e.jsx(Ge,{value:"contacted",children:"Contacted"}),e.jsx(Ge,{value:"converted",children:"Converted"}),e.jsx(Ge,{value:"dismissed",children:"Dismissed"})]})]})]},m.id))})})]})]})}function jos({brokerageId:s}){const{toast:t}=Bi(),n=Wt(),[r,a]=j.useState(!1),[i,l]=j.useState({prospect_id:"",title:"",description:"",due_date:en(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:en(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),y=x.filter(A=>!A.completed_at&&D4(new Date(A.due_date))&&!_v(new Date(A.due_date))),v=x.filter(A=>!A.completed_at&&_v(new Date(A.due_date))),b=x.filter(A=>!A.completed_at&&!D4(new Date(A.due_date))&&!_v(new Date(A.due_date))),w=x.filter(A=>!!A.completed_at),S=A=>{const E=m[A.prospect_id],I=!A.completed_at&&D4(new Date(A.due_date))&&!_v(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(ll,{className:"h-3 w-3"}):e.jsx(Ta,{className:"h-3 w-3"}),en(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"&&y.length+v.length+b.length>0&&`(${y.length+v.length+b.length})`]},A))}),e.jsxs($,{size:"sm",onClick:()=>a(!0),children:[e.jsx(dn,{className:"h-4 w-4 mr-1"})," Add Follow-up"]})]}),o!=="completed"&&y.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"text-xs font-semibold text-destructive flex items-center gap-1",children:[e.jsx(ll,{className:"h-3.5 w-3.5"})," Overdue (",y.length,")"]}),y.map(S)]}),o!=="completed"&&v.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"text-xs font-semibold text-amber-600 flex items-center gap-1",children:[e.jsx(da,{className:"h-3.5 w-3.5"})," Today (",v.length,")"]}),v.map(S)]}),o!=="completed"&&b.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"text-xs font-semibold text-muted-foreground flex items-center gap-1",children:[e.jsx(Ta,{className:"h-3.5 w-3.5"})," Upcoming (",b.length,")"]}),b.map(S)]}),o!=="pending"&&w.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"text-xs font-semibold text-muted-foreground flex items-center gap-1",children:[e.jsx(ca,{className:"h-3.5 w-3.5"})," Completed (",w.length,")"]}),w.map(S)]}),x.length===0&&e.jsxs("p",{className:"text-sm text-muted-foreground text-center py-8",children:["No follow-ups ",o!=="all"?`(${o})`:""]}),e.jsx(zs,{open:r,onOpenChange:a,children:e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Schedule Follow-up"})}),e.jsxs("form",{onSubmit: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(Ls,{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 Llr=[{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 Nos({brokerageId:s}){const{toast:t}=Bi(),n=Wt(),[r,a]=j.useState(null),{data:i,isLoading:l}=st({queryKey:["recruit-landing-settings",s],queryFn:async()=>{const{data:y,error:v}=await q.from("recruit_landing_page_settings").select("*").eq("brokerage_id",s).maybeSingle();if(v)throw v;return y}}),[o,c]=j.useState({brokerage_id:s,hero_headline:"Join Our Team",hero_subtext:"Take your real estate career to the next level.",hero_image_url:null,logo_url:null,primary_color:"#406E71",accent_color:"#2a4c64",benefits:Llr,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 y={brokerage_id:s,hero_headline:o.hero_headline,hero_subtext:o.hero_subtext,hero_image_url:o.hero_image_url,logo_url:o.logo_url,primary_color:o.primary_color,accent_color:o.accent_color,benefits:JSON.parse(JSON.stringify(o.benefits)),testimonials:JSON.parse(JSON.stringify(o.testimonials)),gallery_images:JSON.parse(JSON.stringify(o.gallery_images)),calculator_enabled:o.calculator_enabled,calculator_config:JSON.parse(JSON.stringify(o.calculator_config)),lead_magnet_enabled:o.lead_magnet_enabled,lead_magnet_config:JSON.parse(JSON.stringify(o.lead_magnet_config)),form_style:o.form_style,confidential_messaging:o.confidential_messaging,updated_at:new Date().toISOString()};if(o.id){const{error:v}=await q.from("recruit_landing_page_settings").update(y).eq("id",o.id);if(v)throw v}else{const{error:v}=await q.from("recruit_landing_page_settings").insert(y);if(v)throw v}},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-landing-settings",s]}),t({title:"Landing page saved!"})},onError:y=>t({title:"Error",description:y.message,variant:"destructive"})}),u=async(y,v)=>{const b=y.name.split(".").pop(),w=`${s}/${v}-${Date.now()}.${b}`,{error:S}=await q.storage.from("recruit-landing").upload(w,y);if(S)throw S;const{data:{publicUrl:A}}=q.storage.from("recruit-landing").getPublicUrl(w);return A},h=async(y,v)=>{var w;const b=(w=y.target.files)==null?void 0:w[0];if(b){a(v);try{const S=await u(b,v);c(A=>({...A,[v]:S})),t({title:"Image uploaded!"})}catch(S){t({title:"Upload failed",description:S.message,variant:"destructive"})}finally{a(null)}}},m=async y=>{var b;const v=(b=y.target.files)==null?void 0:b[0];if(v){a("gallery");try{const w=await u(v,"gallery");c(S=>({...S,gallery_images:[...S.gallery_images,w]})),t({title:"Gallery image added!"})}catch(w){t({title:"Upload failed",description:w.message,variant:"destructive"})}finally{a(null)}}},f=async(y,v)=>{var w;const b=(w=y.target.files)==null?void 0:w[0];if(b){a(`testimonial-${v}`);try{const S=await u(b,`testimonial-${v}`);c(A=>{const E=[...A.testimonials];return E[v]={...E[v],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:y,error:v}=await q.from("brokerages").select("recruit_form_slug, recruit_form_enabled").eq("id",s).single();if(v)throw v;return y}}),x=`https://bestbrokerage.relevelup.com/join-brokerage/${(g==null?void 0:g.recruit_form_slug)||""}`;return l?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):e.jsxs("div",{className:"space-y-6",children:[(g==null?void 0:g.recruit_form_enabled)&&e.jsxs("div",{className:"flex items-center gap-2 p-3 bg-muted/50 rounded-lg border",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Live page:"}),e.jsx("code",{className:"text-xs flex-1 truncate",children:x}),e.jsx($,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:x,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Fr,{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(Ie,{className:"space-y-4",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Logo"}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[o.logo_url&&e.jsx("img",{src:o.logo_url,alt:"Logo",className:"h-10 w-auto rounded"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx($,{variant:"outline",size:"sm",asChild:!0,disabled:r==="logo_url",children:e.jsxs("span",{children:[e.jsx(ni,{className:"h-3.5 w-3.5 mr-1"}),r==="logo_url"?"Uploading...":"Upload Logo"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:y=>h(y,"logo_url")})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Primary Color"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("input",{type:"color",value:o.primary_color,onChange:y=>c(v=>({...v,primary_color:y.target.value})),className:"h-9 w-12 rounded border cursor-pointer"}),e.jsx(pe,{value:o.primary_color,onChange:y=>c(v=>({...v,primary_color:y.target.value})),className:"font-mono text-xs"})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Accent Color"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("input",{type:"color",value:o.accent_color,onChange:y=>c(v=>({...v,accent_color:y.target.value})),className:"h-9 w-12 rounded border cursor-pointer"}),e.jsx(pe,{value:o.accent_color,onChange:y=>c(v=>({...v,accent_color:y.target.value})),className:"font-mono text-xs"})]})]})]})]})})]}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-base",children:"Hero Section"})}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Headline"}),e.jsx(pe,{value:o.hero_headline,onChange:y=>c(v=>({...v,hero_headline:y.target.value})),placeholder:"Join Our Team"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Subtext"}),e.jsx(Ls,{value:o.hero_subtext,onChange:y=>c(v=>({...v,hero_subtext:y.target.value})),rows:2,placeholder:"Take your career to the next level..."})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Background Image"}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[o.hero_image_url&&e.jsx("img",{src:o.hero_image_url,alt:"Hero",className:"h-16 w-28 object-cover rounded"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx($,{variant:"outline",size:"sm",asChild:!0,disabled:r==="hero_image_url",children:e.jsxs("span",{children:[e.jsx(ni,{className:"h-3.5 w-3.5 mr-1"}),r==="hero_image_url"?"Uploading...":"Upload Image"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:y=>h(y,"hero_image_url")})]}),o.hero_image_url&&e.jsx($,{variant:"ghost",size:"sm",onClick:()=>c(y=>({...y,hero_image_url:null})),children:e.jsx(Hn,{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(y=>({...y,benefits:[...y.benefits,{title:"",description:"",icon:"✨"}]})),children:[e.jsx(dn,{className:"h-3.5 w-3.5 mr-1"})," Add"]})]}),e.jsxs(Ie,{className:"space-y-3",children:[o.benefits.map((y,v)=>e.jsxs("div",{className:"flex items-start gap-3 p-3 border rounded-lg",children:[e.jsx(Ug,{className:"h-4 w-4 mt-2 text-muted-foreground"}),e.jsx(pe,{value:y.icon,onChange:b=>{const w=[...o.benefits];w[v]={...y,icon:b.target.value},c(S=>({...S,benefits:w}))},className:"w-14 text-center"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(pe,{value:y.title,onChange:b=>{const w=[...o.benefits];w[v]={...y,title:b.target.value},c(S=>({...S,benefits:w}))},placeholder:"Benefit title"}),e.jsx(pe,{value:y.description,onChange:b=>{const w=[...o.benefits];w[v]={...y,description:b.target.value},c(S=>({...S,benefits:w}))},placeholder:"Short description"})]}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>c(b=>({...b,benefits:b.benefits.filter((w,S)=>S!==v)})),children:e.jsx(Hn,{className:"h-3.5 w-3.5 text-destructive"})})]},v)),o.benefits.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No benefits added yet"})]})]}),e.jsxs(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(y=>({...y,testimonials:[...y.testimonials,{name:"",role:"",quote:""}]})),children:[e.jsx(dn,{className:"h-3.5 w-3.5 mr-1"})," Add"]})]}),e.jsxs(Ie,{className:"space-y-3",children:[o.testimonials.map((y,v)=>{var b;return e.jsxs("div",{className:"flex items-start gap-3 p-3 border rounded-lg",children:[e.jsxs("div",{className:"flex flex-col items-center gap-1",children:[y.photo_url?e.jsx("img",{src:y.photo_url,alt:y.name,className:"h-10 w-10 rounded-full object-cover"}):e.jsx("div",{className:"h-10 w-10 rounded-full bg-muted flex items-center justify-center text-xs text-muted-foreground",children:((b=y.name)==null?void 0:b[0])||"?"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx("span",{className:"text-[10px] text-primary hover:underline",children:r===`testimonial-${v}`?"...":"Photo"}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:w=>f(w,v)})]})]}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(pe,{value:y.name,onChange:w=>{const S=[...o.testimonials];S[v]={...y,name:w.target.value},c(A=>({...A,testimonials:S}))},placeholder:"Name"}),e.jsx(pe,{value:y.role,onChange:w=>{const S=[...o.testimonials];S[v]={...y,role:w.target.value},c(A=>({...A,testimonials:S}))},placeholder:"Role / Title"})]}),e.jsx(Ls,{value:y.quote,onChange:w=>{const S=[...o.testimonials];S[v]={...y,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!==v)})),children:e.jsx(Hn,{className:"h-3.5 w-3.5 text-destructive"})})]},v)}),o.testimonials.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No testimonials added yet"})]})]}),e.jsxs(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(Ie,{children:o.gallery_images.length>0?e.jsx("div",{className:"grid grid-cols-3 md:grid-cols-4 gap-2",children:o.gallery_images.map((y,v)=>e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:y,alt:`Gallery ${v+1}`,className:"h-24 w-full object-cover rounded-lg"}),e.jsx($,{variant:"destructive",size:"sm",className:"absolute top-1 right-1 h-6 w-6 p-0 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>c(b=>({...b,gallery_images:b.gallery_images.filter((w,S)=>S!==v)})),children:e.jsx(Hn,{className:"h-3 w-3"})})]},v))}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No gallery images added yet"})})]}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsxs(Et,{className:"text-base flex items-center gap-2",children:[e.jsx(Nn,{className:"h-4 w-4 text-primary"})," Form Style & Trust"]})}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Application Form Style"}),e.jsxs(ms,{value:o.form_style,onValueChange:y=>c(v=>({...v,form_style:y})),children:[e.jsx(us,{className:"mt-1.5",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"classic",children:"Classic — single-page form (all fields visible)"}),e.jsx(Ge,{value:"multi_step",children:"Multi-Step Wizard — 3-step soft CTA (recommended)"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1.5",children:"Multi-step wizards convert ~30% better than single long forms."})]}),e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border bg-muted/30",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(pc,{className:"h-4 w-4 mt-0.5 text-primary"}),e.jsxs("div",{children:[e.jsx(ee,{children:"Show Confidentiality Badges"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:'Adds "100% Confidential" + "No spam" trust signals around the form.'})]})]}),e.jsx(Sn,{checked:o.confidential_messaging,onCheckedChange:y=>c(v=>({...v,confidential_messaging:y}))})]})]})]}),e.jsxs(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"})," Split & Income Calculator"]}),e.jsx(Sn,{checked:o.calculator_enabled,onCheckedChange:y=>c(v=>({...v,calculator_enabled:y}))})]}),o.calculator_enabled&&e.jsxs(Ie,{className:"space-y-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Highest-converting recruiting tool. Agents enter their GCI and instantly see what they'd earn at your brokerage."}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Calculator Headline"}),e.jsx(pe,{value:o.calculator_config.headline||"",onChange:y=>c(v=>({...v,calculator_config:{...v.calculator_config,headline:y.target.value}})),placeholder:"See What You Could Earn With Us"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Subtext"}),e.jsx(pe,{value:o.calculator_config.subtext||"",onChange:y=>c(v=>({...v,calculator_config:{...v.calculator_config,subtext:y.target.value}})),placeholder:"Confidential 60-second calculator"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Pre-Cap Split % (agent keeps)"}),e.jsx(pe,{type:"number",value:o.calculator_config.commission_split_pct??80,onChange:y=>c(v=>({...v,calculator_config:{...v.calculator_config,commission_split_pct:parseFloat(y.target.value)||0}}))}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:"e.g. 80 for an 80/20"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Cap Amount ($)"}),e.jsx(pe,{type:"number",value:o.calculator_config.cap_amount??16e3,onChange:y=>c(v=>({...v,calculator_config:{...v.calculator_config,cap_amount:parseFloat(y.target.value)||0}}))}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:"Annual cap to brokerage"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Post-Cap Split % (agent keeps)"}),e.jsx(pe,{type:"number",value:o.calculator_config.post_cap_split_pct??100,onChange:y=>c(v=>({...v,calculator_config:{...v.calculator_config,post_cap_split_pct:parseFloat(y.target.value)||0}}))}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:"e.g. 95 for 95/5 after cap, 100 for 100%"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Monthly Fee ($)"}),e.jsx(pe,{type:"number",value:o.calculator_config.monthly_fee??99,onChange:y=>c(v=>({...v,calculator_config:{...v.calculator_config,monthly_fee:parseFloat(y.target.value)||0}}))})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Per-Transaction Fee ($)"}),e.jsx(pe,{type:"number",value:o.calculator_config.transaction_fee??0,onChange:y=>c(v=>({...v,calculator_config:{...v.calculator_config,transaction_fee:parseFloat(y.target.value)||0}}))}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:"Multiplied by # of transactions"})]})]}),e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border bg-muted/30",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm",children:"Capture email at end of calculator"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"After seeing results, agents can request a full breakdown via email."})]}),e.jsx(Sn,{checked:o.calculator_config.show_email_capture!==!1,onCheckedChange:y=>c(v=>({...v,calculator_config:{...v.calculator_config,show_email_capture:y}}))})]})]})]}),e.jsxs(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(o2,{className:"h-4 w-4 text-primary"})," Lead Magnet (Gated PDF)"]}),e.jsx(Sn,{checked:o.lead_magnet_enabled,onCheckedChange:y=>c(v=>({...v,lead_magnet_enabled:y}))})]}),o.lead_magnet_enabled&&e.jsxs(Ie,{className:"space-y-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Captures emails from agents not ready to talk. Offer a comp plan PDF, recruiting deck, or guide."}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Title"}),e.jsx(pe,{value:o.lead_magnet_config.title||"",onChange:y=>c(v=>({...v,lead_magnet_config:{...v.lead_magnet_config,title:y.target.value}})),placeholder:"Get the Full Comp Plan PDF"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Description"}),e.jsx(Ls,{rows:2,value:o.lead_magnet_config.description||"",onChange:y=>c(v=>({...v,lead_magnet_config:{...v.lead_magnet_config,description:y.target.value}})),placeholder:"See exactly how splits, caps, and fees work..."})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Button Text"}),e.jsx(pe,{value:o.lead_magnet_config.button_text||"",onChange:y=>c(v=>({...v,lead_magnet_config:{...v.lead_magnet_config,button_text:y.target.value}})),placeholder:"Email Me the PDF"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"PDF / File URL"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(pe,{value:o.lead_magnet_config.pdf_url||"",onChange:y=>c(v=>({...v,lead_magnet_config:{...v.lead_magnet_config,pdf_url:y.target.value||null}})),placeholder:"https://...",className:"flex-1"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx($,{variant:"outline",size:"sm",asChild:!0,disabled:r==="lead_magnet_pdf",children:e.jsxs("span",{children:[e.jsx(ni,{className:"h-3.5 w-3.5 mr-1"}),r==="lead_magnet_pdf"?"...":"Upload"]})}),e.jsx("input",{type:"file",accept:"application/pdf,.pdf,.doc,.docx",className:"hidden",onChange:async y=>{var b;const v=(b=y.target.files)==null?void 0:b[0];if(v){a("lead_magnet_pdf");try{const w=await u(v,"lead-magnet");c(S=>({...S,lead_magnet_config:{...S.lead_magnet_config,pdf_url:w}})),t({title:"PDF uploaded!"})}catch(w){t({title:"Upload failed",description:w.message,variant:"destructive"})}finally{a(null)}}}})]})]})]})]})]})]}),e.jsx(Rlr,{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 Rlr({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(xi,{className:"h-4 w-4 text-primary"})," Lead Magnet Downloads (",t.length,")"]})}),e.jsx(Ie,{children:e.jsx("div",{className:"space-y-2 max-h-80 overflow-y-auto",children:t.map(n=>e.jsx("div",{className:"flex items-center justify-between gap-3 p-2.5 border rounded-lg text-sm",children:e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium truncate",children:[n.first_name||"—"," · ",n.email]}),e.jsxs("div",{className:"text-[11px] text-muted-foreground",children:[en(new Date(n.created_at),"MMM d, yyyy h:mm a")," · via ",n.source]})]})},n.id))})})]})}function kos({brokerageId:s,trigger:t,initialProspectId:n,open:r,onOpenChange:a}){const[i,l]=j.useState(!1),o=r??i,c=a??l,[d,u]=j.useState("pick-recipients"),[h,m]=j.useState(new Set(n?[n]:[])),[f,g]=j.useState("all"),[x,y]=j.useState(""),[v,b]=j.useState(null),[w,S]=j.useState(""),[A,E]=j.useState(0),[I,P]=j.useState(0),[R,D]=j.useState(""),[O,U]=j.useState(""),{data:W}=cFe(),[V,G]=j.useState("default");j.useEffect(()=>{G(W!=null&&W.massEmail?"mass_email":W!=null&&W.gmail?"gmail":"default")},[W==null?void 0:W.massEmail,W==null?void 0:W.gmail]);const[Y,X]=j.useState(null),{prospects:ae,stages:le}=_9(s),ne=fos(),te=p3(),{data:J=[]}=st({queryKey:["brokerage-recruit-video-pool",s],queryFn:async()=>{const{data:ke,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 ke??[]},enabled:o&&d==="pick-video"}),ce=j.useCallback(()=>{u("pick-recipients"),m(new Set(n?[n]:[])),g("all"),y(""),b(null),S(""),E(0),P(0),D(""),U(""),G("default"),X(null)},[n]),_e=ke=>{!ke&&(d==="uploading"||d==="processing"||d==="sending")||(c(ke),ke||setTimeout(ce,200))},he=j.useMemo(()=>ae.filter(ke=>{if(!ke.email||f!=="all"&&ke.stage_id!==f)return!1;if(x){const Be=x.toLowerCase();if(!`${ke.first_name} ${ke.last_name??""}`.toLowerCase().includes(Be)&&!ke.email.toLowerCase().includes(Be))return!1}return!0}),[ae,f,x]),ue=ke=>{m(Be=>{const Ne=new Set(Be);return Ne.has(ke)?Ne.delete(ke):Ne.add(ke),Ne})},ve=()=>{h.size===he.length?m(new Set):m(new Set(he.map(ke=>ke.id)))},Ee=j.useCallback(async(ke,Be)=>{u("uploading");try{const Ne=`Recruiting blast (${h.size} recipients)`,{videoId:Ae,libraryId:Ce}=await A6(Ne),{uploadUrl:Ve,apiKey:ze}=await E6(Ae),qe=new XMLHttpRequest;qe.upload.onprogress=gt=>{gt.lengthComputable&&E(gt.loaded/gt.total*100)},await new Promise((gt,ss)=>{qe.onload=()=>qe.status>=200&&qe.status<300?gt():ss(new Error("Upload failed")),qe.onerror=()=>ss(new Error("Upload failed")),qe.open("PUT",Ve),qe.setRequestHeader("AccessKey",ze),qe.send(ke)}),u("processing");const dt=`https://iframe.mediadelivery.net/embed/${Ce}/${Ae}`;let Xe=0;const at=Date.now(),rt=9e4;for(;Xe<4&&(await new Promise(ss=>setTimeout(ss,3e3)),!(Date.now()-at>rt));){const gt=await mk(Ae);if(Xe=gt.status,P(gt.encodeProgress||0),Xe===5||Xe===6)throw new Error("Video processing failed")}const Ke=await mk(Ae),Je=(Ke.storageSize||ke.size)/(1024*1024),pt=await te.mutateAsync({bunny_video_id:Ae,playback_url:Ke.directPlayUrl||dt,thumbnail_url:Ke.thumbnailUrl,preview_url:Ke.previewUrl||null,duration_seconds:Ke.length||Be,file_size_mb:Je,title:Ne,status:Xe>=4?"ready":"processing",touch_type:"recruiting"});b(pt.id),S(Ne),u("compose")}catch(Ne){re.error((Ne==null?void 0:Ne.message)||"Failed to upload video"),u("pick-video")}},[h.size,te]),Se=j.useCallback(async()=>{if(!(!v||h.size===0)){u("sending");try{const ke=[];for(const Ae of h){const Ce=await ne.mutateAsync({prospect_id:Ae,video_id:v,brokerage_id:s,message:O||void 0});ke.push(Ce.id)}const{data:Be,error:Ne}=await q.functions.invoke("send-recruit-video-email",{body:{recruit_video_ids:ke,brokerage_id:s,subject_override:R||void 0,message_override:O||void 0,send_via:V}});if(Ne)throw new Error(Ne.message);X({sent:(Be==null?void 0:Be.sent)??0,total:(Be==null?void 0:Be.total)??ke.length}),u("done"),re.success(`Sent ${(Be==null?void 0:Be.sent)??0} of ${(Be==null?void 0:Be.total)??ke.length} videos`)}catch(ke){re.error((ke==null?void 0:ke.message)||"Failed to send"),u("compose")}}},[v,h,s,O,R,V,ne]),Le=h.size,Fe=ae.filter(ke=>!ke.email).length;return e.jsxs(zs,{open:o,onOpenChange:_e,children:[t&&e.jsx(jl,{asChild:!0,children:t}),e.jsxs(Os,{className:"max-w-3xl max-h-[90vh] overflow-hidden flex flex-col",children:[e.jsx(Us,{children:e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(ua,{className:"h-5 w-5 text-primary"}),"Send Recruiting Video",Le>0&&e.jsxs($e,{variant:"secondary",className:"ml-2",children:[e.jsx(Yn,{className:"h-3 w-3 mr-1"}),Le," ",Le===1?"recipient":"recipients"]})]})}),d==="pick-recipients"&&e.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Zr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search prospects...",value:x,onChange:ke=>y(ke.target.value),className:"pl-9"})]}),e.jsxs(ms,{value:f,onValueChange:g,children:[e.jsx(us,{className:"w-48",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All stages"}),le.map(ke=>e.jsx(Ge,{value:ke.id,children:ke.name},ke.id))]})]})]}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[e.jsxs("button",{onClick:ve,className:"hover:underline",children:[h.size===he.length&&he.length>0?"Deselect all":"Select all"," ","(",he.length,")"]}),Fe>0&&e.jsxs("span",{children:[Fe," prospect(s) hidden — no email on file"]})]}),e.jsx(uo,{className:"flex-1 border rounded-md",children:he.length===0?e.jsx("div",{className:"p-8 text-center text-sm text-muted-foreground",children:"No prospects match. Make sure prospects have email addresses."}):e.jsx("div",{className:"divide-y",children:he.map(ke=>{const Be=h.has(ke.id),Ne=le.find(Ae=>Ae.id===ke.stage_id);return e.jsxs("label",{className:"flex items-center gap-3 p-3 hover:bg-muted/30 cursor-pointer",children:[e.jsx(ai,{checked:Be,onCheckedChange:()=>ue(ke.id)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("p",{className:"font-medium text-sm truncate",children:[ke.first_name," ",ke.last_name]}),Ne&&e.jsx($e,{variant:"outline",className:"text-[10px]",style:{borderColor:Ne.color,color:Ne.color},children:Ne.name})]}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[ke.email," ",ke.current_brokerage&&`· ${ke.current_brokerage}`]})]})]},ke.id)})})}),e.jsxs(Sr,{children:[e.jsx($,{variant:"outline",onClick:()=>_e(!1),children:"Cancel"}),e.jsx($,{disabled:Le===0,onClick:()=>u("pick-video"),children:"Next: Choose Video"})]})]}),d==="pick-video"&&e.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(ha,{defaultValue:"record",className:"flex-1 flex flex-col overflow-hidden",children:[e.jsxs(ma,{className:"self-start",children:[e.jsxs(Zt,{value:"record",children:[e.jsx(dn,{className:"h-3.5 w-3.5 mr-1"}),"Record New"]}),e.jsxs(Zt,{value:"library",children:[e.jsx(d2,{className:"h-3.5 w-3.5 mr-1"}),"Use Existing"]})]}),e.jsx(Xt,{value:"record",className:"flex-1 overflow-auto",children:e.jsxs("div",{className:"text-center py-8 space-y-4",children:[e.jsx(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 ",Le," ",Le===1?"recipient":"recipients"," — each gets their own tracked link."]})]}),e.jsxs($,{onClick:()=>u("record"),children:[e.jsx(ua,{className:"h-4 w-4 mr-2"}),"Start Recording"]})]})}),e.jsx(Xt,{value:"library",className:"flex-1 overflow-auto",children:J.length===0?e.jsx("div",{className:"text-center py-8 text-sm text-muted-foreground",children:"No recruiting videos in library yet."}):e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-3 p-1",children:J.map(ke=>e.jsxs("button",{onClick:()=>{b(ke.id),S(ke.title||"Untitled"),u("compose")},className:"text-left group rounded-md border overflow-hidden hover:border-primary transition-colors",children:[e.jsx("div",{className:"aspect-video bg-muted relative",children:_4(ke)?e.jsx("img",{src:_4(ke),alt:"",className:"w-full h-full object-cover",referrerPolicy:"no-referrer"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(ua,{className:"h-8 w-8 text-muted-foreground"})})}),e.jsx("div",{className:"p-2",children:e.jsx("p",{className:"text-xs font-medium truncate",children:ke.title||"Untitled"})})]},ke.id))})})]}),e.jsx(Sr,{children:e.jsx($,{variant:"outline",onClick:()=>u("pick-recipients"),children:"Back"})})]}),d==="record"&&e.jsxs("div",{className:"flex-1 overflow-auto",children:[e.jsx(FT,{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:Le})," recipient",Le===1?"":"s"]})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Subject (optional override)"}),e.jsx(pe,{value:R,onChange:ke=>D(ke.target.value),placeholder:"[First Name], I made you a quick video 🎥",className:"mt-1"}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-1",children:"Leave blank to use the default personalized subject."})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Personal message shown in the email & on the landing page"}),e.jsx(Ls,{value:O,onChange:ke=>U(ke.target.value),placeholder:"Hey there — wanted to share a quick thought on what we're building here...",rows:5,className:"mt-1"})]}),e.jsx(Flt,{value:V,onChange:G}),e.jsxs(Sr,{children:[e.jsx($,{variant:"outline",onClick:()=>u("pick-video"),children:"Back"}),e.jsxs($,{onClick:Se,disabled:!v||Le===0,children:[e.jsx(Kr,{className:"h-4 w-4 mr-2"})," Send to ",Le," ",Le===1?"prospect":"prospects"]})]})]}),d==="sending"&&e.jsxs("div",{className:"py-12 text-center space-y-3",children:[e.jsx(Ct,{className:"h-8 w-8 animate-spin mx-auto text-primary"}),e.jsxs("p",{className:"font-medium",children:["Sending to ",Le," recipient",Le===1?"":"s","…"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Each prospect gets their own tracked share link."})]}),d==="done"&&Y&&e.jsxs("div",{className:"py-12 text-center space-y-4",children:[e.jsx("div",{className:`h-16 w-16 rounded-full mx-auto flex items-center justify-center ${Y.sent===Y.total?"bg-primary/10":"bg-muted"}`,children:Y.sent===Y.total?e.jsx(Vr,{className:"h-8 w-8 text-primary"}):e.jsx(ll,{className:"h-8 w-8 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-semibold text-lg",children:[Y.sent," of ",Y.total," sent"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"View engagement under the Video Outreach tab."})]}),e.jsx($,{onClick:()=>_e(!1),children:"Done"})]})]})]})}function Dlr(s){if(!s)return"—";const t=Math.floor(s/60),n=s%60;return t>0?`${t}m ${n}s`:`${n}s`}function Flr({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(Ca,{className:"h-3 w-3 mr-1"}),s.view_count," views"]}):s.sent_at?e.jsxs($e,{variant:"secondary",children:[e.jsx(Kr,{className:"h-3 w-3 mr-1"}),"Sent"]}):e.jsxs($e,{variant:"outline",children:[e.jsx(da,{className:"h-3 w-3 mr-1"}),"Draft"]})}function Sos({brokerageId:s}){var w,S,A,E;const{data:t=[],isLoading:n}=Nlr(s),{data:r=[]}=gos(s),a=Slr(),i=Clr(),l=pos(),[o,c]=j.useState(""),[d,u]=j.useState(!1),[h,m]=j.useState({title:"",script_text:"",category:"general"}),[f,g]=j.useState(null),x=t.filter(I=>{var R,D,O,U;return o?`${((R=I.prospect)==null?void 0:R.first_name)||""} ${((D=I.prospect)==null?void 0:D.last_name)||""}`.toLowerCase().includes(o.toLowerCase())||((U=(O=I.video)==null?void 0:O.title)==null?void 0:U.toLowerCase().includes(o.toLowerCase())):!0}),y={total:t.length,sent:t.filter(I=>I.sent_at).length,viewed:t.filter(I=>I.view_count>0).length,ctaClicked:t.filter(I=>I.cta_clicked_at).length},v=j.useCallback(I=>{if(!I)return;const P=`${window.location.origin}/recruit-video/${I}`;navigator.clipboard.writeText(P),re.success("Share link copied")},[]);j.useCallback((I,P)=>{l.mutate({id:I,sent_via:P})},[l]);const b=()=>{!h.title.trim()||!h.script_text.trim()||a.mutate({brokerage_id:s,...h},{onSuccess:()=>{m({title:"",script_text:"",category:"general"}),u(!1)}})};return e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[{label:"Total Videos",value:y.total,icon:ua,color:"text-primary"},{label:"Sent",value:y.sent,icon:Kr,color:"text-blue-500"},{label:"Viewed",value:y.viewed,icon:Ca,color:"text-amber-500"},{label:"CTA Clicked",value:y.ctaClicked,icon:Vr,color:"text-emerald-500"}].map(I=>e.jsx(je,{children:e.jsxs(Ie,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:`h-10 w-10 rounded-lg bg-muted flex items-center justify-center ${I.color}`,children:e.jsx(I.icon,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:I.value}),e.jsx("p",{className:"text-xs text-muted-foreground",children:I.label})]})]})},I.label))}),e.jsxs(ha,{defaultValue:"videos",className:"space-y-4",children:[e.jsxs(ma,{children:[e.jsxs(Zt,{value:"videos",children:[e.jsx(ua,{className:"h-4 w-4 mr-1.5"}),"All Videos"]}),e.jsxs(Zt,{value:"scripts",children:[e.jsx(Jr,{className:"h-4 w-4 mr-1.5"}),"Script Library"]}),e.jsxs(Zt,{value:"analytics",children:[e.jsx(Gl,{className:"h-4 w-4 mr-1.5"}),"Engagement"]})]}),e.jsx(Xt,{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(Zr,{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(kos,{brokerageId:s,trigger:e.jsxs($,{size:"sm",className:"gap-1.5",children:[e.jsx(mn,{className:"h-4 w-4"})," Send Video Email"]})})]})]})}),e.jsx(Ie,{children:n?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):x.length===0?e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(ua,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{className:"font-medium",children:"No video outreach yet"}),e.jsx("p",{className:"text-sm mt-1",children:"Record a personalized video from any prospect's profile card"})]}):e.jsx("div",{className:"space-y-3",children:x.map(I=>{var P,R,D,O,U,W,V;return e.jsxs("div",{className:"flex items-center gap-4 p-3 rounded-lg border bg-card hover:bg-muted/30 transition-colors",children:[e.jsxs("div",{className:"relative h-16 w-28 rounded-md overflow-hidden bg-muted flex-shrink-0",children:[_4(I.video)?e.jsx("img",{src:_4(I.video),alt:"",className:"h-full w-full object-cover",referrerPolicy:"no-referrer"}):e.jsx("div",{className:"h-full w-full flex items-center justify-center",children:e.jsx(ua,{className:"h-6 w-6 text-muted-foreground"})}),e.jsx("div",{className:"absolute bottom-1 right-1 bg-black/70 text-white text-[10px] px-1 rounded",children:Dlr(((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(Flr,{video:I})]}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:((O=I.video)==null?void 0:O.title)||"Untitled video"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[en(new Date(I.created_at),"MMM d, yyyy"),((U=I.prospect)==null?void 0:U.current_brokerage)&&` · ${I.prospect.current_brokerage}`]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>v(I.share_token),title:"Copy share link",children:e.jsx(Ha,{className:"h-4 w-4"})}),e.jsxs($,{variant:I.sent_at?"ghost":"default",size:"sm",className:"h-8 gap-1.5",onClick:()=>g(I),disabled:!((W=I.prospect)!=null&&W.email),title:(V=I.prospect)!=null&&V.email?"Email this video to the prospect":"Prospect has no email",children:[e.jsx(mn,{className:"h-4 w-4"}),I.sent_at?"Resend":"Email"]}),I.share_token&&e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>window.open(`/recruit-video/${I.share_token}`,"_blank"),title:"Preview landing page",children:e.jsx(Fr,{className:"h-4 w-4"})})]})]},I.id)})})})]})}),e.jsx(Xt,{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(zs,{open:d,onOpenChange:u,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{size:"sm",children:[e.jsx(dn,{className:"h-4 w-4 mr-1.5"}),"New Script"]})}),e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Create Recruiting Script"})}),e.jsxs("div",{className:"space-y-4 mt-2",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Title"}),e.jsx(pe,{value:h.title,onChange:I=>m(P=>({...P,title:I.target.value})),placeholder:"e.g., Why Switch to Our Brokerage"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Category"}),e.jsxs(ms,{value:h.category,onValueChange:I=>m(P=>({...P,category:I})),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:nQe.map(I=>e.jsx(Ge,{value:I.value,children:I.label},I.value))})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Script"}),e.jsx(Ls,{value:h.script_text,onChange:I=>m(P=>({...P,script_text:I.target.value})),placeholder:"Hi [Name], I noticed you've been doing great work at [Brokerage]...",rows:8})]}),e.jsx($,{onClick:b,disabled:!h.title.trim()||!h.script_text.trim(),className:"w-full",children:"Save Script"})]})]})]})]})}),e.jsx(Ie,{children:r.length===0?e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(Jr,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{className:"font-medium",children:"No scripts yet"}),e.jsx("p",{className:"text-sm mt-1",children:"Create teleprompter scripts for common recruiting conversations"})]}):e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:r.map(I=>{var R;const P=((R=nQe.find(D=>D.value===I.category))==null?void 0:R.label)||I.category;return e.jsx(je,{className:"relative group",children:e.jsxs(Ie,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx($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(Hn,{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(Xt,{value:"analytics",children:e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-lg",children:"Engagement Funnel"})}),e.jsxs(Ie,{children:[e.jsx("div",{className:"space-y-4",children:[{label:"Videos Created",count:y.total,pct:100,color:"bg-primary"},{label:"Sent to Prospects",count:y.sent,pct:y.total?Math.round(y.sent/y.total*100):0,color:"bg-blue-500"},{label:"Viewed by Prospect",count:y.viewed,pct:y.sent?Math.round(y.viewed/y.sent*100):0,color:"bg-amber-500"},{label:"CTA Clicked",count:y.ctaClicked,pct:y.viewed?Math.round(y.ctaClicked/y.viewed*100):0,color:"bg-emerald-500"}].map(I=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{children:I.label}),e.jsxs("span",{className:"font-medium",children:[I.count," (",I.pct,"%)"]})]}),e.jsx("div",{className:"h-3 bg-muted rounded-full overflow-hidden",children:e.jsx("div",{className:`h-full ${I.color} rounded-full transition-all`,style:{width:`${I.pct}%`}})})]},I.label))}),t.filter(I=>I.view_count>0).length>0&&e.jsxs("div",{className:"mt-8",children:[e.jsx("h4",{className:"font-medium text-sm mb-3",children:"Most Engaged Prospects"}),e.jsx("div",{className:"space-y-2",children:t.filter(I=>I.view_count>0).sort((I,P)=>P.view_count-I.view_count).slice(0,5).map(I=>{var P,R;return e.jsxs("div",{className:"flex items-center justify-between text-sm p-2 rounded-md bg-muted/30",children:[e.jsxs("span",{className:"font-medium",children:[(P=I.prospect)==null?void 0:P.first_name," ",(R=I.prospect)==null?void 0:R.last_name]}),e.jsxs("div",{className:"flex items-center gap-3 text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ca,{className:"h-3.5 w-3.5"})," ",I.view_count]}),I.cta_clicked_at&&e.jsx(Vr,{className:"h-4 w-4 text-emerald-500"})]})]},I.id)})})]})]})]})})]}),f&&e.jsx(mos,{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 Cos({brokerageId:s}){const{toast:t}=Bi(),n=Wt(),{stages:r,prospects:a}=_9(s),[i,l]=j.useState(!1),[o,c]=j.useState({title:"",target_count:"10",target_stage_id:"",period_start:en(new Date,"yyyy-MM-dd"),period_end:en(new Date(new Date().getFullYear(),new Date().getMonth()+3,0),"yyyy-MM-dd")}),{data:d=[],isLoading:u}=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:y}=await q.from("recruit_goals").insert({brokerage_id:s,title:g.title,target_count:parseInt(g.target_count),target_stage_id:g.target_stage_id||null,period_start:g.period_start,period_end:g.period_end,created_by:x.id});if(y)throw y},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-goals",s]}),t({title:"Goal created"}),l(!1)},onError:g=>t({title:"Error",description:g.message,variant:"destructive"})}),m=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(v=>v.id===g.target_stage_id);return{count:a.filter(v=>IS(new Date(v.created_at),{start:new Date(g.period_start),end:new Date(g.period_end)})?g.target_stage_id?v.stage_id===g.target_stage_id:!0:!1).length,stage:x}};return u?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:[d.length," goal",d.length!==1?"s":""]}),e.jsxs($,{size:"sm",onClick:()=>l(!0),children:[e.jsx(dn,{className:"h-4 w-4 mr-1"})," New Goal"]})]}),d.length===0?e.jsxs(je,{className:"py-12 text-center",children:[e.jsx(nh,{className:"h-10 w-10 mx-auto text-muted-foreground mb-3"}),e.jsx("p",{className:"text-muted-foreground",children:"No goals set. Create a recruiting target to track progress."})]}):e.jsx("div",{className:"grid md:grid-cols-2 gap-4",children:d.map(g=>{const{count:x,stage:y}=f(g),v=Math.min(100,x/g.target_count*100),b=IS(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:[en(new Date(g.period_start),"MMM d")," – ",en(new Date(g.period_end),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[b?e.jsx($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(Hn,{className:"h-3.5 w-3.5"})})]})]})}),e.jsxs(Ie,{className:"space-y-2",children:[y&&e.jsxs($e,{variant:"outline",className:"text-[10px]",style:{borderColor:y.color,color:y.color},children:["Stage: ",y.name]}),e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"font-bold text-lg",children:x}),e.jsxs("span",{className:"text-muted-foreground",children:["/ ",g.target_count]})]}),e.jsx(Yi,{value:v,className:"h-2"}),e.jsxs("p",{className:"text-xs text-muted-foreground text-right",children:[v.toFixed(0),"% complete"]})]})]},g.id)})}),e.jsx(zs,{open:i,onOpenChange:l,children:e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Create Recruiting Goal"})}),e.jsxs("form",{onSubmit:g=>{g.preventDefault(),h.mutate(o)},className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Goal Title *"}),e.jsx(pe,{required:!0,value:o.title,onChange:g=>c(x=>({...x,title:g.target.value})),placeholder:"e.g. Q2 Recruiting Target"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Target Count *"}),e.jsx(pe,{type:"number",min:"1",required:!0,value:o.target_count,onChange:g=>c(x=>({...x,target_count:g.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Target Stage (optional)"}),e.jsxs("select",{className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm",value:o.target_stage_id,onChange:g=>c(x=>({...x,target_stage_id:g.target.value})),children:[e.jsx("option",{value:"",children:"All stages (total prospects)"}),r.map(g=>e.jsx("option",{value:g.id,children:g.name},g.id))]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Count prospects that reach this stage"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Start Date"}),e.jsx(pe,{type:"date",required:!0,value:o.period_start,onChange:g=>c(x=>({...x,period_start:g.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"End Date"}),e.jsx(pe,{type:"date",required:!0,value:o.period_end,onChange:g=>c(x=>({...x,period_end:g.target.value}))})]})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx($,{type:"submit",disabled:h.isPending,children:"Create Goal"})]})]})]})})]})}const Olr={first_name:"Sarah",brokerage_name:"ABC Realty",city:"Austin",sender_name:"Jeremy"};function Aos({email:s,mergeValues:t=Olr,selectedSubjectIndex:n,onClose:r}){var c;const a=d=>d.replace(/\{\{first_name\}\}/g,t.first_name).replace(/\{\{brokerage_name\}\}/g,t.brokerage_name).replace(/\{\{city\}\}/g,t.city).replace(/\{\{sender_name\}\}/g,t.sender_name).replace(/\{\{landing_page_link\}\}/g,"https://bestbrokerage.relevelup.com/join-brokerage/your-slug"),i=((c=s.subject_line_options)==null?void 0:c.length)>0?s.subject_line_options:[s.subject_line],l=n??0,o=i[l]||s.subject_line;return e.jsx(zs,{open:!0,onOpenChange:()=>r(),children:e.jsxs(Os,{className:"max-w-2xl max-h-[85vh] overflow-y-auto p-0",children:[e.jsxs(Us,{className:"px-6 pt-6 pb-4 border-b",children:[e.jsxs(Bs,{className:"text-base",children:["Email #",s.email_number," — ",s.title]}),e.jsxs("div",{className:"flex items-center gap-3 mt-2",children:[e.jsxs($e,{variant:"outline",className:"text-xs gap-1",children:[e.jsx(da,{className:"h-3 w-3"}),s.email_number===1?"Sent immediately":`Day ${s.delay_days}`]}),i.length>1&&e.jsxs($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 Blt({brokerageId:s}){const t=Wt(),{user:n}=bs(),[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?re.error(g.message):re.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]}),re.success("Recruiting email settings saved!")},onError:g=>re.error(g.message)}),f=(g,x)=>{c(y=>({...y,merge_fields:{...y.merge_fields,[g]:x}}))};return e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Configure the sender identity and merge fields for recruiting emails sent to this brokerage's prospects."}),e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-4 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ta,{className:"h-4 w-4 text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Your Scheduling Link"})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["This URL powers the ",e.jsx("strong",{children:'"Schedule a Conversation"'})," button on every recruiting video page you send. Paste your Calendly, HubSpot Meetings, Google Calendar booking link, etc."]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{value:r,onChange:g=>a(g.target.value),placeholder:"https://calendly.com/your-name/intro"}),e.jsxs($,{onClick:h,disabled:i,size:"sm",children:[e.jsx(tl,{className:"h-4 w-4 mr-1"})," Save"]})]}),!r&&e.jsx("p",{className:"text-xs text-amber-600",children:"⚠️ No link set — the CTA button will be hidden on your video pages until you add one."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(ee,{className:"text-xs",children:"Sender Display Name"}),e.jsx(pe,{value:o.sender_name,onChange:g=>c({...o,sender_name:g.target.value}),placeholder:"e.g. Jeremy at LevelUp"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ee,{className:"text-xs",children:"Sender Email Address"}),e.jsx(pe,{value:o.sender_email,onChange:g=>c({...o,sender_email:g.target.value}),placeholder:"recruiting@relevelup.com"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Must be a verified SES identity. Verify your own address below to send from it."})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ee,{className:"text-xs",children:"Reply-To Email (optional)"}),e.jsx(pe,{value:o.reply_to_email,onChange:g=>c({...o,reply_to_email:g.target.value}),placeholder:"jeremy@relevelup.com"})]})]}),e.jsxs("div",{className:"border-t pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(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(oos,{brokerageId:s,onVerifiedSelect:g=>{c(x=>({...x,sender_email:g})),re.success(`Sender set to ${g}`)}})]}),e.jsxs("div",{className:"border-t pt-4",children:[e.jsx("p",{className:"text-sm font-medium mb-3",children:"Default Merge Fields"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"These values will auto-fill in campaign emails for this brokerage."}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(ee,{className:"text-xs",children:"{{brokerage_name}}"}),e.jsx(pe,{value:o.merge_fields.brokerage_name||"",onChange:g=>f("brokerage_name",g.target.value),placeholder:(u==null?void 0:u.name)||"Brokerage Name"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ee,{className:"text-xs",children:"{{city}}"}),e.jsx(pe,{value:o.merge_fields.city||"",onChange:g=>f("city",g.target.value),placeholder:"e.g. Austin"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ee,{className:"text-xs",children:"{{sender_name}}"}),e.jsx(pe,{value:o.merge_fields.sender_name||"",onChange:g=>f("sender_name",g.target.value),placeholder:"e.g. Jeremy"})]})]})]}),e.jsxs($,{onClick:()=>m.mutate(),disabled:m.isPending,className:"w-full",children:[e.jsx(tl,{className:"h-4 w-4 mr-1"})," Save Settings"]})]})}const Eos=pC.create({name:"underline",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"u"},{style:"text-decoration",consuming:!1,getAttrs:s=>s.includes("underline")?{}:!1}]},renderHTML({HTMLAttributes:s}){return["u",ep(this.options.HTMLAttributes,s),0]},addCommands(){return{setUnderline:()=>({commands:s})=>s.setMark(this.name),toggleUnderline:()=>({commands:s})=>s.toggleMark(this.name),unsetUnderline:()=>({commands:s})=>s.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-u":()=>this.editor.commands.toggleUnderline(),"Mod-U":()=>this.editor.commands.toggleUnderline()}}}),mEt=[{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 Kv({onClick:s,active:t,disabled:n,icon:r,tooltip:a}){return e.jsxs(iy,{children:[e.jsx(oy,{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(jx,{side:"bottom",className:"text-xs",children:a})]})}function zlr({content:s,onChange:t}){const n=$6e({extensions:[U6e.configure({heading:{levels:[1,2,3]}}),Eos,V6e.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline cursor-pointer"}}),H6e.configure({types:["heading","paragraph"]}),Knt,EXt],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(bk,{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(Kv,{onClick:()=>n.chain().focus().toggleBold().run(),active:n.isActive("bold"),icon:SE,tooltip:"Bold"}),e.jsx(Kv,{onClick:()=>n.chain().focus().toggleItalic().run(),active:n.isActive("italic"),icon:EE,tooltip:"Italic"}),e.jsx(Kv,{onClick:()=>n.chain().focus().toggleUnderline().run(),active:n.isActive("underline"),icon:s7,tooltip:"Underline"}),e.jsx(Kv,{onClick:()=>n.chain().focus().toggleStrike().run(),active:n.isActive("strike"),icon:JJ,tooltip:"Strikethrough"}),e.jsx(Vc,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Kv,{onClick:()=>n.chain().focus().toggleHeading({level:1}).run(),active:n.isActive("heading",{level:1}),icon:Rq,tooltip:"Heading 1"}),e.jsx(Kv,{onClick:()=>n.chain().focus().toggleHeading({level:2}).run(),active:n.isActive("heading",{level:2}),icon:$z,tooltip:"Heading 2"}),e.jsx(Kv,{onClick:()=>n.chain().focus().toggleHeading({level:3}).run(),active:n.isActive("heading",{level:3}),icon:Dq,tooltip:"Heading 3"}),e.jsx(Vc,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Kv,{onClick:()=>n.chain().focus().toggleBulletList().run(),active:n.isActive("bulletList"),icon:T0,tooltip:"Bullet List"}),e.jsx(Kv,{onClick:()=>n.chain().focus().toggleOrderedList().run(),active:n.isActive("orderedList"),icon:u2,tooltip:"Numbered List"}),e.jsx(Kv,{onClick:()=>n.chain().focus().toggleBlockquote().run(),active:n.isActive("blockquote"),icon:h2,tooltip:"Blockquote"}),e.jsx(Kv,{onClick:()=>n.chain().focus().setHorizontalRule().run(),icon:ZN,tooltip:"Divider"}),e.jsx(Vc,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Kv,{onClick:()=>n.chain().focus().setTextAlign("left").run(),active:n.isActive({textAlign:"left"}),icon:FI,tooltip:"Align Left"}),e.jsx(Kv,{onClick:()=>n.chain().focus().setTextAlign("center").run(),active:n.isActive({textAlign:"center"}),icon:DI,tooltip:"Align Center"}),e.jsx(Kv,{onClick:()=>n.chain().focus().setTextAlign("right").run(),active:n.isActive({textAlign:"right"}),icon:OI,tooltip:"Align Right"}),e.jsx(Vc,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Kv,{onClick:r,active:n.isActive("link"),icon:Sd,tooltip:"Insert Link"}),e.jsx(Vc,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Kv,{onClick:()=>n.chain().focus().undo().run(),disabled:!n.can().undo(),icon:OE,tooltip:"Undo"}),e.jsx(Kv,{onClick:()=>n.chain().focus().redo().run(),disabled:!n.can().redo(),icon:DE,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($u,{children:[e.jsx(Uu,{asChild:!0,children:e.jsxs($,{type:"button",variant:"outline",size:"sm",className:"h-8 gap-1.5 text-xs font-medium",children:[e.jsx(hV,{className:"h-3.5 w-3.5"}),"Merge Tags"]})}),e.jsx(Au,{align:"end",className:"w-56",children:mEt.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(B6e,{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:"}),mEt.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 Blr({open:s,onClose:t,campaignName:n,stat:r}){return e.jsx(zs,{open:s,onOpenChange:a=>!a&&t(),children:e.jsxs(Os,{className:"max-w-3xl max-h-[85vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(Zl,{className:"h-5 w-5 text-primary"}),n," — Engagement Stats"]}),e.jsx(Pr,{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(Kr,{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(the,{icon:mn,color:"text-blue-500",label:"Total Sent",value:r.sent.toLocaleString()}),e.jsx(the,{icon:Ca,color:"text-amber-500",label:"Opens",value:`${r.opened.toLocaleString()}`,sub:`${r.openRate.toFixed(1)}% open rate`}),e.jsx(the,{icon:Pm,color:"text-green-500",label:"Clicks",value:`${r.clicked.toLocaleString()}`,sub:`${r.clickRate.toFixed(1)}% click rate`}),e.jsx(the,{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(da,{className:"h-3 w-3"})," Last sent: ",en(new Date(r.lastSentAt),"MMM d, yyyy h:mm a")]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-semibold mb-2 mt-4",children:"Per-Email Performance"}),e.jsx("div",{className:"space-y-2",children:r.byEmail.map(a=>{const i=a.sent_count>0?a.opened_count/a.sent_count*100:0,l=a.sent_count>0?a.clicked_count/a.sent_count*100:0;return e.jsx(je,{className:"overflow-hidden",children:e.jsxs(Ie,{className:"py-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"h-8 w-8 rounded-full bg-primary/10 text-primary font-bold text-xs flex items-center justify-center shrink-0",children:["#",a.email_number]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:a.title}),e.jsxs("div",{className:"flex flex-wrap gap-1.5 mt-1",children:[e.jsxs($e,{variant:"outline",className:"text-[10px] gap-1",children:[e.jsx(mn,{className:"h-2.5 w-2.5"})," ",a.sent_count.toLocaleString()," sent"]}),e.jsxs($e,{variant:"outline",className:"text-[10px] gap-1 border-amber-500/30 text-amber-600",children:[e.jsx(Ca,{className:"h-2.5 w-2.5"})," ",a.opened_count.toLocaleString()," (",i.toFixed(1),"%)"]}),e.jsxs($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 the({icon:s,color:t,label:n,value:r,sub:a}){return e.jsx(je,{children:e.jsx(Ie,{className:"pt-4 pb-3",children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx(s,{className:`h-6 w-6 ${t}`}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-xl font-bold leading-none",children:r}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:n}),a&&e.jsx("p",{className:"text-[10px] text-muted-foreground",children:a})]})]})})})}function $lt(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 fEt={cold:{icon:Xj,color:"text-blue-500",bg:"bg-blue-50 dark:bg-blue-950/30",label:"Cold — Curiosity"},warm:{icon:ek,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 Tos({brokerageId:s}){var ve,Ee,Se,Le;const{user:t}=bs(),n=Wt(),[r,a]=j.useState(null),[i,l]=j.useState(null),[o,c]=j.useState(null),[d,u]=j.useState(!1),[h,m]=j.useState(!1),[f,g]=j.useState("editor"),[x,y]=j.useState(null),[v,b]=j.useState(null),{data:w={}}=$lt(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:ke}=await q.from("brokerages").select("name, city, state").eq("id",s).single();if(ke)throw ke;return Fe}}),{data:I}=st({queryKey:["brokerage-recruit-settings",s],queryFn:async()=>{const{data:Fe,error:ke}=await q.from("brokerage_recruit_settings").select("*").eq("brokerage_id",s).maybeSingle();if(ke)throw ke;return Fe}}),P={first_name:"Sarah",brokerage_name:((ve=I==null?void 0:I.merge_fields)==null?void 0:ve.brokerage_name)||(E==null?void 0:E.name)||"Your Brokerage",city:((Ee=I==null?void 0:I.merge_fields)==null?void 0:Ee.city)||(E==null?void 0:E.city)||"Your City",sender_name:((Se=I==null?void 0:I.merge_fields)==null?void 0:Se.sender_name)||(I==null?void 0:I.sender_name)||"Your Name"},R=Fe=>Fe.replace(/\{\{first_name\}\}/g,P.first_name).replace(/\{\{brokerage_name\}\}/g,P.brokerage_name).replace(/\{\{city\}\}/g,P.city).replace(/\{\{sender_name\}\}/g,P.sender_name),{data:D=[],isLoading:O}=st({queryKey:["recruit-campaigns",s],queryFn:async()=>{const{data:Fe,error:ke}=await q.from("recruit_campaigns").select("*").or(`brokerage_id.is.null,brokerage_id.eq.${s}`).order("sort_order");if(ke)throw ke;return Fe}}),{data:U={}}=st({queryKey:["recruit-campaign-emails",s],enabled:D.length>0,queryFn:async()=>{const Fe=D.map(Ae=>Ae.id),{data:ke,error:Be}=await q.from("recruit_campaign_emails").select("*").in("campaign_id",Fe).order("email_number");if(Be)throw Be;const Ne={};return ke.forEach(Ae=>{Ne[Ae.campaign_id]||(Ne[Ae.campaign_id]=[]),Ne[Ae.campaign_id].push(Ae)}),Ne}}),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:ke}=await q.from("recruit_brokerage_subject_overrides").select("*").eq("brokerage_id",s);if(ke)throw ke;return Fe}}),G={};V.forEach(Fe=>{G[Fe.campaign_email_id]=Fe.selected_subject_index});const Y=mt({mutationFn:async({campaignEmailId:Fe,selectedIndex:ke})=>{const{error:Be}=await q.from("recruit_brokerage_subject_overrides").upsert({brokerage_id:s,campaign_email_id:Fe,selected_subject_index:ke,updated_at:new Date().toISOString()},{onConflict:"brokerage_id,campaign_email_id"});if(Be)throw Be},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-subject-overrides",s]}),re.success("Subject line updated for your brokerage")},onError:Fe=>re.error(Fe.message)}),X=mt({mutationFn:async Fe=>{const{error:ke}=await q.from("recruit_campaign_emails").update({title:Fe.title,subject_line:Fe.subject_line,subject_line_options:Fe.subject_line_options,body_html:Fe.body_html,body_text:Fe.body_text,delay_days:Fe.delay_days,updated_at:new Date().toISOString()}).eq("id",Fe.id);if(ke)throw ke},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),re.success("Email template saved!"),l(null)},onError:Fe=>re.error(Fe.message)}),ae=mt({mutationFn:async()=>{const Fe=S.name.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,""),{data:ke,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 Ne=[{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(Ne.map(Ce=>({campaign_id:ke.id,...Ce,body_html:"

Hi {{first_name}},

Write your message here...

Best,
{{sender_name}}

",body_text:"",subject_line_options:[],is_active:!0})));if(Ae)throw Ae;return ke},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaigns"]}),n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),re.success("Campaign created with 4 starter emails!"),m(!1),A({name:"",description:"",theme:"",goal:"",primary_cta:"Learn more",warmth_level:"warm",sender_name:"",sender_email:"",reply_to_email:""})},onError:Fe=>re.error(Fe.message)}),le=mt({mutationFn:async Fe=>{const{error:ke}=await q.from("recruit_campaigns").update({name:Fe.name,description:Fe.description,theme:Fe.theme,goal:Fe.goal,primary_cta:Fe.primary_cta,warmth_level:Fe.warmth_level,sender_name:Fe.sender_name,sender_email:Fe.sender_email,reply_to_email:Fe.reply_to_email,updated_at:new Date().toISOString()}).eq("id",Fe.id);if(ke)throw ke},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaigns"]}),re.success("Campaign settings saved!"),y(null)},onError:Fe=>re.error(Fe.message)}),ne=mt({mutationFn:async Fe=>{var Ve,ze;const{data:ke}=await q.from("recruit_campaign_emails").select("email_number, delay_days").eq("campaign_id",Fe).order("email_number",{ascending:!1}).limit(1),Be=((Ve=ke==null?void 0:ke[0])==null?void 0:Ve.email_number)??0,Ne=((ze=ke==null?void 0:ke[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:Ne+7,is_active:!0});if(Ce)throw Ce},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),re.success("Email added to campaign!")},onError:Fe=>re.error(Fe.message)}),te=mt({mutationFn:async Fe=>{const{error:ke}=await q.from("recruit_campaigns").delete().eq("id",Fe);if(ke)throw ke},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaigns"]}),n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),re.success("Campaign deleted")},onError:Fe=>re.error(Fe.message)}),J=mt({mutationFn:async Fe=>{const{error:ke}=await q.from("recruit_campaign_emails").delete().eq("id",Fe);if(ke)throw ke},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),re.success("Email removed from campaign")},onError:Fe=>re.error(Fe.message)}),ce=mt({mutationFn:async({emailId:Fe,delay_days:ke})=>{const{error:Be}=await q.from("recruit_campaign_emails").update({delay_days:ke,updated_at:new Date().toISOString()}).eq("id",Fe);if(Be)throw Be},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),re.success("Send delay updated")},onError:Fe=>re.error(Fe.message)});if(O)return e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})});const _e=D.filter(Fe=>!Fe.brokerage_id),he=D.filter(Fe=>Fe.brokerage_id===s);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-bold",children:"Recruiting Campaigns"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"System campaigns + custom campaigns · Each can have its own email settings"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{variant:"outline",size:"sm",onClick:()=>u(!0),className:"gap-1.5",children:[e.jsx(Nd,{className:"h-4 w-4"})," Default Settings"]}),e.jsxs($,{size:"sm",onClick:()=>m(!0),className:"gap-1.5",children:[e.jsx(dn,{className:"h-4 w-4"})," New Campaign"]})]})]}),e.jsx(je,{className:"border-primary/20 bg-primary/5",children:e.jsx(Ie,{className:"py-3",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Nn,{className:"h-5 w-5 text-primary mt-0.5 shrink-0"}),e.jsxs("div",{className:"text-sm",children:[e.jsx("p",{className:"font-semibold",children:"Per-Campaign Email Settings"}),e.jsxs("p",{className:"text-muted-foreground",children:["Each campaign can override the default sender name, email, and reply-to. Click the ",e.jsx(Nd,{className:"inline h-3.5 w-3.5"})," icon on any campaign to customize."]})]})]})})}),he.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"text-sm font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-2",children:[e.jsx(Uq,{className:"h-4 w-4"})," Your Custom Campaigns"]}),e.jsx("div",{className:"space-y-3",children:he.map(Fe=>ue(Fe,!0))})]}),_e.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"text-sm font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-2",children:[e.jsx(Nn,{className:"h-4 w-4"})," System Campaigns"]}),e.jsx("div",{className:"space-y-3",children:_e.map(Fe=>ue(Fe,!1))})]}),D.length===0&&e.jsx(je,{children:e.jsxs(Ie,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(mn,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No campaigns yet. Create your first campaign to start automated outreach."}),e.jsxs($,{className:"mt-4",onClick:()=>m(!0),children:[e.jsx(dn,{className:"h-4 w-4 mr-1"})," Create Campaign"]})]})}),e.jsx(Blr,{open:!!v,onClose:()=>b(null),campaignName:(v==null?void 0:v.name)||"",stat:v&&w[v.id]||null}),o&&e.jsx(Aos,{email:o,mergeValues:P,selectedSubjectIndex:G[o.id],onClose:()=>c(null)}),e.jsx(zs,{open:!!i,onOpenChange:Fe=>!Fe&&l(null),children:e.jsxs(Os,{className:"max-w-4xl max-h-[90vh] overflow-y-auto p-0",children:[e.jsxs(Us,{className:"px-6 pt-6 pb-4 border-b",children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(HI,{className:"h-5 w-5 text-primary"}),"Edit Email #",i==null?void 0:i.email_number]}),e.jsx(Pr,{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(Ls,{value:((Le=i.subject_line_options)==null?void 0:Le.join(` `))||"",onChange:Fe=>l({...i,subject_line_options:Fe.target.value.split(` `).filter(Boolean)}),rows:2,className:"text-sm resize-none"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Email Body"}),e.jsx(ha,{value:f,onValueChange:Fe=>g(Fe),children:e.jsxs(ma,{className:"h-7",children:[e.jsx(Zt,{value:"editor",className:"text-xs px-3 h-6",children:"Editor"}),e.jsx(Zt,{value:"preview",className:"text-xs px-3 h-6",children:"Preview"})]})})]}),f==="editor"?e.jsx(zlr,{content:i.body_html,onChange:Fe=>l({...i,body_html:Fe})}):e.jsxs("div",{className:"border rounded-xl overflow-hidden",children:[e.jsxs("div",{className:"bg-muted/50 px-4 py-2 border-b space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{className:"font-medium w-12",children:"From:"}),e.jsxs("span",{children:[P.sender_name," "]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{className:"font-medium w-12",children:"To:"}),e.jsxs("span",{children:[P.first_name," "]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"font-medium w-12 text-muted-foreground",children:"Subject:"}),e.jsx("span",{className:"font-medium",children:R(i.subject_line)})]})]}),e.jsx("div",{className:"bg-white p-6",children:e.jsx("div",{className:"prose prose-sm max-w-none",style:{fontSize:"15px",lineHeight:"1.75",color:"#1a1a1a"},dangerouslySetInnerHTML:{__html:R(i.body_html)}})})]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Changes are saved to this campaign's templates"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",size:"sm",onClick:()=>l(null),children:"Cancel"}),e.jsxs($,{size:"sm",onClick:()=>X.mutate(i),disabled:X.isPending,className:"gap-1.5",children:[e.jsx(tl,{className:"h-3.5 w-3.5"})," Save Changes"]})]})]})]})]})}),e.jsx(zs,{open:h,onOpenChange:m,children:e.jsxs(Os,{className:"max-w-lg",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(dn,{className:"h-5 w-5 text-primary"})," Create Custom Campaign"]}),e.jsx(Pr,{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(Ls,{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(v1,{children:[e.jsx(b1,{asChild:!0,children:e.jsxs($,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs font-medium text-muted-foreground hover:text-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(mn,{className:"h-3.5 w-3.5"})," Email Settings Override"]}),e.jsx(wl,{className:"h-3.5 w-3.5"})]})}),e.jsxs(_1,{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(dn,{className:"h-4 w-4 mr-1"})," Create Campaign"]})]})]})}),e.jsx(zs,{open:!!x,onOpenChange:Fe=>!Fe&&y(null),children:e.jsxs(Os,{className:"max-w-lg",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(Nd,{className:"h-5 w-5 text-primary"})," Campaign Email Settings"]}),e.jsx(Pr,{children:"Override the default sender for this campaign. Leave blank to use brokerage defaults."})]}),x&&e.jsxs("div",{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs font-medium",children:"Campaign Name"}),e.jsx(pe,{value:x.name,onChange:Fe=>y({...x,name:Fe.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs font-medium",children:"Warmth Level"}),e.jsxs(ms,{value:x.warmth_level,onValueChange:Fe=>y({...x,warmth_level:Fe}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"cold",children:"❄️ Cold"}),e.jsx(Ge,{value:"warm",children:"☀️ Warm"}),e.jsx(Ge,{value:"hot",children:"🔥 Hot"})]})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs font-medium",children:"Goal"}),e.jsx(pe,{value:x.goal||"",onChange:Fe=>y({...x,goal:Fe.target.value})})]}),e.jsxs("div",{className:"border-t pt-4 space-y-3",children:[e.jsxs("p",{className:"text-sm font-semibold flex items-center gap-1.5",children:[e.jsx(mn,{className:"h-4 w-4 text-primary"})," Email Sender Override"]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Sender Name"}),e.jsx(pe,{value:x.sender_name||"",onChange:Fe=>y({...x,sender_name:Fe.target.value}),placeholder:"Uses brokerage default"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Sender Email"}),e.jsx(pe,{value:x.sender_email||"",onChange:Fe=>y({...x,sender_email:Fe.target.value}),placeholder:"Uses brokerage default"}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Must be a verified sending domain"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Reply-To Email"}),e.jsx(pe,{value:x.reply_to_email||"",onChange:Fe=>y({...x,reply_to_email:Fe.target.value}),placeholder:"Uses brokerage default"})]})]}),e.jsxs($,{className:"w-full",onClick:()=>le.mutate(x),disabled:le.isPending,children:[e.jsx(tl,{className:"h-4 w-4 mr-1"})," Save Campaign Settings"]})]})]})}),e.jsx(zs,{open:d,onOpenChange:u,children:e.jsxs(Os,{className:"max-w-lg",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Default Recruiting Email Settings"}),e.jsx(Pr,{children:"These defaults apply to campaigns without their own overrides."})]}),e.jsx(Blt,{brokerageId:s})]})})]});function ue(Fe,ke){const Be=fEt[Fe.warmth_level]||fEt.cold,Ne=Be.icon,Ae=U[Fe.id]||[],Ce=r===Fe.id,Ve=!!(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(Ne,{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"}),ke&&e.jsx($e,{variant:"outline",className:"text-[10px] px-1.5",children:"Custom"}),Ve&&e.jsxs($e,{variant:"outline",className:"text-[10px] px-1.5 border-primary/30 text-primary",children:[e.jsx(mn,{className:"h-2.5 w-2.5 mr-0.5"})," Custom Sender"]})]}),e.jsx(Gn,{className:"text-xs mt-0.5",children:Fe.theme||Fe.description})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:qe=>{qe.stopPropagation(),y({...Fe})},children:e.jsx(Nd,{className:"h-4 w-4 text-muted-foreground"})}),ke&&e.jsx($,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:async qe=>{qe.stopPropagation(),await fo("Delete this campaign and all its emails? This cannot be undone.")&&te.mutate(Fe.id)},children:e.jsx(Hn,{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(mn,{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(Ca,{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:qe=>{qe.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(mn,{className:"h-3.5 w-3.5"}),e.jsxs("span",{children:[Ae.length," emails"]})]}),e.jsx("div",{className:"h-7 w-7 rounded-md flex items-center justify-center",children:Ce?e.jsx(yb,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(wl,{className:"h-4 w-4 text-muted-foreground"})})]})]})}),Ce&&e.jsxs(Ie,{className:"pt-0 pb-4 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4 p-3 rounded-lg bg-muted/40 text-sm",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Goal"}),e.jsx("p",{className:"mt-0.5",children:Fe.goal||"—"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Primary CTA"}),e.jsx("p",{className:"mt-0.5",children:Fe.primary_cta||"—"})]})]}),Ve&&e.jsxs("div",{className:"p-3 rounded-lg bg-primary/5 border border-primary/10 text-sm",children:[e.jsxs("p",{className:"text-xs font-semibold text-primary mb-1 flex items-center gap-1",children:[e.jsx(mn,{className:"h-3 w-3"})," Campaign Sender Override"]}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 text-xs text-muted-foreground",children:[Fe.sender_name&&e.jsxs("p",{children:[e.jsx("span",{className:"font-medium",children:"Name:"})," ",Fe.sender_name]}),Fe.sender_email&&e.jsxs("p",{children:[e.jsx("span",{className:"font-medium",children:"Email:"})," ",Fe.sender_email]}),Fe.reply_to_email&&e.jsxs("p",{children:[e.jsx("span",{className:"font-medium",children:"Reply-To:"})," ",Fe.reply_to_email]})]})]}),e.jsx("div",{className:"relative",children:Ae.map((qe,dt)=>{var Xe,at;return e.jsxs("div",{className:"relative flex gap-4 pb-4 last:pb-0",children:[dtrt.stopPropagation(),onBlur:rt=>{const Ke=parseInt(rt.target.value)||0;Ke!==qe.delay_days&&ce.mutate({emailId:qe.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(da,{className:"h-3 w-3"}),qe.email_number===1?"Sent immediately":`Day ${qe.delay_days}`]}),e.jsx("span",{className:"text-border",children:"•"}),e.jsxs("span",{className:"truncate",children:["Subject: ",R(((Xe=qe.subject_line_options)==null?void 0:Xe.length)>0&&qe.subject_line_options[G[qe.id]??0]||qe.subject_line)]})]}),((at=qe.subject_line_options)==null?void 0:at.length)>1&&e.jsx("div",{className:"mt-2",children:e.jsxs(ms,{value:String(G[qe.id]??0),onValueChange:rt=>Y.mutate({campaignEmailId:qe.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:qe.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(qe),children:e.jsx(Ca,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>{l({...qe}),g("editor")},children:e.jsx(pi,{className:"h-4 w-4"})}),ke&&Ae.length>1&&e.jsx($,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:async()=>{await fo("Delete this email from the sequence?")&&J.mutate(qe.id)},children:e.jsx(Hn,{className:"h-4 w-4"})})]})]})})]},qe.id)})}),ke&&e.jsxs($,{variant:"outline",size:"sm",className:"w-full gap-1.5",onClick:()=>ne.mutate(Fe.id),disabled:ne.isPending,children:[e.jsx(dn,{className:"h-3.5 w-3.5"})," Add Email to Sequence"]})]})]},Fe.id)}}const pEt={active:{icon:zu,color:"bg-green-500/10 text-green-600",label:"Active"},paused:{icon:Av,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:Nu,color:"bg-red-500/10 text-red-600",label:"Cancelled"}},gEt={sent:{icon:mn,color:"text-blue-500"},opened:{icon:Ca,color:"text-amber-500"},clicked:{icon:Pm,color:"text-green-500"},failed:{icon:Al,color:"text-destructive"}};function Mos({brokerageId:s}){var Le,Fe,ke,Be,Ne;const{user:t}=bs(),n=Wt(),[r,a]=j.useState(!1),[i,l]=j.useState(""),[o,c]=j.useState(new Set),[d,u]=j.useState("assignments"),[h,m]=j.useState(null),[f,g]=j.useState(""),[x,y]=j.useState("all"),[v,b]=j.useState("all"),[w,S]=j.useState(!1),{data:A}=sie(),{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 Ve={};return(Ae??[]).forEach(ze=>{Ve[ze.campaign_id]||(Ve[ze.campaign_id]=[]),Ve[ze.campaign_id].push(ze)}),Ve}}),{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:((Le=h==null?void 0:h.prospect)==null?void 0:Le.first_name)||"Sarah",brokerage_name:((Fe=P==null?void 0:P.merge_fields)==null?void 0:Fe.brokerage_name)||(I==null?void 0:I.name)||"Your Brokerage",city:((ke=P==null?void 0:P.merge_fields)==null?void 0:ke.city)||(I==null?void 0:I.city)||"Your City",sender_name:((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]||[],Ve=Ae.current_email_number+1;return Ce.find(ze=>ze.email_number===Ve)||null},{data:W=[],isLoading:V}=st({queryKey:["recruit-campaign-assignments",s],queryFn:async()=>{let Ce=[],Ve=0;for(;;){const{data:ze,error:qe}=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(Ve,Ve+1e3-1);if(qe)throw qe;if(Ce=Ce.concat(ze??[]),!ze||ze.length<1e3)break;Ve+=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:Y=[]}=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=[],Ve=0;for(;;){const{data:ze,error:qe}=await q.from("recruit_prospects").select("id, first_name, last_name, email").eq("brokerage_id",s).order("first_name").range(Ve,Ve+1e3-1);if(qe)throw qe;if(Ce=Ce.concat(ze??[]),!ze||ze.length<1e3)break;Ve+=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:Ve}=await q.from("recruit_campaign_assignments").insert(Ce);if(Ve)throw Ve},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-assignments",s]}),re.success(`Campaign assigned to ${o.size} prospect(s)!`),a(!1),l(""),c(new Set)},onError:Ae=>re.error(Ae.message)}),ne=mt({mutationFn:async({id:Ae,newStatus:Ce})=>{const{error:Ve}=await q.from("recruit_campaign_assignments").update({status:Ce,updated_at:new Date().toISOString()}).eq("id",Ae);if(Ve)throw Ve},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-assignments",s]}),re.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]}),re.success(`Wave sent! ${Ae.sent} emails delivered, ${Ae.skipped} skipped, ${Ae.failed} failed`)},onError:Ae=>re.error(`Send failed: ${Ae.message}`)}),J=W.filter(Ae=>Ae.status==="active").length;W.filter(Ae=>Ae.status==="completed").length;const ce=W.filter(Ae=>Ae.status==="active"&&Ae.next_send_at&&new Date(Ae.next_send_at)<=new Date).length,{data:_e={}}=$lt(s),he=W.reduce((Ae,Ce)=>Ae+Math.max(0,Ce.current_email_number||0),0),ue=Object.values(_e).reduce((Ae,Ce)=>Ae+Ce.opened,0),ve=Object.values(_e).reduce((Ae,Ce)=>Ae+Ce.clicked,0);Object.values(_e).reduce((Ae,Ce)=>Ae+Ce.failed,0);const Ee=he>0?Math.round(ue/he*100):0,Se=he>0?ve/he*100:0;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-bold",children:"Campaign Assignments"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Assign recruiting campaigns to prospects — emails auto-send weekly via SES"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[ce>0&&e.jsxs($,{variant:"outline",onClick:()=>{te.mutate()},disabled:te.isPending,className:"border-amber-500/50 text-amber-600 hover:bg-amber-500/10",children:[e.jsx(eg,{className:"h-4 w-4 mr-1"}),te.isPending?"Sending...":`Send Next Wave (${ce})`]}),e.jsxs($,{onClick:()=>a(!0),children:[e.jsx(Kr,{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(Ie,{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(Ie,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(zu,{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(Ie,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(mn,{className:"h-7 w-7 text-blue-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xl font-bold",children:he.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Emails Sent"})]})]})}),e.jsx(je,{children:e.jsxs(Ie,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(Ca,{className:"h-7 w-7 text-amber-500"}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-xl font-bold",children:[Ee,"%"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Open Rate (",ue.toLocaleString(),")"]})]})]})}),e.jsx(je,{children:e.jsxs(Ie,{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:[Se.toFixed(1),"%"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Click Rate (",ve.toLocaleString(),")"]})]})]})})]}),e.jsxs(ha,{value:d,onValueChange:u,children:[e.jsxs(ma,{children:[e.jsxs(Zt,{value:"assignments",children:["Active Drips (",J,")"]}),e.jsxs(Zt,{value:"history",children:["Send History (",he.toLocaleString(),")"]})]}),e.jsx(Xt,{value:"assignments",className:"mt-4",children:V?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-2 border-primary border-t-transparent"})}):W.length===0?e.jsx(je,{children:e.jsxs(Ie,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(Kr,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{className:"font-medium",children:"No campaigns assigned yet"}),e.jsx("p",{className:"text-sm",children:"Assign a recruiting campaign to your prospects to start automated outreach"})]})}):e.jsx("div",{className:"space-y-2",children:W.map(Ae=>{var Xe,at,rt,Ke;const Ce=pEt[Ae.status]||pEt.active,Ve=Ce.icon,qe=(E[Ae.campaign_id]||[]).length||4,dt=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(Ve,{className:"h-3 w-3 mr-1"}),Ce.label]}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"font-medium text-sm",children:[(Xe=Ae.prospect)==null?void 0:Xe.first_name," ",(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,"/",qe,Ae.next_send_at&&Ae.status==="active"&&e.jsxs(e.Fragment,{children:[" ","· ",e.jsx(da,{className:"h-3 w-3 inline"})," Next: ",en(new Date(Ae.next_send_at),"MMM d, h:mm a"),new Date(Ae.next_send_at)<=new Date&&e.jsx($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:[dt&&e.jsx($,{variant:"ghost",size:"sm",title:"Preview next email",onClick:()=>m(Ae),children:e.jsx(Ca,{className:"h-3.5 w-3.5"})}),Ae.status==="active"&&e.jsx($,{variant:"ghost",size:"sm",onClick:()=>ne.mutate({id:Ae.id,newStatus:"paused"}),children:e.jsx(Av,{className:"h-3.5 w-3.5"})}),Ae.status==="paused"&&e.jsx($,{variant:"ghost",size:"sm",onClick:()=>ne.mutate({id:Ae.id,newStatus:"active"}),children:e.jsx(zu,{className:"h-3.5 w-3.5"})}),(Ae.status==="active"||Ae.status==="paused")&&e.jsx($,{variant:"ghost",size:"sm",className:"text-destructive",onClick:()=>ne.mutate({id:Ae.id,newStatus:"cancelled"}),children:e.jsx(Nu,{className:"h-3.5 w-3.5"})})]})]},Ae.id)})})}),e.jsxs(Xt,{value:"history",className:"mt-4 space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Filter:"}),e.jsxs(ms,{value:x,onValueChange:y,children:[e.jsx(us,{className:"w-[220px] h-8 text-xs",children:e.jsx(fs,{placeholder:"All campaigns"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All campaigns"}),Y.map(Ae=>e.jsx(Ge,{value:Ae.id,children:Ae.name},Ae.id))]})]}),e.jsxs(ms,{value:v,onValueChange:b,children:[e.jsx(us,{className:"w-[160px] h-8 text-xs",children:e.jsx(fs,{placeholder:"All statuses"})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All statuses"}),e.jsx(Ge,{value:"sent",children:"Sent (no engagement)"}),e.jsx(Ge,{value:"opened",children:"Opened"}),e.jsx(Ge,{value:"clicked",children:"Clicked"})]})]}),(x!=="all"||v!=="all")&&e.jsx($,{variant:"ghost",size:"sm",className:"h-8 text-xs",onClick:()=>{y("all"),b("all")},children:"Clear"})]}),(()=>{var Ce;const Ae=G.filter(Ve=>{var ze;return!(x!=="all"&&((ze=Ve.campaign_email)==null?void 0:ze.campaign_id)!==x||v==="opened"&&!Ve.opened_at||v==="clicked"&&!Ve.clicked_at||v==="sent"&&(Ve.opened_at||Ve.clicked_at))});return Ae.length===0?e.jsx(je,{children:e.jsxs(Ie,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(mn,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{className:"font-medium",children:G.length===0?"No emails sent yet":"No emails match these filters"}),e.jsx("p",{className:"text-sm",children:G.length===0?"Emails will appear here once campaigns start sending":"Try clearing the filters above"})]})}):e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Showing ",Ae.length," of ",G.length," recent sends",x!=="all"&&` · ${(Ce=Y.find(Ve=>Ve.id===x))==null?void 0:Ce.name}`]}),e.jsx("div",{className:"space-y-1",children:Ae.map(Ve=>{var Xe,at,rt;const ze=gEt[Ve.status]||gEt.sent,qe=ze.icon,dt=(Xe=Y.find(Ke=>{var Je;return Ke.id===((Je=Ve.campaign_email)==null?void 0:Je.campaign_id)}))==null?void 0:Xe.name;return e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border hover:bg-muted/30 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx(qe,{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=Ve.prospect)==null?void 0:at.first_name," ",(rt=Ve.prospect)==null?void 0:rt.last_name,e.jsxs("span",{className:"text-muted-foreground font-normal ml-2",children:["Email #",Ve.email_number]}),dt&&e.jsx($e,{variant:"outline",className:"ml-2 text-[10px] px-1.5 py-0 font-normal",children:dt})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:Ve.subject})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground flex-shrink-0",children:[Ve.opened_at&&e.jsxs("span",{className:"flex items-center gap-1 text-amber-500",children:[e.jsx(Ca,{className:"h-3 w-3"})," ",en(new Date(Ve.opened_at),"MMM d")]}),Ve.clicked_at&&e.jsxs("span",{className:"flex items-center gap-1 text-green-500",children:[e.jsx(Pm,{className:"h-3 w-3"})," ",en(new Date(Ve.clicked_at),"MMM d")]}),e.jsx("span",{children:en(new Date(Ve.sent_at),"MMM d, h:mm a")})]})]},Ve.id)})})]})})()]})]}),e.jsx(zs,{open:r,onOpenChange:Ae=>{a(Ae),Ae||(g(""),c(new Set),l(""))},children:e.jsxs(Os,{className:"max-w-lg max-h-[85vh] flex flex-col p-0",children:[e.jsxs(Us,{className:"px-6 pt-6 pb-4",children:[e.jsx(Bs,{children:"Assign Campaign to Prospects"}),e.jsx(Pr,{children:"Select a campaign and choose which prospects to enroll. The first email will be sent automatically."})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto px-6 space-y-4 pb-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-sm font-medium",children:"1. Select Campaign"}),e.jsxs(ms,{value:i,onValueChange:l,children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Choose a campaign..."})}),e.jsx(hs,{children:Y.map(Ae=>e.jsx(Ge,{value:Ae.id,children:Ae.name},Ae.id))})]})]}),i&&(()=>{const Ae=f.toLowerCase(),Ce=X.filter(qe=>`${qe.first_name} ${qe.last_name}`.toLowerCase().includes(Ae)||qe.email.toLowerCase().includes(Ae)),Ve=Ce.filter(qe=>!ae.has(`${qe.id}-${i}`)),ze=Ve.length>0&&Ve.every(qe=>o.has(qe.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(Zr,{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:qe=>g(qe.target.value),className:"pl-9 h-9"})]}),e.jsxs($,{variant:"outline",size:"sm",className:"h-9 whitespace-nowrap",onClick:()=>{if(ze){const qe=new Set(o);Ve.forEach(dt=>qe.delete(dt.id)),c(qe)}else{const qe=new Set(o);Ve.forEach(dt=>qe.add(dt.id)),c(qe)}},children:[e.jsx(Dz,{className:"h-3.5 w-3.5 mr-1"}),ze?"Deselect All":`Select All (${Ve.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(qe=>{const dt=ae.has(`${qe.id}-${i}`);return e.jsxs("label",{className:`flex items-center gap-3 p-2.5 hover:bg-muted/50 cursor-pointer ${dt?"opacity-40":""}`,children:[e.jsx(ai,{checked:o.has(qe.id),disabled:dt,onCheckedChange:Xe=>{const at=new Set(o);Xe?at.add(qe.id):at.delete(qe.id),c(at)}}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"text-sm font-medium truncate",children:[qe.first_name," ",qe.last_name]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:qe.email})]}),dt&&e.jsx($e,{variant:"outline",className:"text-[10px] shrink-0",children:"Already assigned"})]},qe.id)})}),Ce.length>0&&e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Showing ",Ce.length," of ",X.length," prospects",Ve.length0&&e.jsx(je,{className:"bg-primary/5 border-primary/20",children:e.jsxs(Ie,{className:"pt-3 pb-2 text-sm space-y-1",children:[e.jsxs("p",{className:"font-medium text-primary",children:["✅ Ready to assign ",o.size," prospect",o.size>1?"s":""]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["• Campaign: ",e.jsx("strong",{children:(Ne=Y.find(Ae=>Ae.id===i))==null?void 0:Ne.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(Sr,{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(Kr,{className:"h-4 w-4 mr-1"}),le.isPending?"Assigning...":`Assign & Start (${o.size})`]})]})]})}),h&&(()=>{const Ae=U(h);return Ae?e.jsx(Aos,{email:Ae,mergeValues:O,selectedSubjectIndex:D[Ae.id],onClose:()=>m(null)}):null})(),e.jsx(w6e,{open:w,onOpenChange:S,hasPending:A==null?void 0:A.hasPendingSes,pendingEmails:A==null?void 0:A.pendingEmails})]})}function Pos({brokerageId:s}){const t=Wt(),[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:y,error:v}=await q.from("recruit_pipeline_stages").select("*").eq("brokerage_id",s).order("sort_order");if(v)throw v;return y},enabled:!!s});j.useEffect(()=>{if(d){if(c.current){c.current=!1;return}r(d.map(y=>({id:y.id,name:y.name,color:y.color,sort_order:y.sort_order}))),i([]),o(!1)}},[d]);const h=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 y=n.filter(b=>b.id&&!b.isNew),v=n.filter(b=>!b.id||b.isNew);for(const b of y){const{error:w}=await q.from("recruit_pipeline_stages").update({name:b.name,color:b.color,sort_order:b.sort_order}).eq("id",b.id);if(w)throw w}if(v.length>0){const{error:b}=await q.from("recruit_pipeline_stages").insert(v.map(w=>({brokerage_id:s,name:w.name,color:w.color,sort_order:w.sort_order})));if(b)throw b}},onSuccess:()=>{i([]),t.invalidateQueries({queryKey:["recruit-stages-editor",s]}),t.invalidateQueries({queryKey:["recruit-stages",s]}),re.success("Pipeline stages saved!"),o(!1)},onError:y=>re.error(y.message)}),m=(y,v,b)=>{r(w=>w.map((S,A)=>A===y?{...S,[v]:b}:S)),o(!0)},f=()=>{const y=n.length>0?Math.max(...n.map(v=>v.sort_order)):0;r(v=>[...v,{name:"",color:"#6366f1",sort_order:y+1,isNew:!0}]),o(!0)},g=y=>{const v=n[y];v.id&&!v.isNew&&i(b=>[...b,v.id]),r(b=>b.filter((w,S)=>S!==y)),o(!0)},x=(y,v)=>{const b=y+v;if(b<0||b>=n.length)return;const w=[...n];[w[y],w[b]]=[w[b],w[y]],w.forEach((S,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((y,v)=>e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg border bg-card",children:[e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx("button",{type:"button",onClick:()=>x(v,-1),disabled:v===0,className:"text-muted-foreground hover:text-foreground disabled:opacity-30 text-xs",children:"▲"}),e.jsx("button",{type:"button",onClick:()=>x(v,1),disabled:v===n.length-1,className:"text-muted-foreground hover:text-foreground disabled:opacity-30 text-xs",children:"▼"})]}),e.jsx(Ug,{className:"h-4 w-4 text-muted-foreground/50 shrink-0"}),e.jsx("input",{type:"color",value:y.color,onChange:b=>m(v,"color",b.target.value),className:"h-8 w-8 rounded cursor-pointer border-0 p-0 shrink-0"}),e.jsx(pe,{value:y.name,onChange:b=>m(v,"name",b.target.value),placeholder:"Stage name…",className:"flex-1"}),e.jsx("span",{className:"text-xs text-muted-foreground w-6 text-center shrink-0",children:v+1}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>g(v),className:"text-destructive hover:text-destructive shrink-0 h-8 w-8",children:e.jsx(Hn,{className:"h-4 w-4"})})]},y.id||`new-${v}`))}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{variant:"outline",size:"sm",onClick:f,className:"gap-1",children:[e.jsx(dn,{className:"h-4 w-4"})," Add Stage"]}),l&&e.jsxs($,{size:"sm",onClick:()=>h.mutate(),disabled:h.isPending,className:"gap-1",children:[e.jsx(tl,{className:"h-4 w-4"})," Save Changes"]})]}),n.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No stages configured. Add stages to build your recruiting pipeline."})]})}function $lr({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(Xz,{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(Ie,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(Xz,{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(mn,{className:"h-3 w-3"}),r.email]}),r.current_brokerage&&e.jsxs("span",{children:["· ",r.current_brokerage]})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground whitespace-nowrap",children:[e.jsx(Ta,{className:"h-3 w-3"}),r.unsubscribed_at&&en(new Date(r.unsubscribed_at),"MMM d, yyyy")]})]})}),r.unsubscribe_reason&&e.jsx(Ie,{className:"pt-0",children:e.jsxs("div",{className:"text-sm bg-muted/40 rounded-md px-3 py-2 italic text-muted-foreground",children:['"',r.unsubscribe_reason,'"']})})]},r.id))})]})}function Ulr(){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(ji,{className:"mr-2 h-4 w-4"}),e.jsx(fs,{placeholder:"Select brokerage"})]}),e.jsx(hs,{children:a.map(c=>e.jsx(Ge,{value:c.id,children:c.name},c.id))})]})]}):e.jsx("div",{}),l&&e.jsx(kos,{brokerageId:l,trigger:e.jsxs($,{size:"sm",className:"gap-1.5",children:[e.jsx(ua,{className:"h-4 w-4"})," Record & Send Video"]})})]}),l?e.jsxs(ha,{defaultValue:"pipeline",className:"space-y-4",children:[e.jsxs(ma,{className:"flex-wrap h-auto gap-1",children:[e.jsx(Zt,{value:"pipeline",children:"Pipeline"}),e.jsxs(Zt,{value:"contacts",children:[e.jsx(Yn,{className:"h-3.5 w-3.5 mr-1"}),"Contacts"]}),e.jsxs(Zt,{value:"video-outreach",children:[e.jsx(ua,{className:"h-3.5 w-3.5 mr-1"}),"Video Outreach"]}),e.jsx(Zt,{value:"follow-ups",children:"Follow-ups"}),e.jsx(Zt,{value:"referrals",children:"Referrals"}),e.jsx(Zt,{value:"interest",children:"Interest Form"}),e.jsx(Zt,{value:"landing-page",children:"Landing Page"}),e.jsx(Zt,{value:"goals",children:"Goals"}),e.jsx(Zt,{value:"metrics",children:"Metrics"}),e.jsx(Zt,{value:"templates",children:"Email Templates"}),e.jsxs(Zt,{value:"campaigns",children:[e.jsx(mn,{className:"h-3.5 w-3.5 mr-1"}),"Campaigns"]}),e.jsxs(Zt,{value:"drip-assignments",children:[e.jsx(Kr,{className:"h-3.5 w-3.5 mr-1"}),"Drip Assignments"]}),e.jsx(Zt,{value:"activity",children:"Recruiter Activity"}),e.jsxs(Zt,{value:"email-settings",children:[e.jsx(Nd,{className:"h-3.5 w-3.5 mr-1"}),"Email Settings"]}),e.jsxs(Zt,{value:"pipeline-stages",children:[e.jsx(XI,{className:"h-3.5 w-3.5 mr-1"}),"Pipeline Stages"]}),e.jsxs(Zt,{value:"unsubscribed",children:[e.jsx(Xz,{className:"h-3.5 w-3.5 mr-1"}),"Unsubscribed"]})]}),e.jsxs(Xt,{value:"pipeline",children:[e.jsx("div",{className:"flex justify-end mb-3",children:e.jsxs("div",{className:"flex items-center rounded-md border bg-muted p-0.5",children:[e.jsxs($,{variant:n==="board"?"default":"ghost",size:"sm",className:"h-7 px-2.5 gap-1.5",onClick:()=>r("board"),children:[e.jsx(Qf,{className:"h-3.5 w-3.5"})," Board"]}),e.jsxs($,{variant:n==="table"?"default":"ghost",size:"sm",className:"h-7 px-2.5 gap-1.5",onClick:()=>r("table"),children:[e.jsx(rV,{className:"h-3.5 w-3.5"})," Table"]})]})}),n==="board"?e.jsx(xos,{brokerageId:l}):e.jsx(rQe,{brokerageId:l})]}),e.jsx(Xt,{value:"contacts",children:e.jsx(rQe,{brokerageId:l})}),e.jsx(Xt,{value:"video-outreach",children:e.jsx(Sos,{brokerageId:l})}),e.jsx(Xt,{value:"follow-ups",children:e.jsx(jos,{brokerageId:l})}),e.jsx(Xt,{value:"referrals",children:e.jsx(_os,{brokerageId:l})}),e.jsx(Xt,{value:"interest",children:e.jsx(wos,{brokerageId:l})}),e.jsx(Xt,{value:"landing-page",children:e.jsx(Nos,{brokerageId:l})}),e.jsx(Xt,{value:"goals",children:e.jsx(Cos,{brokerageId:l})}),e.jsx(Xt,{value:"metrics",children:e.jsx(yos,{brokerageId:l})}),e.jsx(Xt,{value:"templates",children:e.jsx(vos,{brokerageId:l})}),e.jsx(Xt,{value:"campaigns",children:e.jsx(Tos,{brokerageId:l})}),e.jsx(Xt,{value:"drip-assignments",children:e.jsx(Mos,{brokerageId:l})}),e.jsx(Xt,{value:"activity",children:e.jsx(bos,{brokerageId:l})}),e.jsx(Xt,{value:"email-settings",children:e.jsxs("div",{className:"max-w-2xl",children:[e.jsx("h3",{className:"text-lg font-semibold mb-1",children:"Email Settings"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Configure sender identity, merge fields, and brokerage location for recruiting emails."}),e.jsx(Blt,{brokerageId:l})]})}),e.jsx(Xt,{value:"pipeline-stages",children:e.jsx("div",{className:"max-w-2xl",children:e.jsx(Pos,{brokerageId:l})})}),e.jsx(Xt,{value:"unsubscribed",children:e.jsx($lr,{brokerageId:l})})]}):e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(ji,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No brokerages found. Create a brokerage first."})]})]})})}const xEt=()=>{const s=new Date;return new Date(s.getFullYear(),s.getMonth(),s.getDate()).getTime()},eU=s=>{const t=s.split(/[-/T]/).slice(0,3).map(Number);return new Date(t[0],(t[1]||1)-1,t[2]||1).getTime()},tU=s=>Date.parse(s);async function kX(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 qlr(s){var o;const t=_9(s),n=$lt(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?kX("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?kX("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([]),kX("recruit_goals","id, title, target_count, target_stage_id, period_start, period_end",g=>g.eq("brokerage_id",s).order("period_end",{ascending:!1})),kX("recruit_campaign_assignments","id, prospect_id, status",g=>g.eq("brokerage_id",s)),kX("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 _e,he,ue,ve,Ee;const c=t.prospects,d=t.stages,u=((_e=r.data)==null?void 0:_e.followUps)??[],h=((he=r.data)==null?void 0:he.activities)??[],m=((ue=r.data)==null?void 0:ue.goals)??[],f=((ve=r.data)==null?void 0:ve.assignments)??[],g=((Ee=r.data)==null?void 0:Ee.campaigns)??[],x=xEt(),y=x+864e5,v=Date.now()-30*864e5,b=Date.now()-21*864e5,w=new Map(c.map(Se=>[Se.id,Se])),S=u.filter(Se=>!Se.completed_at),A=S.filter(Se=>tU(Se.due_date){const Le=tU(Se.due_date);return Le>=x&&Le{const Le=w.get(Se.prospect_id);if(!Le)return[];const Fe=tU(Se.due_date)Se.prospect_id));c.filter(Se=>tU(Se.updated_at)I.push({id:`stalled-${Se.id}`,prospect:Se,title:"No next step scheduled",detail:"No movement in 21+ days",tone:"stalled",dueAt:null}));const R=d.map(Se=>({...Se,count:c.filter(Le=>Le.stage_id===Se.id).length,stalled:c.filter(Le=>Le.stage_id===Se.id&&tU(Le.updated_at)eU(Se.period_start)<=D&&eU(Se.period_end)>=D)??null,U=O?c.filter(Se=>eU(Se.created_at)>=eU(O.period_start)&&eU(Se.created_at)<=eU(O.period_end)&&(!O.target_stage_id||Se.stage_id===O.target_stage_id)).length:0,W=Object.values(n.data??{}),V=W.reduce((Se,Le)=>Se+Le.sent,0),G=W.reduce((Se,Le)=>Se+Le.opened,0),Y=V?Math.round(G/V*100):0,X=new Map((i.data??[]).map(Se=>[Se.id,Se])),ae=a.map(Se=>{var Be;const Le=h.filter(Ne=>Ne.created_by===Se),Fe=Le.filter(Ne=>tU(Ne.created_at)>=v),ke=X.get(Se);return{id:Se,name:(ke==null?void 0:ke.name)||(ke==null?void 0:ke.email)||"Unknown recruiter",email:(ke==null?void 0:ke.email)||"",prospects:c.filter(Ne=>Ne.created_by===Se).length,activities30d:Fe.length,lastActivityAt:((Be=Le[0])==null?void 0:Be.created_at)??null}}).sort((Se,Le)=>Le.activities30d-Se.activities30d),le=new Map;c.forEach(Se=>{const Le=(Se.source||"Not recorded").replace(/_/g," ");le.set(Le,(le.get(Le)??0)+1)});const ne=[...le.entries()].sort((Se,Le)=>Le[1]-Se[1]).slice(0,6),te=new Set(["signed","onboarded","hired","joined"]),J=new Set(d.filter(Se=>te.has(Se.name.toLowerCase())).map(Se=>Se.id)),ce=c.filter(Se=>Se.stage_id&&J.has(Se.stage_id)).length;return{prospects:c,stages:R,followUps:u,activities:h,priority:I.slice(0,12),overdueCount: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:Y,campaignSent:V,activeCampaigns:g.filter(Se=>Se.is_active).length,activeAssignments:f.filter(Se=>Se.status==="active").length,recruiters:ae,sources:ne,converted:ce,conversionRate:c.length?Math.round(ce/c.length*100):0}},[t.prospects,t.stages,r.data,n.data,i.data,a]),pipeline:t,isLoading:t.isLoading||r.isLoading||n.isLoading||i.isLoading}}const Vlr=s=>s.split(/\s+/).filter(Boolean).slice(0,2).map(t=>t[0]).join("").toUpperCase(),Hlr=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`},she=({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 Glr({brokerageId:s,onNavigate:t,onOpenProspect:n,onAddProspect:r}){var u;const a=qlr(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(she,{label:"Active pipeline",value:a.prospects.length,detail:`${a.converted} converted · ${a.conversionRate}% rate`,icon:y0,tone:"bg-primary/10 text-primary",onClick:()=>t("pipeline-board")}),e.jsx(she,{label:"Follow-ups due",value:a.overdueCount+a.dueTodayCount,detail:`${a.overdueCount} overdue · ${a.dueTodayCount} today`,icon:Cq,tone:a.overdueCount?"bg-destructive/10 text-destructive":"bg-amber-500/10 text-amber-700",onClick:()=>t("pipeline-follow-ups")}),e.jsx(she,{label:"Campaign engagement",value:`${a.campaignOpenRate}%`,detail:`${a.campaignSent} sent · ${a.activeAssignments} enrolled`,icon:$q,tone:"bg-emerald-500/10 text-emerald-700",onClick:()=>t("campaigns-manager")}),e.jsx(she,{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:nh,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:Vlr(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 ",Hlr(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 Wlr({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 y;const{data:d,error:u}=await q.from("recruit_prospects").select("id, first_name, last_name, email").eq("brokerage_id",s);if(u)throw u;const h=new Map((d||[]).map(v=>[v.id,v]));if(Array.from(h.keys()).length===0)return[];const{data:f}=await q.from("recruit_videos").select("id, prospect_id, share_token, sent_at, sent_via, view_count, first_viewed_at, cta_clicked_at, video:agent_videos(title)").eq("brokerage_id",s).not("sent_at","is",null).order("sent_at",{ascending:!1}),{data:g}=await q.from("recruit_campaign_sends").select("id, prospect_id, subject, status, sent_at, opened_at, clicked_at, error_message, email_number").eq("brokerage_id",s).order("sent_at",{ascending:!1,nullsFirst:!1}),x=[];for(const v of f||[]){const b=h.get(v.prospect_id);b&&x.push({id:`v-${v.id}`,kind:"video",prospect_id:v.prospect_id,prospect_name:`${b.first_name||""} ${b.last_name||""}`.trim()||"—",prospect_email:b.email,subject:(y=v.video)!=null&&y.title?`Video: ${v.video.title}`:"Recruiting Video",status:v.cta_clicked_at?"clicked":v.first_viewed_at?"viewed":"sent",sent_at:v.sent_at,opened_at:v.first_viewed_at,clicked_at:v.cta_clicked_at,view_count:v.view_count,share_token:v.share_token})}for(const v of g||[]){if(!v.sent_at)continue;const b=h.get(v.prospect_id);b&&x.push({id:`c-${v.id}`,kind:"campaign",prospect_id:v.prospect_id,prospect_name:`${b.first_name||""} ${b.last_name||""}`.trim()||"—",prospect_email:b.email,subject:v.subject||`Email #${v.email_number}`,status:v.status||"sent",sent_at:v.sent_at,opened_at:v.opened_at,clicked_at:v.clicked_at,error:v.error_message})}return x.sort((v,b)=>new Date(b.sent_at).getTime()-new Date(v.sent_at).getTime()),x}}),o=j.useMemo(()=>{const d=i||[];return{total:d.length,videos:d.filter(u=>u.kind==="video").length,campaigns:d.filter(u=>u.kind==="campaign").length,opened:d.filter(u=>u.opened_at).length,clicked:d.filter(u=>u.clicked_at).length}},[i]),c=j.useMemo(()=>(i||[]).filter(u=>{if(r!=="all"&&u.kind!==r)return!1;if(!t)return!0;const h=t.toLowerCase();return u.prospect_name.toLowerCase().includes(h)||(u.prospect_email||"").toLowerCase().includes(h)||u.subject.toLowerCase().includes(h)}),[i,t,r]);return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[{label:"Total Sent",value:o.total,icon:Kr,color:"text-primary"},{label:"Video Emails",value:o.videos,icon:ua,color:"text-blue-500"},{label:"Campaign Emails",value:o.campaigns,icon:mn,color:"text-violet-500"},{label:"Opened / Viewed",value:o.opened,icon:Ca,color:"text-amber-500"},{label:"Clicked",value:o.clicked,icon:Pm,color:"text-emerald-500"}].map(d=>e.jsx(je,{children:e.jsxs(Ie,{className:"p-3 flex items-center gap-2.5",children:[e.jsx("div",{className:`h-9 w-9 rounded-lg bg-muted flex items-center justify-center ${d.color}`,children:e.jsx(d.icon,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xl font-bold leading-tight",children:d.value}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:d.label})]})]})},d.label))}),e.jsxs(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(ha,{value:r,onValueChange:d=>a(d),children:e.jsxs(ma,{className:"h-8",children:[e.jsx(Zt,{value:"all",className:"text-xs h-7",children:"All"}),e.jsx(Zt,{value:"video",className:"text-xs h-7",children:"Video"}),e.jsx(Zt,{value:"campaign",className:"text-xs h-7",children:"Campaign"})]})}),e.jsxs("div",{className:"relative w-56",children:[e.jsx(Zr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pe,{placeholder:"Search recruit, subject...",value:t,onChange:d=>n(d.target.value),className:"pl-9 h-9"})]})]})]})}),e.jsx(Ie,{children:l?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):c.length===0?e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(mn,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{className:"font-medium",children:"No emails sent yet"}),e.jsx("p",{className:"text-sm mt-1",children:"Emails sent from Video Outreach or Drip Campaigns will appear here."})]}):e.jsx("div",{className:"rounded-lg border overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-muted/40 text-xs text-muted-foreground",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left font-medium px-3 py-2",children:"Type"}),e.jsx("th",{className:"text-left font-medium px-3 py-2",children:"Recruit"}),e.jsx("th",{className:"text-left font-medium px-3 py-2",children:"Subject"}),e.jsx("th",{className:"text-left font-medium px-3 py-2",children:"Status"}),e.jsx("th",{className:"text-left font-medium px-3 py-2",children:"Sent"}),e.jsx("th",{className:"text-right font-medium px-3 py-2",children:"Engagement"})]})}),e.jsx("tbody",{children:c.map(d=>e.jsxs("tr",{className:"border-t hover:bg-muted/30 transition-colors",children:[e.jsx("td",{className:"px-3 py-2",children:d.kind==="video"?e.jsxs($e,{variant:"outline",className:"gap-1",children:[e.jsx(ua,{className:"h-3 w-3"}),"Video"]}):e.jsxs($e,{variant:"outline",className:"gap-1",children:[e.jsx(mn,{className:"h-3 w-3"}),"Campaign"]})}),e.jsxs("td",{className:"px-3 py-2",children:[e.jsx("div",{className:"font-medium",children:d.prospect_name}),d.prospect_email&&e.jsx("div",{className:"text-xs text-muted-foreground",children:d.prospect_email})]}),e.jsx("td",{className:"px-3 py-2 max-w-xs truncate",children:d.subject}),e.jsxs("td",{className:"px-3 py-2",children:[d.status==="failed"||d.status==="bounced"?e.jsxs($e,{variant:"destructive",className:"gap-1",children:[e.jsx(ll,{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(Ca,{className:"h-3 w-3"}),"Opened"]}):e.jsxs($e,{variant:"secondary",className:"gap-1",children:[e.jsx(Kr,{className:"h-3 w-3"}),"Sent"]}),d.error&&e.jsx("p",{className:"text-[10px] text-destructive mt-0.5 max-w-[200px] truncate",title:d.error,children:d.error})]}),e.jsxs("td",{className:"px-3 py-2 text-xs text-muted-foreground whitespace-nowrap",children:[en(new Date(d.sent_at),"MMM d, yyyy"),e.jsx("div",{className:"text-[10px]",children:en(new Date(d.sent_at),"h:mm a")})]}),e.jsx("td",{className:"px-3 py-2 text-right",children:e.jsxs("div",{className:"flex items-center gap-2 justify-end text-xs text-muted-foreground",children:[d.kind==="video"&&d.view_count!=null&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ca,{className:"h-3 w-3"}),d.view_count]}),d.kind==="video"&&d.share_token&&e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>window.open(`/recruit-video/${d.share_token}`,"_blank"),title:"Open landing page",children:e.jsx(Fr,{className:"h-3.5 w-3.5"})})]})})]},d.id))})]})})})]})]})}const yEt={pipeline:[{value:"pipeline-board",label:"Board",icon:Qf},{value:"pipeline-table",label:"Table",icon:rV},{value:"pipeline-contacts",label:"Contacts",icon:Yn},{value:"pipeline-follow-ups",label:"Follow-ups",icon:zg},{value:"pipeline-referrals",label:"Referrals",icon:dV}],outreach:[{value:"outreach-video",label:"Video outreach",icon:ua},{value:"outreach-templates",label:"Email templates",icon:Uq},{value:"outreach-sent",label:"Sent emails",icon:mn}],campaigns:[{value:"campaigns-manager",label:"Campaigns",icon:mn},{value:"campaigns-assignments",label:"Drip assignments",icon:Kr}],assets:[{value:"assets-landing",label:"Landing page",icon:CN},{value:"assets-interest",label:"Interest form",icon:zg}],reporting:[{value:"reporting-metrics",label:"Analytics",icon:Gl},{value:"reporting-goals",label:"Goals",icon:nh},{value:"reporting-activity",label:"Recruiter activity",icon:Yn}],settings:[{value:"settings-email",label:"Email settings",icon:Nd},{value:"settings-stages",label:"Pipeline stages",icon:XI}]},Ios=[{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"}],Klr=s=>{var t;return((t=Ios.find(n=>s===n.value||s.startsWith(`${n.value}-`)))==null?void 0:t.value)??"command"};function Ylr(){var I;const{managedBrokerages:s,selectedBrokerageId:t,setSelectedBrokerageId:n}=bs(),r=t||((I=s[0])==null?void 0:I.id)||"",a=_9(r||null),[i,l]=j.useState("command"),[o,c]=j.useState(!1),[d,u]=j.useState(!1),[h,m]=j.useState(null),[f,g]=j.useState(!1),[x,y]=j.useState(""),v=Klr(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),y("")},E=P=>l(P==="command"?"command":yEt[P][0].value);return s.length===0?e.jsx(Vs,{title:"Recruiting",description:"Brokerage recruiting command center",children:e.jsxs("div",{className:"py-16 text-center text-muted-foreground",children:[e.jsx(ji,{className:"mx-auto mb-4 h-12 w-12 opacity-50"}),e.jsx("p",{children:"No brokerages assigned to you. Contact an admin for access."})]})}):e.jsx(Vs,{title:"Recruiting",description:"Brokerage recruiting command center",children:e.jsxs("div",{className:"recruiting-console -m-4 min-h-[calc(100vh-72px)] bg-background font-['Figtree'] sm:-m-6 lg:-m-8",children:[e.jsxs("header",{className:"bg-secondary px-4 py-4 text-secondary-foreground sm:px-6 lg:px-8",children:[e.jsxs("div",{className:"flex flex-col gap-4 xl:flex-row xl:items-center xl:justify-between",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-4",children:[e.jsx("span",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-md bg-primary text-primary-foreground",children:e.jsx(dV,{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(Zr,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-secondary-foreground/60"}),e.jsx(pe,{value:x,onChange:P=>y(P.target.value),placeholder:"Search prospects…",className:"border-secondary-foreground/15 bg-primary/40 pl-9 text-secondary-foreground placeholder:text-secondary-foreground/55 focus-visible:ring-recruit-gold"}),x.trim()&&e.jsxs("div",{className:"absolute left-0 right-0 top-[calc(100%+6px)] z-40 overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-lg",children:[w.map(P=>e.jsxs("button",{type:"button",className:"flex w-full items-center justify-between gap-3 border-b px-3 py-2.5 text-left text-sm last:border-0 hover:bg-accent",onClick:()=>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($u,{children:[e.jsx(Uu,{asChild:!0,children:e.jsxs($,{className:"bg-recruit-gold text-recruit-navy hover:bg-recruit-gold/90",children:[e.jsx(dn,{className:"mr-1.5 h-4 w-4"}),"New prospect ",e.jsx(wl,{className:"ml-2 h-3.5 w-3.5"})]})}),e.jsxs(Au,{align:"end",children:[e.jsxs(ja,{onSelect:()=>c(!0),children:[e.jsx(dn,{className:"mr-2 h-4 w-4"}),"Add prospect"]}),e.jsxs(ja,{onSelect:()=>u(!0),children:[e.jsx(ni,{className:"mr-2 h-4 w-4"}),"Import CSV"]})]})]})]})]}),e.jsx("nav",{className:"-mx-4 mt-4 overflow-x-auto px-4 sm:-mx-6 sm:px-6 lg:-mx-8 lg:px-8","aria-label":"Recruiting sections",children:e.jsx("div",{className:"flex min-w-max items-center gap-1",children:Ios.map(P=>e.jsx($,{variant:"ghost",size:"sm",onClick:()=>E(P.value),className:Pt("h-9 rounded-none border-b-2 px-3 text-secondary-foreground/70 hover:bg-secondary-foreground/5 hover:text-secondary-foreground",v===P.value?"border-recruit-gold text-recruit-gold":"border-transparent"),children:P.label},P.value))})})]}),e.jsxs("div",{className:"px-4 py-5 sm:px-6 lg:px-8",children:[s.length>1&&e.jsxs("div",{className:"mb-4 flex items-center gap-3",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Managing:"}),e.jsxs(ms,{value:r,onValueChange:n,children:[e.jsxs(us,{className:"w-[280px] bg-card",children:[e.jsx(ji,{className:"mr-2 h-4 w-4"}),e.jsx(fs,{})]}),e.jsx(hs,{children:s.map(P=>e.jsx(Ge,{value:P.id,children:P.name},P.id))})]})]}),v!=="command"&&e.jsx("div",{className:"mb-5 overflow-x-auto pb-1",children:e.jsx(ha,{value:i,onValueChange:l,children:e.jsx(ma,{className:"h-auto min-w-max rounded-md border bg-card p-1",children:yEt[v].map(P=>{const R=P.icon;return e.jsxs(Zt,{value:P.value,className:"gap-1.5",children:[e.jsx(R,{className:"h-3.5 w-3.5"}),P.label]},P.value)})})})}),v==="command"&&r&&e.jsx(Glr,{brokerageId:r,onNavigate:S,onOpenProspect:A,onAddProspect:()=>c(!0)}),i==="pipeline-board"&&e.jsx(xos,{brokerageId:r}),(i==="pipeline-table"||i==="pipeline-contacts")&&e.jsx(rQe,{brokerageId:r}),i==="pipeline-follow-ups"&&e.jsx(jos,{brokerageId:r}),i==="pipeline-referrals"&&e.jsx(_os,{brokerageId:r}),i==="outreach-video"&&e.jsx(Sos,{brokerageId:r}),i==="outreach-templates"&&e.jsx(vos,{brokerageId:r}),i==="outreach-sent"&&e.jsx(Wlr,{brokerageId:r}),i==="campaigns-manager"&&e.jsx(Tos,{brokerageId:r}),i==="campaigns-assignments"&&e.jsx(Mos,{brokerageId:r}),i==="assets-landing"&&e.jsx(Nos,{brokerageId:r}),i==="assets-interest"&&e.jsx(wos,{brokerageId:r}),i==="reporting-metrics"&&e.jsx(yos,{brokerageId:r}),i==="reporting-goals"&&e.jsx(Cos,{brokerageId:r}),i==="reporting-activity"&&e.jsx(bos,{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(Blt,{brokerageId:r})]}),i==="settings-stages"&&e.jsx("div",{className:"max-w-3xl rounded-md border bg-card p-5",children:e.jsx(Pos,{brokerageId:r})})]}),e.jsx(Dlt,{open:o,onOpenChange:c,stages:a.stages,onSubmit:P=>a.addProspect.mutate(P),isSubmitting:a.addProspect.isPending}),e.jsx(zlt,{open:d,onOpenChange:u,brokerageId:r,stages:a.stages}),e.jsx(Olt,{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 Zlr=[{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"}],Xlr=({brokerageId:s,agentUserId:t,readOnly:n})=>{const{toast:r}=Bi(),{data:a}=DRn(s,t),{saveRecord:i}=QRe(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:Zlr.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"]})]})},Qlr=({brokerageId:s,agentUserId:t})=>{const{data:n=[]}=FRn(s,t),{data:r=[]}=LXt(s,t),{addNote:a,deleteNote:i}=QRe(s),[l,o]=j.useState("");return e.jsxs("div",{className:"grid gap-6 xl:grid-cols-2",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pc,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("h3",{className:"font-medium",children:"Private notes"}),e.jsx($e,{variant:"secondary",children:"Managers only"})]}),e.jsx(Ls,{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(Hn,{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))]})]})]})},vEt=s=>s.split(/\s+/).filter(Boolean).slice(0,2).map(t=>t[0]).join("").toUpperCase(),Los=s=>s?s.split(/[-/T]/).slice(0,3).join("/"):null,Jlr=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"},nhe=({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"})})]}),ecr=({brokerageId:s,agentUserId:t})=>{const{data:n=[]}=LXt(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:Los(r.created_at)})]})]},r.id))]})]})},tcr=({brokerageId:s})=>{var O,U;const{toast:t}=Bi(),{data:n=[],isLoading:r}=PXt(s),{data:a=[]}=MXt(s),{assignTemplate:i,removeAssignment:l}=QRe(s),[o,c]=j.useState(""),[d,u]=j.useState("all"),[h,m]=j.useState(null),[f,g]=j.useState(!1),[x,y]=j.useState(null),[v,b]=j.useState(""),w=j.useMemo(()=>{const W=o.trim().toLowerCase();return n.filter(V=>{if(W&&!V.name.toLowerCase().includes(W)&&!V.email.toLowerCase().includes(W))return!1;const G=!!V.assignment&&V.total>0&&V.done===V.total;return d==="not_started"?!V.assignment:d==="in_progress"?!!V.assignment&&!G:d==="finished"?G:d==="review"?V.needsReview>0:d==="overdue"?V.overdue>0:!0})},[n,o,d]);j.useEffect(()=>{var W;h&&w.some(V=>V.agentId===h)||m(((W=w[0])==null?void 0:W.agentId)??null)},[w,h]);const S=n.find(W=>W.agentId===h)||null,{data:A}=IXt((O=S==null?void 0:S.assignment)==null?void 0:O.id),E=(A==null?void 0:A.steps)||[],I=E.filter(uE).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(nhe,{label:"In progress",value:R.inProgress,icon:y0,active:d==="in_progress",tone:"bg-primary/10 text-primary",onClick:()=>u(d==="in_progress"?"all":"in_progress")}),e.jsx(nhe,{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(nhe,{label:"Waiting on review",value:R.needsReview,icon:Cq,active:d==="review",tone:"bg-amber-500/10 text-amber-700",onClick:()=>u(d==="review"?"all":"review")}),e.jsx(nhe,{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(Zr,{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=Jlr(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:vEt(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:vEt(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 ${Los(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(Hn,{className:"mr-2 h-4 w-4"}),"Remove checklist"]}):e.jsxs($,{onClick:()=>{var W,V;y(S),b(((W=a.find(G=>G.is_default))==null?void 0:W.id)||((V=a[0])==null?void 0:V.id)||"")},disabled:a.length===0,children:[e.jsx(zu,{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(ha,{defaultValue:"checklist",className:"space-y-4",children:[e.jsx("div",{className:"overflow-x-auto pb-1",children:e.jsxs(ma,{className:"grid h-auto min-w-[500px] grid-cols-4 rounded-md border bg-muted/40 p-1",children:[e.jsx(Zt,{value:"checklist",children:"Checklist"}),e.jsx(Zt,{value:"record",children:"Record"}),e.jsx(Zt,{value:"notes",children:"Notes & activity"}),e.jsx(Zt,{value:"documents",children:"Documents"})]})}),e.jsx(Xt,{value:"checklist",children:S.assignment?e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,1.6fr)_minmax(240px,.8fr)]",children:[e.jsx(yYe,{brokerageId:s,agentUserId:S.agentId,steps:E,documents:(A==null?void 0:A.documents)||[],mode:"manager"}),e.jsx(ecr,{brokerageId:s,agentUserId:S.agentId})]}):e.jsx("p",{className:"py-12 text-center text-sm text-muted-foreground",children:"No checklist assigned yet."})}),e.jsx(Xt,{value:"record",children:e.jsx(Xlr,{brokerageId:s,agentUserId:S.agentId})}),e.jsx(Xt,{value:"notes",children:e.jsx(Qlr,{brokerageId:s,agentUserId:S.agentId})}),e.jsx(Xt,{value:"documents",children:S.assignment?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mb-4 flex items-center gap-2",children:[e.jsx(zz,{className:"h-4 w-4 text-primary"}),e.jsx("h3",{className:"font-['Outfit'] font-semibold",children:"Onboarding documents"})]}),e.jsx(yYe,{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(KN,{className:"mb-3 h-10 w-10 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Select an agent to see their onboarding."})]})})]}),e.jsx(zs,{open:!!x,onOpenChange:W=>!W&&y(null),children:e.jsxs(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Start onboarding"}),e.jsxs(Pr,{children:["Pick the flow for ",x==null?void 0:x.name,". Later flow edits will not change this checklist."]})]}),e.jsxs(ms,{value:v,onValueChange:b,children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Choose a flow"})}),e.jsx(hs,{children:a.map(W=>e.jsx(Ge,{value:W.id,children:W.name},W.id))})]}),e.jsxs(Sr,{children:[e.jsx($,{variant:"outline",onClick:()=>y(null),children:"Cancel"}),e.jsxs($,{disabled:!v||!x,onClick:async()=>{if(x)try{await i.mutateAsync({agentUserId:x.agentId,templateId:v}),t({title:"Onboarding started"}),y(null)}catch(W){t({title:"Could not start",description:W.message,variant:"destructive"})}},children:[e.jsx(aP,{className:"mr-2 h-4 w-4"}),"Start"]})]})]})})]})},scr=s=>s==="document"?Jr:s==="form"?c_:Vj,ncr=({brokerageId:s})=>{var W,V;const{toast:t}=Bi(),{data:n=[],isLoading:r}=MXt(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=[]}=LRn(l),{createTemplate:d,updateTemplate:u,deleteTemplate:h,upsertStep:m,deleteStep:f,reorderSteps:g}=ORn(s),{data:x=[]}=st({queryKey:["brokerage-form-templates",s],queryFn:async()=>{const{data:G,error:Y}=await q.from("form_templates").select("id, name").eq("brokerage_id",s).eq("is_archived",!1).order("name");if(Y)throw Y;return G||[]}}),[y,v]=j.useState(!1),[b,w]=j.useState(""),[S,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,Y)=>{const X=[...c],ae=G+Y;ae<0||ae>=X.length||([X[G],X[ae]]=[X[ae],X[G]],await g.mutateAsync({steps:X,templateId:l}))};return e.jsxs("div",{className:"grid min-h-[620px] overflow-hidden rounded-md border bg-card shadow-sm lg:grid-cols-[300px_minmax(0,1fr)]",children:[e.jsxs(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:()=>v(!0),children:e.jsx(dn,{className:"h-4 w-4"})})]}),e.jsx(Gn,{children:"Reusable checklists for new agents"})]}),e.jsxs(Ie,{className:"space-y-2",children:[r&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading…"}),!r&&n.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No flows yet. Create your first one."}),n.map(G=>e.jsxs("button",{onClick:()=>i(G.id),className:`w-full rounded-md border p-3 text-left transition-colors ${G.id===l?"border-primary bg-primary/5":"hover:bg-muted/50"}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"font-medium text-sm",children:G.name}),G.is_default&&e.jsxs($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(Gn,{children:o.description||"No description"})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs($,{size:"sm",variant:"outline",onClick:()=>u.mutate({id:o.id,is_default:!o.is_default}),children:[e.jsx(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(dn,{className:"mr-2 h-4 w-4"})," Add step"]}),e.jsx($,{size:"sm",variant:"ghost",className:"text-destructive",onClick:async()=>{await h.mutateAsync(o.id),i(null)},children:e.jsx(Hn,{className:"h-4 w-4"})})]})]})}),e.jsxs(Ie,{className:"space-y-2",children:[c.length===0&&e.jsx("p",{className:"py-8 text-center text-sm text-muted-foreground",children:"No steps yet — add documents, forms and tasks agents need to complete."}),c.map((G,Y)=>{const X=scr(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(Y,-1),"aria-label":"Move up",children:e.jsx(Zf,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"ghost",onClick:()=>U(Y,1),"aria-label":"Move down",children:e.jsx(Dg,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"ghost",onClick:()=>{R(G),I(!0)},"aria-label":"Edit step",children:e.jsx(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(Hn,{className:"h-4 w-4"})})]})]},G.id)})]})]}):e.jsxs(Ie,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(zg,{className:"mb-3 h-10 w-10 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Select or create an onboarding flow."})]})}),e.jsx(zs,{open:y,onOpenChange:v,children:e.jsxs(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"New onboarding flow"}),e.jsx(Pr,{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(Ls,{value:S,onChange:G=>A(G.target.value),rows:3})]})]}),e.jsxs(Sr,{children:[e.jsx($,{variant:"outline",onClick:()=>v(!1),children:"Cancel"}),e.jsx($,{disabled:!b.trim(),onClick:async()=>{const G=await d.mutateAsync({name:b.trim(),description:S});i(G.id),w(""),A(""),v(!1)},children:"Create"})]})]})}),e.jsx(zs,{open:E,onOpenChange:I,children:e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsx(Bs,{children:P!=null&&P.id?"Edit step":"Add step"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Title"}),e.jsx(pe,{value:(P==null?void 0:P.title)||"",onChange:G=>R({...P,title:G.target.value}),placeholder:"Independent contractor agreement"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Instructions"}),e.jsx(Ls,{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(Sr,{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"})]})]})})]})},rcr=()=>{const{user:s,isBrokerageManager:t,isAdmin:n,brokerageId:r,managedBrokerages:a,selectedBrokerageId:i,setSelectedBrokerageId:l}=bs(),o=Xn(),[c,d]=j.useState(!1),u=i||(a.length>0?a[0].id:r);return j.useEffect(()=>{if(s){if(!t&&!n){o("/dashboard");return}!i&&a.length>0&&l(a[0].id),d(!0)}},[s,t,n,o,a,i,l]),c?e.jsx(Vs,{title:"Agent Onboarding",description:"Build your onboarding flow, collect documents and keep notes",children:e.jsxs("div",{className:"onboarding-console space-y-5 font-['Figtree']",children:[a.length>1&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Managing:"}),e.jsxs(ms,{value:i||"",onValueChange:l,children:[e.jsxs(us,{className:"w-[280px]",children:[e.jsx(ji,{className:"mr-2 h-4 w-4"}),e.jsx(fs,{placeholder:"Select brokerage"})]}),e.jsx(hs,{children:a.map(h=>e.jsx(Ge,{value:h.id,children:h.name},h.id))})]})]}),u?e.jsxs(ha,{defaultValue:"board",className:"space-y-4",children:[e.jsxs(ma,{className:"grid h-10 w-full max-w-sm grid-cols-2 rounded-md border bg-muted/40 p-1",children:[e.jsx(Zt,{value:"board",children:"Agents"}),e.jsx(Zt,{value:"flows",children:"Flows"})]}),e.jsx(Xt,{value:"board",children:e.jsx(tcr,{brokerageId:u})}),e.jsx(Xt,{value:"flows",children:e.jsx(ncr,{brokerageId:u})})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(ji,{className:"mb-4 h-12 w-12 text-muted-foreground"}),e.jsx("h2",{className:"mb-1 text-xl font-semibold",children:"No Brokerage Assigned"}),e.jsx("p",{className:"text-muted-foreground",children:"You don't have any brokerages to manage."})]})]})}):null},acr={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 icr({dealId:s}){const{data:t=[]}=DLs(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:acr[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 ocr({brokerageId:s,deal:t,open:n,onOpenChange:r}){const{data:a=[]}=Fzt(s),i=OLs(),[l,o]=j.useState("");if(!t)return null;const c=KHe(t),d=async()=>{if(l)try{await i.mutateAsync({dealId:t.deal_id,brokerageId:s,templateId:l,deal:{contract_date:t.contract_date,target_close_date:t.target_close_date}}),re.success("Checklist added to this file")}catch(u){re.error(u.message||"Could not apply checklist")}};return e.jsx(Gy,{open:n,onOpenChange:r,children:e.jsxs(my,{className:"w-full overflow-y-auto sm:max-w-xl",children:[e.jsxs(L0,{className:"text-left",children:[e.jsx(R0,{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:Dzt[c]})]})]}),e.jsxs("div",{className:"mt-5 grid grid-cols-3 gap-3 rounded-lg border p-3 text-center text-xs",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Contract"}),e.jsx("p",{className:"font-medium",children:t.contract_date||"—"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Target close"}),e.jsx("p",{className:"font-medium",children:t.target_close_date||"—"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Approved"}),e.jsxs("p",{className:"font-medium",children:[t.approved_items,"/",t.total_items]})]})]}),e.jsxs(ha,{defaultValue:"checklist",className:"mt-5",children:[e.jsxs(ma,{className:"grid w-full grid-cols-3",children:[e.jsx(Zt,{value:"checklist",children:"Checklist"}),e.jsx(Zt,{value:"messages",children:"Messages"}),e.jsx(Zt,{value:"audit",children:"Audit trail"})]}),e.jsxs(Xt,{value:"checklist",className:"mt-4 space-y-4",children:[t.total_items===0&&a.length>0&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(ms,{value:l,onValueChange:o,children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Apply a checklist"})}),e.jsx(hs,{children:a.map(u=>e.jsx(Ge,{value:u.id,children:u.name},u.id))})]}),e.jsx($,{onClick:d,disabled:!l||i.isPending,children:"Apply"})]}),e.jsx(Vrs,{dealId:t.deal_id,canReview:!0})]}),e.jsx(Xt,{value:"messages",className:"mt-4",children:e.jsx(Hrs,{dealId:t.deal_id,brokerageId:s,role:"staff",counterpartName:t.agent_name})}),e.jsx(Xt,{value:"audit",className:"mt-4",children:e.jsx(icr,{dealId:t.deal_id})})]})]})})}function lcr({metrics:s}){const t=[{label:"Active transactions",value:String(s.activeDeals),caption:`${s.closedThisYear} closed this year`,icon:ji,tint:"bg-blue-500/10 text-blue-600"},{label:"Pipeline volume",value: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:nu,tint:"bg-emerald-500/10 text-emerald-600"},{label:"Est. brokerage share",value:Gf(s.brokerageShare),caption:`${Gf(s.closedCompanyDollarYtd)} company dollar YTD`,icon:HJ,tint:"bg-teal-500/10 text-teal-600"},{label:"Closing soon",value:String(s.closingNext30),caption:`${s.closingThisMonth} this month`,icon:Cu,tint:"bg-amber-500/10 text-amber-600"}],n=[{label:"Files awaiting review",value:s.needsReview,icon:zz,tint:"text-blue-600"},{label:"Changes requested",value:s.changesRequested,icon:zJ,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(Ie,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("span",{className:Pt("flex h-9 w-9 shrink-0 items-center justify-center rounded-lg",r.tint),children:e.jsx(r.icon,{className:"h-4.5 w-4.5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:r.label}),e.jsx("p",{className:"text-2xl font-bold tabular-nums tracking-tight",children:r.value}),e.jsx("p",{className:"mt-0.5 truncate text-[11px] text-muted-foreground",children:r.caption})]})]})})},r.label))}),e.jsx(je,{className:"border-border/60",children:e.jsx(Ie,{className:"flex flex-wrap items-center gap-x-8 gap-y-3 p-4",children:n.map(r=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(r.icon,{className:Pt("h-4 w-4",r.tint)}),e.jsx("span",{className:"text-sm font-semibold tabular-nums",children:r.value}),e.jsx("span",{className:"text-xs text-muted-foreground",children:r.label})]},r.label))})})]})}function ccr({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(Gn,{children:"Expected closings over the next 6 months"})]}),e.jsx(Ie,{className:"pt-2",children:t?e.jsx("div",{className:"h-[220px] w-full",children:e.jsx(N_,{width:"100%",height:"100%",children:e.jsxs(LK,{data:s,margin:{top:8,right:8,left:0,bottom:0},children:[e.jsx(gT,{strokeDasharray:"3 3",vertical:!1,stroke:"hsl(var(--border))"}),e.jsx(Ab,{dataKey:"label",tickLine:!1,axisLine:!1,fontSize:11,stroke:"hsl(var(--muted-foreground))"}),e.jsx(Eb,{tickLine:!1,axisLine:!1,fontSize:11,stroke:"hsl(var(--muted-foreground))",tickFormatter:n=>Gf(Number(n)),width:54}),e.jsx(Cg,{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(Fw,{dataKey:"volume",radius:[6,6,0,0],children:s.map(n=>e.jsx(ZB,{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 dcr({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(Gn,{children:"Company-visible transactions by agent — tap a row to filter the board"})]}),e.jsx(Ie,{className:"space-y-1 pt-2",children:s.slice(0,12).map(a=>{const i=t>0?Math.round(a.volume/t*100):0,l=n===a.userId;return e.jsxs("button",{onClick:()=>r(l?"all":a.userId),className:`flex w-full items-center gap-3 rounded-lg px-2 py-2 text-left transition-colors hover:bg-muted/60 ${l?"bg-muted":""}`,children:[e.jsxs(Oa,{className:"h-8 w-8 shrink-0",children:[e.jsx(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 bEt={ownerUserId:"",dealName:"",dealType:"buyer",stageId:"",propertyAddress:"",city:"",state:"",zipCode:"",contractDate:"",targetCloseDate:"",actualCloseDate:"",price:"",commissionPercentage:"",notes:""};function ucr({brokerageId:s,open:t,onOpenChange:n}){const[r,a]=j.useState(bEt),[i,l]=j.useState(""),{data:o=[],isLoading:c}=VLs(t?s:null),{data:d=[],isLoading:u}=HLs(r.ownerUserId||null),h=GLs();j.useEffect(()=>{t||(a(bEt),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,y=g!=null&&x!=null&&Number.isFinite(g)&&Number.isFinite(x)?Math.round(g*(x/100)*100)/100:null,v=!!r.ownerUserId&&!!r.stageId&&r.dealName.trim().length>0&&!h.isPending,b=async()=>{try{await h.mutateAsync({brokerageId:s,ownerUserId:r.ownerUserId,dealName:r.dealName,dealType:r.dealType,stageId:r.stageId||null,propertyAddress:r.propertyAddress,city:r.city,state:r.state,zipCode:r.zipCode,contractDate:r.contractDate,targetCloseDate:r.targetCloseDate,actualCloseDate:r.actualCloseDate,price:g!=null&&Number.isFinite(g)?g:null,commissionPercentage:x!=null&&Number.isFinite(x)?x:null,notes:r.notes});const w=o.find(S=>S.id===r.ownerUserId);re.success(`Deal added to ${(w==null?void 0:w.name)||"the agent"}'s pipeline.`),n(!1)}catch(w){re.error((w==null?void 0:w.message)||"Could not add the deal.")}};return e.jsx(zs,{open:t,onOpenChange:n,children:e.jsxs(Os,{className:"max-h-[90vh] max-w-2xl overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Add a deal for an agent"}),e.jsx(Pr,{children:"The deal is created in the agent's own pipeline, so it shows up here and in their account."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Agent"}),e.jsx(pe,{placeholder:"Search agents by name or email",value:i,onChange:w=>l(w.target.value)}),e.jsxs(ms,{value:r.ownerUserId,onValueChange:w=>f("ownerUserId",w),children:[e.jsx(us,{children:e.jsx(fs,{placeholder:c?"Loading agents…":"Select an agent"})}),e.jsx(hs,{children:m.map(w=>e.jsx(Ge,{value:w.id,children:w.name||w.email||"Agent"},w.id))})]})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2 sm:col-span-2",children:[e.jsx(ee,{children:"Deal name"}),e.jsx(pe,{placeholder:"Client name or property address",value:r.dealName,onChange:w=>f("dealName",w.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Type"}),e.jsxs(ms,{value:r.dealType,onValueChange:w=>f("dealType",w),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"buyer",children:"Buyer"}),e.jsx(Ge,{value:"seller",children:"Seller"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Stage"}),e.jsxs(ms,{value:r.stageId,onValueChange:w=>f("stageId",w),disabled:!r.ownerUserId||u,children:[e.jsx(us,{children:e.jsx(fs,{placeholder:r.ownerUserId?u?"Loading stages…":"Select a stage":"Pick an agent first"})}),e.jsx(hs,{children:d.map(w=>e.jsx(Ge,{value:w.id,children:w.name},w.id))})]})]}),e.jsxs("div",{className:"space-y-2 sm:col-span-2",children:[e.jsx(ee,{children:"Property address"}),e.jsx(pe,{value:r.propertyAddress,onChange:w=>f("propertyAddress",w.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"City"}),e.jsx(pe,{value:r.city,onChange:w=>f("city",w.target.value)})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"State"}),e.jsx(pe,{value:r.state,onChange:w=>f("state",w.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"ZIP"}),e.jsx(pe,{value:r.zipCode,onChange:w=>f("zipCode",w.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Contract date"}),e.jsx(pe,{type:"date",value:r.contractDate,onChange:w=>f("contractDate",w.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Target close date"}),e.jsx(pe,{type:"date",value:r.targetCloseDate,onChange:w=>f("targetCloseDate",w.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Actual close date"}),e.jsx(pe,{type:"date",value:r.actualCloseDate,onChange:w=>f("actualCloseDate",w.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Price"}),e.jsx(pe,{type:"number",inputMode:"decimal",value:r.price,onChange:w=>f("price",w.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Commission %"}),e.jsx(pe,{type:"number",inputMode:"decimal",step:"0.01",value:r.commissionPercentage,onChange:w=>f("commissionPercentage",w.target.value)}),y!=null&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Expected commission: $",y.toLocaleString()]})]}),e.jsxs("div",{className:"space-y-2 sm:col-span-2",children:[e.jsx(ee,{children:"Notes"}),e.jsx(Ls,{rows:3,value:r.notes,onChange:w=>f("notes",w.target.value)})]})]})]}),e.jsxs(Sr,{children:[e.jsx($,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsxs($,{onClick:b,disabled:!v,children:[h.isPending&&e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}),"Add deal"]})]})]})})}const hcr={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 mcr({brokerageId:s,canAddDeals:t=!1}){const{data:n=[],isLoading:r}=Ett(s),[a,i]=j.useState(""),[l,o]=j.useState("all"),[c,d]=j.useState("all"),[u,h]=j.useState("all"),[m,f]=j.useState("stage"),[g,x]=j.useState(null),[y,v]=j.useState(!1),b=j.useMemo(()=>far(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=KHe(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:()=>v(!0),children:[e.jsx(dn,{className:"mr-2 h-4 w-4"}),"Add deal"]})}),t&&e.jsx(ucr,{brokerageId:s,open:y,onOpenChange:v}),n.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(lcr,{metrics:b}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-2",children:[e.jsx(ccr,{outlook:b.outlook}),e.jsx(dcr,{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(Zr,{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(Ie,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(kv,{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=KHe(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 ${hcr[P]}`,children:Dzt[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(ocr,{brokerageId:s,deal:g,open:!!g,onOpenChange:I=>!I&&x(null)})]})}const _Et=[{value:"any",label:"Any deal type"},{value:"listing",label:"Listing"},{value:"buyer",label:"Buyer"},{value:"lease",label:"Lease"},{value:"referral",label:"Referral"}];function fcr({brokerageId:s}){var b,w;const{data:t=[],isLoading:n}=Fzt(s),r=PLs(),a=ILs(),[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=[]}=MLs(o),u=LLs(),h=RLs(),[m,f]=j.useState(!1),[g,x]=j.useState(null),y=async()=>{try{const S=await r.mutateAsync({brokerage_id:s,name:"New checklist",deal_type:null,is_active:!0});l(S)}catch(S){re.error(S.message||"Could not create checklist")}},v=async()=>{var S;if(!(!o||!((S=g==null?void 0:g.title)!=null&&S.trim())))try{await u.mutateAsync({...g,template_id:o,title:g.title.trim(),sort_order:g.sort_order??d.length}),f(!1),x(null)}catch(A){re.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:y,children:e.jsx(dn,{className:"h-4 w-4"})})]}),e.jsx(Ie,{className:"space-y-2",children:t.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Create a checklist per deal type — Listing, Buyer, Lease."}):t.map(S=>{var 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=_Et.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(Gn,{children:"Applied automatically when a deal becomes company-visible."})]}),e.jsxs(Ie,{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Name"}),e.jsx(pe,{defaultValue:c.name,onBlur:S=>r.mutate({id:c.id,brokerage_id:s,name:S.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Applies to"}),e.jsxs(ms,{value:c.deal_type||"any",onValueChange:S=>r.mutate({id:c.id,brokerage_id:s,deal_type:S==="any"?null:S}),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:_Et.map(S=>e.jsx(Ge,{value:S.value,children:S.label},S.value))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{children:"Required items"}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>{x({phase:"contract",requires_document:!0,required_for_closing:!0}),f(!0)},children:[e.jsx(dn,{className:"mr-1 h-4 w-4"})," Add item"]})]}),d.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No items yet."}):e.jsx("div",{className:"space-y-2",children:d.map(S=>{var 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=AEe.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(Hn,{className:"h-4 w-4 text-destructive"})})]},S.id)})})]}),e.jsxs($,{variant:"outline",className:"text-destructive",onClick:async()=>{await fo(`Delete "${c.name}"?`)&&(a.mutate({id:c.id,brokerageId:s}),l(null))},children:[e.jsx(Hn,{className:"mr-2 h-4 w-4"})," Delete checklist"]})]})]}):e.jsx(je,{children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(Jr,{className:"mb-3 h-10 w-10 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Select or create a checklist to add required documents."})]})}),e.jsx(zs,{open:m,onOpenChange:f,children:e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsx(Bs,{children:g!=null&&g.id?"Edit item":"Add item"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Title"}),e.jsx(pe,{value:(g==null?void 0:g.title)||"",onChange:S=>x(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(Ls,{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:AEe.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(Sn,{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(Sn,{checked:(g==null?void 0:g.required_for_closing)??!0,onCheckedChange:S=>x(A=>({...A,required_for_closing:S}))})]})]}),e.jsxs(Sr,{children:[e.jsx($,{variant:"outline",onClick:()=>f(!1),children:"Cancel"}),e.jsxs($,{onClick:v,disabled:!((w=g==null?void 0:g.title)!=null&&w.trim())||u.isPending,children:[u.isPending&&e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}),"Save"]})]})]})})]})}function pcr({brokerageId:s}){const{data:t,isLoading:n}=ELs(s),r=TLs(),{data:a=[]}=SLs(s),i=CLs(),l=ALs(),[o,c]=j.useState(["contract","closing","closed"]),[d,u]=j.useState(!0),[h,m]=j.useState(!0),[f,g]=j.useState(""),[x,y]=j.useState(!1);j.useEffect(()=>{t&&(c(t.visible_phases||[]),u(t.include_contract_dated_deals),m(t.is_enabled))},[t]);const v=S=>c(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}),re.success("Compliance settings saved")}catch(S){re.error(S.message||"Could not save settings")}},w=async()=>{const S=f.trim().toLowerCase();if(S){y(!0);try{const{data:A,error:E}=await q.from("profiles").select("id, email").ilike("email",S).maybeSingle();if(E)throw E;if(!A){re.error("No LevelUp account found with that email");return}await i.mutateAsync({brokerageId:s,userId:A.id}),g(""),re.success("Transaction admin added")}catch(A){re.error(A.message||"Could not add transaction admin")}finally{y(!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(Gn,{children:"Agent leads, consultations and early conversations stay private. Deals become visible to compliance once they reach one of the phases below."})]}),e.jsxs(Ie,{className:"space-y-5",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm font-medium",children:"Compliance tracking on"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Turn off to hide all agent deals from the company view."})]}),e.jsx(Sn,{checked:h,onCheckedChange:m})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-sm font-medium",children:"Company-visible phases"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:AEe.map(S=>e.jsx("button",{type:"button",onClick:()=>v(S.value),className:`rounded-full border px-3 py-1.5 text-xs font-medium transition-colors ${o.includes(S.value)?"border-primary bg-primary/10 text-primary":"border-border text-muted-foreground hover:bg-muted"}`,children:S.label},S.value))})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm font-medium",children:"Include any deal with a contract date"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:'Recommended — catches "agreement signed" deals even when an agent uses custom stage names.'})]}),e.jsx(Sn,{checked:d,onCheckedChange:u})]}),e.jsxs($,{onClick:b,disabled:r.isPending,children:[r.isPending&&e.jsx(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(Gn,{children:"Give staff compliance-only access — deals, documents, checklists and notes. No recruiting or billing."})]}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{placeholder:"admin@yourbrokerage.com",value:f,onChange:S=>g(S.target.value),onKeyDown:S=>S.key==="Enter"&&w()}),e.jsx($,{onClick:w,disabled:x||!f.trim(),children:x?e.jsx(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(Hn,{className:"h-4 w-4 text-destructive"})})]})]},S.id))})]})]})]})}const gcr=()=>{const{user:s,isBrokerageManager:t,isAdmin:n,brokerageId:r,managedBrokerages:a,selectedBrokerageId:i,setSelectedBrokerageId:l}=bs(),o=Xn(),{data:c=[],isLoading:d}=Att(),[u,h]=j.useState(!1),m=c.length>0,f=t||n,g=j.useMemo(()=>{var x;return i||(a.length>0?a[0].id:null)||((x=c[0])==null?void 0:x.brokerage_id)||r},[i,a,c,r]);return j.useEffect(()=>{if(!(!s||d)){if(!f&&!m){o("/dashboard");return}!i&&a.length>0&&l(a[0].id),h(!0)}},[s,d,f,m,o,a,i,l]),u?e.jsx(Vs,{title:"Transactions & Compliance",description:"Review agent files, required documents and closing compliance",children:e.jsxs("div",{className:"space-y-6",children:[a.length>1&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Managing:"}),e.jsxs(ms,{value:i||"",onValueChange:l,children:[e.jsxs(us,{className:"w-[280px]",children:[e.jsx(ji,{className:"mr-2 h-4 w-4"}),e.jsx(fs,{placeholder:"Select brokerage"})]}),e.jsx(hs,{children:a.map(x=>e.jsx(Ge,{value:x.id,children:x.name},x.id))})]})]}),g?e.jsxs(ha,{defaultValue:"board",className:"space-y-4",children:[e.jsxs(ma,{className:`grid w-full ${f?"max-w-lg grid-cols-3":"max-w-xs grid-cols-1"}`,children:[e.jsx(Zt,{value:"board",children:"Transactions"}),f&&e.jsx(Zt,{value:"checklists",children:"Checklists"}),f&&e.jsx(Zt,{value:"settings",children:"Settings"})]}),e.jsx(Xt,{value:"board",children:e.jsx(mcr,{brokerageId:g,canAddDeals:f||m})}),f&&e.jsx(Xt,{value:"checklists",children:e.jsx(fcr,{brokerageId:g})}),f&&e.jsx(Xt,{value:"settings",children:e.jsx(pcr,{brokerageId:g})})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(ji,{className:"mb-4 h-12 w-12 text-muted-foreground"}),e.jsx("h2",{className:"mb-1 text-xl font-semibold",children:"No Brokerage Assigned"}),e.jsx("p",{className:"text-muted-foreground",children:"You don't have any brokerages to manage."})]})]})}):null},Tne=q,fUe={draft:"Draft",approved:"Approved",paid:"Paid",void:"Void"},o_=s=>{const t=Number(s);return Number.isFinite(t)?t:0};function EW(s){const t=o_(s.gross_commission),n=o_(s.referral_amount)>0?o_(s.referral_amount):t*o_(s.referral_fee_pct)/100,r=Math.max(0,t-n),a=r*(100-o_(s.agent_split_pct))/100,i=r*o_(s.franchise_fee_pct)/100,l=o_(s.transaction_fee),o=(s.line_items||[]).reduce((u,h)=>u+o_(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 xcr(s,t){const n=o_(s.brokerage_split_pct),r=(t==null?void 0:t.agent_split_pct)!=null?o_(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:CW(s),gross_commission:AW(s),agent_split_pct:r,franchise_fee_pct:s.franchise_fee_pct!=null?o_(s.franchise_fee_pct):o_(t==null?void 0:t.franchise_fee_pct),transaction_fee:s.transaction_fee!=null?o_(s.transaction_fee):o_(t==null?void 0:t.transaction_fee),referral_fee_pct:o_(t==null?void 0:t.referral_fee_pct),referral_amount:0,referral_payee:null,line_items:[],notes:null}}function Ros(s){return st({queryKey:["disbursements",s],enabled:!!s,queryFn:async()=>{const t=[];for(let r=0;;r+=1e3){const{data:a,error:i}=await Tne.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 ycr(s){const t=Wt(),{user:n}=bs();return mt({mutationFn:async r=>{const a=EW(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 Tne.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 Tne.from("brokerage_disbursements").insert(i);if(l)throw l}},onSuccess:()=>{t.invalidateQueries({queryKey:["disbursements",s]}),re.success("Disbursement saved")},onError:r=>re.error(r.message||"Could not save the disbursement")})}function vcr(s){const t=Wt(),{user:n}=bs();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 Tne.from("brokerage_disbursements").update(i).eq("id",r);if(l)throw l},onSuccess:()=>t.invalidateQueries({queryKey:["disbursements",s]}),onError:r=>re.error(r.message||"Could not update the status")})}function bcr(s){const t=Wt();return mt({mutationFn:async n=>{const{error:r}=await Tne.from("brokerage_disbursements").delete().eq("id",n);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["disbursements",s]}),re.success("Disbursement removed")},onError:n=>re.error(n.message||"Could not remove the disbursement")})}function Dos(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 DPe=q;function _cr(s){return st({queryKey:["ops-follow-ups",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await DPe.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 DPe.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 wcr(s){return st({queryKey:["ops-help-requests",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await DPe.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 DPe.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 s3=q,Fos=[{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"}],FPe=Object.fromEntries(Fos.map(s=>[s.value,s.label])),aQe={todo:"To do",in_progress:"In progress",done:"Done"},jcr={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 s3.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 kcr(s){const t=Wt(),{user:n}=bs();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 s3.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 s3.from("brokerage_operations_tasks").insert(a).select("id").single();if(l)throw l;return i.id},onSuccess:()=>{t.invalidateQueries({queryKey:["ops-tasks",s]}),t.invalidateQueries({queryKey:["my-ops-tasks"]}),re.success("Task saved")},onError:r=>re.error(r.message||"Could not save task")})}function Scr(s){const t=Wt();return mt({mutationFn:async({id:n,status:r})=>{const{error:a}=await s3.from("brokerage_operations_tasks").update({status:r,completed_at:r==="done"?new Date().toISOString():null}).eq("id",n);if(a)throw a},onSuccess:()=>{t.invalidateQueries({queryKey:["ops-tasks",s]}),t.invalidateQueries({queryKey:["my-ops-tasks"]})},onError:n=>re.error(n.message||"Could not update task")})}function Ccr(s){const t=Wt();return mt({mutationFn:async n=>{const{error:r}=await s3.from("brokerage_operations_tasks").delete().eq("id",n);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["ops-tasks",s]}),t.invalidateQueries({queryKey:["my-ops-tasks"]}),re.success("Task removed")},onError:n=>re.error(n.message||"Could not remove task")})}function Acr(s){const t=Wt(),{user:n}=bs();return mt({mutationFn:async r=>{const{error:a}=await s3.from("brokerage_operations_tasks").insert({brokerage_id:s,created_by:(n==null?void 0:n.id)??null,title:r.title,category:r.category,status:"done",source_type:r.sourceType,source_id:r.sourceId,dismissed_at:new Date().toISOString(),dismissed_by:(n==null?void 0:n.id)??null,completed_at:new Date().toISOString()});if(a)throw a},onSuccess:()=>{t.invalidateQueries({queryKey:["ops-tasks",s]}),re.success("Dismissed")},onError:r=>re.error(r.message||"Could not dismiss")})}function Ecr(s){return st({queryKey:["ops-task-comments",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await s3.from("brokerage_operations_task_comments").select("*").eq("task_id",s).order("created_at",{ascending:!0});if(n)throw n;return t||[]}})}function Tcr(){const s=Wt(),{user:t}=bs();return mt({mutationFn:async({taskId:n,body:r})=>{const{error:a}=await s3.from("brokerage_operations_task_comments").insert({task_id:n,body:r.trim(),author_user_id:t==null?void 0:t.id});if(a)throw a},onSuccess:(n,r)=>s.invalidateQueries({queryKey:["ops-task-comments",r.taskId]}),onError:n=>re.error(n.message||"Could not add note")})}function Mcr(s){const{user:t}=bs();return st({queryKey:["ops-digest-prefs",s,t==null?void 0:t.id],enabled:!!s&&!!t,queryFn:async()=>{const{data:n,error:r}=await s3.from("brokerage_operations_digest_prefs").select("*").eq("brokerage_id",s).eq("user_id",t.id).maybeSingle();if(r)throw r;return n||null}})}function Pcr(s){const t=Wt(),{user:n}=bs();return mt({mutationFn:async r=>{const{error:a}=await s3.from("brokerage_operations_digest_prefs").upsert({user_id:n.id,brokerage_id:s,email_enabled:r.email_enabled??!1,push_enabled:r.push_enabled??!1,send_day:r.send_day??1},{onConflict:"user_id,brokerage_id"});if(a)throw a},onSuccess:()=>{t.invalidateQueries({queryKey:["ops-digest-prefs",s]}),re.success("Notification settings saved")},onError:r=>re.error(r.message||"Could not save settings")})}const Icr={license:"License renewal",eo:"E&O insurance",anniversary:"Work anniversary",birthday:"Birthday"},Oos=864e5,zos=()=>{const s=new Date;return{y:s.getFullYear(),m:s.getMonth()+1,d:s.getDate()}},fq=(s,t,n)=>Date.UTC(s,t-1,n),Ult=s=>{const t=PC(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},OPe=s=>String(s).padStart(2,"0");function wEt(s){const t=PC(s||"");if(!t)return null;const n=zos(),r=Math.round((fq(t.y,t.m,t.d)-fq(n.y,n.m,n.d))/Oos);return{dueDate:`${t.y}-${OPe(t.m)}-${OPe(t.d)}`,daysUntil:r,expired:r<0}}function jEt(s){const t=PC(s||"");if(!t)return null;const n=zos();let r=n.y;fq(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=wEt(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=wEt(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=jEt(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=jEt(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 Lcr(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 Rcr=864e5;function SX(s){const t=PC(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)/Rcr)}function Dcr(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:SX(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:SX(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=SX(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"})}),Bos(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=SX(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=SX(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 Fcr={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"},Ocr=s=>(s||"?").split(" ").map(t=>t[0]).filter(Boolean).slice(0,2).join("").toUpperCase();function zcr({items:s,loading:t,onDismiss:n,onTrack:r}){const a=Xn(),[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(Ie,{className:"p-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Needs attention"}),e.jsx("p",{className:"text-2xl font-semibold",children:s.length})]})}),e.jsx(je,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Overdue"}),e.jsx("p",{className:Pt("text-2xl font-semibold",d>0&&"text-destructive"),children:d})]})}),e.jsx(je,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Due this week"}),e.jsx("p",{className:"text-2xl font-semibold",children:u})]})})]}),e.jsxs(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(Gn,{children:"Pulled live from compliance, financials, onboarding, recruiting and the help board."})]}),e.jsxs(ms,{value:i,onValueChange:l,children:[e.jsx(us,{className:"w-[160px] shrink-0",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All areas"}),o.map(h=>e.jsx(Ge,{value:h,children:FPe[h]||h},h))]})]})]}),e.jsx(Ie,{className:"space-y-2",children:c.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(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:Ocr(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]",Fcr[h.priority]),children:FPe[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(Cu,{className:"h-3 w-3"}),Ult(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(PJ,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:"ghost",title:"Dismiss",onClick:()=>n(h),children:e.jsx(pr,{className:"h-4 w-4"})})]})]},h.key))})]})]})}const rhe=["todo","in_progress","done"],Bcr={urgent:"bg-destructive",high:"bg-amber-500",medium:"bg-primary/60",low:"bg-muted-foreground/40"};function $cr({tasks:s,people:t,loading:n,onNew:r,onEdit:a,onStatus:i,onDelete:l}){const[o,c]=j.useState("all"),[d,u]=j.useState("all"),h=j.useMemo(()=>s.filter(x=>!x.dismissed_at).filter(x=>o==="all"?!0:o==="unassigned"?!x.assignee_user_id:x.assignee_user_id===o).filter(x=>d==="all"?!0:x.category===d),[s,o,d]),m=x=>{var y;return x?((y=t.find(v=>v.id===x))==null?void 0:y.name)||"Team member":"Unassigned"},f=j.useMemo(()=>Array.from(new Set(s.map(x=>x.category))),[s]);if(n)return e.jsx(xn,{className:"h-72 w-full"});const g=(x,y)=>{const v=rhe.indexOf(x.status),b=rhe[v+y];b&&i(x,b)};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(ms,{value:o,onValueChange:c,children:[e.jsx(us,{className:"w-[180px]",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"Everyone"}),e.jsx(Ge,{value:"unassigned",children:"Unassigned"}),t.map(x=>e.jsx(Ge,{value:x.id,children:x.name},x.id))]})]}),e.jsxs(ms,{value:d,onValueChange:u,children:[e.jsx(us,{className:"w-[170px]",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All categories"}),f.map(x=>e.jsx(Ge,{value:x,children:FPe[x]||x},x))]})]}),e.jsxs($,{className:"ml-auto",onClick:r,children:[e.jsx(dn,{className:"mr-2 h-4 w-4"})," New task"]})]}),e.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:rhe.map(x=>{const y=h.filter(v=>v.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:[aQe[x],e.jsx($e,{variant:"secondary",children:y.length})]})}),e.jsxs(Ie,{className:"space-y-2",children:[y.length===0&&e.jsx("p",{className:"py-6 text-center text-sm text-muted-foreground",children:"Nothing here"}),y.map(v=>{const b=!!v.due_date&&v.status!=="done"&&v.due_datea(v),children:[e.jsx("p",{className:"truncate font-medium",children:v.title}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[FPe[v.category]||v.category," · ",m(v.assignee_user_id)]})]}),e.jsxs($u,{children:[e.jsx(Uu,{asChild:!0,children:e.jsx($,{size:"icon",variant:"ghost",className:"h-7 w-7",children:e.jsx(Jx,{className:"h-4 w-4"})})}),e.jsxs(Au,{align:"end",children:[e.jsxs(ja,{onClick:()=>a(v),children:[e.jsx(pi,{className:"mr-2 h-4 w-4"})," Edit"]}),rhe.filter(w=>w!==v.status).map(w=>e.jsxs(ja,{onClick:()=>i(v,w),children:["Move to ",aQe[w]]},w)),e.jsxs(ja,{className:"text-destructive",onClick:()=>l(v),children:[e.jsx(Hn,{className:"mr-2 h-4 w-4"})," Delete"]})]})]})]}),v.due_date&&e.jsxs("p",{className:Pt("mt-2 flex items-center gap-1 text-xs",b?"text-destructive":"text-muted-foreground"),children:[e.jsx(Cu,{className:"h-3 w-3"})," ",Ult(v.due_date)]}),e.jsxs("div",{className:"mt-2 flex gap-1 md:hidden",children:[e.jsx($,{size:"sm",variant:"outline",className:"flex-1",disabled:x==="todo",onClick:()=>g(v,-1),children:e.jsx(Va,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:"outline",className:"flex-1",disabled:x==="done",onClick:()=>g(v,1),children:e.jsx(Qa,{className:"h-4 w-4"})})]})]},v.id)})]})]},x)})})]})}const Ucr=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],NEt=(s,t,n)=>`${s}-${String(t+1).padStart(2,"0")}-${String(n).padStart(2,"0")}`;function qcr({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=NEt(r.getFullYear(),r.getMonth(),r.getDate()),y=l?d.get(l)||[]:[],v=b=>i(w=>{const S=w.m+b;return S<0?{y:w.y-1,m:11}:S>11?{y:w.y+1,m:0}:{y:w.y,m:S}});return e.jsxs("div",{className:"grid gap-4 lg:grid-cols-[2fr,1fr]",children:[e.jsxs(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(Gn,{children:"Closings, renewals and due dates in one place."})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{size:"icon",variant:"outline",onClick:()=>v(-1),children:e.jsx(kd,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"outline",onClick:()=>v(1),children:e.jsx(Di,{className:"h-4 w-4"})})]})]}),e.jsxs(Ie,{children:[e.jsx("div",{className:"grid grid-cols-7 gap-1 text-center text-xs text-muted-foreground",children:Ucr.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=NEt(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(Gn,{children:l?`${y.length} item${y.length===1?"":"s"}`:"Select a date to see what is happening."})]}),e.jsxs(Ie,{className:"space-y-2",children:[l&&y.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nothing scheduled."}),y.map(b=>e.jsxs("div",{className:"flex items-start gap-2 rounded-md border p-2 text-sm",children:[e.jsx("span",{className:Pt("mt-1.5 h-2 w-2 shrink-0 rounded-full",b.tone)}),e.jsx("span",{className:"min-w-0 flex-1",children:b.label})]},b.id)),e.jsx("div",{className:"pt-2",children:e.jsxs("div",{className:"flex flex-wrap gap-2 text-xs text-muted-foreground",children:[e.jsxs($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 Vcr({taskId:s,people:t}){const{data:n=[]}=Ecr(s),r=Tcr(),[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(Ls,{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 kEt={title:"",description:"",category:"general",status:"todo",priority:"medium",due_date:null,assignee_user_id:null};function Hcr({open:s,onOpenChange:t,task:n,initial:r,people:a,onSave:i,saving:l}){const[o,c]=j.useState(kEt);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}:{...kEt,...r||{}})},[s,n,r]);const d=u=>c(h=>({...h,...u}));return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-h-[90vh] max-w-lg overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:n?"Edit task":"New task"}),e.jsx(Pr,{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(Ls,{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:Fos.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(jcr).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(aQe).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(Vcr,{taskId:n.id,people:a})]}),e.jsxs(Sr,{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 Gcr=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];function Wcr({brokerageId:s}){const{data:t}=Mcr(s),n=Pcr(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(Gn,{children:"Off by default. Turn it on and you alone get a weekly rundown of what is open, due and overdue."})]}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4 rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"digest-email",children:"Email me the weekly summary"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Sent once a week to your account email."})]}),e.jsx(Sn,{id:"digest-email",checked:r,onCheckedChange:a})]}),e.jsxs("div",{className:"flex items-center justify-between gap-4 rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"digest-push",children:"Send me a phone notification"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Same summary, delivered as a push alert."})]}),e.jsx(Sn,{id:"digest-push",checked:i,onCheckedChange:l})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Send day"}),e.jsxs(ms,{value:o,onValueChange:c,disabled:!r&&!i,children:[e.jsx(us,{className:"w-[200px]",children:e.jsx(fs,{})}),e.jsx(hs,{children:Gcr.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 Kcr=()=>{const{user:s,rolesLoading:t,isBrokerageManager:n,isAdmin:r,brokerageId:a,managedBrokerages:i,selectedBrokerageId:l,setSelectedBrokerageId:o}=bs(),c=Xn(),{data:d=[],isLoading:u}=Att(),[h,m]=j.useState(!1),f=d.length>0,g=n||r,x=j.useMemo(()=>{var ve;return l||(i.length>0?i[0].id:null)||((ve=d[0])==null?void 0:ve.brokerage_id)||a},[l,i,d,a]);j.useEffect(()=>{if(!(!s||u||t)){if(!g&&!f){c("/dashboard");return}!l&&i.length>0&&o(i[0].id),m(!0)}},[s,u,t,g,f,c,i,l,o]);const{data:y=[],isLoading:v}=Ett(x),{data:b=[]}=Ros(x),{data:w=[]}=Dos(x),{data:S=[]}=PXt(x),{data:A=[]}=_cr(x),{data:E=[]}=wcr(x),{data:I=[],isLoading:P}=Ncr(x),R=kcr(x),D=Scr(x),O=Ccr(x),U=Acr(x),[W,V]=j.useState(!1),[G,Y]=j.useState(null),[X,ae]=j.useState(null),le=j.useMemo(()=>S.map(ve=>({id:ve.agentId,name:ve.name})),[S]),ne=ve=>{var Ee;return ve?((Ee=le.find(Se=>Se.id===ve))==null?void 0:Ee.name)??null:null},te=j.useMemo(()=>Dcr({complianceDeals:y,disbursements:b,agentRecords:w,renewalAgents:S.map(ve=>({agentId:ve.agentId,name:ve.name,avatarUrl:ve.avatarUrl})),roster:S.map(ve=>({agentId:ve.agentId,name:ve.name,avatarUrl:ve.avatarUrl,overdue:ve.overdue,needsReview:ve.needsReview})),followUps:A,helpRequests:E,tasks:I,nameFor:ne}),[y,b,w,S,A,E,I]),J=j.useMemo(()=>y.filter(ve=>ve.target_close_date).map(ve=>({id:ve.deal_id,label:ve.property_address||ve.deal_name,date:ve.target_close_date})),[y]),ce=()=>{Y(null),ae(null),V(!0)},_e=ve=>{Y(null),ae(ve),V(!0)},he=ve=>{Y(ve),ae(null),V(!0)},ue=ve=>U.mutate({sourceType:ve.sourceType,sourceId:ve.sourceId,title:ve.title,category:ve.category});return h?e.jsx(Vs,{title:"Operations",description:"Everything that needs a decision today, plus your office task board and calendar",children:e.jsxs("div",{className:"space-y-6",children:[i.length>1&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Managing:"}),e.jsxs(ms,{value:l||"",onValueChange:o,children:[e.jsxs(us,{className:"w-[280px]",children:[e.jsx(ji,{className:"mr-2 h-4 w-4"}),e.jsx(fs,{placeholder:"Select brokerage"})]}),e.jsx(hs,{children:i.map(ve=>e.jsx(Ge,{value:ve.id,children:ve.name},ve.id))})]})]}),x?e.jsxs(ha,{defaultValue:"today",className:"space-y-4",children:[e.jsx("div",{className:"overflow-x-auto pb-1",children:e.jsxs(ma,{className:"grid h-auto min-w-[460px] grid-cols-4",children:[e.jsx(Zt,{value:"today",children:"Today"}),e.jsx(Zt,{value:"tasks",children:"Task board"}),e.jsx(Zt,{value:"calendar",children:"Calendar"}),e.jsx(Zt,{value:"notifications",children:"Notifications"})]})}),e.jsx(Xt,{value:"today",children:e.jsx(zcr,{items:te,loading:v,onDismiss:ue,onTrack:_e})}),e.jsx(Xt,{value:"tasks",children:e.jsx($cr,{tasks:I,people:le,loading:P,onNew:ce,onEdit:he,onStatus:(ve,Ee)=>D.mutate({id:ve.id,status:Ee}),onDelete:ve=>O.mutate(ve.id)})}),e.jsx(Xt,{value:"calendar",children:e.jsx(qcr,{items:te,tasks:I,closings:J})}),e.jsx(Xt,{value:"notifications",children:e.jsx(Wcr,{brokerageId:x})})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(ji,{className:"mb-4 h-12 w-12 text-muted-foreground"}),e.jsx("h2",{className:"mb-1 text-xl font-semibold",children:"No Brokerage Assigned"}),e.jsx("p",{className:"text-muted-foreground",children:"You don't have any brokerages to manage."})]}),e.jsx(Hcr,{open:W,onOpenChange:V,task:G,initial:X,people:le,saving:R.isPending,onSave:ve=>R.mutate(ve,{onSuccess:()=>V(!1)})})]})}):null},SEt="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 pUe(s,t){return t?`https://${t}`:s?`https://${s}.thelocalmove.com`:null}function $os(){const{user:s,isAdmin:t,isBrokerageManager:n,managedBrokerages:r,brokerageId:a,selectedBrokerageId:i}=bs(),{data:l=[]}=Mae(),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(SEt).eq("agent_id",s.id).order("created_at",{ascending:!0}),d.length||u.length?q.from("lead_sites").select(SEt).or([d.length?`brokerage_id.in.(${d.join(",")})`:"",u.length?`team_id.in.(${u.join(",")})`:""].filter(Boolean).join(",")):Promise.resolve({data:[],error:null})]);if(f.error)throw f.error;if(g.error)throw g.error;return{own:(f.data||[]).filter(x=>(x.owner_type||"agent")==="agent"),org:g.data||[]}}}),m=j.useMemo(()=>{var v,b,w;const f=((v=h.data)==null?void 0:v.own)||[],g=((b=h.data)==null?void 0:b.org)||[],x=[],y=f.find(S=>S.is_active)||f[0]||null;y?x.push({kind:"agent",id:y.id,ownerId:null,name:y.site_title||"My website",kindLabel:"My agent site",slug:y.subdomain_slug,customDomain:y.custom_domain,isActive:!!y.is_active,logoUrl:null,brandColor:y.brand_color,editPath:`/my-website/${y.id}/edit`,publicUrl:pUe(y.subdomain_slug,y.custom_domain),exists:!0}):x.push({kind:"agent",id:null,ownerId:null,name:"My agent site",kindLabel:"My agent site",slug:null,customDomain:null,isActive:!1,logoUrl:null,brandColor:null,editPath:"/need-a-website",publicUrl:null,exists:!1});for(const S of c){const 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:pUe((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:pUe((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 Ycr={agent:dl,brokerage:ji,team:Yn};function Zcr({site:s}){const t=Xn(),n=Ycr[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(Ie,{className:"flex flex-col gap-5 p-6 sm:flex-row sm:items-center",children:[e.jsx("div",{className:"flex h-16 w-16 shrink-0 items-center justify-center overflow-hidden rounded-xl",style:{backgroundColor:s.brandColor||"hsl(var(--muted))"},children:s.logoUrl?e.jsx("img",{src:s.logoUrl,alt:"",className:"max-h-full max-w-full object-contain"}):e.jsx(n,{className:`h-7 w-7 ${s.brandColor?"text-white":"text-muted-foreground"}`})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"truncate text-lg font-semibold",children:s.name}),s.exists?s.isActive?e.jsx($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(Fr,{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(dn,{className:"mr-2 h-4 w-4"})," Create site"]})})]})]})})}function Xcr(){const{websites:s,isLoading:t}=$os();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(Zcr,{site:n},`${n.kind}-${n.ownerId||"me"}`)),e.jsxs("p",{className:"pt-2 text-center text-sm text-muted-foreground",children:["Looking for lead magnets, pop-ups and other add-ons?"," ",e.jsx(wr,{to:"/website-apps",className:"underline",children:"Website Apps"})]})]})})})}const CEt={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 fCr(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=CEt[n]||CEt.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 Uos=[{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 qos(s){return(s==null?void 0:s.orgProfile)||{}}function pCr(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 gCr(s){var n;if((s==null?void 0:s.ownerType)!=="team")return null;const t=(n=qos(s).affiliation)==null?void 0:n.trim();return t||null}function xCr(s){const t=qos(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 Qcr=10*1024*1024;function gUe({label:s,hint:t,value:n,onChange:r,slot:a,siteId:i,dark:l,className:o}){const c=j.useRef(null),[d,u]=j.useState(!1),[h,m]=j.useState(!1),f=async g=>{if(!g.type.startsWith("image/")){re.error("Please choose an image file");return}if(g.size>Qcr){re.error("Image must be under 10MB");return}u(!0);try{const x=(g.name.split(".").pop()||"png").toLowerCase(),y=`org-sites/${i}/${a}-${Date.now()}.${x}`,{error:v}=await q.storage.from("agent-uploads").upload(y,g,{upsert:!0,contentType:g.type});if(v)throw v;const{data:b}=q.storage.from("agent-uploads").getPublicUrl(y);r(b.publicUrl),re.success(`${s} uploaded`)}catch(x){re.error(x.message||"Upload failed")}finally{u(!1),c.current&&(c.current.value="")}};return e.jsxs("div",{className:o,children:[e.jsx(ee,{className:"text-sm font-medium",children:s}),t&&e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:t}),e.jsxs("div",{onDragOver:g=>{g.preventDefault(),m(!0)},onDragLeave:()=>m(!1),onDrop:g=>{var y;g.preventDefault(),m(!1);const x=(y=g.dataTransfer.files)==null?void 0:y[0];x&&f(x)},onClick:()=>{var g;return!d&&((g=c.current)==null?void 0:g.click())},className:`mt-2 flex cursor-pointer items-center gap-4 rounded-lg border-2 border-dashed p-4 transition-colors ${h?"border-primary bg-primary/5":"border-muted-foreground/25 hover:border-muted-foreground/50"}`,children:[e.jsx("div",{className:`flex h-20 w-28 shrink-0 items-center justify-center overflow-hidden rounded-md ${l?"bg-slate-900":"bg-muted"}`,children:n?e.jsx("img",{src:n,alt:s,className:"max-h-full max-w-full object-contain"}):e.jsx(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 y;const x=(y=g.target.files)==null?void 0:y[0];x&&f(x)}}),e.jsxs("div",{className:"mt-2 flex items-center gap-2",children:[e.jsx(pe,{value:n||"",onChange:g=>r(g.target.value||null),placeholder:"…or paste an image URL",className:"h-9 text-xs"}),n&&e.jsx($,{type:"button",variant:"ghost",size:"icon",className:"h-9 w-9 shrink-0",onClick:()=>r(null),children:e.jsx(Hn,{className:"h-4 w-4"})})]})]})}const Jcr="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 edr(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(Jcr).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 tdr(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 sdr(s){const t=Wt();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]}),re.success(n?`${n} agent${n===1?"":"s"} added to the roster.`:"Roster is already up to date.")},onError:n=>re.error(n.message||"Could not refresh the roster.")})}function ndr(s){const t=Wt();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=>re.error(n.message||"Could not save that change.")})}function rdr(s){const t=Wt();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"]}),re.success("Saved.")},onError:n=>re.error(n.message||"Could not save the website.")})}function ahe(s){return s.toLowerCase().trim().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,40)}function qlt({brokerageId:s,teamId:t,orgLabel:n="brokerage"}){const{data:r,isLoading:a,refetch:i}=edr({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(idr,{site:r,orgLabel:n}):e.jsx(adr,{brokerageId:s,teamId:t,orgLabel:n,onCreated:()=>i()})}function adr({brokerageId:s,teamId:t,orgLabel:n,onCreated:r}){const{user:a}=bs(),[i,l]=j.useState(""),[o,c]=j.useState(""),[d,u]=j.useState("editorial_boutique"),[h,m]=j.useState(!1),[f,g]=j.useState(null);j.useEffect(()=>{let y=!1;return(async()=>{if(t){const{data:S}=await q.from("teams").select("name, description, avatar_url, brokerage_id").eq("id",t).maybeSingle();if(y||!S)return;const A=S.name||"";A&&(l(P=>P||A),c(P=>P||ahe(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(y)return;g({logo:S.avatar_url||null,primary:(I==null?void 0:I.primary_color)||null,accent:(I==null?void 0:I.accent_color)||null,legalName:(I==null?void 0:I.legal_name)||null,license:(I==null?void 0:I.license_number)||null,about:S.description||null,affiliation:E});return}if(!s)return;const[{data:v},{data:b}]=await Promise.all([q.from("brokerage_brand_profiles").select("logo_url, primary_color, accent_color, legal_name, license_number").eq("brokerage_id",s).maybeSingle(),q.from("brokerages").select("name").eq("id",s).maybeSingle()]);if(y)return;const w=(b==null?void 0:b.name)||"";w&&(l(S=>S||w),c(S=>S||ahe(w))),g({logo:(v==null?void 0:v.logo_url)||null,primary:(v==null?void 0:v.primary_color)||null,accent:(v==null?void 0:v.accent_color)||null,legalName:(v==null?void 0:v.legal_name)||null,license:(v==null?void 0:v.license_number)||null,about:null,affiliation:null})})(),()=>{y=!0}},[s,t]);const x=async()=>{if(!a||!s&&!t)return;if(!i.trim()||!o.trim()){re.error(`Add a ${n} name and web address.`);return}m(!0);const{error:y}=await q.from("lead_sites").insert({agent_id:a.id,brokerage_id:t?null:s,team_id:t||null,owner_type:t?"team":"brokerage",org_tier:"essential",org_name:i.trim(),site_title:i.trim(),subdomain_slug:o.trim(),is_active:!1,org_logo_url:(f==null?void 0:f.logo)||null,brand_color:(f==null?void 0:f.primary)||"#12222e",accent_color:(f==null?void 0:f.accent)||"#c9a96e",brokerage_legal_name:(f==null?void 0:f.legalName)||null,brokerage_license_number:(f==null?void 0:f.license)||null,org_profile:{offices:[{name:t?`${i.trim()} — Office`:`${i.trim()} — Main Office`}],...f!=null&&f.about?{about:f.about}:{},...f!=null&&f.affiliation?{affiliation:f.affiliation}:{}},theme_config:{orgPreset:d}});if(m(!1),y){re.error(y.message.includes("duplicate")?"That web address is taken — try another.":y.message);return}re.success("Website created as a private preview."),r()};return e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(dl,{className:"h-5 w-5"})," Create your ",n," website"]}),e.jsxs(Gn,{children:["One site for your whole ",n," — every agent's profile, every listing, city pages, blog, recruiting page and lead capture straight into LevelUp. It starts as a private preview that only you can see."]})]}),e.jsxs(Ie,{className:"space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:n==="team"?"Team name":"Company name"}),e.jsx(pe,{value:i,onChange:y=>{l(y.target.value),o||c(ahe(y.target.value))},placeholder:n==="team"?"The Bishop Group":"RE/MAX Executives"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Web address"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pe,{value:o,onChange:y=>c(ahe(y.target.value)),placeholder:"bishop-group"}),e.jsx("span",{className:"whitespace-nowrap text-sm text-muted-foreground",children:".thelocalmove.com"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"You can point your own domain at it later."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Design"}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:Uos.map(y=>e.jsxs("button",{type:"button",onClick:()=>u(y.key),className:`rounded-lg border p-4 text-left transition-colors ${d===y.key?"border-primary bg-primary/5":"border-border hover:border-primary/40"}`,children:[e.jsx("p",{className:"font-medium",children:y.label}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:y.description})]},y.key))})]}),(f==null?void 0:f.logo)&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"We'll start the site with your company logo and brand colors — you can change them anytime."}),e.jsx($,{onClick:x,disabled:h,className:"w-full",children:h?"Creating…":"Create website"})]})]})}function idr({site:s,orgLabel:t}){var X;const{isAdmin:n}=bs(),r=rdr(s.id),{data:a=[],isLoading:i}=tdr(s.id),l=sdr(s.id),o=ndr(s.id),[c,d]=j.useState(s.site_title||""),[u,h]=j.useState(s.site_tagline||""),[m,f]=j.useState(s.org_name||""),[g,x]=j.useState(s.org_logo_url||null),[y,v]=j.useState(s.org_logo_dark_url||null),[b,w]=j.useState(s.org_profile||{}),S=(ae,le)=>w(ne=>({...ne,[ae]:le})),A=b.offices||[],E=(ae,le)=>S("offices",A.map((ne,te)=>te===ae?{...ne,...le}:ne)),I=b.stats||[],[P,R]=j.useState(s.brand_color||"#12222e"),[D,O]=j.useState(s.accent_color||"#c9a96e"),[U,W]=j.useState(s.custom_domain||""),V=((X=s.theme_config)==null?void 0:X.orgPreset)||"editorial_boutique",G=s.custom_domain?`https://${s.custom_domain}`:`https://${s.subdomain_slug}.thelocalmove.com`,Y=`${G}?previewSlug=${s.subdomain_slug}`;return e.jsxs("div",{className:"space-y-6",children:[e.jsx(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(Gn,{children:G})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:s.is_active?G:Y,target:"_blank",rel:"noreferrer",children:[e.jsx(Fr,{className:"mr-2 h-4 w-4"})," Preview"]})}),e.jsxs("div",{className:"flex items-center gap-2 rounded-md border px-3 py-2",children:[e.jsx("span",{className:"text-sm",children:"Published"}),e.jsx(Sn,{checked:s.is_active,onCheckedChange:ae=>r.mutate({is_active:ae})})]})]})]})}),e.jsxs(ha,{defaultValue:"brand",children:[e.jsxs(ma,{className:"h-auto flex-wrap justify-start gap-1",children:[e.jsx(Zt,{value:"brand",children:"Identity"}),e.jsx(Zt,{value:"story",children:"Story"}),e.jsx(Zt,{value:"offices",children:"Offices"}),e.jsx(Zt,{value:"social",children:"Social"}),e.jsxs(Zt,{value:"agents",children:["Agents (",a.length,")"]}),e.jsx(Zt,{value:"domain",children:"Address"}),e.jsx(Zt,{value:"plan",children:"Plan"})]}),e.jsx(Xt,{value:"brand",className:"mt-6",children:e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{children:"Brand & content"}),e.jsx(Gn,{children:"The look adapts to your colors, logo and chosen design."})]}),e.jsxs(Ie,{className:"space-y-5",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:t==="team"?"Team name":"Company name"}),e.jsx(pe,{value:m,onChange:ae=>f(ae.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Headline"}),e.jsx(pe,{value:c,onChange:ae=>d(ae.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Tagline"}),e.jsx(Ls,{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(gUe,{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(gUe,{label:"Logo for dark backgrounds",hint:"Optional — used in the footer and dark headers.",value:y,onChange:v,slot:"logo-dark",siteId:s.id,dark:!0})]}),e.jsx(gUe,{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:Uos.map(ae=>e.jsxs("button",{type:"button",onClick:()=>r.mutate({theme_config:{...s.theme_config||{},orgPreset:ae.key}}),className:`rounded-lg border p-4 text-left transition-colors ${V===ae.key?"border-primary bg-primary/5":"border-border hover:border-primary/40"}`,children:[e.jsx("p",{className:"font-medium",children:ae.label}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:ae.description})]},ae.key))})]}),e.jsx($,{onClick:()=>r.mutate({org_name:m||null,site_title:c||null,site_tagline:u||null,org_logo_url:g||null,org_logo_dark_url:y||null,org_profile:b,brand_color:P,accent_color:D}),disabled:r.isPending,children:r.isPending?"Saving…":"Save changes"})]})]})}),e.jsx(Xt,{value:"story",className:"mt-6",children:e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{children:"Your story"}),e.jsxs(Gn,{children:["This is your ",t," speaking — not any individual agent. It fills the About page and the homepage numbers."]})]}),e.jsxs(Ie,{className:"space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{children:["About ",t==="team"?"the team":"the company"]}),e.jsx(Ls,{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(Ls,{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:ne=>S("stats",I.map((te,J)=>J===le?{...te,value:ne.target.value}:te)),placeholder:"$412M",className:"max-w-[140px]"}),e.jsx(pe,{value:ae.label,onChange:ne=>S("stats",I.map((te,J)=>J===le?{...te,label:ne.target.value}:te)),placeholder:"Sold last year"}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>S("stats",I.filter((ne,te)=>te!==le)),children:e.jsx(Hn,{className:"h-4 w-4"})})]},le)),I.length<4&&e.jsxs($,{variant:"outline",size:"sm",onClick:()=>S("stats",[...I,{label:"",value:""}]),children:[e.jsx(dn,{className:"mr-2 h-4 w-4"})," Add a number"]})]}),e.jsx($,{onClick:()=>r.mutate({org_profile:b}),disabled:r.isPending,children:r.isPending?"Saving…":"Save story"})]})]})}),e.jsx(Xt,{value:"offices",className:"mt-6",children:e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{children:"Offices"}),e.jsx(Gn,{children:"These appear on your contact page and in the footer. The first one is your main office."})]}),e.jsxs(Ie,{className:"space-y-5",children:[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((ne,te)=>te!==le)),children:e.jsx(Hn,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsx(pe,{value:ae.name||"",onChange:ne=>E(le,{name:ne.target.value}),placeholder:"Office name"}),e.jsx(pe,{value:ae.phone||"",onChange:ne=>E(le,{phone:ne.target.value}),placeholder:"Phone"}),e.jsx(pe,{value:ae.email||"",onChange:ne=>E(le,{email:ne.target.value}),placeholder:"Email"}),e.jsx(pe,{value:ae.hours||"",onChange:ne=>E(le,{hours:ne.target.value}),placeholder:"Mon–Fri 9–5"}),e.jsx(pe,{value:ae.address||"",onChange:ne=>E(le,{address:ne.target.value}),placeholder:"Street address"}),e.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[e.jsx(pe,{value:ae.city||"",onChange:ne=>E(le,{city:ne.target.value}),placeholder:"City"}),e.jsx(pe,{value:ae.state||"",onChange:ne=>E(le,{state:ne.target.value}),placeholder:"ST"}),e.jsx(pe,{value:ae.zip||"",onChange:ne=>E(le,{zip:ne.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(dn,{className:"mr-2 h-4 w-4"})," Add an office"]}),e.jsx($,{onClick:()=>r.mutate({org_profile:b}),disabled:r.isPending,children:r.isPending?"Saving…":"Save offices"})]})]})]})}),e.jsx(Xt,{value:"social",className:"mt-6",children:e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{children:"Social profiles"}),e.jsxs(Gn,{children:["Your ",t," accounts — linked in the footer and on the contact page."]})]}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Facebook"}),e.jsx(pe,{value:b.facebookUrl||"",onChange:ae=>S("facebookUrl",ae.target.value),placeholder:"https://facebook.com/…"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Instagram"}),e.jsx(pe,{value:b.instagramUrl||"",onChange:ae=>S("instagramUrl",ae.target.value),placeholder:"https://instagram.com/…"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"LinkedIn"}),e.jsx(pe,{value:b.linkedinUrl||"",onChange:ae=>S("linkedinUrl",ae.target.value),placeholder:"https://linkedin.com/company/…"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"YouTube"}),e.jsx(pe,{value:b.youtubeUrl||"",onChange:ae=>S("youtubeUrl",ae.target.value),placeholder:"https://youtube.com/@…"})]})]}),e.jsx($,{onClick:()=>r.mutate({org_profile:b}),disabled:r.isPending,children:r.isPending?"Saving…":"Save social links"})]})]})}),e.jsx(Xt,{value:"agents",className:"mt-6",children:e.jsxs(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(Gn,{children:"Everyone here gets a profile page on your site with their own listings."})]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>l.mutate(),disabled:l.isPending,children:[e.jsx(ro,{className:`mr-2 h-4 w-4 ${l.isPending?"animate-spin":""}`})," Refresh from LevelUp"]})]}),e.jsx(Ie,{className:"space-y-3",children:i?e.jsx("p",{className:"py-8 text-center text-sm text-muted-foreground",children:"Loading roster…"}):a.length===0?e.jsx("p",{className:"py-8 text-center text-sm text-muted-foreground",children:"No agents yet — click “Refresh from LevelUp” to pull in your agents."}):a.map(ae=>{var le,ne,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:((ne=ae.profile)==null?void 0:ne.name)||"Unnamed agent"}),e.jsx("p",{className:"truncate text-xs text-muted-foreground",children:ae.headline||((te=ae.profile)==null?void 0:te.title)||((J=ae.profile)==null?void 0:J.email)})]}),e.jsxs($,{variant:ae.is_featured?"default":"outline",size:"sm",onClick:()=>o.mutate({id:ae.id,patch:{is_featured:!ae.is_featured}}),children:[e.jsx(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(Ca,{className:"mr-2 h-4 w-4"}):e.jsx($g,{className:"mr-2 h-4 w-4"}),ae.is_visible?"Shown":"Hidden"]})]},ae.id)})})]})}),e.jsx(Xt,{value:"domain",className:"mt-6",children:e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{children:"Web address"}),e.jsx(Gn,{children:"Use the free address or point your own domain at the site."})]}),e.jsxs(Ie,{className:"space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Free address"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[s.subdomain_slug,".thelocalmove.com"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Your own domain"}),e.jsx(pe,{value:U,onChange:ae=>W(ae.target.value.trim().toLowerCase()),placeholder:"www.yourcompany.com"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Add the domain here, then point its DNS to LevelUp. Our team confirms it once the DNS is in place."})]}),e.jsx($,{onClick:()=>r.mutate({custom_domain:U||null}),disabled:r.isPending,children:r.isPending?"Saving…":"Save address"})]})]})}),e.jsxs(Xt,{value:"plan",className:"mt-6 space-y-5",children:[e.jsxs("div",{className:"grid gap-5 md:grid-cols-2",children:[e.jsxs(je,{className:s.org_tier==="essential"?"border-primary":"",children:[e.jsxs(St,{children:[e.jsx(Et,{children:"Essential"}),e.jsx(Gn,{children:"Everything except live MLS search."})]}),e.jsxs(Ie,{className:"space-y-2 text-sm text-muted-foreground",children:[e.jsx("p",{children:"• Company homepage, about and contact"}),e.jsx("p",{children:"• Full agent roster with individual profile pages"}),e.jsx("p",{children:"• Every agent's Listing Exchange listings"}),e.jsx("p",{children:"• Blog, city pages, SEO and lead capture"}),e.jsx("p",{children:"• Recruiting page tied to your pipeline"})]})]}),e.jsxs(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(Nn,{className:"h-4 w-4"})," Pro"]}),e.jsx(Gn,{children:"Everything in Essential, plus live MLS."})]}),e.jsxs(Ie,{className:"space-y-2 text-sm text-muted-foreground",children:[e.jsx("p",{children:"• Full IDX property search"}),e.jsx("p",{children:"• Office listing feed and sold comps"}),e.jsx("p",{children:"• Saved searches and buyer alerts"}),e.jsx("p",{children:"• Market reports and CMA tools"}),e.jsx("p",{className:"pt-2 text-foreground",children:s.org_tier==="pro"?"Your site is on Pro.":"Ask your LevelUp rep to switch this site to Pro — nothing gets rebuilt."})]})]})]}),n&&e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsx(Et,{className:"text-base",children:"Admin: plan control"}),e.jsx(Gn,{children:"Switch this site between Essential and Pro."})]}),e.jsxs(Ie,{className:"flex items-center gap-3",children:[e.jsx($,{variant:s.org_tier==="essential"?"default":"outline",size:"sm",onClick:()=>r.mutate({org_tier:"essential"}),children:"Essential"}),e.jsx($,{variant:s.org_tier==="pro"?"default":"outline",size:"sm",onClick:()=>r.mutate({org_tier:"pro"}),children:"Pro (IDX)"})]})]})]})]})]})}const AEt={agent:dl,brokerage:ji,team:Yn};function Vos({current:s,className:t}){const n=Xn(),{websites:r}=$os();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=AEt[(a==null?void 0:a.kind)||"agent"];return e.jsx("div",{className:t,children:e.jsxs($u,{children:[e.jsx(Uu,{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(Sw,{className:"h-4 w-4 shrink-0 text-muted-foreground"})]})}),e.jsxs(Au,{align:"start",className:"w-[320px]",children:[e.jsx(jL,{children:"Switch website"}),r.map(l=>{const o=AEt[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(ca,{className:"h-4 w-4 shrink-0"})]},`${l.kind}-${l.ownerId||"me"}`)}),e.jsx(I0,{}),e.jsxs(ja,{onSelect:()=>n("/websites"),className:"gap-3",children:[e.jsx(Qf,{className:"h-4 w-4 text-muted-foreground"})," See all my websites"]})]})]})})}function odr(){const s=Xn(),[t]=gc(),{data:n=[],isLoading:r}=Mae(),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(Vos,{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(qlt,{teamId:l.teamId,orgLabel:"team"}):e.jsx(je,{children:e.jsx(Ie,{className:"p-8 text-center text-sm text-muted-foreground",children:"Only team leaders can build a team website."})})]})})}function ldr(){const{user:s,isAdmin:t,isBrokerageManager:n,rolesLoading:r,brokerageId:a,managedBrokerages:i,selectedBrokerageId:l}=bs(),o=Xn(),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(Vos,{current:{kind:"brokerage",ownerId:c}}),e.jsx(qlt,{brokerageId:c,orgLabel:"brokerage"})]})})}const EEt={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 cdr({open:s,onOpenChange:t,plan:n,onSave:r,saving:a}){const[i,l]=j.useState(EEt);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}:EEt)},[s,n]);const o=(d,u)=>l(h=>({...h,[d]:u})),c=()=>{r({id:n==null?void 0:n.id,name:i.name.trim(),description:i.description.trim()||null,agent_split_pct:parseFloat(i.agent_split_pct)||0,team_split_pct:i.team_split_pct?Math.min(100,Math.max(0,parseFloat(i.team_split_pct)||0)):0,cap_amount:i.cap_amount?parseFloat(i.cap_amount):null,monthly_fee:i.monthly_fee?parseFloat(i.monthly_fee):0,transaction_fee:i.transaction_fee?parseFloat(i.transaction_fee):0,franchise_fee_pct:i.franchise_fee_pct?parseFloat(i.franchise_fee_pct):0,referral_fee_pct:i.referral_fee_pct?parseFloat(i.referral_fee_pct):null,commission_calc_method:i.commission_calc_method,is_active:i.is_active})};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-h-[90vh] overflow-y-auto sm:max-w-lg",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:n?"Edit commission plan":"New commission plan"}),e.jsx(Pr,{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(Ls,{id:"plan-desc",value:i.description,onChange:d=>o("description",d.target.value),rows:2})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"plan-split",children:"Agent split %"}),e.jsx(pe,{id:"plan-split",type:"number",min:"0",max:"100",step:"0.5",value:i.agent_split_pct,onChange:d=>o("agent_split_pct",d.target.value)}),e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Brokerage keeps ",Math.max(0,100-(parseFloat(i.agent_split_pct)||0)),"%"]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"plan-cap",children:"Annual cap ($)"}),e.jsx(pe,{id:"plan-cap",type:"number",min:"0",value:i.cap_amount,onChange:d=>o("cap_amount",d.target.value),placeholder:"No cap"}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Total brokerage takes before 100%"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"plan-monthly",children:"Monthly desk fee ($)"}),e.jsx(pe,{id:"plan-monthly",type:"number",min:"0",value:i.monthly_fee,onChange:d=>o("monthly_fee",d.target.value),placeholder:"0"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"plan-txn",children:"Per-transaction fee ($)"}),e.jsx(pe,{id:"plan-txn",type:"number",min:"0",value:i.transaction_fee,onChange:d=>o("transaction_fee",d.target.value),placeholder:"0"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"plan-franchise",children:"Franchise fee %"}),e.jsx(pe,{id:"plan-franchise",type:"number",min:"0",step:"0.1",value:i.franchise_fee_pct,onChange:d=>o("franchise_fee_pct",d.target.value),placeholder:"0"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"plan-referral",children:"Default referral fee %"}),e.jsx(pe,{id:"plan-referral",type:"number",min:"0",step:"0.1",value:i.referral_fee_pct,onChange:d=>o("referral_fee_pct",d.target.value),placeholder:"Optional"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"plan-team",children:"Team split %"}),e.jsx(pe,{id:"plan-team",type:"number",min:"0",max:"100",step:"0.5",value:i.team_split_pct,onChange:d=>o("team_split_pct",d.target.value),placeholder:"0"}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Only applies to agents on a team"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Calculation method"}),e.jsxs(ms,{value:i.commission_calc_method,onValueChange:d=>o("commission_calc_method",d),children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"standard",children:"Standard — all fees off gross commission"}),e.jsx(Ge,{value:"referral_first",children:"Referral first — split applies after referral fee"})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Active"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Only active plans can be assigned to agents"})]}),e.jsx(Sn,{checked:i.is_active,onCheckedChange:d=>o("is_active",d)})]})]}),e.jsxs(Sr,{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 TEt=()=>new Date().toISOString().slice(0,10);function ddr({open:s,onOpenChange:t,agent:n,plans:r,onAssign:a,saving:i}){const[l,o]=j.useState(""),[c,d]=j.useState(TEt()),[u,h]=j.useState(""),[m,f]=j.useState("");return j.useEffect(()=>{var g,x,y,v,b;s&&(o(((g=n==null?void 0:n.plan)==null?void 0:g.id)||((x=r[0])==null?void 0:x.id)||""),d(((y=n==null?void 0:n.assignment)==null?void 0:y.start_date)||TEt()),h(((v=n==null?void 0:n.assignment)==null?void 0:v.anniversary_date)||""),f(((b=n==null?void 0:n.assignment)==null?void 0:b.notes)||""))},[s,n,r]),e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{children:[n!=null&&n.assignment?"Change plan":"Assign plan"," — ",n==null?void 0:n.name]}),e.jsx(Pr,{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(Ls,{id:"ap-notes",rows:2,value:m,onChange:g=>f(g.target.value),placeholder:"e.g. Negotiated 80/20 for first year"})]})]}),e.jsxs(Sr,{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 dFe=q,jAe={monthly_fee:"Monthly desk fee",transaction_fee:"Transaction fee",adjustment:"Adjustment",payment:"Payment received"};function udr(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 dFe.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 hdr(s){const t=Wt(),{user:n}=bs();return mt({mutationFn:async r=>{const{error:a}=await dFe.from("agent_fee_ledger").insert({agent_user_id:r.agent_user_id,brokerage_id:s,entry_type:r.entry_type,amount:r.amount,entry_date:r.entry_date,note:r.note||null,created_by:(n==null?void 0:n.id)??null});if(a)throw a},onSuccess:()=>{t.invalidateQueries({queryKey:["fee-ledger",s]}),re.success("Ledger entry added")},onError:r=>re.error(r.message||"Could not add entry")})}function mdr(s){const t=Wt();return mt({mutationFn:async n=>{const{error:r}=await dFe.from("agent_fee_ledger").delete().eq("id",n);if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["fee-ledger",s]}),re.success("Entry removed")},onError:n=>re.error(n.message||"Could not remove entry")})}function fdr(s){const t=Wt(),{user:n}=bs();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 dFe.from("agent_fee_ledger").insert(l);if(o)throw o;return l.length},onSuccess:r=>{t.invalidateQueries({queryKey:["fee-ledger",s]}),re.success(r?`Posted ${r} desk fee${r===1?"":"s"}`:"All desk fees already posted")},onError:r=>re.error(r.message||"Could not post desk fees")})}const pdr=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function Hos(s,t){return s.filter(n=>{const r=PC(n.actual_close_date);return!!r&&r.y===t})}function Gos(s,t,n,r=[]){const a=Hos(s,n),i=Array.from({length:12},(c,d)=>({key:`${n}-${String(d+1).padStart(2,"0")}`,label:pdr[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=CW(c),u=AW(c),h=Ene(c),m=Math.max(0,u-h);o.volume+=d,o.gci+=u,o.companyDollar+=h,o.agentShare+=m;const f=PC(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 gdr=[64,110,113],xUe=[42,76,100],IM=[110,118,125],wj=s=>`$${Math.round(s).toLocaleString("en-US")}`,MEt=s=>{const t=PC(s);return t?`${String(t.m).padStart(2,"0")}/${String(t.d).padStart(2,"0")}/${String(t.y).slice(2)}`:"—"},PEt=(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 xdr(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(...xUe),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(...IM);const l=[s.agentEmail,s.planName?`Plan: ${s.planName}`:null,s.planSummary].filter(Boolean).join(" · ");l&&t.text(l,a,i+14),i+=40;const o=s.deals.reduce((v,b)=>{const w=AW(b),S=Ene(b);return v.volume+=CW(b),v.gci+=w,v.company+=S,v.agent+=Math.max(0,w-S),v},{volume:0,gci:0,company:0,agent:0}),c=s.ledger.filter(v=>v.entry_type!=="payment").reduce((v,b)=>v+(Number(b.amount)||0),0),d=s.ledger.filter(v=>v.entry_type==="payment").reduce((v,b)=>v+Math.abs(Number(b.amount)||0),0),u=c-d,h=[{label:"Closed sides",value:String(s.deals.length)},{label:"Volume",value:wj(o.volume)},{label:"Gross commission",value:wj(o.gci)},{label:"Agent share",value:wj(o.agent)}],m=(n-a*2-18)/4;if(h.forEach((v,b)=>{const w=a+b*(m+6);t.setDrawColor(224,228,232),t.setFillColor(248,250,250),t.roundedRect(w,i,m,48,6,6,"FD"),t.setFontSize(8),t.setTextColor(...IM),t.text(v.label,w+10,i+17),t.setFontSize(13),t.setFont("helvetica","bold"),t.setTextColor(...xUe),t.text(v.value,w+10,i+36),t.setFont("helvetica","normal")}),i+=72,s.capAmount){const v=Math.min(100,(s.capProgress||0)/s.capAmount*100);t.setFontSize(9),t.setTextColor(...IM),t.text(`Cap progress: ${wj(s.capProgress||0)} of ${wj(s.capAmount)} (${Math.round(v)}%)`,a,i);const b=n-a*2;t.setFillColor(232,236,238),t.roundedRect(a,i+6,b,7,3.5,3.5,"F"),t.setFillColor(...gdr),t.roundedRect(a,i+6,Math.max(2,b*v/100),7,3.5,3.5,"F"),i+=34}const f=v=>{i>r-120&&(t.addPage(),i=60),t.setFont("helvetica","bold"),t.setFontSize(11),t.setTextColor(...xUe),t.text(v,a,i),t.setFont("helvetica","normal"),i+=14},g=()=>{t.setDrawColor(234,238,240),t.line(a,i,n-a,i)};f("Closed transactions");const x=[a,a+62,a+280,a+360,a+440];t.setFontSize(8),t.setTextColor(...IM),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(...IM),t.text("No closed transactions in this period.",a,i),i+=18,t.setTextColor(30,34,38)),s.deals.slice().sort((v,b)=>(v.actual_close_date||"").localeCompare(b.actual_close_date||"")).forEach(v=>{i>r-90&&(t.addPage(),i=60);const b=AW(v),w=Math.max(0,b-Ene(v));t.text(MEt(v.actual_close_date),x[0],i),t.text(PEt(t,v.property_address||v.deal_name||"Transaction",205),x[1],i),t.text(wj(CW(v)),x[2],i,{align:"right"}),t.text(wj(b),x[3],i,{align:"right"}),t.text(wj(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(wj(o.volume),x[2],i,{align:"right"}),t.text(wj(o.gci),x[3],i,{align:"right"}),t.text(wj(o.agent),n-a,i,{align:"right"}),t.setFont("helvetica","normal"),i+=34,f("Fees & payments"),t.setFontSize(8),t.setTextColor(...IM),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(...IM),t.text("No fees or payments recorded.",a,i),i+=18,t.setTextColor(30,34,38)),s.ledger.slice().sort((v,b)=>(v.entry_date||"").localeCompare(b.entry_date||"")).forEach(v=>{i>r-90&&(t.addPage(),i=60);const b=Number(v.amount)||0,w=v.entry_type==="payment",S=jAe[v.entry_type]||v.entry_type;t.text(MEt(v.entry_date),x[0],i),t.text(PEt(t,v.note?`${S} — ${v.note}`:S,330),x[1],i),t.text(`${w?"-":""}${wj(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(wj(u),n-a,i,{align:"right"});const y=t.getNumberOfPages();for(let v=1;v<=y;v++)t.setPage(v),t.setFont("helvetica","normal"),t.setFontSize(8),t.setTextColor(...IM),t.text("Estimated figures based on recorded transactions and plan terms. Not an accounting document.",a,r-28),t.text(`Page ${v} of ${y}`,n-a,r-28,{align:"right"});return t}function ydr(s){const t=xdr(s),n=s.agentName.replace(/[^a-z0-9]+/gi,"-").toLowerCase();t.save(`statement-${n}-${s.year}.pdf`)}const IEt=s=>`$${Math.round(s).toLocaleString()}`;function vdr({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=PC(f.actual_close_date);g&&m.add(g.y)}),Array.from(m).sort((f,g)=>g-f)},[s,i]),d=j.useMemo(()=>Gos(s,t,Number(l),n.map(m=>({agentId:m.agentId,name:m.name,avatarUrl:m.avatarUrl}))),[s,t,n,l]),u=Math.max(1,...d.months.map(m=>m.companyDollar)),h=m=>{var y,v,b;const f=n.find(w=>w.agentId===m),g=d.agents.find(w=>w.userId===m),x=Hos(s,Number(l)).filter(w=>w.owner_user_id===m);ydr({brokerageName:r,agentName:(f==null?void 0:f.name)||(g==null?void 0:g.name)||"Agent",agentEmail:(f==null?void 0:f.email)||null,planName:((y=f==null?void 0:f.plan)==null?void 0:y.name)||null,planSummary:f!=null&&f.plan?`${f.plan.agent_split_pct}/${Math.max(0,100-f.plan.agent_split_pct)} split`:null,year:Number(l),deals:x,ledger:t.filter(w=>w.agent_user_id===m&&(w.entry_date||"").slice(0,4)===l),capAmount:((v=f==null?void 0:f.plan)==null?void 0:v.cap_amount)??null,capProgress:((b=f==null?void 0:f.progress)==null?void 0:b.cap_progress)??null})};return a?e.jsxs("div",{className:"space-y-3",children:[e.jsx(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(Ie,{className:"p-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:m.label}),e.jsx("p",{className:`text-2xl font-bold tabular-nums tracking-tight ${m.accent?"text-teal-600":""}`,children:m.value})]})},m.label))}),e.jsxs(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(Gn,{children:"Brokerage split, franchise fees and transaction fees on closed deals"})]}),e.jsx(Ie,{children:e.jsx("div",{className:"flex h-40 items-end gap-1.5",children:d.months.map(m=>e.jsxs("div",{className:"group flex flex-1 flex-col items-center gap-1",children:[e.jsx("span",{className:"text-[10px] font-medium tabular-nums text-muted-foreground opacity-0 transition group-hover:opacity-100",children: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}: ${IEt(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(Gn,{children:"Download a per-agent statement with closed deals, fees and balance"})]}),e.jsx(Ie,{className:"pt-1",children:d.agents.length===0?e.jsx("p",{className:"py-8 text-center text-sm text-muted-foreground",children:"No closed deals recorded yet."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full min-w-[640px] text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b text-[11px] uppercase tracking-wide text-muted-foreground",children:[e.jsx("th",{className:"py-2 text-left font-medium",children:"Agent"}),e.jsx("th",{className:"py-2 text-right font-medium",children:"Closed"}),e.jsx("th",{className:"py-2 text-right font-medium",children:"Volume"}),e.jsx("th",{className:"py-2 text-right font-medium",children:"GCI"}),e.jsx("th",{className:"py-2 text-right font-medium",children:"Company $"}),e.jsx("th",{className:"py-2 text-right font-medium",children:"Balance"}),e.jsx("th",{className:"py-2"})]})}),e.jsx("tbody",{children:d.agents.map(m=>e.jsxs("tr",{className:"border-b last:border-0 hover:bg-muted/40",children:[e.jsx("td",{className:"py-2.5",children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsxs(Oa,{className:"h-7 w-7",children:[e.jsx(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:IEt(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(o2,{className:"mr-1.5 h-4 w-4"})," Statement"]})})]},m.userId))})]})})})]})]})}const LEt=s=>`$${Math.round(s).toLocaleString()}`,bdr=()=>new Date().toISOString().slice(0,10),_dr=()=>new Date().toISOString().slice(0,7);function wdr({brokerageId:s,ledger:t,roster:n,loading:r}){const a=hdr(s),i=mdr(s),l=fdr(s),[o,c]=j.useState(!1),[d,u]=j.useState(""),[h,m]=j.useState("adjustment"),[f,g]=j.useState(""),[x,y]=j.useState(bdr()),[v,b]=j.useState(""),[w,S]=j.useState(_dr()),[A,E]=j.useState("all"),I=V=>{var G;return((G=n.find(Y=>Y.agentId===V))==null?void 0:G.name)||"Agent"},P=j.useMemo(()=>{const V=new Map;return t.forEach(G=>{const Y=Number(G.amount)||0,X=G.entry_type==="payment"?-Math.abs(Y):Y;V.set(G.agent_user_id,(V.get(G.agent_user_id)||0)+X)}),V},[t]),R=j.useMemo(()=>Array.from(P.values()).reduce((V,G)=>V+Math.max(0,G),0),[P]),D=j.useMemo(()=>t.filter(V=>V.entry_type==="payment").reduce((V,G)=>V+Math.abs(Number(G.amount)||0),0),[t]),O=j.useMemo(()=>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:v},{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(Ie,{className:"p-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Outstanding fees"}),e.jsx("p",{className:"text-2xl font-bold tabular-nums text-amber-600",children:Gf(R)})]})}),e.jsx(je,{className:"border-border/60",children:e.jsxs(Ie,{className:"p-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Payments recorded"}),e.jsx("p",{className:"text-2xl font-bold tabular-nums text-emerald-600",children:Gf(D)})]})}),e.jsx(je,{className:"border-border/60",children:e.jsxs(Ie,{className:"p-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Agents with a desk fee"}),e.jsx("p",{className:"text-2xl font-bold tabular-nums",children:U.length})]})})]}),e.jsxs(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(Gn,{children:"Desk fees, transaction fees, adjustments and payments received"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(pe,{type:"month",value:w,onChange:V=>S(V.target.value),className:"h-9 w-[150px]"}),e.jsxs($,{variant:"outline",size:"sm",disabled:l.isPending||U.length===0,onClick:()=>l.mutate({month:w,agents:U,existing:t}),children:[e.jsx(bv,{className:"mr-1.5 h-4 w-4"})," Post desk fees"]}),e.jsxs($,{size:"sm",onClick:()=>c(!0),children:[e.jsx(dn,{className:"mr-1.5 h-4 w-4"})," Add entry"]})]})]})}),e.jsxs(Ie,{className:"space-y-3",children:[e.jsxs(ms,{value: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)?` · ${LEt(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:jAe[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"?"-":"",LEt(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(Hn,{className:"h-4 w-4"})})})]},V.id))})]})})]})]}),e.jsx(zs,{open:o,onOpenChange:c,children:e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Add ledger entry"}),e.jsx(Pr,{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(jAe).map(V=>e.jsx(Ge,{value:V,children:jAe[V]},V))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Amount"}),e.jsx(pe,{type:"number",min:"0",step:"0.01",value:f,onChange:V=>g(V.target.value),placeholder:"0.00"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Date"}),e.jsx(pe,{type:"date",value:x,onChange:V=>y(V.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{children:"Note (optional)"}),e.jsx(Ls,{rows:2,value:v,onChange:V=>b(V.target.value)})]})]}),e.jsxs(Sr,{children:[e.jsx($,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx($,{onClick:W,disabled:a.isPending||!d||!f,children:"Add entry"})]})]})})]})}const jdr={license:TJ,eo:Rm,anniversary:Cx,birthday:Fg},Ndr=[30,60,90,180];function kdr({records:s,roster:t,deals:n,loading:r}){const[a,i]=j.useState(90),l=j.useMemo(()=>t.map(y=>({agentId:y.agentId,name:y.name,avatarUrl:y.avatarUrl})),[t]),o=j.useMemo(()=>Bos(s,l,a),[s,l,a]),c=o.filter(y=>y.expired),d=o.filter(y=>!y.expired&&(y.kind==="license"||y.kind==="eo")),u=o.filter(y=>y.kind==="anniversary"||y.kind==="birthday"),h=j.useMemo(()=>{const y=new Map(s.map(v=>[v.agent_user_id,v]));return t.filter(v=>{const b=y.get(v.agentId);return!(b!=null&&b.license_expiration)||!(b!=null&&b.eo_expiration)})},[s,t]),m=new Date().getFullYear(),f=j.useMemo(()=>Gos(n,[],m,l).agents,[n,l,m]),g=j.useMemo(()=>Lcr(s,l,f),[s,l,f]);if(r)return e.jsx("div",{className:"space-y-3",children:Array.from({length:3}).map((y,v)=>e.jsx(xn,{className:"h-32 w-full rounded-xl"},v))});const x=(y,v)=>{const b=jdr[y.kind];return e.jsxs("div",{className:"flex items-center gap-3 rounded-lg px-2 py-2.5 hover:bg-muted/50",children:[e.jsxs(Oa,{className:"h-8 w-8 shrink-0",children:[e.jsx(Ii,{src:y.avatarUrl||void 0,alt:y.agentName}),e.jsx(za,{className:"text-[10px]",children:y.agentName.slice(0,2).toUpperCase()})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:y.agentName}),e.jsxs("p",{className:"flex items-center gap-1.5 truncate text-[11px] text-muted-foreground",children:[e.jsx(b,{className:"h-3 w-3"}),Icr[y.kind],y.detail?` · ${y.detail}`:""]})]}),e.jsxs("div",{className:"shrink-0 text-right",children:[e.jsx("p",{className:"text-xs font-medium tabular-nums",children:Ult(y.dueDate)}),y.expired?e.jsxs($e,{variant:"destructive",className:"mt-0.5 h-5 text-[10px]",children:[Math.abs(y.daysUntil)," days overdue"]}):e.jsx("p",{className:`text-[11px] ${y.daysUntil<=30?"font-medium text-amber-600":"text-muted-foreground"}`,children:y.daysUntil===0?"Today":`in ${y.daysUntil} days`})]})]},`${y.agentId}-${y.kind}-${v}`)};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-3",children:[e.jsx(je,{className:"border-border/60",children:e.jsxs(Ie,{className:"flex items-center gap-3 p-4",children:[e.jsx("span",{className:"flex h-9 w-9 items-center justify-center rounded-lg bg-red-500/10 text-red-600",children:e.jsx(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(Ie,{className:"flex items-center gap-3 p-4",children:[e.jsx("span",{className:"flex h-9 w-9 items-center justify-center rounded-lg bg-amber-500/10 text-amber-600",children:e.jsx(Cu,{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(Ie,{className:"flex items-center gap-3 p-4",children:[e.jsx("span",{className:"flex h-9 w-9 items-center justify-center rounded-lg bg-slate-500/10 text-slate-600",children:e.jsx(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(y=>e.jsxs($,{size:"sm",variant:a===y?"default":"outline",onClick:()=>i(y),children:[y," days"]},y))]}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsxs(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(Gn,{children:"Expired items first, then everything due inside your window"})]}),e.jsx(Ie,{className:"space-y-0.5 pt-2",children:c.length===0&&d.length===0?e.jsxs("p",{className:"py-8 text-center text-sm text-muted-foreground",children:["Nothing expiring in the next ",a," days."]}):[...c,...d].map(x)})]}),e.jsxs(je,{className:"border-border/60",children:[e.jsxs(St,{className:"pb-2",children:[e.jsx(Et,{className:"text-base",children:"Anniversaries & birthdays"}),e.jsx(Gn,{children:"Reach out before the day — retention lives here"})]}),e.jsx(Ie,{className:"space-y-0.5 pt-2",children:u.length===0?e.jsxs("p",{className:"py-8 text-center text-sm text-muted-foreground",children:["No milestones in the next ",a," days."]}):u.map(x)})]})]}),e.jsxs(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(nh,{className:"h-4 w-4 text-teal-600"})," Production goals — ",m]}),e.jsx(Gn,{children:"Goal amounts come from each agent's record; progress uses closed volume this year"})]}),e.jsx(Ie,{className:"space-y-2 pt-2",children:g.length===0?e.jsx("p",{className:"py-8 text-center text-sm text-muted-foreground",children:"No production goals set yet — add one on an agent's record in Onboarding."}):g.map(y=>e.jsxs("div",{className:"rounded-lg px-2 py-2.5 hover:bg-muted/50",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(Oa,{className:"h-8 w-8 shrink-0",children:[e.jsx(Ii,{src:y.avatarUrl||void 0,alt:y.name}),e.jsx(za,{className:"text-[10px]",children:y.name.slice(0,2).toUpperCase()})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:y.name}),e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:[Gf(y.volume)," of ",Gf(y.goal)," · ",y.closedDeals," closed"]})]}),e.jsxs("span",{className:"shrink-0 text-sm font-semibold tabular-nums",children:[Math.round(y.pct),"%"]})]}),e.jsx(Yi,{value:Math.min(100,y.pct),className:"mt-2 h-1.5"})]},y.agentId))})]})]})}const ihe=s=>`${s<0?"-":""}$${Math.abs(Math.round(s)).toLocaleString()}`;function Sdr({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(()=>EW(l||{}),[l]);if(!l)return null;const d=m=>o({...l,...m}),u=(m,f,g)=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:f}),e.jsxs("div",{className:"relative",children:[e.jsx(pe,{type:"number",value:l[m]??0,onChange:x=>d({[m]:parseFloat(x.target.value)||0})}),g&&e.jsx("span",{className:"pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 text-xs text-muted-foreground",children:g})]})]}),h=(m,f)=>{const g=[...l.line_items||[]];g[m]={...g[m],...f},d({line_items:g})};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"max-h-[90vh] max-w-3xl overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:l.id?"Edit disbursement":"New disbursement"}),e.jsx(Pr,{children:"Set the closing details and how the commission is split. The CDA is generated from these numbers."})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Agent"}),e.jsxs(ms,{value:l.agent_user_id,onValueChange:m=>d({agent_user_id:m}),children:[e.jsx(us,{children:e.jsx(fs,{placeholder:"Choose an agent"})}),e.jsx(hs,{children:r.map(m=>e.jsx(Ge,{value:m.agentId,children:m.name},m.agentId))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Closing date"}),e.jsx(pe,{type:"date",value:l.closing_date||"",onChange:m=>d({closing_date:m.target.value||null})})]}),e.jsxs("div",{className:"space-y-1.5 sm:col-span-2",children:[e.jsx(ee,{className:"text-xs",children:"Property"}),e.jsx(pe,{value:l.property_address||"",onChange:m=>d({property_address:m.target.value}),placeholder:"123 Main St, Nashville TN"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Escrow / title company"}),e.jsx(pe,{value:l.escrow_company||"",onChange:m=>d({escrow_company:m.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Escrow / file number"}),e.jsx(pe,{value:l.escrow_number||"",onChange:m=>d({escrow_number:m.target.value})})]}),u("sale_price","Sale price","$"),u("gross_commission","Gross commission","$"),u("agent_split_pct","Agent split","%"),u("franchise_fee_pct","Franchise fee","%"),u("transaction_fee","Transaction fee","$"),u("referral_fee_pct","Referral fee","%"),u("referral_amount","Referral flat amount","$"),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-xs",children:"Referral paid to"}),e.jsx(pe,{value:l.referral_payee||"",onChange:m=>d({referral_payee:m.target.value})})]})]}),e.jsxs("div",{className:"space-y-2 rounded-lg border border-border/60 p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-sm font-medium",children:"Other charges & credits"}),e.jsxs($,{type:"button",size:"sm",variant:"outline",onClick:()=>d({line_items:[...l.line_items||[],{label:"",amount:0}]}),children:[e.jsx(dn,{className:"mr-1 h-3.5 w-3.5"})," Add line"]})]}),(l.line_items||[]).length===0&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Positive amounts are deducted from the agent; use a negative amount for a credit."}),(l.line_items||[]).map((m,f)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pe,{className:"flex-1",value:m.label,placeholder:"E&O fee, sign rental, admin fee…",onChange:g=>h(f,{label:g.target.value})}),e.jsx(pe,{className:"w-32",type:"number",value:m.amount,onChange:g=>h(f,{amount:parseFloat(g.target.value)||0})}),e.jsx($,{type:"button",size:"icon",variant:"ghost",onClick:()=>d({line_items:(l.line_items||[]).filter((g,x)=>x!==f)}),children:e.jsx(Hn,{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(Ls,{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:ihe(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:ihe(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:ihe(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:ihe(c.agentNet)})]})]}),e.jsxs(Sr,{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 yUe=[42,76,100],REt=[64,110,113],vUe=[110,118,125],ohe=s=>`${s<0?"-":""}$${Math.abs(Math.round(s)).toLocaleString("en-US")}`,DEt=s=>{const t=PC(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 Cdr(s){const t=s.disbursement,n=EW(t),r=new Go({unit:"pt",format:"letter"}),a=r.internal.pageSize.getWidth(),i=r.internal.pageSize.getHeight(),l=48;r.setFillColor(...yUe),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 ${DEt(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(...vUe),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",DEt(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",ohe(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(...yUe),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?REt:[25,30,35];r.setTextColor(g[0],g[1],g[2]),r.text(h,l,o),r.text(ohe(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(...yUe),r.text(`Pay to ${s.brokerageName}`,l+14,o),r.text(ohe(n.companyDollar+n.otherCharges),a-l-14,o,{align:"right"}),o+=24,r.setTextColor(...REt),r.text(`Pay to ${s.agentName}`,l+14,o),r.text(ohe(n.agentNet),a-l-14,o,{align:"right"}),r.setFont("helvetica","normal"),o+=52,t.notes&&(r.setFontSize(9),r.setTextColor(...vUe),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(...vUe),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 Adr(s){const t=(s.disbursement.property_address||s.agentName||"cda").replace(/[^a-z0-9]+/gi,"-").toLowerCase().slice(0,48);Cdr(s).save(`cda-${t}.pdf`)}const Edr=s=>{const t=s==null?"":String(s);return/[",\n]/.test(t)?`"${t.replace(/"/g,'""')}"`:t},wR=s=>Math.round(s*100)/100,Tdr=["Date","Ref Number","Name","Account","Memo","Debit","Credit"];function Mdr(s,t){const n=[];return s.forEach((r,a)=>{const i=EW(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:wR(i.gross)}),i.referral>0&&n.push({date:l,refNumber:o,name:r.referral_payee||"Referral partner",account:"Referral Fees",memo:d,debit:wR(i.referral),credit:""}),i.agentNet!==0&&n.push({date:l,refNumber:o,name:c,account:"Agent Commission Expense",memo:d,debit:wR(i.agentNet),credit:""}),i.franchiseFee>0&&n.push({date:l,refNumber:o,name:c,account:"Franchise Fees",memo:d,debit:wR(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?wR(-m):"",credit:m>0?wR(m):""})});const u=wR(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 Pdr(s){const t=[Tdr.join(",")];return s.forEach(n=>t.push([n.date,n.refNumber,n.name,n.account,n.memo,n.debit,n.credit].map(Edr).join(","))),t.join(` `)}function Idr(s,t,n=`quickbooks-disbursements-${new Date().toISOString().slice(0,10)}.csv`){const r=new Blob([Pdr(Mdr(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 Ldr={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"},bUe=s=>`${s<0?"-":""}$${Math.abs(Math.round(s)).toLocaleString()}`,Rdr=s=>{const t=PC(s);return t?`${t.m}/${t.d}/${String(t.y).slice(2)}`:"—"};function Ddr({brokerageId:s,disbursements:t,deals:n,roster:r,brokerageName:a,loading:i}){const l=ycr(s),o=vcr(s),c=bcr(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=EW(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]),y=j.useMemo(()=>{const w=new Set(t.map(S=>S.deal_id).filter(Boolean));return n.filter(S=>!!S.actual_close_date&&!w.has(S.deal_id)).slice(0,20)},[n,t]),v=w=>{var A;const S=((A=r.find(E=>E.agentId===w.owner_user_id))==null?void 0:A.plan)||null;u(xcr(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(Ie,{className:"p-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Commission authorized"}),e.jsx("p",{className:"text-2xl font-bold tabular-nums",children:Gf(x.gross)})]})}),e.jsx(je,{className:"border-border/60",children:e.jsxs(Ie,{className:"p-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"To the brokerage"}),e.jsx("p",{className:"text-2xl font-bold tabular-nums text-teal-600",children:Gf(x.company)})]})}),e.jsx(je,{className:"border-border/60",children:e.jsxs(Ie,{className:"p-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"To agents"}),e.jsx("p",{className:"text-2xl font-bold tabular-nums text-emerald-600",children:Gf(x.agent)})]})}),e.jsx(je,{className:"border-border/60",children:e.jsxs(Ie,{className:"p-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Awaiting approval"}),e.jsx("p",{className:"text-2xl font-bold tabular-nums text-amber-600",children:x.pending})]})})]}),y.length>0&&e.jsxs(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(Gn,{children:"Start a CDA prefilled from the deal and the agent's commission plan"})]}),e.jsx(Ie,{className:"flex flex-wrap gap-2 pt-2",children:y.map(w=>e.jsxs($,{size:"sm",variant:"outline",onClick:()=>v(w),children:[e.jsx(Kq,{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(Gn,{children:"Approve, mark paid, print the CDA or export to QuickBooks"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(ms,{value:h,onValueChange:w=>m(w),children:[e.jsx(us,{className:"h-9 w-[150px]",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"all",children:"All statuses"}),Object.keys(fUe).map(w=>e.jsx(Ge,{value:w,children:fUe[w]},w))]})]}),e.jsxs($,{size:"sm",variant:"outline",disabled:!g.length,onClick:()=>Idr(g,f),children:[e.jsx(xi,{className:"mr-1.5 h-4 w-4"})," QuickBooks CSV"]}),e.jsxs($,{size:"sm",disabled:!r.length,onClick:()=>u(b()),children:[e.jsx(dn,{className:"mr-1.5 h-4 w-4"})," New CDA"]})]})]}),e.jsxs(Ie,{className:"space-y-1 pt-2",children:[!g.length&&e.jsx("p",{className:"py-8 text-center text-sm text-muted-foreground",children:"No disbursements yet — start one from a closed deal above."}),g.map(w=>{const S=EW(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 ",Rdr(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:bUe(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:bUe(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:bUe(S.agentNet)})]}),e.jsx($e,{variant:"secondary",className:Ldr[w.status],children:fUe[w.status]}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>Adr({disbursement:w,brokerageName:a,agentName:f(w.agent_user_id)}),children:[e.jsx(Jr,{className:"mr-1.5 h-3.5 w-3.5"})," CDA"]}),e.jsxs($u,{children:[e.jsx(Uu,{asChild:!0,children:e.jsx($,{size:"icon",variant:"ghost",children:e.jsx(Jx,{className:"h-4 w-4"})})}),e.jsxs(Au,{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(r7,{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(Hn,{className:"mr-2 h-4 w-4"})," Delete"]})]})]})]},w.id)})]})]}),e.jsx(Sdr,{open:!!d,onOpenChange:w=>!w&&u(null),draft:d,roster:r,saving:l.isPending,onSave:w=>l.mutate(w,{onSuccess:()=>u(null)})})]})}const lhe=s=>`$${Math.round(s).toLocaleString()}`,Fdr=()=>{var G;const{brokerageId:s,managedBrokerages:t,selectedBrokerageId:n}=bs(),r=j.useMemo(()=>{var Y;return n||((Y=t[0])==null?void 0:Y.id)||s},[n,t,s]),{data:a=[],isLoading:i}=TQn(r,!0),{data:l=[],isLoading:o}=IQn(r),c=MQn(r),d=LQn(r),u=RQn(r),{data:h=[],isLoading:m}=Ett(r),{data:f=[],isLoading:g}=udr(r),{data:x=[],isLoading:y}=Dos(r),{data:v=[],isLoading:b}=Ros(r),w=((G=t.find(Y=>Y.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(Y=>Y.is_active),W=l.filter(Y=>Y.assignment),V=W.reduce((Y,X)=>{var ae;return Y+(((ae=X.plan)==null?void 0:ae.monthly_fee)||0)},0);return e.jsxs(Vs,{title:"Brokerage Financials",description:"Commission plans, cap progress, company dollar and agent fee statements",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-3",children:[e.jsx(je,{className:"border-border/60",children:e.jsxs(Ie,{className:"flex items-center gap-3 p-4",children:[e.jsx("span",{className:"flex h-9 w-9 items-center justify-center rounded-lg bg-teal-500/10 text-teal-600",children:e.jsx(Ew,{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(Ie,{className:"flex items-center gap-3 p-4",children:[e.jsx("span",{className:"flex h-9 w-9 items-center justify-center rounded-lg bg-blue-500/10 text-blue-600",children:e.jsx(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(Ie,{className:"flex items-center gap-3 p-4",children:[e.jsx("span",{className:"flex h-9 w-9 items-center justify-center rounded-lg bg-emerald-500/10 text-emerald-600",children:e.jsx(r7,{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(ha,{defaultValue:"agents",className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsx("div",{className:"overflow-x-auto pb-1",children:e.jsxs(ma,{children:[e.jsx(Zt,{value:"agents",children:"Agents"}),e.jsx(Zt,{value:"plans",children:"Plans"}),e.jsx(Zt,{value:"company",children:"Company dollar"}),e.jsx(Zt,{value:"ledger",children:"Fees & statements"}),e.jsx(Zt,{value:"disbursements",children:"Disbursements"}),e.jsx(Zt,{value:"renewals",children:"Renewals & goals"})]})}),e.jsxs($,{size:"sm",onClick:()=>{I(null),A(!0)},children:[e.jsx(dn,{className:"mr-1.5 h-4 w-4"})," New plan"]})]}),e.jsx(Xt,{value:"agents",className:"space-y-2",children:e.jsxs(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(Gn,{children:"Assign a plan to each agent — their new deals inherit the splits and fees automatically"})]}),e.jsx(Ie,{className:"space-y-1 pt-2",children:o?Array.from({length:4}).map((Y,X)=>e.jsx(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(Y=>{var ae;const X=(ae=Y.progress)==null?void 0:ae.pct_to_cap;return e.jsxs("div",{className:"flex flex-col gap-3 rounded-lg px-2 py-3 hover:bg-muted/50 sm:flex-row sm:items-center",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-3",children:[e.jsxs(Oa,{className:"h-9 w-9 shrink-0",children:[e.jsx(Ii,{src:Y.avatarUrl||void 0,alt:Y.name}),e.jsx(za,{className:"text-[11px]",children:Y.name.slice(0,2).toUpperCase()})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:Y.name}),e.jsx("p",{className:"truncate text-[11px] text-muted-foreground",children:Y.email})]})]}),e.jsx("div",{className:"min-w-0 flex-1",children:Y.plan?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsx($e,{variant:"secondary",className:"font-medium",children:Y.plan.name}),e.jsxs("span",{className:"text-[11px] text-muted-foreground",children:[Y.plan.agent_split_pct,"/",Math.max(0,100-Y.plan.agent_split_pct),Y.plan.cap_amount?` · ${Gf(Y.plan.cap_amount)} cap`:" · no cap"]})]}),Y.plan.cap_amount&&Y.progress?e.jsxs("div",{className:"mt-1.5 max-w-xs",children:[e.jsxs("div",{className:"mb-1 flex justify-between text-[11px] text-muted-foreground",children:[e.jsxs("span",{children:[lhe(Y.progress.cap_progress)," to cap"]}),e.jsxs("span",{children:[Math.round(X??0),"%"]})]}),e.jsx(Yi,{value:Math.min(100,X??0),className:"h-1.5"})]}):e.jsx("p",{className:"mt-1 text-[11px] text-muted-foreground",children:"No cap on this plan"})]}):e.jsx("p",{className:"text-[12px] italic text-muted-foreground",children:"No plan assigned"})}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[e.jsx($,{variant:"outline",size:"sm",disabled:U.length===0,onClick:()=>{O(Y),R(!0)},children:Y.assignment?"Change plan":"Assign plan"}),Y.assignment&&e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground",title:"Remove plan",onClick:()=>u.mutate(Y.assignment.id),children:e.jsx(uV,{className:"h-4 w-4"})})]})]},Y.agentId)})})]})}),e.jsx(Xt,{value:"plans",className:"space-y-3",children:i?e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:Array.from({length:2}).map((Y,X)=>e.jsx(xn,{className:"h-44 w-full rounded-xl"},X))}):a.length===0?e.jsx(je,{className:"border-dashed",children:e.jsxs(Ie,{className:"flex flex-col items-center gap-3 py-12 text-center",children:[e.jsx("span",{className:"flex h-11 w-11 items-center justify-center rounded-xl bg-teal-500/10 text-teal-600",children:e.jsx(Ew,{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(dn,{className:"mr-1.5 h-4 w-4"})," Create plan"]})]})}):e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:a.map(Y=>e.jsxs(je,{className:`border-border/60 ${Y.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:Y.name}),Y.description&&e.jsx(Gn,{className:"mt-1",children:Y.description})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[!Y.is_active&&e.jsx($e,{variant:"outline",children:"Retired"}),e.jsxs($e,{variant:"secondary",children:["v",Y.version_no]}),e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>{I(Y),A(!0)},children:e.jsx(pi,{className:"h-4 w-4"})})]})]})}),e.jsxs(Ie,{className:"grid grid-cols-2 gap-x-4 gap-y-2 pt-1 text-sm",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Split (agent/brokerage)"}),e.jsxs("p",{className:"font-medium tabular-nums",children:[Y.agent_split_pct,"/",Math.max(0,100-Y.agent_split_pct)]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Annual cap"}),e.jsx("p",{className:"font-medium tabular-nums",children:Y.cap_amount?lhe(Y.cap_amount):"None"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Monthly desk fee"}),e.jsx("p",{className:"font-medium tabular-nums",children:Y.monthly_fee?lhe(Y.monthly_fee):"—"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Per-transaction fee"}),e.jsx("p",{className:"font-medium tabular-nums",children:Y.transaction_fee?lhe(Y.transaction_fee):"—"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Franchise fee"}),e.jsx("p",{className:"font-medium tabular-nums",children:Y.franchise_fee_pct?`${Y.franchise_fee_pct}%`:"—"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Team split"}),e.jsx("p",{className:"font-medium tabular-nums",children:Y.team_split_pct?`${Y.team_split_pct}%`:"—"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Agents on plan"}),e.jsx("p",{className:"font-medium tabular-nums",children:l.filter(X=>{var ae;return((ae=X.plan)==null?void 0:ae.id)===Y.id}).length})]})]})]},Y.id))})}),e.jsx(Xt,{value:"company",children:e.jsx(vdr,{deals:h,ledger:f,roster:l,brokerageName:w,loading:m||o})}),e.jsx(Xt,{value:"ledger",children:e.jsx(wdr,{brokerageId:r,ledger:f,roster:l,loading:g||o})}),e.jsx(Xt,{value:"renewals",children:e.jsx(kdr,{records:x,roster:l,deals:h,loading:y||o})}),e.jsx(Xt,{value:"disbursements",children:e.jsx(Ddr,{brokerageId:r,disbursements:v,deals:h,roster:l,brokerageName:w,loading:b||o})})]})]}),e.jsx(cdr,{open:S,onOpenChange:A,plan:E,saving:c.isPending,onSave:Y=>c.mutate(Y,{onSuccess:()=>A(!1)})}),e.jsx(ddr,{open:P,onOpenChange:R,agent:D,plans:U,saving:d.isPending,onAssign:Y=>d.mutate(Y,{onSuccess:()=>R(!1)})})]})};function Odr(){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(v=>v.brokerage_id===f.id),x=h.filter(v=>v.brokerage_id===f.id),y=g.length>0?g.reduce((v,b)=>b.created_at>v?b.created_at:v,g[0].created_at):null;return{brokerage_id:f.id,brokerage_name:f.name,total_items:g.length,videos:g.filter(v=>v.content_type==="video").length,pdfs:g.filter(v=>v.content_type==="pdf").length,links:g.filter(v=>v.content_type==="link"||v.content_type==="canva_link").length,events:g.filter(v=>v.content_type==="event").length,graphics:g.filter(v=>v.content_type==="graphic").length,latest_item_date:y,categories:x.length}});return m.sort((f,g)=>g.total_items-f.total_items),m}}),a=(n||[]).filter(o=>o.brokerage_name.toLowerCase().includes(s.toLowerCase())),i=a.reduce((o,c)=>o+c.total_items,0),l=a.filter(o=>o.total_items>0).length;return e.jsx(Vs,{title:"Brokerage Content Activity",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(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(Ie,{children:[e.jsx("p",{className:"text-2xl font-bold",children:l}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"with content uploaded"})]})]}),e.jsxs(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(Ie,{children:[e.jsx("p",{className:"text-2xl font-bold",children:i}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"across all brokerages"})]})]}),e.jsxs(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(Ie,{children:[e.jsx("p",{className:"text-2xl font-bold",children:a.length}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"registered"})]})]})]}),e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(Zr,{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(Ie,{className:"p-0",children:e.jsxs(hi,{children:[e.jsx(mi,{children:e.jsxs(En,{children:[e.jsx(Dt,{children:"Brokerage"}),e.jsx(Dt,{className:"text-center",children:"Total"}),e.jsx(Dt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(ua,{className:"h-3 w-3"})," Videos"]})}),e.jsx(Dt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(Jr,{className:"h-3 w-3"})," PDFs"]})}),e.jsx(Dt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(Wd,{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(En,{children:e.jsx(_t,{colSpan:9,className:"text-center py-8 text-muted-foreground",children:"Loading..."})}):a.length===0?e.jsx(En,{children:e.jsx(_t,{colSpan:9,className:"text-center py-8 text-muted-foreground",children:"No brokerages found"})}):a.map(o=>e.jsxs(En,{className:o.total_items===0?"opacity-50":"",children:[e.jsx(_t,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ji,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("span",{className:"font-medium",children:o.brokerage_name})]})}),e.jsx(_t,{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(_t,{className:"text-center",children:o.videos||"–"}),e.jsx(_t,{className:"text-center",children:o.pdfs||"–"}),e.jsx(_t,{className:"text-center",children:o.links||"–"}),e.jsx(_t,{className:"text-center",children:o.events||"–"}),e.jsx(_t,{className:"text-center",children:o.graphics||"–"}),e.jsx(_t,{className:"text-center",children:o.categories||"–"}),e.jsx(_t,{children:o.latest_item_date?e.jsx("span",{className:"text-sm text-muted-foreground",children:en(new Date(o.latest_item_date),"MMM d, yyyy")}):e.jsx("span",{className:"text-muted-foreground",children:"–"})})]},o.brokerage_id))})]})})})]})})}const zdr=[{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:"📉"}],FEt=[{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(Qp,{className:"h-4 w-4"})}],Bdr=[{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:"📰"}],OEt=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),zEt={"luxury-dark":Art,"modern-clean":Ert,"bold-colorful":Trt,editorial:Mrt};function $dr(){const[s,t]=j.useState(""),[n,r]=j.useState("address"),[a,i]=j.useState(!1),[l,o]=j.useState([]),[c,d]=j.useState(null),[u,h]=j.useState(0),[m,f]=j.useState("just-listed"),[g,x]=j.useState(["instagram-square"]),[y,v]=j.useState("luxury-dark"),[b,w]=j.useState(!1),[S,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([]),[Y,X]=j.useState("search"),ae=j.useRef({});j.useEffect(()=>{(async()=>{const{data:{user:Ee}}=await q.auth.getUser();if(!Ee)return;const{data:Se}=await q.from("profiles").select("name, avatar_url, brokerages(name)").eq("id",Ee.id).single();if(Se){A(Se.name||""),R(Se.avatar_url||"");const Le=Se.brokerages;I((Le==null?void 0:Le.name)||"")}})()},[]);const le=async()=>{var ve;if(s.trim()){i(!0),o([]);try{const{data:Ee,error:Se}=await q.functions.invoke("repliers-mls-search",{body:{searchType:n,query:s.trim()}});if(Se)throw Se;if(Ee.error)throw new Error(Ee.error);o(Ee.listings||[]),((ve=Ee.listings)==null?void 0:ve.length)===0&&re.info("No listings found. Try a different search.")}catch(Ee){re.error(Ee.message||"Search failed")}finally{i(!1)}}},ne=ve=>{var Ee;d(ve),h(0),X("customize"),ve.soldDate||(Ee=ve.status)!=null&&Ee.toLowerCase().includes("sold")?f("just-sold"):f("just-listed")},te=ve=>{x(Ee=>Ee.includes(ve)?Ee.filter(Se=>Se!==ve):[...Ee,ve])},J=j.useCallback(async()=>{if(!(!c||g.length===0)){O(!0),G([]),X("generate");try{await new Promise(Ee=>setTimeout(Ee,500));const ve=[];for(const Ee of g){const Se=`${y}-${Ee}`,Le=ae.current[Se];if(!Le)continue;const Fe=bI[Ee],ke=await FG(Le,{width:Fe.width,height:Fe.height,pixelRatio:1,cacheBust:!0,style:{transform:"none",transformOrigin:"top left"}});ve.push({format:Ee,imageUrl:ke})}G(ve),re.success(`Generated ${ve.length} social post${ve.length>1?"s":""}!`)}catch(ve){re.error(ve.message||"Generation failed")}finally{O(!1)}}},[c,g,y,u,b,S,E,P,m]),ce=async()=>{if(!(!c||g.length===0)){O(!0),G([]),X("generate");try{const ve={...c,photos:c.photos.length>0?[c.photos[u]]:[]},Ee=[];for(const Se of g){const{data:Le,error:Fe}=await q.functions.invoke("generate-listing-social-post",{body:{listing:ve,postType:m,format:Se,branding:b?{enabled:!0,agentName:S,brokerage:E}:{enabled:!1}}});if(Fe)throw Fe;if(Le.error)throw new Error(Le.error);Ee.push({format:Se,imageUrl:Le.imageUrl})}G(Ee),re.success(`Generated ${Ee.length} AI post${Ee.length>1?"s":""}!`)}catch(ve){re.error(ve.message||"AI generation failed")}finally{O(!1)}}},_e=()=>U?ce():J(),he=(ve,Ee)=>{var Le;const Se=document.createElement("a");Se.href=ve,Se.download=`${((Le=c==null?void 0:c.address)==null?void 0:Le.replace(/\s+/g,"-"))||"listing"}-${m}-${Ee}.png`,document.body.appendChild(Se),Se.click(),document.body.removeChild(Se)},ue=c?{listing:c,postType:m,format:"instagram-square",branding:b?{enabled:!0,agentName:S,brokerage:E,agentPhotoUrl:P||void 0}:{enabled:!1},selectedPhotoIndex:u}:null;return e.jsx(Vs,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-8",children:[e.jsx(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 ${Y==="search"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground hover:text-foreground"}`,children:[e.jsx(Zr,{className:"h-3.5 w-3.5"})," 1. Find Listing"]}),e.jsx(Di,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("button",{onClick:()=>c&&X("customize"),disabled:!c,className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full transition-colors ${Y==="customize"?"bg-primary text-primary-foreground":c?"bg-muted text-muted-foreground hover:text-foreground":"bg-muted text-muted-foreground/50 cursor-not-allowed"}`,children:[e.jsx(Nn,{className:"h-3.5 w-3.5"})," 2. Customize"]}),e.jsx(Di,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full ${Y==="generate"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground/50"}`,children:[e.jsx(Hc,{className:"h-3.5 w-3.5"})," 3. Generate"]})]}),Y==="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(Zr,{className:"h-5 w-5 text-primary"})," Search MLS Listings ",e.jsx(HUt,{})]}),e.jsx(Gn,{children:"Find a listing by MLS number or property address using Repliers.io"})]}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsx(ha,{value:n,onValueChange:ve=>r(ve),children:e.jsxs(ma,{children:[e.jsxs(Zt,{value:"address",children:[e.jsx(ci,{className:"h-4 w-4 mr-1.5"})," Address"]}),e.jsxs(Zt,{value:"mls",children:[e.jsx(Ap,{className:"h-4 w-4 mr-1.5"})," MLS #"]})]})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{value:s,onChange:ve=>t(ve.target.value),placeholder:n==="mls"?"Enter MLS number...":"Enter property address...",className:"flex-1",onKeyDown:ve=>ve.key==="Enter"&&le()}),e.jsxs($,{onClick:le,disabled:a||!s.trim(),children:[a?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Zr,{className:"h-4 w-4"})," Search"]})]})]})]}),l.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h3",{className:"text-sm font-medium text-muted-foreground",children:[l.length," listing",l.length!==1?"s":""," found"]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:l.map((ve,Ee)=>{var Se;return e.jsx(je,{className:"cursor-pointer hover:border-primary/50 hover:shadow-md transition-all group",onClick:()=>ne(ve),children:e.jsx(Ie,{className:"p-0",children:e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-32 h-28 flex-shrink-0 bg-muted rounded-l-lg overflow-hidden",children:(Se=ve.photos)!=null&&Se[0]?e.jsx("img",{src:ve.photos[0],alt:ve.address,className:"w-full h-full object-cover group-hover:scale-105 transition-transform"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(va,{className:"h-8 w-8 text-muted-foreground/40"})})}),e.jsxs("div",{className:"flex-1 p-3 min-w-0",children:[e.jsx("p",{className:"font-bold text-foreground",children:OEt(ve.price)}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:ve.address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[ve.city,", ",ve.state," ",ve.zip]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1.5 text-xs text-muted-foreground",children:[ve.bedrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(A4,{className:"h-3 w-3"})," ",ve.bedrooms]}),ve.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(A0,{className:"h-3 w-3"})," ",ve.bathrooms]}),ve.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(Gz,{className:"h-3 w-3"})," ",ve.sqft.toLocaleString()]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx($e,{variant:"outline",className:"text-[10px]",children:ve.mlsNumber}),e.jsx($e,{variant:"outline",className:"text-[10px]",children:ve.status})]})]})]})})},ve.mlsNumber||Ee)})})]})]}),Y==="customize"&&c&&e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs(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(Ie,{className:"space-y-3",children:[c.photos.length>0&&e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"aspect-[4/3] rounded-lg overflow-hidden bg-muted",children:e.jsx("img",{src:c.photos[u],alt:"Listing photo",className:"w-full h-full object-cover"})}),c.photos.length>1&&e.jsxs("div",{className:"flex items-center justify-between mt-2",children:[e.jsx($,{variant:"outline",size:"icon",className:"h-7 w-7",onClick:()=>h(ve=>Math.max(0,ve-1)),disabled:u===0,children:e.jsx(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(ve=>Math.min(c.photos.length-1,ve+1)),disabled:u===c.photos.length-1,children:e.jsx(Di,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-bold text-lg",children:OEt(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(Ax,{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(Nn,{className:"h-5 w-5 text-primary"})," Customize Your Post"]}),e.jsx(Gn,{children:"Choose template, post type, format, and branding"})]}),e.jsxs(Ie,{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border bg-muted/30",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(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(Sn,{checked:U,onCheckedChange:W}),U&&e.jsx(ey,{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:Bdr.map(ve=>e.jsxs("button",{onClick:()=>v(ve.value),className:`flex flex-col items-center gap-1 px-3 py-3 rounded-lg border-2 transition-all text-center ${y===ve.value?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("span",{className:"text-2xl",children:ve.preview}),e.jsx("span",{className:"text-sm font-medium",children:ve.label}),e.jsx("span",{className:"text-[10px] text-muted-foreground leading-tight",children:ve.description})]},ve.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-sm font-medium",children:"Post Type"}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:zdr.map(ve=>e.jsxs("button",{onClick:()=>f(ve.value),className:`flex items-center gap-2 px-3 py-2.5 rounded-lg border-2 transition-all text-sm font-medium ${m===ve.value?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("span",{className:"text-lg",children:ve.icon})," ",ve.label]},ve.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-sm font-medium",children:"Output Formats"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-2",children:FEt.map(ve=>e.jsxs("button",{onClick:()=>te(ve.value),className:`flex items-center gap-2 px-3 py-2.5 rounded-lg border-2 transition-all text-sm ${g.includes(ve.value)?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[ve.icon,e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"font-medium",children:ve.label}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:ve.dimensions})]})]},ve.value))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(ee,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(sl,{className:"h-4 w-4"})," Agent Branding"]}),e.jsx(Sn,{checked:b,onCheckedChange:w})]}),b&&e.jsxs("div",{className:"space-y-3 pl-6 border-l-2 border-primary/20",children:[P&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("img",{src:P,alt:"Agent",className:"w-12 h-12 rounded-full object-cover border-2 border-primary/30"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Profile photo will appear on the post"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(ee,{className:"text-xs text-muted-foreground",children:"Agent Name"}),e.jsx(pe,{value:S,onChange:ve=>A(ve.target.value),placeholder:"Jane Smith"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ee,{className:"text-xs text-muted-foreground",children:"Brokerage (optional)"}),e.jsx(pe,{value:E,onChange:ve=>I(ve.target.value),placeholder:"XYZ Realty"})]})]})]})]}),!U&&ue&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-sm font-medium",children:"Preview"}),e.jsx("div",{className:"bg-muted/30 rounded-lg p-4 flex justify-center overflow-hidden",children:e.jsx("div",{style:{width:400,height:400*(bI[g[0]||"instagram-square"].height/bI[g[0]||"instagram-square"].width)},children:(()=>{const ve=zEt[y],Ee=g[0]||"instagram-square";return e.jsx(ve,{...ue,format:Ee})})()})})]}),e.jsx($,{onClick:_e,disabled:g.length===0||D,size:"lg",className:"w-full gap-2",children:D?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"h-5 w-5 animate-spin"})," Generating ",g.length," post",g.length>1?"s":"","..."]}):e.jsxs(e.Fragment,{children:[U?e.jsx(ey,{className:"h-5 w-5"}):e.jsx(Nn,{className:"h-5 w-5"}),"Generate ",g.length," Social Post",g.length>1?"s":"",U&&e.jsx($e,{variant:"outline",className:"ml-2 text-[10px]",children:"Uses Credits"})]})})]})]})]}),Y==="generate"&&e.jsxs("div",{className:"space-y-4",children:[D&&e.jsx(je,{children:e.jsxs(Ie,{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(Ax,{className:"h-3.5 w-3.5 mr-1.5"})," Regenerate"]})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:V.map((ve,Ee)=>{const Se=FEt.find(Le=>Le.value===ve.format);return e.jsxs(je,{className:"overflow-hidden",children:[e.jsx("div",{className:"bg-muted/30 p-1",children:e.jsx("img",{src:ve.imageUrl,alt:`${ve.format} social post`,className:"w-full rounded"})}),e.jsxs(Ie,{className:"p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[Se==null?void 0:Se.icon,e.jsx("span",{className:"text-sm font-medium",children:Se==null?void 0:Se.label})]}),e.jsx($e,{variant:"outline",className:"text-[10px]",children:Se==null?void 0:Se.dimensions})]}),e.jsxs($,{size:"sm",className:"w-full gap-1.5",onClick:()=>he(ve.imageUrl,ve.format),children:[e.jsx(xi,{className:"h-3.5 w-3.5"})," Download"]})]})]},Ee)})})]})]}),Y==="generate"&&!U&&c&&ue&&e.jsx("div",{style:{position:"absolute",left:"-9999px",top:0},"aria-hidden":!0,children:g.map(ve=>{const Ee=zEt[y],Se=bI[ve];return e.jsx("div",{style:{width:Se.width,height:Se.height},children:e.jsx(Ee,{ref:Le=>{ae.current[`${y}-${ve}`]=Le},...ue,format:ve})},`${y}-${ve}`)})})]})})}function Udr(){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 qdr(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 Vdr(){const s=Wt();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 Wos(){const s=Wt();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 Hdr(){const s=Wt();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 Gdr(){const s=Wt();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 Wdr(){const s=Wt();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 Kdr(){const s=Wt();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 Ydr(){const s=Wt();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 Zdr(){const s=Wt();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 Xdr(){const s=Wt();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 Qdr(){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 Jdr(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 Kos(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 eur(){const s=Wt();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 tur(){const{user:s}=bs(),t=Xn(),{data:n,isLoading:r}=Udr(),a=Vdr(),i=Wos(),l=Hdr(),[o,c]=j.useState(!1),[d,u]=j.useState(""),[h,m]=j.useState(""),[f,g]=j.useState(!0),x=async()=>{if(!(!d.trim()||!s))try{const b=await a.mutateAsync({title:d.trim(),description:h.trim()||void 0,is_sequential:f,created_by:s.id});re.success("Course created"),c(!1),u(""),m(""),g(!0),t(`/admin/lms/${b.id}`)}catch{re.error("Failed to create course")}},y=async b=>{try{await i.mutateAsync({id:b.id,is_published:!b.is_published}),re.success(b.is_published?"Course unpublished":"Course published")}catch{re.error("Failed to update course")}},v=async b=>{if(await fo("Delete this course and all its modules? This cannot be undone."))try{await l.mutateAsync(b),re.success("Course deleted")}catch{re.error("Failed to delete")}};return e.jsxs(Vs,{title:"LevelUp U - Admin",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl font-bold text-foreground flex items-center gap-2",children:[e.jsx(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(dn,{className:"h-4 w-4 mr-2"}),"New Course"]})]})]}),r?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4",children:[1,2,3].map(b=>e.jsx(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(Gn,{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(Ie,{className:"pt-0",children:[e.jsxs("div",{className:"flex items-center gap-4 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Xf,{className:"h-3.5 w-3.5"}),w," module",w!==1?"s":""]}),e.jsxs("span",{className:"flex items-center gap-1",children:[b.is_sequential?e.jsx(u2,{className:"h-3.5 w-3.5"}):e.jsx(Jz,{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(),y(b)},children:[b.is_published?e.jsx($g,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(Ca,{className:"h-3.5 w-3.5 mr-1"}),b.is_published?"Unpublish":"Publish"]}),e.jsx($,{size:"sm",variant:"ghost",className:"text-destructive",onClick:P=>{P.stopPropagation(),v(b.id)},children:e.jsx(Hn,{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(Ie,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(Xf,{className:"h-12 w-12 text-muted-foreground/50 mb-4"}),e.jsx("h3",{className:"text-lg font-semibold text-foreground mb-1",children:"No courses yet"}),e.jsx("p",{className:"text-muted-foreground text-sm mb-4",children:"Create your first training course to get started"}),e.jsxs($,{onClick:()=>c(!0),children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Create Course"]})]})})]}),e.jsx(zs,{open:o,onOpenChange:c,children:e.jsxs(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Create New Course"}),e.jsx(Pr,{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(Ls,{value:h,onChange:b=>m(b.target.value),placeholder:"What will agents learn?",rows:3})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Sequential Learning"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Agents must complete modules in order"})]}),e.jsx(Sn,{checked:f,onCheckedChange:g})]})]}),e.jsxs(Sr,{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 sur(){const{courseId:s}=Wi(),t=Xn(),{data:n,isLoading:r}=qdr(s),a=Wos(),i=Gdr(),l=Wdr(),o=Kdr(),c=Ydr(),d=Zdr(),u=Xdr(),{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),[y,v]=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),[Y,X]=j.useState(!1),[ae,le]=j.useState(""),[ne,te]=j.useState(""),[J,ce]=j.useState(""),[_e,he]=j.useState(!1);if(r)return e.jsx(Vs,{title:"Loading...",children:e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})});if(!n)return e.jsx(Vs,{title:"Course Not Found",children:e.jsxs("div",{className:"text-center py-20",children:[e.jsx("p",{className:"text-muted-foreground",children:"Course not found"}),e.jsxs($,{variant:"outline",className:"mt-4",onClick:()=>t("/admin/lms"),children:[e.jsx(Va,{className:"h-4 w-4 mr-2"})," Back to Courses"]})]})});const ue=n.modules||[],ve=n.access||[],Ee=ve.some(at=>at.access_type==="all"),Se=ve.filter(at=>at.access_type==="brokerage").map(at=>at.brokerage_id),Le=(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)},ke=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:pt,error:gt}=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:Ke,libraryId:Je}});if(gt)throw new Error(gt.message);const ss=new XMLHttpRequest;return await new Promise((Yt,ts)=>{ss.upload.onprogress=ys=>{ys.lengthComputable&&O(Math.round(ys.loaded/ys.total*100))},ss.onload=()=>ss.status>=200&&ss.status<300?Yt():ts(new Error(`Upload failed: ${ss.status}`)),ss.onerror=()=>ts(new Error("Upload failed")),ss.open("PUT",pt.uploadUrl),ss.setRequestHeader("AccessKey",pt.apiKey),ss.send(P)}),`https://iframe.mediadelivery.net/embed/${Je}/${Ke}`}catch(at){return console.error("Bunny upload error:",at),re.error("Video upload failed"),null}finally{W(!1),O(0)}},Be=async()=>{if(y.title.trim())try{let at=y.video_url.trim()||void 0;if(P){const rt=await ke();if(!rt)return;at=rt}await i.mutateAsync({course_id:n.id,title:y.title.trim(),description:y.description.trim()||void 0,video_url:at,text_content:y.text_content.trim()||void 0,duration_minutes:y.duration_minutes?parseInt(y.duration_minutes):void 0,sort_order:ue.length}),re.success("Module added"),x(!1),v({title:"",description:"",video_url:"",text_content:"",duration_minutes:""}),R(null)}catch{re.error("Failed to add module")}},Ne=async()=>{if(m)try{let at=y.video_url.trim()||null;if(P){const rt=await ke();if(!rt)return;at=rt}await l.mutateAsync({id:m.id,title:y.title.trim(),description:y.description.trim()||null,video_url:at,text_content:y.text_content.trim()||null,duration_minutes:y.duration_minutes?parseInt(y.duration_minutes):null}),re.success("Module updated"),f(null),R(null)}catch{re.error("Failed to update")}},Ae=async at=>{if(await fo("Delete this module?"))try{await o.mutateAsync(at),re.success("Module deleted")}catch{re.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}),re.success("Resource added"),w(null),A({title:"",resource_type:"link",url:""})}catch{re.error("Failed to add resource")}},Ve=async()=>{try{await u.mutateAsync({courseId:n.id,accessRules:[{access_type:"all"}]}),re.success("Access updated: All brokerages / all agents")}catch{re.error("Failed to update access")}},ze=async at=>{const rt=ve.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 pt=Je.map(gt=>({access_type:"brokerage",brokerage_id:gt}));try{await u.mutateAsync({courseId:n.id,accessRules:pt}),re.success(Ke?"Brokerage removed":"Brokerage added")}catch{re.error("Failed to update access")}},qe=async()=>{try{await u.mutateAsync({courseId:n.id,accessRules:[]}),re.success("Access cleared")}catch{re.error("Failed")}},dt=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{re.error("Failed to reorder")}},Xe=async()=>{try{await a.mutateAsync({id:n.id,title:ne,description:J||null}),re.success("Course updated"),he(!1)}catch{re.error("Failed to update")}};return e.jsxs(Vs,{title:n.title,children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>t("/admin/lms"),children:e.jsx(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(u2,{className:"h-3.5 w-3.5"}):e.jsx(Jz,{className:"h-3.5 w-3.5"}),n.is_sequential?"Sequential":"Free order"]}),e.jsxs("span",{children:[ue.length," module",ue.length!==1?"s":""]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{variant:"outline",size:"sm",onClick:()=>{te(n.title),ce(n.description||""),he(!0)},children:[e.jsx(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(()=>re.success(n.is_published?"Unpublished":"Published")),children:[n.is_published?e.jsx($g,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(Ca,{className:"h-3.5 w-3.5 mr-1"}),n.is_published?"Unpublish":"Publish"]})]})]}),e.jsxs(ha,{defaultValue:"modules",className:"w-full",children:[e.jsxs(ma,{children:[e.jsx(Zt,{value:"modules",children:"Modules"}),e.jsx(Zt,{value:"access",children:"Access & Permissions"}),e.jsx(Zt,{value:"settings",children:"Settings"})]}),e.jsxs(Xt,{value:"modules",className:"mt-6 space-y-4",children:[ue.map((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(),dt(rt,"up")},disabled:rt===0,className:"hover:text-foreground disabled:opacity-30",children:e.jsx(yb,{className:"h-3.5 w-3.5"})}),e.jsx("button",{onClick:Ke=>{Ke.stopPropagation(),dt(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(ua,{className:"h-3 w-3"})," Video"]}),at.text_content&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(Jr,{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(Wd,{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),v({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(Hn,{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(dn,{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(pr,{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),v({title:"",description:"",video_url:"",text_content:"",duration_minutes:""})},children:[e.jsx(dn,{className:"h-4 w-4 mr-2"})," Add Module"]})]}),e.jsx(Xt,{value:"access",className:"mt-6 space-y-4",children:e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-base",children:"Who can access this course?"})}),e.jsxs(Ie,{className:"space-y-5",children:[e.jsxs("div",{className:Pt("flex items-center gap-3 p-4 rounded-xl border-2 cursor-pointer transition-all",Ee?"border-primary bg-primary/5":"border-muted hover:border-muted-foreground/30"),onClick:Ve,children:[e.jsx("div",{className:Pt("h-10 w-10 rounded-full flex items-center justify-center shrink-0",Ee?"bg-primary/15 text-primary":"bg-muted text-muted-foreground"),children:e.jsx(dl,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-semibold",children:"All Brokerages / All Agents"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Every agent on the platform can access this course"})]}),e.jsx(Sn,{checked:Ee,onCheckedChange:Ve})]}),!Ee&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold",children:"Select Brokerages"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Se.length===0?"No brokerages selected — agents won't see this course":`${Se.length} brokerage${Se.length!==1?"s":""} selected`})]}),Se.length>0&&e.jsx($,{size:"sm",variant:"ghost",className:"text-xs text-muted-foreground",onClick:qe,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:Le.length===0?e.jsx("div",{className:"p-4 text-center text-sm text-muted-foreground",children:"No brokerages found"}):Le.map(at=>{const rt=Se.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(ji,{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(Xt,{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(Ie,{children:e.jsxs("div",{className:"flex items-start gap-6",children:[n.thumbnail_url?e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:n.thumbnail_url,alt:"Course thumbnail",className:"w-48 h-28 object-cover rounded-lg border"}),e.jsx("button",{onClick:()=>a.mutateAsync({id:n.id,thumbnail_url:null}).then(()=>re.success("Thumbnail removed")),className:"absolute -top-2 -right-2 bg-destructive text-destructive-foreground rounded-full p-1 opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx(pr,{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(Sv,{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(),pt=`${n.id}/thumbnail.${Je}`,{error:gt}=await q.storage.from("lms-thumbnails").upload(pt,rt,{upsert:!0});if(gt)throw gt;const{data:ss}=q.storage.from("lms-thumbnails").getPublicUrl(pt),Yt=`${ss.publicUrl}?t=${Date.now()}`;await a.mutateAsync({id:n.id,thumbnail_url:Yt}),re.success("Thumbnail uploaded")}catch{re.error("Failed to upload thumbnail")}finally{X(!1),G.current&&(G.current.value="")}}}}),e.jsxs($,{variant:"outline",size:"sm",disabled:Y,onClick:()=>{var at;return(at=G.current)==null?void 0:at.click()},children:[Y?e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(ni,{className:"h-4 w-4 mr-2"}),Y?"Uploading...":"Upload Thumbnail"]})]})]})})]}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-base",children:"Course Settings"})}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Sequential Learning"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Agents must complete modules in order before advancing"})]}),e.jsx(Sn,{checked:n.is_sequential,onCheckedChange:at=>a.mutateAsync({id:n.id,is_sequential:at}).then(()=>re.success("Updated"))})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Published"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Make this course visible to agents with access"})]}),e.jsx(Sn,{checked:n.is_published,onCheckedChange:at=>a.mutateAsync({id:n.id,is_published:at}).then(()=>re.success("Updated"))})]})]})]})]})]})]}),e.jsx(zs,{open:g||!!m,onOpenChange:at=>{at||(x(!1),f(null))},children:e.jsxs(Os,{className:"max-w-lg",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:m?"Edit Module":"Add Module"}),e.jsx(Pr,{children:"Configure the module content"})]}),e.jsxs("div",{className:"space-y-4 max-h-[60vh] overflow-auto",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Title"}),e.jsx(pe,{value:y.title,onChange:at=>v(rt=>({...rt,title:at.target.value})),placeholder:"Module title"})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Description"}),e.jsx(Ls,{value:y.description,onChange:at=>v(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),v(Je=>({...Je,video_url:""})))}}),P?e.jsxs("div",{className:"flex items-center justify-center gap-2 text-sm",children:[e.jsx(ua,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"font-medium text-primary",children:P.name}),e.jsx($,{type:"button",size:"sm",variant:"ghost",className:"h-6 w-6 p-0",onClick:at=>{at.stopPropagation(),R(null)},children:e.jsx(pr,{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:y.video_url,onChange:at=>v(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(Ls,{value:y.text_content,onChange:at=>v(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:y.duration_minutes,onChange:at=>v(rt=>({...rt,duration_minutes:at.target.value})),placeholder:"e.g. 15"})]})]}),e.jsxs(Sr,{children:[e.jsx($,{variant:"outline",onClick:()=>{x(!1),f(null),R(null)},children:"Cancel"}),e.jsxs($,{onClick:m?Ne:Be,disabled:!y.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(zs,{open:!!b,onOpenChange:at=>{at||w(null)},children:e.jsxs(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Add Resource"}),e.jsx(Pr,{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(Sr,{children:[e.jsx($,{variant:"outline",onClick:()=>w(null),children:"Cancel"}),e.jsx($,{onClick:()=>b&&Ce(b),disabled:!S.title.trim(),children:"Add Resource"})]})]})}),e.jsx(zs,{open:_e,onOpenChange:he,children:e.jsxs(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Edit Course"}),e.jsx(Pr,{children:"Update the course title and description"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Title"}),e.jsx(pe,{value:ne,onChange:at=>te(at.target.value)})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Description"}),e.jsx(Ls,{value:J,onChange:at=>ce(at.target.value),rows:3})]})]}),e.jsxs(Sr,{children:[e.jsx($,{variant:"outline",onClick:()=>he(!1),children:"Cancel"}),e.jsx($,{onClick:Xe,disabled:!ne.trim(),children:"Save"})]})]})})]})}function nur(){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 rur(){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 aur(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 iur(){const s=Xn(),{data:t,isLoading:n}=nur(),{data:r,isLoading:a}=rur(),[i,l]=j.useState(null),{data:o,isLoading:c}=aur(i),[d,u]=j.useState(""),h=r==null?void 0:r.find(g=>g.course_id===i),m=o==null?void 0:o.filter(g=>{var x,y;return!d||((x=g.agent_name)==null?void 0:x.toLowerCase().includes(d.toLowerCase()))||((y=g.email)==null?void 0:y.toLowerCase().includes(d.toLowerCase()))}),f=[{label:"Total Courses",value:(t==null?void 0:t.total_courses)??0,icon:Xf,color:"text-primary"},{label:"Published",value:(t==null?void 0:t.published_courses)??0,icon: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(Ie,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(g.icon,{className:Pt("h-4 w-4",g.color)}),e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:g.label})]}),e.jsx("p",{className:"text-2xl font-bold text-foreground",children:n?"—":g.value})]})},g.label))}),e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-5 gap-6",children:[e.jsxs("div",{className:"xl:col-span-2 space-y-3",children:[e.jsxs("h2",{className:"text-lg font-semibold text-foreground flex items-center gap-2",children:[e.jsx(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(Ie,{className:"p-4",children:e.jsx("div",{className:"h-16 bg-muted rounded"})})},g))}):r!=null&&r.length?e.jsx("div",{className:"space-y-2",children:r.map(g=>{const x=i===g.course_id;return e.jsx(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(Ie,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between mb-3",children:[e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-semibold text-sm text-foreground truncate",children:g.course_title}),e.jsx($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(Ie,{className:"py-10 text-center",children:e.jsx("p",{className:"text-muted-foreground text-sm",children:"No courses created yet"})})})]}),e.jsxs("div",{className:"xl:col-span-3 space-y-3",children:[e.jsxs("h2",{className:"text-lg font-semibold text-foreground flex items-center gap-2",children:[e.jsx(m2,{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(Zr,{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(Ie,{className:"p-4",children:e.jsx("div",{className:"h-12 bg-muted rounded"})})},g))}):m!=null&&m.length?e.jsx("div",{className:"space-y-2 max-h-[600px] overflow-y-auto pr-1",children:m.map((g,x)=>{const y=g.completion_pct>=100;return e.jsx(je,{className:Pt("transition-all",y&&"border-emerald-200 bg-emerald-50/30 dark:border-emerald-900/40 dark:bg-emerald-950/10"),children:e.jsx(Ie,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:Pt("flex items-center justify-center w-7 h-7 rounded-full text-xs font-bold shrink-0",x===0?"bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400":x===1?"bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-400":x===2?"bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400":"bg-muted text-muted-foreground"),children:x+1}),e.jsxs(Oa,{className:"h-9 w-9 shrink-0",children:[e.jsx(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}),y&&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(da,{className:"h-3 w-3"}),en(new Date(g.last_activity),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"text-right shrink-0 w-20",children:[e.jsxs("p",{className:Pt("text-sm font-bold",y?"text-emerald-600 dark:text-emerald-400":"text-foreground"),children:[g.completion_pct,"%"]}),e.jsx(Yi,{value:g.completion_pct,className:"h-1.5 mt-1"})]})]})})},g.user_id)})}):e.jsx(je,{className:"border-dashed",children:e.jsx(Ie,{className:"py-10 text-center",children:e.jsx("p",{className:"text-muted-foreground text-sm",children:d?"No agents match your search":"No agents have started this course yet"})})})]}):e.jsx(je,{className:"border-dashed",children:e.jsxs(Ie,{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 our(){const{user:s}=bs(),t=Xn(),{data:n,isLoading:r}=Qdr();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(Ie,{className:"p-6",children:[e.jsx("div",{className:"h-5 bg-muted rounded w-2/3"}),e.jsx("div",{className:"h-3 bg-muted rounded w-1/2 mt-3"})]})},a))}):n!=null&&n.length?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:n.map(a=>e.jsx(lur,{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(Ie,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(Xf,{className:"h-12 w-12 text-muted-foreground/50 mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-1",children:"No courses available yet"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Check back soon for new training content"})]})})]})})}function lur({course:s,userId:t,onClick:n}){var o;const r=((o=s.modules)==null?void 0:o.length)??0,{data:a}=Kos(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(Ie,{className:"p-4 space-y-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-foreground group-hover:text-primary transition-colors line-clamp-1",children:s.title}),s.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:s.description})]}),e.jsxs("div",{className:"flex items-center gap-3 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Xf,{className:"h-3.5 w-3.5"}),r," module",r!==1?"s":""]}),e.jsxs("span",{className:"flex items-center gap-1",children:[s.is_sequential?e.jsx(u2,{className:"h-3.5 w-3.5"}):e.jsx(Jz,{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 cur(){const{courseId:s}=Wi(),t=Xn(),{user:n}=bs(),{data:r,isLoading:a}=Jdr(s),{data:i}=Kos(s),l=eur(),[o,c]=j.useState(null),d=(r==null?void 0:r.modules)||[],u=new Set((i==null?void 0:i.filter(b=>b.completed).map(b=>b.module_id))||[]),h=u.size,m=d.length>0?Math.round(h/d.length*100):0;j.useEffect(()=>{if(d.length>0&&!o){const b=d.find(w=>!u.has(w.id));c((b==null?void 0:b.id)||d[0].id)}},[d,o,u]);const f=d.find(b=>b.id===o),g=d.findIndex(b=>b.id===o),x=(b,w)=>{if(!(r!=null&&r.is_sequential)||w===0)return!1;for(let S=0;S{if(!(!f||!n||!s))try{await l.mutateAsync({courseId:s,moduleId:f.id,userId:n.id}),re.success("Module completed! 🎉"),g{const w=b.match(/(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([a-zA-Z0-9_-]{11})/);if(w)return`https://www.youtube.com/embed/${w[1]}`;const S=b.match(/vimeo\.com\/(\d+)/);if(S)return`https://player.vimeo.com/video/${S[1]}`;const 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(Ie,{className:"p-0",children:[e.jsx("div",{className:"p-3 border-b",children:e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Modules"})}),e.jsx(uo,{className:"max-h-[calc(100vh-280px)]",children:e.jsx("div",{className:"p-1",children:d.map((b,w)=>{const S=x(b,w),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(pc,{className:"h-4 w-4 text-muted-foreground"}):A?e.jsx(Vr,{className:"h-4 w-4 text-green-500"}):e.jsx(Og,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:Pt("font-medium truncate",E&&"text-primary"),children:[w+1,". ",b.title]}),b.duration_minutes&&e.jsxs("span",{className:"text-[11px] text-muted-foreground flex items-center gap-0.5 mt-0.5",children:[e.jsx(da,{className:"h-3 w-3"})," ",b.duration_minutes," min"]})]})]},b.id)})})})]})}),e.jsx("div",{className:"space-y-4",children:f?e.jsxs(e.Fragment,{children:[f.video_url&&e.jsx(je,{className:"overflow-hidden",children:e.jsx("div",{className:"aspect-video bg-black",children:e.jsx("iframe",{src:v(f.video_url),className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})}),e.jsx(je,{children:e.jsxs(Ie,{className:"p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold",children:f.title}),f.description&&e.jsx("p",{className:"text-muted-foreground mt-1",children:f.description})]}),u.has(f.id)?e.jsxs($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:y,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(Jr,{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(Wd,{className:"h-4 w-4 text-blue-500 shrink-0"}),e.jsx("span",{className:"flex-1 truncate",children:b.title}),e.jsx(Fr,{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(Ie,{className:"flex items-center justify-center py-16 text-muted-foreground",children:"Select a module to begin"})})})]})]})}):e.jsx(Vs,{title:"Not Found",children:e.jsxs("div",{className:"text-center py-20",children:[e.jsx("p",{className:"text-muted-foreground",children:"Course not found"}),e.jsxs($,{variant:"outline",className:"mt-4",onClick:()=>t("/levelup-u"),children:[e.jsx(Va,{className:"h-4 w-4 mr-2"})," Back"]})]})})}function dur({headline:s,subtext:t,primaryColor:n,accentColor:r,heroImageUrl:a,logoUrl:i,brokerageName:l}){return e.jsxs("section",{className:"relative min-h-screen flex items-center justify-center overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0",style:{background:`linear-gradient(160deg, ${r} 0%, ${n} 50%, ${r}ee 100%)`}}),a&&e.jsx("div",{className:"absolute inset-0 bg-cover bg-center opacity-20",style:{backgroundImage:`url(${a})`}}),e.jsx("div",{className:"absolute inset-0 opacity-[0.03]",style:{backgroundImage:"radial-gradient(circle at 25% 25%, white 1px, transparent 1px), radial-gradient(circle at 75% 75%, white 1px, transparent 1px)",backgroundSize:"60px 60px"}}),e.jsx("div",{className:"absolute bottom-0 left-0 right-0 h-32 bg-gradient-to-t from-white to-transparent"}),e.jsxs("div",{className:"relative z-10 text-center max-w-4xl mx-auto px-6 py-24",children:[i&&e.jsx(Br.img,{src:i,alt:l,className:"h-14 md:h-20 w-auto mx-auto mb-10 drop-shadow-2xl",initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1},transition:{duration:.8,delay:.2}}),e.jsx(Br.div,{initial:{opacity:0,y:30},animate:{opacity:1,y:0},transition:{duration:.8,delay:.3},children:e.jsx("span",{className:"inline-block text-white/70 text-sm md:text-base font-medium tracking-[0.2em] uppercase mb-6",children:"Your Next Chapter Starts Here"})}),e.jsx(Br.h1,{className:"text-4xl md:text-6xl lg:text-7xl font-bold text-white mb-8 leading-[1.1] tracking-tight",initial:{opacity:0,y:40},animate:{opacity:1,y:0},transition:{duration:.9,delay:.5},children:s}),e.jsx(Br.p,{className:"text-lg md:text-xl text-white/80 mb-12 max-w-2xl mx-auto leading-relaxed font-light",initial:{opacity:0,y:30},animate:{opacity:1,y:0},transition:{duration:.8,delay:.7},children:t}),e.jsxs(Br.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.7,delay:.9},className:"flex flex-col sm:flex-row items-center justify-center gap-4",children:[e.jsxs("a",{href:"#apply",className:"group inline-flex items-center gap-3 px-10 py-4 rounded-full text-lg font-semibold shadow-2xl transition-all duration-300 hover:scale-105 hover:shadow-3xl",style:{backgroundColor:"white",color:r},children:["Get In Touch",e.jsx(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(Br.div,{className:"absolute bottom-8 left-1/2 -translate-x-1/2 z-10",animate:{y:[0,8,0]},transition:{duration:2,repeat:1/0,ease:"easeInOut"},children:e.jsx("div",{className:"w-6 h-10 border-2 border-white/40 rounded-full flex justify-center pt-2",children:e.jsx("div",{className:"w-1.5 h-3 bg-white/60 rounded-full"})})})]})}function R2({children:s,className:t="",delay:n=0,direction:r="up"}){const a=j.useRef(null),i=a9s(a,{once:!0,margin:"-80px"}),l={hidden:{opacity:0,y:r==="up"?40:0,x:r==="left"?-40:r==="right"?40:0},visible:{opacity:1,y:0,x:0}};return e.jsx(Br.div,{ref:a,initial:"hidden",animate:i?"visible":"hidden",variants:l,transition:{duration:.7,delay:n,ease:[.25,.46,.45,.94]},className:t,children:s})}function uur({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(R2,{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(R2,{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 hur({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(R2,{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(R2,{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(pr,{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 mur({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(R2,{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(R2,{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(h2,{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 fur({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(R2,{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(R2,{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(Ls,{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 pur({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(R2,{children:e.jsxs("div",{className:"text-center mb-8",children:[l&&e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-[11px] font-semibold bg-white/15 text-white backdrop-blur mb-4",children:[e.jsx(pc,{className:"h-2.5 w-2.5"})," 100% Confidential"]}),e.jsx("h2",{className:"text-3xl md:text-4xl font-bold text-white mb-3 tracking-tight",children:"Start a Confidential Conversation"}),e.jsx("p",{className:"text-white/70 text-lg font-light",children:"No high-pressure sales calls. Ever."})]})}),e.jsx(R2,{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(aK,{mode:"wait",children:[o===1&&e.jsxs(Br.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:-20},transition:{duration:.25},className:"space-y-3",children:[e.jsx("h3",{className:"text-lg font-semibold mb-1",style:{color:i},children:"What's most important to you?"}),e.jsx("p",{className:"text-sm text-gray-500 mb-5",children:"Pick the one that resonates most. We'll tailor the conversation."}),[{val:"Better commission split / cap",label:"Better Splits & Caps",icon:"💰"},{val:"Better technology and tools",label:"Better Tech & Tools",icon:"🛠️"},{val:"Better training and mentorship",label:"Better Training",icon:"📚"},{val:"Better culture and team",label:"Better Culture",icon:"🤝"},{val:"Just exploring options confidentially",label:"Just Exploring",icon:"🔍"}].map(g=>e.jsxs("button",{type:"button",onClick:()=>f(g.val),className:"w-full flex items-center gap-3 p-4 rounded-xl border-2 border-gray-100 hover:border-gray-300 transition-all text-left group",children:[e.jsx("span",{className:"text-2xl",children:g.icon}),e.jsx("span",{className:"font-medium text-gray-700 group-hover:text-gray-900 flex-1",children:g.label}),e.jsx(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(Br.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:-20},transition:{duration:.25},className:"space-y-4",children:[e.jsx("h3",{className:"text-lg font-semibold mb-1",style:{color:i},children:"How can we reach you?"}),e.jsx("p",{className:"text-sm text-gray-500 mb-3",children:"We'll text first, on your schedule."}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-gray-700 text-sm font-medium",children:"First Name *"}),e.jsx(pe,{required:!0,value:s.first_name,onChange:g=>t(x=>({...x,first_name:g.target.value})),className:"h-11",placeholder:"John"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-gray-700 text-sm font-medium",children:"Last Name"}),e.jsx(pe,{value:s.last_name,onChange:g=>t(x=>({...x,last_name:g.target.value})),className:"h-11",placeholder:"Smith"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-gray-700 text-sm font-medium",children:"Email *"}),e.jsx(pe,{type:"email",required:!0,value:s.email,onChange:g=>t(x=>({...x,email:g.target.value})),className:"h-11",placeholder:"john@email.com"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-gray-700 text-sm font-medium",children:"Phone (preferred)"}),e.jsx(pe,{value:s.phone,onChange:g=>t(x=>({...x,phone:g.target.value})),className:"h-11",placeholder:"(555) 123-4567"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs($,{type:"button",variant:"ghost",onClick:()=>c(1),className:"h-11",children:[e.jsx(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(Br.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:-20},transition:{duration:.25},className:"space-y-4",children:[e.jsx("h3",{className:"text-lg font-semibold mb-1",style:{color:i},children:"A few quick details (optional)"}),e.jsx("p",{className:"text-sm text-gray-500 mb-3",children:"Helps us prepare a more personalized comp comparison."}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-gray-700 text-sm font-medium",children:"Current Brokerage"}),e.jsx(pe,{value:s.current_brokerage,onChange:g=>t(x=>({...x,current_brokerage:g.target.value})),className:"h-11",placeholder:"(stays private)"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-gray-700 text-sm font-medium",children:"Years Experience"}),e.jsx(pe,{type:"number",min:"0",value:s.experience_years,onChange:g=>t(x=>({...x,experience_years:g.target.value})),className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-gray-700 text-sm font-medium",children:"Annual Production"}),e.jsx(pe,{value:s.annual_production,onChange:g=>t(x=>({...x,annual_production:g.target.value})),className:"h-11",placeholder:"e.g. $5M"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{className:"text-gray-700 text-sm font-medium",children:"Anything else?"}),e.jsx(Ls,{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(ca,{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(eo,{className:"h-3 w-3"})," Text first"]}),e.jsxs("div",{className:"flex items-center gap-1 justify-center",children:[e.jsx(Da,{className:"h-3 w-3"})," No spam"]})]})]})})]})]})}function gur({config:s,primaryColor:t,accentColor:n,brokerageId:r,brokerageName:a}){const{toast:i}=Bi(),[l,o]=j.useState("250000"),[c,d]=j.useState("12"),[u,h]=j.useState("70"),[m,f]=j.useState("150"),[g,x]=j.useState(""),[y,v]=j.useState(!1),[b,w]=j.useState(!1),S=s.commission_split_pct??80,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,Y=U*(V/100)-G*12-P*W,X=1-S/100,ae=X>0?A/X:U,le=Math.min(U,ae),ne=Math.max(0,U-ae),te=le*X+ne*(1-E/100),J=U-te-I*12-P*W,ce=J-Y;return{currentNet:Y,newNet:J,diff:ce}},[l,c,u,m,S,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),v(!0),i({title:"Sent!",description:"Check your email for the full breakdown."})}catch(W){i({title:"Error",description:W.message,variant:"destructive"})}finally{w(!1)}}};return e.jsx("section",{className:"py-20 md:py-28 px-6 bg-gray-50",children:e.jsxs("div",{className:"max-w-5xl mx-auto",children:[e.jsx(R2,{children:e.jsxs("div",{className:"text-center mb-10",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-4 py-1.5 rounded-full text-xs font-semibold mb-4",style:{backgroundColor:`${t}15`,color:n},children:[e.jsx(pc,{className:"h-3 w-3"})," 100% Confidential — No Signup Required"]}),e.jsx("h2",{className:"text-3xl md:text-4xl font-bold tracking-tight mb-3",style:{color:n},children:s.headline||"See What You Could Earn With Us"}),e.jsx("p",{className:"text-gray-500 text-lg font-light max-w-xl mx-auto",children:s.subtext||"Confidential 60-second calculator — no signup required."})]})}),e.jsx(R2,{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(a2,{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(Br.div,{initial:{scale:.95,opacity:0},animate:{scale:1,opacity:1},className:"bg-white/10 backdrop-blur rounded-2xl p-5 text-center",children:[e.jsx("p",{className:"text-white/80 text-xs uppercase tracking-wide mb-1",children:R.diff>=0?"You could earn":"Difference"}),e.jsxs("p",{className:"text-4xl font-bold mb-1",children:[R.diff>=0?"+":"",D(R.diff)]}),e.jsx("p",{className:"text-white/70 text-xs",children:R.diff>=0?"more per year":"per year"})]},R.diff),s.show_email_capture&&!y&&e.jsxs("form",{onSubmit:O,className:"mt-6 space-y-2",children:[e.jsx("p",{className:"text-white/80 text-xs",children:s.email_capture_label||"Want the full breakdown? Enter your email."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pe,{type:"email",required:!0,value:g,onChange:U=>x(U.target.value),placeholder:"you@email.com",className:"bg-white/95 border-0 text-gray-900 h-10 text-sm"}),e.jsx($,{type:"submit",disabled:b,className:"h-10 bg-white text-gray-900 hover:bg-white/90 text-sm font-semibold",children:"Send"})]})]}),y&&e.jsxs("div",{className:"mt-6 flex items-center gap-2 text-sm text-white/90 bg-white/10 rounded-lg p-3",children:[e.jsx(ca,{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 xur({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(R2,{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(o2,{className:"h-12 w-12 text-white"})}),e.jsxs("div",{className:"flex-1 text-center md:text-left",children:[e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-[11px] font-semibold mb-3",style:{backgroundColor:`${t}15`,color:n},children:[e.jsx(pc,{className:"h-2.5 w-2.5"})," No call required — instant download"]}),e.jsx("h3",{className:"text-2xl md:text-3xl font-bold tracking-tight mb-2",style:{color:n},children:s.title||"Get the Full Comp Plan PDF"}),e.jsx("p",{className:"text-gray-500 leading-relaxed mb-5",children:s.description||"See exactly how splits, caps, and fees work — no call required."}),d?e.jsxs("div",{className:"flex items-center gap-2 p-4 rounded-xl bg-green-50 border border-green-200 text-green-800 text-sm",children:[e.jsx(ca,{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(o2,{className:"h-4 w-4 mr-2"}),h?"Sending...":s.button_text||"Email Me the PDF"]})]})]})]})})})})})}function yur(){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(ji,{className:"h-10 w-10 mx-auto text-gray-300 mb-4"}),e.jsx("p",{className:"text-gray-400 text-lg",children:"This page is not available."})]})});const h=d,m=(h==null?void 0:h.primary_color)||"#406E71",f=(h==null?void 0:h.accent_color)||"#2a4c64",g=(h==null?void 0:h.benefits)||[],x=(h==null?void 0:h.testimonials)||[],y=(h==null?void 0:h.gallery_images)||[],v=(h==null?void 0:h.hero_headline)||`Join ${l.name}`,b=(h==null?void 0:h.hero_subtext)||"Take your real estate career to the next level with a brokerage that invests in your growth.",w=(h==null?void 0:h.calculator_enabled)===!0,S=(h==null?void 0:h.calculator_config)||{},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(Br.div,{initial:{opacity:0,scale:.9},animate:{opacity:1,scale:1},transition:{duration:.6},className:"max-w-md w-full mx-4 text-center",children:[e.jsx("div",{className:"h-20 w-20 rounded-full flex items-center justify-center mx-auto mb-6 shadow-lg",style:{background:`linear-gradient(135deg, ${m}, ${f})`},children:e.jsx(ca,{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(dur,{headline:v,subtext:b,primaryColor:m,accentColor:f,heroImageUrl:h==null?void 0:h.hero_image_url,logoUrl:h==null?void 0:h.logo_url,brokerageName:l.name}),e.jsx(uur,{benefits:g,accentColor:f,primaryColor:m}),e.jsx(hur,{images:y,primaryColor:m,accentColor:f}),e.jsx(mur,{testimonials:x,primaryColor:m,accentColor:f}),w&&e.jsx(gur,{config:S,primaryColor:m,accentColor:f,brokerageId:l.id,brokerageName:l.name}),A&&e.jsx(xur,{config:E,primaryColor:m,accentColor:f,brokerageId:l.id}),I==="multi_step"?e.jsx(pur,{form:a,setForm:i,onSubmit:()=>u.mutate(),isPending:u.isPending,primaryColor:m,accentColor:f,showConfidentialBadges:P}):e.jsx(fur,{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 vur(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 bur(){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:y,error:v}=await q.from("recruit_videos").select(` *, prospect:recruit_prospects(first_name, last_name), video:agent_videos(id, title, playback_url, thumbnail_url, duration_seconds, owner_user_id) `).eq("share_token",s).single();if(v)throw v;const{data:b}=await q.from("profiles").select("name, avatar_url, title, recruit_cta_url").eq("id",(A=y.video)==null?void 0:A.owner_user_id).single(),{data:w}=await q.from("brokerages").select("name").eq("id",y.brokerage_id).single(),{data:S}=await q.from("recruit_landing_page_settings").select("logo_url, primary_color, accent_color, hero_headline").eq("brokerage_id",y.brokerage_id).maybeSingle();return{rv:y,profile:b,brokerage:w,settings:S}},enabled:!!s});if(j.useEffect(()=>{var y;!((y=n==null?void 0:n.rv)!=null&&y.id)||t.current||(t.current=!0,q.rpc("log_recruit_video_view",{p_recruit_video_id:n.rv.id,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null}).then(()=>{}))},[(m=n==null?void 0:n.rv)==null?void 0:m.id]),r)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})});if(a||!n)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsx("p",{className:"text-muted-foreground",children:"This video is no longer available."})});const{rv:i,profile:l,brokerage:o,settings:c}=n,d=(c==null?void 0:c.primary_color)||"#3b82f6",u=((f=i.prospect)==null?void 0:f.first_name)||"there",h=(g=i.video)!=null&&g.playback_url?vur(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(Ta,{className:"h-5 w-5 mr-2"})," Schedule a Conversation"]})})})]}),e.jsx("footer",{className:"text-center py-6 text-xs text-muted-foreground",children:"Powered by LevelUp"})]})]})}const _ur="relzejiswnotikjgvjhz",BEt=`https://${_ur}.supabase.co/functions/v1/recruit-unsubscribe`;function wur(){const[s]=gc(),t=s.get("token")||"",[n,r]=j.useState(!0),[a,i]=j.useState(!1),[l,o]=j.useState(!1),[c,d]=j.useState(""),[u,h]=j.useState({});j.useEffect(()=>{document.body.classList.add("recruit-unsubscribe-page");const f=()=>{['[id*="lc_text_widget"]','[class*="lc-text-widget"]','[class*="lc_text_widget"]','[id*="chat-widget"]','[class*="chat-widget"]','iframe[src*="leadconnector"]','iframe[src*="msgsndr"]',"[data-chat-widget]",'div[id^="hubspot"]',".widget-visible"].forEach(v=>document.querySelectorAll(v).forEach(b=>b.style.display="none"))};f();const g=[setTimeout(f,500),setTimeout(f,1500),setTimeout(f,3e3)],x=new MutationObserver(f);return x.observe(document.body,{childList:!0,subtree:!0}),()=>{document.body.classList.remove("recruit-unsubscribe-page"),g.forEach(clearTimeout),x.disconnect()}},[]),j.useEffect(()=>{if(!t){h({error:"Missing unsubscribe token in link."}),r(!1);return}fetch(`${BEt}?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(BEt,{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(ll,{className:"h-7 w-7 text-red-500"})}),e.jsx("h1",{className:"text-xl font-semibold text-slate-800",children:"Link Invalid"}),e.jsx("p",{className:"text-sm text-slate-500",children:u.error}),e.jsx("p",{className:"text-xs text-slate-400 pt-2",children:"If you continue to receive emails you don't want, please reply directly to one of them and we'll remove you immediately."})]}):l?e.jsxs("div",{className:"text-center space-y-4",children:[e.jsx("div",{className:"mx-auto w-14 h-14 rounded-full bg-emerald-50 flex items-center justify-center",children:e.jsx(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(Ls,{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 jur="relzejiswnotikjgvjhz",$Et=`https://${jur}.supabase.co/functions/v1/event-invite-unsubscribe`;function Nur(){const[s]=gc(),t=s.get("token")||"",[n,r]=j.useState(!0),[a,i]=j.useState(!1),[l,o]=j.useState(!1),[c,d]=j.useState({});j.useEffect(()=>(document.body.classList.add("event-invite-unsubscribe-page"),()=>{document.body.classList.remove("event-invite-unsubscribe-page")}),[]),j.useEffect(()=>{if(!t){d({error:"Missing unsubscribe token in link."}),r(!1);return}fetch(`${$Et}?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($Et,{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(ll,{className:"h-7 w-7 text-red-500"})}),e.jsx("h1",{className:"text-xl font-semibold text-slate-800",children:"Link Invalid"}),e.jsx("p",{className:"text-sm text-slate-500",children:c.error})]}):l?e.jsxs("div",{className:"text-center space-y-4",children:[e.jsx("div",{className:"mx-auto w-14 h-14 rounded-full bg-emerald-50 flex items-center justify-center",children:e.jsx(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(pJ,{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 kur(){var R,D,O;const s=Xn(),t=Wt(),{isAdmin:n}=bs(),[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:()=>{re.success("Business updated"),t.invalidateQueries({queryKey:["google-business-status"]}),t.invalidateQueries({queryKey:["my-social-accounts"]})},onError:()=>re.error("Could not update your business selection")}),f=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"]}),re.success("Google Business disconnected")},onError:()=>re.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"]}),re.success("Account disconnected successfully")},onError:()=>{re.error("Failed to disconnect account")}}),x=async U=>{a(!0),sessionStorage.setItem("social-connect-return-to",window.location.pathname);try{const{data:W,error:V}=await q.functions.invoke("meta-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/callback",authMode:U}});if(V)throw V;if(W!=null&&W.authUrl)window.location.href=W.authUrl;else throw new Error("Failed to get authorization URL")}catch(W){console.error("Meta OAuth error:",W),re.error("Failed to start connection. Please try again."),a(!1)}},y=async()=>{a(!0);try{const{data:U,error:W}=await q.functions.invoke("linkedin-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/linkedin-callback"}});if(W)throw W;if(U!=null&&U.authUrl)window.location.href=U.authUrl;else throw new Error("Failed to get LinkedIn authorization URL")}catch(U){console.error("LinkedIn OAuth error:",U),re.error("Failed to start LinkedIn connection. Please try again."),a(!1)}},v=async()=>{a(!0);try{const{data:U,error:W}=await q.functions.invoke("google-business-oauth",{body:{action:"get_auth_url",returnPath:"/social-connections"}});if(W)throw W;if(U!=null&&U.authUrl)window.location.href=U.authUrl;else throw new Error("Failed to get Google authorization URL")}catch(U){console.error("Google OAuth error:",U),re.error("Failed to start Google connection. Please try again."),a(!1)}},b=(d==null?void 0:d.filter(U=>U.platform==="facebook"))||[],w=(d==null?void 0:d.filter(U=>U.platform==="instagram"))||[],S=(d==null?void 0:d.filter(U=>U.platform==="linkedin"))||[];d!=null&&d.filter(U=>U.platform==="google_business");const 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||[]),re.success(V.summary||"API tests completed")}catch(V){console.error("Meta API test error:",V),re.error("Failed to run API tests")}finally{l(null)}};return e.jsx(Vs,{title:"Social Connections",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"relative overflow-hidden rounded-2xl bg-gradient-to-br from-pink-500 via-purple-500 to-blue-500 p-6 md:p-8 text-white",children:[e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmYiIGZpbGwtb3BhY2l0eT0iMC4xIj48cGF0aCBkPSJNMzYgMzRjMC0yIDItNCAyLTRzMiAyIDIgNC0yIDQtMiA0LTItMi0yLTR6Ii8+PC9nPjwvZz48L3N2Zz4=')] opacity-30"}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"flex items-center gap-2 mb-3",children:e.jsxs($e,{variant:"secondary",className:"bg-white/20 text-white border-0 backdrop-blur-sm",children:[e.jsx(Nn,{className:"h-3 w-3 mr-1"}),"Post directly from Social Swag"]})}),e.jsx("h1",{className:"text-2xl md:text-3xl font-bold mb-2",children:"Connect Your Social Accounts"}),e.jsx("p",{className:"text-white/90 max-w-xl",children:"Link your Facebook Pages and Instagram Business accounts to post content directly from Social Swag with one click."})]})]}),e.jsxs($,{variant:"ghost",onClick:()=>s("/social-studio"),className:"gap-2",children:[e.jsx(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(Ie,{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(Qp,{className:"h-6 w-6 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(Et,{className:"text-lg",children:"Facebook"}),e.jsx(Gn,{children:"Connect your Facebook Page"})]})]})}),e.jsxs(Ie,{className:"space-y-4",children:[u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(ro,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):b.length>0?e.jsx("div",{className:"space-y-3",children:b.map(U=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(Oa,{className:"h-10 w-10",children:[e.jsx(Ii,{src:U.profile_picture_url||""}),e.jsx(za,{children:e.jsx(Qp,{className:"h-5 w-5"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:U.page_name||U.platform_username||"Facebook Page"}),e.jsx($e,{variant:U.is_active?"default":"secondary",className:"text-xs",children:U.is_active?"Connected":"Inactive"})]})]}),e.jsxs(fc,{children:[e.jsx(Tg,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Hn,{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(ro,{className:"h-4 w-4 animate-spin"}):e.jsx(dn,{className:"h-4 w-4"}),b.length>0?"Connect Another Page":"Connect Facebook Page"]})]})]}),e.jsxs(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(Gn,{children:"Connect your Instagram Business or Creator account"})]})]})}),e.jsxs(Ie,{className:"space-y-4",children:[u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(ro,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):w.length>0?e.jsx("div",{className:"space-y-3",children:w.map(U=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(Oa,{className:"h-10 w-10",children:[e.jsx(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(Tg,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Hn,{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(ro,{className:"h-4 w-4 animate-spin"}):e.jsx(dn,{className:"h-4 w-4"}),w.length>0?"Reconnect Instagram":"Connect Instagram"]}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"Use Instagram login for Business or Creator accounts; Facebook Page login is only needed if you want to connect Pages."})]})]}),e.jsxs(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(dy,{className:"h-6 w-6 text-blue-700"})}),e.jsxs("div",{children:[e.jsx(Et,{className:"text-lg",children:"LinkedIn"}),e.jsx(Gn,{children:"Connect your LinkedIn profile"})]})]})}),e.jsxs(Ie,{className:"space-y-4",children:[u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(ro,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):S.length>0?e.jsx("div",{className:"space-y-3",children:S.map(U=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(Oa,{className:"h-10 w-10",children:[e.jsx(Ii,{src:U.profile_picture_url||""}),e.jsx(za,{children:e.jsx(dy,{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(Tg,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Hn,{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:y,disabled:r,className:"w-full gap-2",variant:S.length>0?"outline":"default",children:[r?e.jsx(ro,{className:"h-4 w-4 animate-spin"}):e.jsx(dn,{className:"h-4 w-4"}),S.length>0?"Reconnect LinkedIn":"Connect LinkedIn"]}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"Share content directly to your LinkedIn profile"})]})]}),e.jsxs(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(ci,{className:"h-6 w-6 text-red-600"})}),e.jsxs("div",{children:[e.jsx(Et,{className:"text-lg",children:"Google Business"}),e.jsx(Gn,{children:"Connect your Google Business Profile"})]})]})}),e.jsxs(Ie,{className:"space-y-4",children:[(h==null?void 0:h.needsReconnect)&&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(ro,{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(ci,{className:"h-5 w-5"})})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:(E==null?void 0:E.location_name)||(h==null?void 0:h.email)||"Google Business"}),e.jsx($e,{variant:"default",className:"text-xs",children:"Connected"})]})]}),e.jsxs(fc,{children:[e.jsx(Tg,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Hn,{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:v,disabled:r,className:"w-full gap-2",variant:A&&!(h!=null&&h.needsReconnect)?"outline":"default",children:[r?e.jsx(ro,{className:"h-4 w-4 animate-spin"}):e.jsx(dn,{className:"h-4 w-4"}),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(VI,{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(Gn,{children:"Run API tests to trigger all required permissions for Meta App Review"})]})]})}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:['Click "Run Tests" on an account to trigger API calls for: ',e.jsx("strong",{children:"public_profile"}),", ",e.jsx("strong",{children:"pages_show_list"}),", ",e.jsx("strong",{children:"pages_read_engagement"}),", ",e.jsx("strong",{children:"instagram_basic"}),", ",e.jsx("strong",{children:"pages_manage_posts"}),", and ",e.jsx("strong",{children:"instagram_content_publish"}),"."]}),e.jsxs("div",{className:"space-y-3",children:[b.map(U=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border bg-background p-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Qp,{className:"h-5 w-5 text-blue-600"}),e.jsx("span",{className:"font-medium",children:U.page_name||"Facebook Page"})]}),e.jsx($,{size:"sm",variant:"outline",onClick:()=>P(U.id),disabled:i===U.id,children:i===U.id?e.jsxs(e.Fragment,{children:[e.jsx(Ct,{className:"h-4 w-4 mr-2 animate-spin"}),"Testing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(VI,{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(VI,{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(Nu,{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(Ie,{children:e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"flex gap-3",children:[e.jsx("div",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-primary text-primary-foreground text-sm font-medium",children:"1"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Connect your accounts"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Link your Facebook, Instagram, or LinkedIn account"})]})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx("div",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-primary text-primary-foreground text-sm font-medium",children:"2"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Browse Social Swag"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Find the perfect image and caption for your post"})]})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx("div",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-primary text-primary-foreground text-sm font-medium",children:"3"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Post with one click"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:'Click "Create Post" to share directly to your accounts'})]})]})]})})]})]})})}function Sur(){const[s]=gc(),t=Xn(),[n,r]=j.useState("loading"),a=j.useRef(!1),[i,l]=j.useState("Processing your connection..."),[o,c]=j.useState(null),[d,u]=j.useState(!1),h=(()=>{const m=sessionStorage.getItem("social-connect-return-to");return m&&m.startsWith("/")&&!m.startsWith("/admin")?m:"/social-connections"})();return j.useEffect(()=>{if(a.current)return;a.current=!0,(async()=>{var v;const f=s.get("code"),g=s.get("error"),x=s.get("error_description"),y=s.get("state");if(g){r("error"),l(x||"Authorization was denied"),re.error("Connection failed: "+(x||g));return}if(!f){r("error"),l("No authorization code received"),re.error("No authorization code received");return}try{const{data:b,error:w}=await q.functions.invoke("meta-oauth",{body:{action:"exchange_code",code:f,state:y,callbackPath:"/social-connections/callback"}});if(w)throw w;if(b!=null&&b.success)r("success"),l(`Successfully connected ${((v=b.accounts)==null?void 0:v.length)||0} account(s)!`),re.success("Social accounts connected successfully!");else throw c((b==null?void 0:b.code)||null),u(!!(b!=null&&b.existingConnectionPreserved)),new Error((b==null?void 0:b.error)||"Unknown error")}catch(b){console.error("OAuth callback error:",b),r("error");const w=b instanceof Error?b.message:"Failed to connect accounts";l(w),re.error("Failed to connect: "+(b instanceof Error?b.message:"Unknown error"))}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(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(Nu,{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(Gn,{children:i})]}),e.jsxs(Ie,{className:"flex flex-col items-center gap-4",children:[n==="error"&&o==="no_managed_pages"&&e.jsxs("div",{className:"w-full rounded-lg border bg-muted/40 p-4 text-left text-sm space-y-3",children:[e.jsx("p",{className:"font-medium text-foreground",children:"How to connect your Facebook Page"}),e.jsxs("ol",{className:"list-decimal space-y-1.5 pl-5 text-muted-foreground",children:[e.jsxs("li",{children:["Click ",e.jsx("span",{className:"font-medium text-foreground",children:"Try Again"})," below."]}),e.jsxs("li",{children:["On the Meta screen that lists your Pages, choose your Page by name — or pick",e.jsx("span",{className:"font-medium text-foreground",children:" Opt in to all current and future Pages"}),"."]}),e.jsx("li",{children:"Leave every permission switched on, then finish."}),e.jsx("li",{children:"If your Page still doesn’t appear, try once more so LevelUp can recover the exact Page selected in Meta."})]}),d&&e.jsx("p",{className:"font-medium text-foreground",children:"Your existing Facebook Page connection is still active."})]}),n!=="loading"&&e.jsx($,{onClick:()=>t(h),children:n==="success"?"View Connected Accounts":"Try Again"})]})]})})}function Cur(){const[s]=gc(),t=Xn();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 Aur(){const[s]=gc(),t=Xn(),[n,r]=j.useState("loading"),[a,i]=j.useState("Connecting your LinkedIn account...");return j.useEffect(()=>{(async()=>{var h;const o=s.get("code"),c=s.get("state"),d=s.get("error"),u=s.get("error_description");if(d){console.error("LinkedIn OAuth error:",d,u),r("error"),i(u||"Failed to connect LinkedIn account"),re.error(u||"Failed to connect LinkedIn");return}if(!o){r("error"),i("No authorization code received"),re.error("No authorization code received");return}try{const{data:m,error:f}=await q.functions.invoke("linkedin-oauth",{body:{action:"exchange_code",code:o,state:c,callbackPath:"/social-connections/linkedin-callback"}});if(f)throw f;if(m!=null&&m.success)r("success"),i(`Successfully connected ${((h=m.accounts)==null?void 0:h.length)||1} LinkedIn account`),re.success("LinkedIn connected successfully!");else throw new Error((m==null?void 0:m.error)||"Failed to connect LinkedIn account")}catch(m){console.error("LinkedIn callback error:",m),r("error"),i(m instanceof Error?m.message:"Failed to connect LinkedIn account"),re.error("Failed to connect LinkedIn")}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center p-4 bg-background",children:e.jsxs(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(Nu,{className:"h-8 w-8 text-red-600"})]}),e.jsxs(Et,{className:"flex items-center justify-center gap-2",children:[e.jsx(dy,{className:"h-5 w-5 text-blue-600"}),n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(Gn,{children:a})]}),e.jsx(Ie,{className:"flex justify-center",children:e.jsx($,{onClick:()=>t("/mission-control/integrations"),disabled:n==="loading",children:n==="success"?"View Integrations":"Back to Integrations"})})]})})}function Eur(){const s=Xn(),[t,n]=j.useState(null),{data:r,isLoading:a}=dos(t||void 0,!0),{data:i,isLoading:l}=Rlt(!0),{cartItems:o}=BLe(),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(tC,{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(Ie,{className:"p-4",children:[e.jsx("h3",{className:"font-semibold mb-1 line-clamp-1",children:u.name}),u.description&&e.jsx("p",{className:"text-sm text-muted-foreground mb-2 line-clamp-2",children:u.description}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"font-bold text-lg",children:["$",Number(u.base_price).toFixed(2)]}),u.variants&&u.variants.length>0&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:[u.variants.length," options"]})]})]})]},u.id)})}):e.jsxs("div",{className:"text-center py-12",children:[e.jsx(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 Yos=j.forwardRef(({...s},t)=>e.jsx("nav",{ref:t,"aria-label":"breadcrumb",...s}));Yos.displayName="Breadcrumb";const Zos=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}));Zos.displayName="BreadcrumbList";const NAe=j.forwardRef(({className:s,...t},n)=>e.jsx("li",{ref:n,className:Pt("inline-flex items-center gap-1.5",s),...t}));NAe.displayName="BreadcrumbItem";const iQe=j.forwardRef(({asChild:s,className:t,...n},r)=>{const a=s?YJe:"a";return e.jsx(a,{ref:r,className:Pt("transition-colors hover:text-foreground",t),...n})});iQe.displayName="BreadcrumbLink";const Xos=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}));Xos.displayName="BreadcrumbPage";const oQe=({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,{})});oQe.displayName="BreadcrumbSeparator";function Tur(){var W,V;const{productId:s}=Wi(),t=Xn(),{data:n,isLoading:r}=kor(s||""),{addToCart:a,cartItems:i}=BLe(),[l,o]=j.useState(null),[c,d]=j.useState(1),[u,h]=j.useState(0),[m,f]=j.useState(null),[g,x]=j.useState(!1),[y,v]=j.useState(!1),b=(W=n==null?void 0:n.variants)==null?void 0:W.find(G=>G.id===l),w=((V=n==null?void 0:n.variants)==null?void 0:V.filter(G=>G.is_active))||[],S=Number((n==null?void 0:n.base_price)||0),A=b?Number(b.price_adjustment):0,E=S+A,I=Number((n==null?void 0:n.shipping_fee)||0),P=i.reduce((G,Y)=>G+Y.quantity,0),R=async G=>{if(!G.target.files||G.target.files.length===0)return;x(!0);const Y=G.target.files[0],X=Y.name.split(".").pop(),ae=`artwork/${Date.now()}-${Math.random().toString(36).substring(7)}.${X}`;try{const{error:le}=await q.storage.from("marketplace").upload(ae,Y);if(le)throw le;const{data:{publicUrl:ne}}=q.storage.from("marketplace").getPublicUrl(ae);f(ne),re.success("Artwork uploaded successfully")}catch(le){re.error("Failed to upload artwork: "+le.message)}finally{x(!1)}},D=()=>{if(n){if(w.length>0&&!l){re.error("Please select an option");return}a(n,b||void 0,c,m||void 0),v(!0),re.success("Added to cart!"),setTimeout(()=>v(!1),2e3)}},O=()=>{n!=null&&n.images&&h(G=>(G+1)%n.images.length)},U=()=>{n!=null&&n.images&&h(G=>(G-1+n.images.length)%n.images.length)};return r?e.jsx(Vs,{title:"Product",children:e.jsxs("div",{className:"grid gap-8 lg:grid-cols-2",children:[e.jsx(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(Yos,{className:"mb-6",children:e.jsxs(Zos,{children:[e.jsx(NAe,{children:e.jsx(iQe,{asChild:!0,children:e.jsx(wr,{to:"/marketplace",children:"Marketplace"})})}),n.category&&e.jsxs(e.Fragment,{children:[e.jsx(oQe,{}),e.jsx(NAe,{children:e.jsx(iQe,{asChild:!0,children:e.jsx(wr,{to:`/marketplace?category=${n.category.id}`,children:n.category.name})})})]}),e.jsx(oQe,{}),e.jsx(NAe,{children:e.jsx(Xos,{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,Y)=>e.jsx("button",{onClick:()=>h(Y),className:`w-16 h-16 flex-shrink-0 rounded-md overflow-hidden border-2 ${Y===u?"border-primary":"border-transparent"}`,children:e.jsx("img",{src:G.image_url,alt:"",className:"w-full h-full object-cover"})},G.id))}),n.video&&e.jsx(je,{children:e.jsxs(Ie,{className:"p-4",children:[e.jsx("h4",{className:"font-medium mb-2",children:"Product Video"}),e.jsx("div",{className:"aspect-video",children:e.jsx("iframe",{src:n.video.video_url,className:"w-full h-full rounded-lg",allowFullScreen:!0})})]})})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[n.category&&e.jsx($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:y,children:y?e.jsxs(e.Fragment,{children:[e.jsx(ca,{className:"h-5 w-5 mr-2"}),"Added!"]}):e.jsxs(e.Fragment,{children:[e.jsx(tC,{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(tC,{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 Mur(){const s=Xn(),{cartItems:t,removeFromCart:n,updateQuantity:r,getItemPrice:a,getSubtotal:i,getShippingTotal:l,getTotal:o,clearCart:c}=BLe(),[d,u]=j.useState(!1),[h,m]=j.useState(""),f=async()=>{if(t.length===0){re.error("Your cart is empty");return}u(!0);try{const{data:g,error:x}=await q.functions.invoke("marketplace-checkout",{body:{items:t.map(y=>{var v;return{product_id:y.product.id,variant_id:((v=y.variant)==null?void 0:v.id)||null,quantity:y.quantity,artwork_url:y.artworkUrl||null}}),notes:h.trim()||null}});if(x)throw x;if(g!=null&&g.url)c(),window.open(g.url,"_blank");else throw new Error("No checkout URL received")}catch(g){re.error("Checkout failed: "+g.message)}finally{u(!1)}};return t.length===0?e.jsx(Vs,{title:"Shopping Cart",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(I4,{className:"h-16 w-16 mx-auto text-muted-foreground mb-4"}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"Your cart is empty"}),e.jsx("p",{className:"text-muted-foreground mb-6",children:"Add some products to get started!"}),e.jsx($,{onClick:()=>s("/marketplace"),children:"Browse Marketplace"})]})}):e.jsx(Vs,{title:"Shopping Cart",children:e.jsxs("div",{className:"grid gap-8 lg:grid-cols-3",children:[e.jsxs("div",{className:"lg:col-span-2 space-y-4",children:[t.map(g=>{var x,y;return e.jsx(je,{children:e.jsx(Ie,{className:"p-4",children:e.jsxs("div",{className:"flex gap-4",children:[e.jsx("div",{className:"w-24 h-24 flex-shrink-0 bg-muted rounded-lg overflow-hidden",children:g.product.images&&g.product.images.length>0?e.jsx("img",{src:((x=g.product.images.find(v=>v.is_primary))==null?void 0:x.image_url)||g.product.images[0].image_url,alt:g.product.name,className:"w-full h-full object-cover"}):e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx(I4,{className:"h-8 w-8 text-muted-foreground"})})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-semibold line-clamp-1",children:g.product.name}),g.variant&&e.jsx("p",{className:"text-sm text-muted-foreground",children:g.variant.name}),e.jsxs("p",{className:"font-medium mt-1",children:["$",a(g).toFixed(2),Number(g.product.shipping_fee)>0&&e.jsxs("span",{className:"text-sm text-muted-foreground ml-2",children:["+ $",Number(g.product.shipping_fee).toFixed(2)," shipping"]})]}),g.artworkUrl&&e.jsx("div",{className:"mt-2",children:e.jsx("span",{className:"text-xs text-muted-foreground",children:"Artwork uploaded ✓"})})]}),e.jsxs("div",{className:"flex flex-col items-end gap-2",children:[e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>{var v;return n(g.product.id,(v=g.variant)==null?void 0:v.id)},children:e.jsx(Hn,{className:"h-4 w-4 text-destructive"})}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx($,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>{var v;return r(g.product.id,(v=g.variant)==null?void 0:v.id,g.quantity-1)},disabled:g.quantity<=1,children:e.jsx(ZN,{className:"h-3 w-3"})}),e.jsx(pe,{type:"number",value:g.quantity,onChange:v=>{var b;return r(g.product.id,(b=g.variant)==null?void 0:b.id,parseInt(v.target.value)||1)},className:"w-14 h-8 text-center text-sm",min:"1"}),e.jsx($,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>{var v;return r(g.product.id,(v=g.variant)==null?void 0:v.id,g.quantity+1)},children:e.jsx(dn,{className:"h-3 w-3"})})]})]})]})})},`${g.product.id}-${((y=g.variant)==null?void 0:y.id)||"base"}`)}),e.jsx($,{variant:"ghost",className:"text-destructive",onClick:c,children:"Clear Cart"})]}),e.jsx("div",{children:e.jsxs(je,{className:"sticky top-4",children:[e.jsx(St,{children:e.jsx(Et,{children:"Order Summary"})}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsxs("span",{children:["Subtotal (",t.reduce((g,x)=>g+x.quantity,0)," items)"]}),e.jsxs("span",{children:["$",i().toFixed(2)]})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{children:"Shipping"}),e.jsxs("span",{children:["$",l().toFixed(2)]})]}),e.jsx(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(Ls,{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 Pur(){const s=Xn(),{data:t,isLoading:n}=Dor();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(Ie,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold",children:r.order_number}),e.jsx("span",{className:"text-muted-foreground text-sm ml-2",children:en(new Date(r.created_at),"MMM d, yyyy")})]}),e.jsx($e,{className:Llt[r.status],children:HV[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(Fr,{className:"h-4 w-4 mr-1"}),"Track"]}),e.jsx(Di,{className:"h-5 w-5 text-muted-foreground"})]})]})]})},r.id)})})})}const UEt=["order_submitted","awaiting_proof_approval","proof_approved","processing","in_production","shipped","completed"];function Iur({currentStatus:s,statusHistory:t}){const n=UEt.indexOf(s);return e.jsx("div",{className:"space-y-3",children:UEt.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(da,{className:"h-4 w-4"}):e.jsx("span",{className:"text-xs",children:a+1})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:`font-medium ${c?"text-muted-foreground":""}`,children:HV[r]}),i&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[en(new Date(i.created_at),"MMM d, yyyy h:mm a"),i.notes&&` — ${i.notes}`]})]})]},r)})})}function Lur(){var v;const{orderId:s}=Wi(),t=Xn(),{data:n,isLoading:r,refetch:a}=For(s||""),i=Bor(),l=$or(),[o,c]=j.useState(!1),[d,u]=j.useState(null),[h,m]=j.useState(""),[f,g]=j.useState(null),x=async b=>{g(b);try{await i.mutateAsync({orderId:s,itemId:b}),re.success("Proof approved!"),a()}catch{re.error("Failed to approve proof")}finally{g(null)}},y=async()=>{if(d){g(d);try{await l.mutateAsync({orderId:s,itemId:d,reason:h}),re.success("Revision requested"),c(!1),m(""),u(null),a()}catch{re.error("Failed to request revision")}finally{g(null)}}};return r?e.jsx(Vs,{title:"Order Details",children:e.jsxs("div",{className:"grid gap-6 lg:grid-cols-3",children:[e.jsxs("div",{className:"lg:col-span-2 space-y-6",children:[e.jsx(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:Llt[n.status],children:HV[n.status]})]}),e.jsx(Ie,{children:e.jsx(Iur,{currentStatus:n.status,statusHistory:n.status_history})})]}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{children:"Items"})}),e.jsx(Ie,{className:"space-y-4",children:(v=n.items)==null?void 0:v.map(b=>e.jsxs("div",{className:"border rounded-lg p-4",children:[e.jsxs("div",{className:"flex justify-between items-start mb-3",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold",children:b.product_name}),b.variant_name&&e.jsx("p",{className:"text-sm text-muted-foreground",children:b.variant_name}),e.jsxs("p",{className:"text-sm",children:["Qty: ",b.quantity," × $",Number(b.unit_price).toFixed(2)]})]}),e.jsxs("p",{className:"font-semibold",children:["$",(Number(b.unit_price)*b.quantity).toFixed(2)]})]}),b.artwork_url&&e.jsxs("div",{className:"mb-3",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:"Your Artwork:"}),e.jsxs("a",{href:b.artwork_url,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 text-primary hover:underline",children:[e.jsx(qI,{className:"h-4 w-4"}),"View Artwork",e.jsx(Fr,{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(qI,{className:"h-4 w-4"}),"View Proof",e.jsx(Fr,{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(qy,{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(tee,{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(see,{className:"h-5 w-5"}),"Shipping"]})}),e.jsxs(Ie,{children:[e.jsx("p",{className:"font-medium",children:n.shipping_name}),e.jsxs("p",{className:"text-muted-foreground",children:[n.shipping_address,e.jsx("br",{}),n.shipping_city,", ",n.shipping_state," ",n.shipping_zip]}),n.tracking_number&&e.jsxs("div",{className:"mt-4 p-3 bg-muted rounded-lg",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Tracking Number:"}),e.jsx("p",{className:"font-mono font-medium",children:n.tracking_number}),n.tracking_url&&e.jsxs($,{variant:"link",className:"p-0 h-auto mt-1",onClick:()=>window.open(n.tracking_url,"_blank"),children:["Track Package",e.jsx(Fr,{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(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:["Placed on ",en(new Date(n.created_at),"MMMM d, yyyy")]}),e.jsx(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(zs,{open:o,onOpenChange:c,children:e.jsxs(Os,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Request Changes"}),e.jsx(Pr,{children:"Please describe what changes you'd like made to the proof."})]}),e.jsx(Ls,{placeholder:"Describe the changes needed...",value:h,onChange:b=>m(b.target.value),rows:4}),e.jsxs(Sr,{children:[e.jsx($,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsxs($,{onClick:y,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 Rur(){const s=Xn(),[t]=gc();return t.get("session_id"),j.useEffect(()=>{localStorage.removeItem("marketplace-cart")},[]),e.jsx(Vs,{title:"Order Confirmed",children:e.jsx("div",{className:"max-w-lg mx-auto text-center py-8",children:e.jsx(je,{children:e.jsxs(Ie,{className:"pt-8 pb-6",children:[e.jsx("div",{className:"w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-6",children:e.jsx(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 Dur(){const{user:s}=bs(),[t,n]=j.useState("store"),[r,a]=j.useState(null),[i,l]=j.useState(null),[o,c]=j.useState(!1),[d,u]=j.useState(5),[h,m]=j.useState(""),[f,g]=j.useState(!1),[x,y]=j.useState(!1),[v,b]=j.useState(""),[w,S]=j.useState(null),[A,E]=j.useState(!1),{hasSubmittedReview:I,submitReview:P,markPostedToGoogle:R}=i7t(),{data:D}=hos(),{data:O,isLoading:U}=uos(),{data:W,isLoading:V}=Kor(r),{data:G,isLoading:Y}=Yor(s==null?void 0:s.id),{data:X=0}=Xor(s==null?void 0:s.id),ae=Qor(),le=new Set((G==null?void 0:G.map(ue=>ue.item_id))||[]),ne=async()=>{if(i)try{const ue=await ae.mutateAsync(i.id);i.item_type==="reelflow_credits"?re.success(`🎬 ${i.max_quantity} ReelFlow credits added to your balance!`):re.success(`Successfully purchased "${i.name}"!`),l(null)}catch(ue){re.error(ue.message||"Failed to purchase item")}},te=async()=>{if(!h.trim()){re.error("Please write a review");return}g(!0);const ue=await P(d,h);g(!1),ue.success?(re.success("Thank you for your review! You earned 25 points!"),b(h),y(!0),m(""),u(5)):re.error(ue.error||"Failed to submit review")},J=()=>{navigator.clipboard.writeText(v),re.success("Review copied to clipboard!")},ce=()=>{R(),window.open("https://g.page/r/CT8bqTBTm7nJEBM/review","_blank")},_e=()=>{y(!1),c(!1),b("")};return U||V||Y?e.jsx(Vs,{title:"Reward Store",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(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(Ie,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"h-12 w-12 rounded-full bg-primary/20 flex items-center justify-center",children:e.jsx(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(v1,{open:A,onOpenChange:E,children:e.jsxs(je,{className:"border-primary/20",children:[e.jsx(b1,{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(Gn,{children:"See all the ways you can earn spendable points"})]})]}),A?e.jsx(yb,{className:"h-5 w-5 text-muted-foreground"}):e.jsx(wl,{className:"h-5 w-5 text-muted-foreground"})]})})}),e.jsx(_1,{children:e.jsx(Ie,{className:"pt-0",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3",children:[D==null?void 0:D.filter(ue=>ue.is_active).map(ue=>{const ve=Ee=>{switch(Ee){case"event_attendance":return e.jsx(Ta,{className:"h-5 w-5"});case"leave_review":return e.jsx(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(ua,{className:"h-5 w-5"});case"first_community_post":return e.jsx(eo,{className:"h-5 w-5"});default:return e.jsx(ul,{className:"h-5 w-5"})}};return e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg bg-muted/50 border",children:[e.jsx("div",{className:"h-10 w-10 rounded-full bg-primary/10 flex items-center justify-center text-primary shrink-0",children:ve(ue.action_key)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm",children:ue.action_name}),ue.description&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:ue.description})]}),e.jsxs($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(Ie,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"h-12 w-12 rounded-full bg-yellow-500/20 flex items-center justify-center",children:e.jsx(eo,{className:"h-6 w-6 text-yellow-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Earn 25 Free Points!"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Leave a quick review and earn 25 spendable points"})]})]}),e.jsxs($,{onClick:()=>c(!0),className:"bg-yellow-600 hover:bg-yellow-700",children:[e.jsx(ei,{className:"h-4 w-4 mr-2"}),"Leave Review"]})]})})}),e.jsxs(ha,{value:t,onValueChange:n,children:[e.jsxs(ma,{children:[e.jsxs(Zt,{value:"store",className:"flex items-center gap-2",children:[e.jsx(I4,{className:"h-4 w-4"}),"Store"]}),e.jsxs(Zt,{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(Xt,{value:"store",className:"mt-6",children:[O&&O.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-2 mb-6",children:[e.jsx($,{variant:r===null?"default":"outline",size:"sm",onClick:()=>a(null),children:"All"}),O.map(ue=>e.jsxs($,{variant:r===ue.id?"default":"outline",size:"sm",onClick:()=>a(ue.id),children:[ue.icon&&`${ue.icon} `,ue.name]},ue.id))]}),!W||W.length===0?e.jsx(je,{children:e.jsx(Ie,{className:"py-12",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(ul,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{className:"font-medium",children:"No items available"}),e.jsx("p",{className:"text-sm",children:"Check back later for new rewards!"})]})})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:W.map(ue=>{const ve=ue.item_type==="reelflow_credits",Ee=!ve&&le.has(ue.id),Se=!ve&&ue.max_quantity!==null&&ue.current_quantity===0,Le=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"]})}),Se&&!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(ul,{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(Ie,{children:[e.jsx(Gn,{className:"mb-4 line-clamp-2",children:ue.description||"No description available"}),ue.max_quantity!==null&&!Ee&&!ve&&e.jsxs("p",{className:"text-xs text-muted-foreground mb-3",children:[ue.current_quantity," of ",ue.max_quantity," remaining"]}),ve&&e.jsxs("p",{className:"text-xs text-violet-600 font-medium mb-3",children:["🎬 Grants ",ue.max_quantity," ReelFlow credits per purchase"]}),Ee?e.jsx($,{className:"w-full",onClick:Fe=>{Fe.stopPropagation(),ue.file_url&&hUe(ue.file_url,ue.name)},disabled:!ue.file_url,children:ue.item_type==="file"?e.jsxs(e.Fragment,{children:[e.jsx(xi,{className:"h-4 w-4 mr-2"}),"Download"]}):e.jsxs(e.Fragment,{children:[e.jsx(Fr,{className:"h-4 w-4 mr-2"}),"Access"]})}):e.jsx($,{className:"w-full",onClick:Fe=>{Fe.stopPropagation(),l(ue)},disabled:Se||!Le,children:Se?"Sold Out":Le?e.jsxs(e.Fragment,{children:[e.jsx(I4,{className:"h-4 w-4 mr-2"}),"Purchase"]}):`Need ${ue.points_cost-X} more pts`})]})]},ue.id)})})]}),e.jsx(Xt,{value:"my-rewards",className:"mt-6",children:!G||G.length===0?e.jsx(je,{children:e.jsx(Ie,{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 ve,Ee,Se,Le,Fe,ke,Be;return e.jsxs(je,{className:"overflow-hidden",children:[(ve=ue.item)!=null&&ve.preview_image_url?e.jsx("div",{className:"aspect-video relative overflow-hidden bg-muted",children:e.jsx("img",{src:ue.item.preview_image_url,alt:((Ee=ue.item)==null?void 0:Ee.name)||"Reward",className:"w-full h-full object-cover"})}):e.jsx("div",{className:"aspect-video bg-muted flex items-center justify-center",children:e.jsx(ul,{className:"h-12 w-12 text-muted-foreground/50"})}),e.jsxs(St,{className:"pb-2",children:[e.jsx(Et,{className:"text-lg",children:((Se=ue.item)==null?void 0:Se.name)||"Unknown Item"}),e.jsxs(Gn,{className:"text-xs",children:["Purchased for ",ue.points_spent," points • ",new Date(ue.purchased_at).toLocaleDateString()]})]}),e.jsx(Ie,{children:((Le=ue.item)==null?void 0:Le.item_type)==="reelflow_credits"?e.jsxs($,{className:"w-full",variant:"outline",disabled:!0,children:[e.jsx(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 Ne,Ae;(Ne=ue.item)!=null&&Ne.file_url&&hUe(ue.item.file_url,(Ae=ue.item)==null?void 0:Ae.name)},disabled:!((ke=ue.item)!=null&&ke.file_url),children:((Be=ue.item)==null?void 0:Be.item_type)==="file"?e.jsxs(e.Fragment,{children:[e.jsx(xi,{className:"h-4 w-4 mr-2"}),"Download"]}):e.jsxs(e.Fragment,{children:[e.jsx(Fr,{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:ne,disabled:ae.isPending,children:ae.isPending?"Purchasing...":"Confirm Purchase"})]})]})}),e.jsx(zs,{open:o,onOpenChange:ue=>{!ue&&x?_e():c(ue)},children:e.jsx(Os,{children:x?e.jsxs(e.Fragment,{children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(Vr,{className:"h-5 w-5 text-green-500"}),"Thank You for Your Review!"]}),e.jsx(Pr,{children:"Would you also share your review on Google? It helps other agents discover LevelUp!"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"bg-muted p-4 rounded-lg",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:"Your review:"}),e.jsxs("p",{className:"text-sm italic",children:['"',v,'"']})]}),e.jsxs($,{variant:"outline",className:"w-full",onClick:J,children:[e.jsx(Ha,{className:"h-4 w-4 mr-2"}),"Copy Review to Clipboard"]})]}),e.jsxs(Sr,{className:"flex-col sm:flex-row gap-2",children:[e.jsx($,{variant:"outline",onClick:_e,children:"Maybe Later"}),e.jsxs($,{onClick:ce,className:"bg-blue-600 hover:bg-blue-700",children:[e.jsx(Fr,{className:"h-4 w-4 mr-2"}),"Leave Google Review"]})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Leave a Review"}),e.jsx(Pr,{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(Ls,{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(Sr,{children:[e.jsx($,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx($,{onClick:te,disabled:f,className:"bg-yellow-600 hover:bg-yellow-700",children:f?"Submitting...":"Submit & Earn 25 Points"})]})]})})}),e.jsx(zs,{open:!!w,onOpenChange:()=>S(null),children:e.jsxs(Os,{className:"max-w-lg",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[w==null?void 0:w.name,e.jsxs($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(Sr,{children:w&&w.item_type!=="reelflow_credits"&&le.has(w.id)?e.jsx($,{className:"w-full",onClick:()=>{w.file_url&&hUe(w.file_url,w.name)},disabled:!w.file_url,children:w.item_type==="file"?e.jsxs(e.Fragment,{children:[e.jsx(xi,{className:"h-4 w-4 mr-2"}),"Download"]}):e.jsxs(e.Fragment,{children:[e.jsx(Fr,{className:"h-4 w-4 mr-2"}),"Access"]})}):w&&e.jsx($,{className:"w-full",onClick:()=>{S(null),l(w)},disabled:w.item_type!=="reelflow_credits"&&w.max_quantity!==null&&w.current_quantity===0||X{s&&Y()},[s==null?void 0:s.id]);const Y=async()=>{if(!s)return;o(!0),v(!1),x(!0);const{data:Fe}=await q.from("point_reward_settings").select("action_key, points").in("action_key",["referral_signup","referral_paid"]);Fe==null||Fe.forEach(Ae=>{Ae.action_key==="referral_signup"&&h(Ae.points),Ae.action_key==="referral_paid"&&f(Ae.points)});const{data:ke}=await q.from("profiles").select("name").eq("id",s.id).maybeSingle();ke!=null&&ke.name&&w(ke.name);let{data: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:Ve,error:ze}=await q.from("agent_referral_codes").insert({user_id:s.id,code:Ce}).select("code").maybeSingle();!ze&&Ve&&(Be=Ve)}i((Be==null?void 0:Be.code)??null);const{data:Ne}=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(Ne&&Ne.length>0){const Ae=Ne.map(ze=>ze.referred_user_id),{data:Ce}=await q.from("profiles").select("id, name, email").in("id",Ae),Ve=new Map((Ce==null?void 0:Ce.map(ze=>[ze.id,ze]))??[]);d(Ne.map(ze=>({...ze,referred_profile:Ve.get(ze.referred_user_id)??null})))}else d([]);o(!1)},X=j.useMemo(()=>a?`${Fur}/trial?ref=${a}`:"",[a]),ae=c.length,le=c.filter(Fe=>Fe.status==="qualified").length,ne=c.filter(Fe=>Fe.signup_points_awarded).length*u+c.filter(Fe=>Fe.paid_points_awarded).length*m,te=async()=>{X&&(await navigator.clipboard.writeText(X),re.success("Referral link copied!"))},J=()=>{const Fe=encodeURIComponent("Join me on LevelUp"),ke=encodeURIComponent(`Hi — I've been using LevelUp to grow my real estate business and thought you'd love it too. Sign up using my link and we'll both get a head start: ${X} Let me know if you have any questions!`);window.location.href=`mailto:?subject=${Fe}&body=${ke}`},ce=()=>{const Fe=encodeURIComponent(`Hey! I think you'd love LevelUp for your business — sign up with my link: ${X}`);window.location.href=`sms:?&body=${Fe}`},_e=async()=>{if(navigator.share&&X)try{await navigator.share({title:"Join me on LevelUp",text:"I use LevelUp to grow my real estate business — try it with my link:",url:X})}catch{}else te()},he=Fe=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(Fe.trim()),ue=Fe=>{const ke=(Fe??E).trim().replace(/,$/,"");if(!ke)return;const Be=ke.split(/[\s,;]+/).filter(Boolean),Ne=[...P];let Ae=0;for(const Ce of Be){if(!he(Ce)){re.error(`Invalid email: ${Ce}`);continue}Ne.includes(Ce)||(Ne.push(Ce),Ae++)}R(Ne),Ae>0&&I("")},ve=Fe=>R(P.filter(ke=>ke!==Fe)),Ee=()=>{W(`${b?b.split(" ")[0]+" invited you to":"Join me on"} LevelUp`),O("I've been using LevelUp to grow my real estate business and it's been a game changer. I think you'd love it too — sign up with my link and we'll both get a head start."),A(!0)},Se=Fe=>{const ke=Fe.replace(/&/g,"&").replace(//g,">").replace(/\n/g,"
"),Be=b||"A fellow agent",Ne="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 🎉

${ke}

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

Or copy & paste this link:
${Ae}

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

`.trim()},Le=async()=>{if(P.length===0&&(E.trim()&&ue(),P.length===0)){re.error("Add at least one recipient");return}if(!U.trim()){re.error("Subject is required");return}G(!0);const Fe=Se(D);let ke=0,Be=0;for(const Ne of P)try{const{data:Ae,error:Ce}=await q.functions.invoke("gmail-send",{body:{to:Ne,subject:U,body:Fe,source:"referral_invite"}});if(Ce||Ae!=null&&Ae.error)throw new Error((Ce==null?void 0:Ce.message)||(Ae==null?void 0:Ae.error));ke++}catch(Ae){console.error("Gmail send failed for",Ne,Ae),Be++}G(!1),ke>0?(re.success(`Invite sent to ${ke} ${ke===1?"person":"people"}`+(Be>0?` (${Be} failed)`:"")),R([]),I(""),A(!1)):re.error("Failed to send invites")};return!y&&!g?e.jsx(Vs,{title:"Refer & Earn",children:e.jsxs("div",{className:"container max-w-3xl mx-auto p-4 md:p-8",children:[e.jsx(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(pc,{className:"h-6 w-6 text-muted-foreground"})}),e.jsx(Et,{children:"Refer & Earn is for active members"}),e.jsx(Gn,{children:"Activate your subscription to unlock your personal referral link and start earning points."})]}),e.jsx(Ie,{className:"flex justify-center",children:e.jsx($,{onClick:()=>t("/subscription"),children:"View Subscription"})})]})]})}):e.jsxs(Vs,{title:"Refer & Earn",children:[e.jsxs("div",{className:"container max-w-5xl mx-auto p-4 md:p-8 space-y-6",children:[e.jsxs(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(ul,{className:"h-7 w-7 text-primary"}),e.jsx("h1",{className:"text-3xl font-bold tracking-tight",children:"Refer & Earn"})]}),e.jsxs("p",{className:"text-muted-foreground",children:["Share LevelUp with peers, mentees, or fellow agents. Earn"," ",e.jsxs("span",{className:"font-semibold text-foreground",children:[u," points"]})," when they sign up and"," ",e.jsxs("span",{className:"font-semibold text-foreground",children:[m," more"]})," when they activate a paid plan."]})]}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsx(je,{children:e.jsxs(Ie,{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(Ie,{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(Ie,{className:"p-4 flex items-center gap-3",children:[e.jsx(Kl,{className:"h-5 w-5 text-amber-500"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:ne.toLocaleString()}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Points earned"})]})]})})]}),e.jsxs(je,{children:[e.jsxs(St,{children:[e.jsxs(Et,{className:"flex items-center gap-2",children:[e.jsx(Nn,{className:"h-5 w-5 text-primary"}),"Your referral link"]}),e.jsx(Gn,{children:"Anyone who signs up through this link is credited to you."})]}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[e.jsx(pe,{readOnly:!0,value:l?"Loading…":X,className:"font-mono text-sm",onFocus:Fe=>Fe.currentTarget.select()}),e.jsxs($,{onClick:te,disabled:!X,children:[e.jsx(Ha,{className:"h-4 w-4 mr-2"}),"Copy link"]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[n&&e.jsxs($,{size:"sm",onClick:Ee,disabled:!X,className:"bg-primary hover:bg-primary/90",children:[e.jsx(Kr,{className:"h-4 w-4 mr-2"})," Send via Gmail"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:J,disabled:!X,children:[e.jsx(mn,{className:"h-4 w-4 mr-2"})," Email"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:ce,disabled:!X,children:[e.jsx(eo,{className:"h-4 w-4 mr-2"})," Text"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:_e,disabled:!X,children:[e.jsx(Fd,{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(Gn,{children:"Track who joined and when they upgrade."})]}),e.jsx(Ie,{children:l?e.jsx("p",{className:"text-sm text-muted-foreground py-6 text-center",children:"Loading…"}):c.length===0?e.jsxs("div",{className:"text-center py-10 space-y-2",children:[e.jsx(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 Ne,Ae;const ke=((Ne=Fe.referred_profile)==null?void 0:Ne.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:ke}),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(da,{className:"h-3 w-3 mr-1"})," Signed up · +",u," pts"]})]},Fe.id)})})})]}),e.jsx(je,{className:"bg-muted/30",children:e.jsxs(Ie,{className:"p-6",children:[e.jsxs("h3",{className:"font-semibold mb-3 flex items-center gap-2",children:[e.jsx(Nn,{className:"h-4 w-4 text-primary"})," How it works"]}),e.jsxs("ol",{className:"text-sm text-muted-foreground space-y-2 list-decimal list-inside",children:[e.jsx("li",{children:"Share your unique link with peers, mentees, or other agents."}),e.jsxs("li",{children:["They sign up — you instantly earn ",e.jsxs("strong",{className:"text-foreground",children:[u," points"]}),"."]}),e.jsxs("li",{children:["When they activate a paid plan, you earn another ",e.jsxs("strong",{className:"text-foreground",children:[m," points"]}),"."]}),e.jsxs("li",{children:["Redeem points in the ",e.jsx("a",{href:"/reward-store",className:"text-primary underline",children:"Reward Store"}),"."]})]})]})}),e.jsx(Vc,{className:"opacity-0"})]}),e.jsx(zs,{open:S,onOpenChange:A,children:e.jsxs(Os,{className:"sm:max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(Kr,{className:"h-5 w-5 text-primary"})," Send referral invites via Gmail"]}),e.jsxs(Pr,{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:()=>ve(Fe),className:"hover:bg-muted-foreground/20 rounded-full p-0.5","aria-label":`Remove ${Fe}`,children:e.jsx(pr,{className:"h-3 w-3"})})]},Fe)),e.jsx("input",{type:"email",value:E,onChange:Fe=>I(Fe.target.value),onKeyDown:Fe=>{Fe.key==="Enter"||Fe.key===","||Fe.key===" "?(Fe.preventDefault(),ue()):Fe.key==="Backspace"&&!E&&P.length>0&&R(P.slice(0,-1))},onBlur:()=>E.trim()&&ue(),onPaste:Fe=>{const ke=Fe.clipboardData.getData("text");/[\s,;]/.test(ke)&&(Fe.preventDefault(),ue(ke))},placeholder:P.length===0?"name@example.com, another@example.com":"Add another…",className:"flex-1 min-w-[160px] bg-transparent outline-none text-sm"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Press Enter, comma, or space to add. You can paste multiple emails at once."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"email-subject",children:"Subject"}),e.jsx(pe,{id:"email-subject",value:U,onChange:Fe=>W(Fe.target.value),placeholder:"Subject line"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{htmlFor:"personal-note",children:"Your personal note"}),e.jsx(Ls,{id:"personal-note",value:D,onChange:Fe=>O(Fe.target.value),rows:4,placeholder:"Write a quick note explaining why they'd love LevelUp…"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"Preview"}),e.jsxs("div",{className:"border rounded-md overflow-hidden bg-muted/30",children:[e.jsxs("div",{className:"px-3 py-2 bg-muted/60 border-b text-xs text-muted-foreground flex items-center justify-between",children:[e.jsxs("span",{className:"truncate",children:["From: ",r]}),e.jsxs("span",{className:"truncate ml-2",children:["Subject: ",U||"(no subject)"]})]}),e.jsx("iframe",{title:"Email preview",srcDoc:Se(D),className:"w-full h-[420px] bg-white"})]})]})]}),e.jsxs(Sr,{children:[e.jsx($,{variant:"outline",onClick:()=>A(!1),disabled:V,children:"Cancel"}),e.jsxs($,{onClick:Le,disabled:V,children:[e.jsx(Kr,{className:"h-4 w-4 mr-2"}),V?"Sending…":`Send${P.length>0?` to ${P.length}`:""}`]})]})]})})]})}const Qos=()=>{const{user:s}=bs(),t=Wt(),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"]}),re.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"]}),re.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"]}),re.success("Saved as template!")}});return{presentations:n.data||[],templates:r.data||[],isLoading:n.isLoading,templatesLoading:r.isLoading,createPresentation:a,updatePresentation:i,publishPresentation:l,archivePresentation:o,saveAsTemplate:c}},zur=()=>{const s=Xn(),{presentations:t,isLoading:n,archivePresentation:r,saveAsTemplate:a}=Qos(),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),re.success("Link copied!")};return e.jsx(Vs,{title:"Smart Presentations",children:e.jsxs("div",{className:"max-w-5xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("h1",{className:"text-2xl font-serif font-bold text-foreground",children:"Smart Presentations"})}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Create personalized, video-first presentations for your clients"})]}),e.jsxs($,{onClick:()=>s("/mission-control/presentations/new"),className:"gap-2",children:[e.jsx(dn,{className:"h-4 w-4"}),"Create Presentation"]})]}),n?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(o=>e.jsx(xn,{className:"h-20 w-full rounded-lg"},o))}):t.length===0?e.jsx(je,{children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-primary/10 flex items-center justify-center mb-4",children:e.jsx(bb,{className:"h-8 w-8 text-primary"})}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"No presentations yet"}),e.jsx("p",{className:"text-muted-foreground mb-6 max-w-md",children:"Create your first Smart Presentation to impress clients with personalized, video-first content."}),e.jsxs($,{onClick:()=>s("/mission-control/presentations/new"),className:"gap-2",children:[e.jsx(dn,{className:"h-4 w-4"}),"Create Your First Presentation"]})]})}):e.jsx("div",{className:"space-y-3",children:t.map(o=>e.jsx(je,{className:"hover:shadow-sm transition-shadow",children:e.jsx(Ie,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-primary/10 flex items-center justify-center shrink-0",children:e.jsx(Jr,{className:"h-5 w-5 text-primary"})}),e.jsx("div",{className:"min-w-0 flex-1",children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-start sm:justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("h3",{className:"font-semibold truncate",children:o.title}),i(o)]}),e.jsxs("div",{className:"flex items-center gap-x-3 gap-y-0.5 flex-wrap text-sm text-muted-foreground mt-0.5",children:[o.client_name&&e.jsx("span",{children:o.client_name}),e.jsxs("span",{children:["Created ",en(new Date(o.created_at),"MMM d, yyyy")]}),o.view_count>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ca,{className:"h-3 w-3"})," ",o.view_count," view",o.view_count!==1?"s":""]}),o.cta_clicked_count>0&&e.jsx("span",{className:"text-emerald-600 font-medium",children:"CTA clicked"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap sm:flex-nowrap sm:shrink-0",children:[o.status==="published"&&o.share_token&&e.jsxs($,{variant:"outline",size:"sm",onClick:()=>l(o.share_token),children:[e.jsx(Ha,{className:"h-3.5 w-3.5 mr-1"}),"Copy Link"]}),o.status==="published"&&e.jsx($,{variant:"outline",size:"sm",onClick:()=>s(`/mission-control/presentations/${o.id}?edit=true`),children:"Edit"}),e.jsx($,{variant:"outline",size:"sm",onClick:()=>s(`/mission-control/presentations/${o.id}`),children:o.status==="draft"?"Edit":"View"}),e.jsxs($u,{children:[e.jsx(Uu,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(Jx,{className:"h-4 w-4"})})}),e.jsxs(Au,{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(Fr,{className:"h-4 w-4 mr-2"}),"Preview Link"]}),e.jsxs(ja,{onClick:()=>a.mutate(o),children:[e.jsx(Jr,{className:"h-4 w-4 mr-2"}),"Save as Template"]}),e.jsxs(ja,{onClick:()=>r.mutate(o.id),className:"text-destructive",children:[e.jsx(jv,{className:"h-4 w-4 mr-2"}),"Archive"]})]})]})]})]})})]})})},o.id))})]})})},qEt={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."}]},Bur=[{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 $ur(s){const t=qEt[s];if(t)return t;const n=s.toLowerCase();for(const[r,a]of Object.entries(qEt))if(n.includes(r.toLowerCase())||r.toLowerCase().includes(n))return a;return Bur}function Uur({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}=IQt(),m=p3(),[f,g]=j.useState(""),[x,y]=j.useState(!1),[v,b]=j.useState(!0),[w,S]=j.useState(!1),[A,E]=j.useState(null),I=$ur(s),P=()=>{l("script"),c(0),u(0),g(""),y(!1),b(!0),S(!1),E(null)},R=V=>{!V&&(i==="uploading"||i==="processing")||(a(V),V||P())},D=V=>{E(V),g(I[V].text),y(!1)},O=()=>{l("record"),b(f.trim().length>0)},U=()=>{g(""),b(!1),l("record")},W=j.useCallback(async(V,G)=>{l("uploading");try{const Y=s||"Presentation Video",{videoId:X,uploadUrl:ae,libraryId:le}=await A6(Y),{apiKey:ne}=await E6(X),te=new XMLHttpRequest;te.upload.onprogress=ue=>{ue.lengthComputable&&c(ue.loaded/ue.total*100)},await new Promise((ue,ve)=>{te.onload=()=>te.status>=200&&te.status<300?ue():ve(new Error("Upload failed")),te.onerror=()=>ve(new Error("Upload failed")),te.open("PUT",ae),te.setRequestHeader("AccessKey",ne),te.send(V)}),l("processing");let J=0;const ce=Date.now(),_e=9e4;let he=null;for(;J<4;){if(await new Promise(ve=>setTimeout(ve,3e3)),Date.now()-ce>_e){const ve=V.size/1048576,Ee=`https://iframe.mediadelivery.net/embed/${le}/${X}?responsive=true`;await m.mutateAsync({bunny_video_id:X,playback_url:Ee,file_size_mb:ve,title:Y,contact_id:t||void 0,status:"processing",touch_type:"presentation"}),n(Ee),re.success("Video saved — still encoding. It will be ready shortly."),l("done"),setTimeout(()=>a(!1),1500);return}const ue=await mk(X);if(J=ue.status,u(ue.encodeProgress||0),J===4)he={playbackUrl:ue.directPlayUrl,thumbnailUrl:ue.thumbnailUrl,previewUrl:ue.previewUrl||null,duration:ue.length||G,fileSizeMb:(ue.storageSize||V.size)/(1024*1024)};else if(J===5||J===6)throw new Error("Video processing failed")}if(!he)throw new Error("No video data");await m.mutateAsync({bunny_video_id:X,contact_id:t||void 0,playback_url:he.playbackUrl,thumbnail_url:he.thumbnailUrl,preview_url:he.previewUrl,duration_seconds:he.duration,file_size_mb:he.fileSizeMb,title:Y,status:"ready",touch_type:"presentation"}),n(he.playbackUrl),re.success("Video recorded, saved to library & attached!"),l("done"),setTimeout(()=>a(!1),1500)}catch(Y){console.error("Recording upload error:",Y),re.error("Failed to process video. Please try again."),l("record")}},[s,t,n,m]);return e.jsxs(zs,{open:r,onOpenChange:R,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:"gap-1.5 shrink-0",title:"Record a video",children:[e.jsx(ua,{className:"h-3.5 w-3.5"}),"Record"]})}),e.jsxs(Os,{className:"max-w-2xl max-h-[90vh] overflow-y-auto !top-[5%] !translate-y-0 sm:!top-[5%] sm:!translate-y-0",children:[e.jsx(Us,{children:e.jsxs(Bs,{children:[i==="script"&&`Prepare your script for "${s}"`,i==="record"&&`Record video for "${s}"`,i==="uploading"&&"Uploading...",i==="processing"&&"Processing...",i==="done"&&"Done!"]})}),i==="script"&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Choose a starter script below, edit it to make it yours, or skip and speak freely."}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Starter Scripts"}),e.jsx("div",{className:"grid gap-2",children:I.map((V,G)=>e.jsxs("button",{onClick:()=>D(G),className:Pt("text-left p-3 rounded-lg border transition-all hover:bg-accent/50",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(Jr,{className:"h-3.5 w-3.5 text-primary shrink-0"}),e.jsx("span",{className:"text-sm font-medium",children:V.label})]}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 ml-5.5",children:V.text})]},G))})]}),f&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Your Script"}),!x&&e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>y(!0),className:"h-7 text-xs gap-1",children:[e.jsx(pi,{className:"h-3 w-3"}),"Edit"]})]}),x?e.jsx(Ls,{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(Ls,{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(!v),className:"h-7 text-xs gap-1",children:[v?e.jsx($g,{className:"h-3 w-3"}):e.jsx(Ca,{className:"h-3 w-3"}),v?"Hide Script":"Show Script"]})]}),e.jsx(FT,{maxDurationSeconds:600,onRecordingComplete:W,onRecordingStateChange:S,onError:V=>re.error(V),teleprompterContent:f.trim()?e.jsx(Got,{text:f,isVisible:v,onToggleVisibility:()=>b(!v),isRecording:w,startCountdown:!1}):void 0}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>l("script"),className:"text-xs text-muted-foreground",children:"← Back to script"})]}):i==="uploading"?e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12",children:[e.jsx(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 qur({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=p3(),{data:f}=iDe(),g=(f==null?void 0:f.total_storage_mb)||0,y=((f==null?void 0:f.max_storage_mb)||1024)-g,v=()=>{l(null),c("idle"),u(0)},b=I=>{!I&&o!=="idle"&&o!=="done"||(a(I),I||v())},w=I=>{var D;const P=(D=I.target.files)==null?void 0:D[0];if(!P)return;if(!P.type.startsWith("video/")){re.error("Please select a video file");return}const R=P.size/(1024*1024);if(R>500){re.error("Video file must be less than 500MB");return}if(R>y){re.error(`Not enough storage. You have ${y.toFixed(1)} MB remaining.`);return}l(P)},S=j.useCallback(async()=>{if(i){c("creating"),u(0);try{const I=s||i.name,{data:P,error:R}=await q.functions.invoke("bunny-upload",{body:{action:"create",title:I,isAgentVideo:!0}});if(R)throw new Error(R.message);const{videoId:D,libraryId:O}=P;c("uploading");const{data:U,error:W}=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:D,isAgentVideo:!0}});if(W)throw new Error(W.message);await new Promise((Y,X)=>{const ae=new XMLHttpRequest;ae.upload.addEventListener("progress",le=>{le.lengthComputable&&u(Math.round(le.loaded/le.total*100))}),ae.addEventListener("load",()=>ae.status>=200&&ae.status<300?Y():X(new Error(`Upload failed (${ae.status})`))),ae.addEventListener("error",()=>X(new Error("Upload failed"))),ae.open("PUT",U.uploadUrl),ae.setRequestHeader("AccessKey",U.apiKey),ae.send(i)}),c("processing");const V=i.size/(1024*1024),G=`https://iframe.mediadelivery.net/embed/${O}/${D}`;await m.mutateAsync({bunny_video_id:D,playback_url:G,file_size_mb:V,title:I,contact_id:t||void 0,status:"processing",touch_type:"presentation"}),n(G),c("done"),re.success("Video uploaded & attached to section!"),setTimeout(()=>a(!1),1200)}catch(I){console.error("Upload error:",I),re.error(I instanceof Error?I.message:"Failed to upload video"),c("idle")}}},[i,s,t,n,m]),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(zs,{open:r,onOpenChange:b,children:[e.jsx(jl,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:"gap-1.5 shrink-0",title:"Upload a video file",children:[e.jsx(ni,{className:"h-3.5 w-3.5"}),"Upload"]})}),e.jsxs(Os,{className:"sm:max-w-md",children:[e.jsx(Us,{children:e.jsxs(Bs,{children:['Upload Video for "',s,'"']})}),e.jsxs("div",{className:"space-y-4 py-2",children:[i?e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-muted rounded-lg",children:[e.jsx(ua,{className:"h-8 w-8 text-primary flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:i.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(i.size/(1024*1024)).toFixed(1)," MB"]})]}),!E&&e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>l(null),children:e.jsx(pr,{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(Sr,{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 VEt=[{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"}],HEt=()=>{const s=Xn(),{id:t}=Wi(),{user:n}=bs(),{templates:r,templatesLoading:a,createPresentation:i,updatePresentation:l,publishPresentation:o}=Qos(),{isGmailConnected:c,gmailEmail:d}=gy(),[u,h]=j.useState(!1),[m,f]=j.useState("client"),[g,x]=j.useState(!1),[y,v]=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(""),[Y,X]=j.useState("buyer"),[ae,le]=j.useState(""),[ne,te]=j.useState(null),[J,ce]=j.useState(""),[_e,he]=j.useState([]),[ue,ve]=j.useState("schedule_call"),[Ee,Se]=j.useState("Schedule a Call"),[Le,Fe]=j.useState(""),[ke,Be]=j.useState(""),[Ne,Ae]=j.useState(null),[Ce,Ve]=j.useState(t||null),[ze,qe]=j.useState(null),[dt,Xe]=j.useState(!1),at=async(kt,Ks)=>{if(!n)return;const wt=5*1024*1024;if(kt.size>wt){re.error("Image must be under 5MB");return}if(!kt.type.startsWith("image/")){re.error("Please upload an image file");return}Ae(Ks);try{const gs=kt.name.split(".").pop()||"jpg",ks=`${n.id}/${Date.now()}.${gs}`,{error:Is}=await q.storage.from("listing-photos").upload(ks,kt);if(Is)throw Is;const{data:{publicUrl:Xs}}=q.storage.from("listing-photos").getPublicUrl(ks);ss(Ks,{image_url:Xs}),re.success("Image uploaded")}catch{re.error("Failed to upload image")}finally{Ae(null)}};j.useEffect(()=>{t&&rt(t)},[t]);const rt=async kt=>{const{data:Ks,error:wt}=await q.from("smart_presentations").select("*").eq("id",kt).single();if(wt||!Ks)return;const gs=Ks;if(x(!0),ce(gs.title),O(gs.client_name||""),le(gs.property_address||""),he(gs.sections||[]),ve(gs.cta_type||"schedule_call"),Se(gs.cta_label||"Schedule a Call"),Fe(gs.cta_url||""),Be(gs.heading||""),qe(gs.share_token),Xe(gs.status==="published"),Ve(gs.id),f("builder"),gs.contact_id){const{data:ks}=await q.from("innercircle_contacts").select("id, first_name, last_name, email, phone").eq("id",gs.contact_id).maybeSingle();ks&&(I(ks),W(ks.email||""),G(ks.phone||""))}};j.useEffect(()=>{if(!n||y.length<1){w([]);return}const kt=setTimeout(async()=>{A(!0);const{data:Ks}=await q.from("innercircle_contacts").select("id, first_name, last_name, email, phone, lead_source").eq("owner_user_id",n.id).or(`first_name.ilike.%${y}%,last_name.ilike.%${y}%,email.ilike.%${y}%`).limit(10);w(Ks||[]),A(!1)},300);return()=>clearTimeout(kt)},[y,n]);const Ke=kt=>{I(kt),O(`${kt.first_name} ${kt.last_name||""}`.trim()),W(kt.email||""),G(kt.phone||""),R(!1)},Je=async()=>{if(!D.trim()){re.error("Client name is required");return}const kt=D.trim().split(" "),Ks=kt[0],wt=kt.slice(1).join(" ")||null,{data:gs,error:ks}=await q.from("innercircle_contacts").insert({owner_user_id:n.id,first_name:Ks,last_name:wt,email:U||null,phone:V||null,lead_source:"Smart Presentation"}).select().single();if(ks){re.error("Failed to create client");return}I(gs),re.success("Client created & saved to Agent OS"),f("template")},pt=kt=>{te(kt);const Ks=(kt.sections||[]).map(wt=>({...wt,is_visible:!0,video_url:"",text:""}));if(he(Ks),ce(kt.name+(D?` for ${D}`:"")),kt.cta_config){const wt=kt.cta_config;ve(wt.type||"schedule_call"),Se(wt.label||"Schedule a Call")}f("builder")},gt=()=>{he([{title:"Welcome",description:"A personal welcome",type:"video",icon:"👋",is_visible:!0}]),ce(D?`Presentation for ${D}`:"New Presentation"),f("builder")},ss=(kt,Ks)=>{he(wt=>wt.map((gs,ks)=>ks===kt?{...gs,...Ks}:gs))},Yt=kt=>{ss(kt,{is_visible:!_e[kt].is_visible})},ts=()=>{he(kt=>[...kt,{title:"New Section",description:"",type:"video",icon:"📝",is_visible:!0}])},ys=kt=>{he(Ks=>Ks.filter((wt,gs)=>gs!==kt))},Bt=async()=>{if(!J.trim()){re.error("Title is required");return}try{if(Ce){const kt=await l.mutateAsync({id:Ce,title:J,sections:_e,client_name:D,property_address:ae||null,cta_type:ue,cta_label:Ee,cta_url:Le||null,heading:ke||null});re.success("Saved")}else{const kt=await i.mutateAsync({title:J,contact_id:(E==null?void 0:E.id)||void 0,client_name:D,property_address:ae||void 0,template_id:(ne==null?void 0:ne.id)||void 0,sections:_e,cta_type:ue,cta_label:Ee,cta_url:Le||void 0,heading:ke||void 0});Ve(kt.id),qe(kt.share_token),re.success("Presentation created!")}}catch(kt){console.error("Failed to save presentation:",kt);const Ks=(kt==null?void 0:kt.message)||(kt==null?void 0:kt.toString())||"Unknown error";re.error(`Failed to save: ${Ks}`)}},Ft=async()=>{try{await Bt();const kt=Ce;if(kt){const Ks=await o.mutateAsync(kt);qe(Ks.share_token),Xe(!0),f("share")}}catch(kt){console.error("Failed to publish presentation:",kt),re.error(`Failed to publish: ${(kt==null?void 0:kt.message)||"Unknown error"}`)}},as=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((kt,Ks)=>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===kt?"bg-primary text-primary-foreground":Ks<["client","template","builder","share"].indexOf(m)?"bg-emerald-100 text-emerald-700":"bg-muted text-muted-foreground"),children:Ks<["client","template","builder","share"].indexOf(m)?e.jsx(ca,{className:"h-4 w-4"}):Ks+1}),e.jsx("span",{className:"text-sm font-medium capitalize hidden sm:inline",children:kt}),Ks<3&&e.jsx("div",{className:"w-8 h-px bg-border"})]},kt))}),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(Kr,{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(Zr,{className:"h-4 w-4 text-muted-foreground"}),"Select Existing Client"]})}),e.jsxs(Ie,{className:"space-y-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Zr,{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:kt=>v(kt.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(kt=>e.jsxs("button",{onClick:()=>Ke(kt),className:Pt("w-full text-left p-3 rounded-lg border transition-colors",(E==null?void 0:E.id)===kt.id?"border-primary bg-primary/5":"border-border hover:border-primary/50"),children:[e.jsxs("p",{className:"font-medium text-sm",children:[kt.first_name," ",kt.last_name]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:kt.email||kt.phone||"No contact info"})]},kt.id)),!y&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"Start typing to search your contacts"}),y&&b.length===0&&!S&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No clients found"})]}),E&&e.jsxs($,{onClick:()=>f("template"),className:"w-full gap-2",children:["Continue with ",E.first_name,e.jsx(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(Ie,{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"col-span-2",children:[e.jsx(ee,{className:"text-xs",children:"Name *"}),e.jsx(pe,{value:D,onChange:kt=>{O(kt.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:kt=>W(kt.target.value),placeholder:"Optional",type:"email"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Phone"}),e.jsx(pe,{value:V,onChange:kt=>G(kt.target.value),placeholder:"Optional"})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Client Type"}),e.jsxs(ms,{value:Y,onValueChange:X,children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"buyer",children:"Buyer"}),e.jsx(Ge,{value:"seller",children:"Seller"}),e.jsx(Ge,{value:"recruit",children:"Recruit"}),e.jsx(Ge,{value:"other",children:"Other"})]})]})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Property Address"}),e.jsx(pe,{value:ae,onChange:kt=>le(kt.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(ha,{defaultValue:"system",children:[e.jsxs(ma,{children:[e.jsx(Zt,{value:"mine",children:"My Core Templates"}),e.jsx(Zt,{value:"system",children:"LevelUp Smart Templates"}),e.jsx(Zt,{value:"blank",children:"+ Start Blank"})]}),e.jsx(Xt,{value:"mine",className:"mt-4",children:a?e.jsx("div",{className:"grid grid-cols-2 gap-4",children:[1,2].map(kt=>e.jsx(xn,{className:"h-32"},kt))}):e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:r.filter(kt=>!kt.is_system).length===0?e.jsx("p",{className:"text-muted-foreground col-span-2 text-center py-8",children:"You haven't saved any templates yet. Create a presentation and save it as a template!"}):r.filter(kt=>!kt.is_system).map(kt=>e.jsx(GEt,{template:kt,onSelect:pt},kt.id))})}),e.jsx(Xt,{value:"system",className:"mt-4",children:e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:r.filter(kt=>kt.is_system).map(kt=>e.jsx(GEt,{template:kt,onSelect:pt},kt.id))})}),e.jsx(Xt,{value:"blank",className:"mt-4",children:e.jsx(je,{children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx("p",{className:"text-muted-foreground mb-4",children:"Start with a blank canvas and add your own sections."}),e.jsx($,{onClick: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(Ie,{className:"pt-6 space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Presentation Title"}),e.jsx(pe,{value:J,onChange:kt=>ce(kt.target.value)})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Page Heading"}),e.jsx(pe,{value:ke,onChange:kt=>Be(kt.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:kt=>O(kt.target.value)})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Property Address"}),e.jsx(pe,{value:ae,onChange:kt=>le(kt.target.value),placeholder:"Optional"})]})]})]})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Sections"}),e.jsx($,{variant:"outline",size:"sm",onClick:ts,children:"+ Add Section"})]}),e.jsx("div",{className:"space-y-3",children:_e.map((kt,Ks)=>e.jsx(je,{className:Pt(!kt.is_visible&&"opacity-50"),children:e.jsx(Ie,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs("div",{className:"flex flex-col items-center gap-1 pt-1",children:[e.jsx(Ug,{className:"h-4 w-4 text-muted-foreground cursor-grab"}),e.jsx("span",{className:"text-lg",children:kt.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:kt.title,onChange:wt=>ss(Ks,{title:wt.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:()=>Yt(Ks),children:kt.is_visible?e.jsx(Ca,{className:"h-4 w-4"}):e.jsx($g,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>ys(Ks),className:"text-destructive hover:text-destructive",children:e.jsx(Hn,{className:"h-4 w-4"})})]})]}),e.jsx(pe,{value:kt.description||"",onChange:wt=>ss(Ks,{description:wt.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:kt.video_url||"",onChange:wt=>ss(Ks,{video_url:wt.target.value}),placeholder:"Paste a YouTube or video URL...",className:"text-sm"})]}),e.jsx(Uur,{sectionTitle:kt.title,contactId:E==null?void 0:E.id,onVideoReady:wt=>ss(Ks,{video_url:wt})}),e.jsx(qur,{sectionTitle:kt.title,contactId:E==null?void 0:E.id,onVideoReady:wt=>ss(Ks,{video_url:wt})}),e.jsx(s9,{userId:n==null?void 0:n.id,onSelect:wt=>ss(Ks,{video_url:wt})})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Image (optional — shown if no video is set)"}),kt.image_url?e.jsxs("div",{className:"relative mt-1 rounded-lg overflow-hidden border border-border bg-muted/30 group",children:[e.jsx("img",{src:kt.image_url,alt:"",className:"w-full max-h-40 object-cover"}),e.jsx($,{variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>ss(Ks,{image_url:""}),children:e.jsx(pr,{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:[Ne===Ks?e.jsx(Ct,{className:"h-4 w-4 animate-spin text-muted-foreground"}):e.jsx(Sv,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:Ne===Ks?"Uploading...":"Click to upload an image"}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",disabled:Ne===Ks,onChange:wt=>{var ks;const gs=(ks=wt.target.files)==null?void 0:ks[0];gs&&at(gs,Ks),wt.target.value=""}})]})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Text (optional)"}),e.jsx(Sk,{content:kt.text||"",onChange:wt=>ss(Ks,{text:wt}),placeholder:"Add supporting text...",minHeight:"80px",compact:!0})]})]})]})})},Ks))})]}),e.jsxs(je,{children:[e.jsx(St,{children:e.jsx(Et,{className:"text-base",children:"Call to Action"})}),e.jsxs(Ie,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"CTA Type"}),e.jsxs(ms,{value:ue,onValueChange:kt=>{ve(kt);const Ks=VEt.find(wt=>wt.value===kt);Ks&&Se(Ks.label)},children:[e.jsx(us,{children:e.jsx(fs,{})}),e.jsx(hs,{children:VEt.map(kt=>e.jsx(Ge,{value:kt.value,children:kt.label},kt.value))})]})]}),e.jsxs("div",{children:[e.jsx(ee,{children:"Button Label"}),e.jsx(pe,{value:Ee,onChange:kt=>Se(kt.target.value)})]}),e.jsxs("div",{children:[e.jsxs(ee,{children:["Link URL ",e.jsx("span",{className:"text-muted-foreground",children:"(optional — leave blank to show a lead capture form instead)"})]}),e.jsx(pe,{value:Le,onChange:kt=>Fe(kt.target.value),placeholder:"https://calendly.com/..."}),!Le&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Without a URL, clients will see a contact form — their info gets added to your contacts and you'll receive an email notification."})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[!g&&e.jsxs($,{variant:"outline",onClick:()=>f("template"),className:"gap-2",children:[e.jsx(Va,{className:"h-4 w-4"}),"Back"]}),e.jsxs("div",{className:"flex gap-3 ml-auto",children:[e.jsx($,{variant:"outline",onClick:Bt,disabled:i.isPending||l.isPending,children:"Save Draft"}),e.jsxs($,{onClick:Ft,disabled:o.isPending,className:"gap-2",children:[e.jsx(Kr,{className:"h-4 w-4"}),dt?"Update & Reshare":"Publish & Share"]})]})]})]}),m==="share"&&ze&&e.jsxs("div",{className:"space-y-6",children:[e.jsx(je,{children:e.jsxs(Ie,{className:"flex flex-col items-center py-12 text-center",children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-emerald-100 flex items-center justify-center mb-4",children:e.jsx(ca,{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:as,readOnly:!0,className:"text-center font-mono text-sm"}),e.jsx($,{onClick:()=>{navigator.clipboard.writeText(as),re.success("Link copied!")},children:e.jsx(Ha,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex gap-3 mt-6",children:[e.jsxs($,{variant:"outline",className:"gap-2",onClick:()=>{const kt=`Hi ${D||""}! I put together something for you — check it out: ${as}`;navigator.clipboard.writeText(kt),re.success("Message copied!")},children:[e.jsx(eo,{className:"h-4 w-4"}),"Copy Text Message"]}),e.jsxs($,{variant:"outline",className:"gap-2",onClick:()=>{c?h(!0):window.open(`mailto:${U||""}?subject=${encodeURIComponent(J)}&body=${encodeURIComponent(`Hi ${(E==null?void 0:E.first_name)||(D==null?void 0:D.split(" ")[0])||""}, I put together a personalized presentation for you: ${as} Looking forward to connecting!`)}`)},children:[e.jsx(mn,{className:"h-4 w-4"}),"Send Email"]})]}),c&&e.jsx(kk,{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: ${as} 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"})]})]})]})})},GEt=({template:s,onSelect:t})=>e.jsx(je,{className:"hover:shadow-sm transition-shadow",children:e.jsxs(Ie,{className:"p-5",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("span",{className:"text-2xl",children:s.icon}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-semibold",children:s.name}),e.jsx("p",{className:"text-sm text-muted-foreground mt-0.5",children:s.description}),e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[e.jsx($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"})]})}),Vur=()=>{var x;const{shareToken:s}=Wi(),[t,n]=j.useState(null),[r,a]=j.useState(!0),[i,l]=j.useState(0),[o,c]=j.useState(!1);j.useEffect(()=>(document.body.classList.add("presentation-page"),()=>{document.body.classList.remove("presentation-page")}),[]),j.useEffect(()=>{s&&d()},[s]);const d=async()=>{const{data:y,error:v}=await q.from("smart_presentations").select("*").eq("share_token",s).eq("status","published").single();if(v||!y){c(!0),a(!1);return}const{data:b}=await q.from("profiles").select("name, email, phone, avatar_url, title, brokerage_id").eq("id",y.owner_user_id).single();let w;if(b!=null&&b.brokerage_id){const{data: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(y.contact_id){const{data:A}=await q.from("innercircle_contacts").select("first_name, last_name, email, phone").eq("id",y.contact_id).single();S=A}n({...y,owner_name:b==null?void 0:b.name,owner_email:b==null?void 0:b.email,owner_phone:b==null?void 0:b.phone,owner_avatar:b==null?void 0:b.avatar_url,owner_title:(b==null?void 0:b.title)||void 0,brokerage_name:w,contact_name:S?[S.first_name,S.last_name].filter(Boolean).join(" "):void 0,contact_email:(S==null?void 0:S.email)||void 0,contact_phone:(S==null?void 0:S.phone)||void 0}),a(!1);try{await q.rpc("log_presentation_view",{p_presentation_id:y.id,p_section_index:0,p_cta_clicked:!1,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null})}catch{}},u=async()=>{if(t){try{await q.rpc("log_presentation_view",{p_presentation_id:t.id,p_section_index:null,p_cta_clicked:!0,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:null})}catch{}t.cta_url&&window.open(t.cta_url,"_blank")}};if(r)return e.jsx("div",{className:"min-h-screen bg-white flex items-center justify-center",children:e.jsxs("div",{className:"space-y-4 w-full max-w-2xl px-4",children:[e.jsx(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(y=>y.is_visible!==!1),m=h[i],f=y=>{const v=y.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/)([a-zA-Z0-9_-]+)/);if(v)return`https://www.youtube.com/embed/${v[1]}?rel=0`;if(y.includes("iframe.mediadelivery.net/play/")){const S=y.replace("/play/","/embed/"),A=S.includes("?")?"&":"?";return`${S}${A}responsive=true`}if(y.includes("iframe.mediadelivery.net")){if(y.match(/\/embed\/(\d+)\/([a-f0-9-]+)/)){const A=y.includes("?")?"&":"?";return`${y}${A}responsive=true`}return""}const b=y.match(/loom\.com\/share\/([a-zA-Z0-9]+)/);if(b)return`https://www.loom.com/embed/${b[1]}`;const w=y.match(/video\.bunnycdn\.com\/play\/(\d+)\/([a-f0-9-]+)/);return w?`https://iframe.mediadelivery.net/embed/${w[1]}/${w[2]}?responsive=true`:y},g=!!((x=t.cta_url)!=null&&x.trim());return e.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white",children:[e.jsx("header",{className:"bg-white border-b border-gray-100 sticky top-0 z-10",children:e.jsxs("div",{className:"max-w-5xl mx-auto px-4 py-3 flex items-center justify-between",children:[e.jsx("div",{}),e.jsxs("div",{className:"flex items-center gap-3",children:[t.owner_avatar&&e.jsx("img",{src:t.owner_avatar,alt:t.owner_name||"Agent",className:"h-10 w-10 rounded-full object-cover border border-gray-200"}),e.jsxs("div",{className:"text-right text-sm",children:[e.jsx("p",{className:"font-semibold text-gray-900",children:t.owner_name}),t.owner_title&&e.jsx("p",{className:"text-gray-500 text-xs",children:t.owner_title}),t.brokerage_name&&!t.owner_title&&e.jsx("p",{className:"text-gray-500 text-xs",children:t.brokerage_name})]})]})]})}),e.jsxs("main",{className:"max-w-5xl mx-auto px-4 py-8",children:[e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("h1",{className:"text-3xl md:text-4xl font-bold text-gray-900 mb-2",children:t.heading||(t.client_name?`Welcome, ${t.client_name}!`:t.title)}),t.property_address&&e.jsxs("p",{className:"text-lg text-gray-600",children:["Here's the plan for your home at ",e.jsx("strong",{children:t.property_address}),"."]})]}),e.jsxs("div",{className:"grid md:grid-cols-5 gap-8",children:[e.jsxs("div",{className:"md:col-span-3",children:[m!=null&&m.video_url&&f(m.video_url)?e.jsx("div",{className:"relative w-full rounded-xl overflow-hidden shadow-lg bg-gray-900",style:{paddingTop:"56.25%"},children:e.jsx("iframe",{src:f(m.video_url),className:"absolute inset-0 w-full h-full border-0",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,loading:"lazy"})}):m!=null&&m.image_url?e.jsx("div",{className:"rounded-xl overflow-hidden shadow-lg",children:e.jsx("img",{src:m.image_url,alt:m.title,className:"w-full h-auto object-cover",loading:"lazy"})}):e.jsxs("div",{className:"aspect-video bg-gradient-to-br from-blue-50 to-slate-100 rounded-xl flex flex-col items-center justify-center shadow-lg",children:[e.jsx("span",{className:"text-5xl mb-3",children:m==null?void 0:m.icon}),e.jsx("h3",{className:"text-xl font-semibold text-gray-800",children:m==null?void 0:m.title}),e.jsx("p",{className:"text-gray-500 mt-1 text-sm",children:m==null?void 0:m.description})]}),(m==null?void 0:m.text)&&e.jsx("div",{className:"mt-4 p-4 bg-white rounded-lg border text-gray-700 text-sm leading-relaxed prose prose-sm max-w-none",dangerouslySetInnerHTML:{__html:m.text}})]}),e.jsx("div",{className:"md:col-span-2 space-y-3",children:h.map((y,v)=>e.jsx("button",{onClick:()=>l(v),className:Pt("w-full text-left p-4 rounded-xl border transition-all",i===v?"border-blue-500 bg-blue-50 shadow-sm":"border-gray-200 bg-white hover:border-blue-200 hover:bg-blue-50/50"),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs("span",{className:"text-blue-600 font-bold text-sm mt-0.5",children:[String(v+1).padStart(2,"0"),"."]}),e.jsxs("div",{children:[e.jsx("span",{className:"mr-2",children:y.icon}),e.jsx("span",{className:"font-semibold text-gray-900",children:y.title}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:y.description})]})]})},v))})]}),e.jsxs("div",{className:"mt-12 max-w-md mx-auto bg-white rounded-2xl border border-gray-200 shadow-sm p-6 text-center",children:[t.owner_avatar&&e.jsx("img",{src:t.owner_avatar,alt:t.owner_name||"Agent",className:"h-20 w-20 rounded-full object-cover mx-auto mb-3 border-2 border-gray-100"}),e.jsx("h3",{className:"text-lg font-bold text-gray-900",children:t.owner_name}),t.owner_title&&e.jsx("p",{className:"text-sm text-gray-500",children:t.owner_title}),t.brokerage_name&&e.jsx("p",{className:"text-sm text-gray-500",children:t.brokerage_name}),e.jsxs("div",{className:"mt-3 flex flex-col items-center gap-1 text-sm text-gray-600",children:[t.owner_phone&&e.jsx("a",{href:`tel:${t.owner_phone}`,className:"hover:text-blue-600 transition-colors",children:t.owner_phone}),t.owner_email&&e.jsx("a",{href:`mailto:${t.owner_email}`,className:"hover:text-blue-600 transition-colors",children:t.owner_email})]})]}),t.cta_label&&e.jsxs("div",{className:"text-center mt-8 py-8",children:[e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-4",children:"Ready to Get Started?"}),g?e.jsxs($,{size:"lg",onClick:u,className:"text-lg px-8 py-6 rounded-xl bg-blue-600 hover:bg-blue-700 text-white shadow-lg",children:[t.cta_label,e.jsx(Fr,{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(H7t,{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"})]})},_Ue="__none__";function Hur({value:s,onChange:t}){const{data:n=[],isLoading:r}=Iie(),a=git(),[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(JI,{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??_Ue,onValueChange:h=>t(h===_Ue?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:_Ue,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(Nn,{className:"h-3.5 w-3.5 text-primary"}),'Add the "Open House Follow-Up" starter (6 emails)']}),o.length===0&&!c&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Create a campaign in Smart Drips first, then choose it here."})]})}function Gur({openHouseId:s,enableSurvey:t,onToggleSurvey:n}){const{data:r,isLoading:a}=hFs(s),i=gFs(),l=xFs(),o=yFs(),c=vFs(),[d,u]=j.useState(""),[h,m]=j.useState("rating"),f=async v=>{n(v),v&&(!r||r.length===0)&&await c.mutateAsync(s)},g=async()=>{if(!d.trim())return;const v=(r==null?void 0:r.reduce((b,w)=>Math.max(b,w.sort_order),0))??0;await i.mutateAsync({open_house_id:s,question_type:h,question_text:d.trim(),sort_order:v+1}),u("")},x=async v=>{await l.mutateAsync({id:v.id,open_house_id:s,is_active:!v.is_active})},y=async v=>{await o.mutateAsync({id:v.id,open_house_id:s})};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsxs(ee,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(zg,{className:"h-4 w-4"}),"Property Feedback Survey"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show a quick feedback survey after visitors sign in"})]}),e.jsx(Sn,{checked:t,onCheckedChange:f})]}),t&&e.jsx("div",{className:"space-y-3 pt-2 border-t border-border",children:a?e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(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(v=>e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg border border-border bg-muted/20",children:[e.jsx(Ug,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm truncate",children:v.question_text}),e.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:v.question_type.replace("_"," ")})]}),e.jsx(Sn,{checked:v.is_active,onCheckedChange:()=>x(v),className:"scale-75"}),e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0 text-muted-foreground hover:text-destructive",onClick:()=>y(v),children:e.jsx(Hn,{className:"h-3.5 w-3.5"})})]},v.id))}),e.jsxs("div",{className:"flex items-end gap-2",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(ee,{className:"text-xs text-muted-foreground",children:"Add Question"}),e.jsx(pe,{value:d,onChange:v=>u(v.target.value),placeholder:"e.g. How did you hear about this listing?",className:"mt-1 h-9 text-sm",onKeyDown:v=>v.key==="Enter"&&g()})]}),e.jsxs(ms,{value:h,onValueChange:m,children:[e.jsx(us,{className:"w-28 h-9 text-xs",children:e.jsx(fs,{})}),e.jsxs(hs,{children:[e.jsx(Ge,{value:"rating",children:"Rating"}),e.jsx(Ge,{value:"open_text",children:"Text"})]})]}),e.jsx($,{size:"sm",variant:"outline",onClick:g,disabled:!d.trim()||i.isPending,className:"h-9",children:e.jsx(dn,{className:"h-3.5 w-3.5"})})]})]})})]})}function Wur({openHouseId:s}){const{user:t}=bs(),{data:n=[],isLoading:r}=jFs(s),a=kFs(),i=TFs(),l=(m,f)=>{const g=m+f;if(g<0||g>=n.length)return;const x=n.map(y=>y.id);[x[m],x[g]]=[x[g],x[m]],i.mutate({open_house_id:s,orderedIds:x})},[o,c]=j.useState(""),[d,u]=j.useState(!1),h=async()=>{const m=o.trim();if(m){u(!0);try{await a.mutateAsync({open_house_id:s,name:m,sort_order:n.length}),c("")}finally{u(!1)}}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-sm font-medium",children:"Rooms"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Add rooms and upload photos or videos (or pull a clip from your Video Library). Use the up/down arrows to reorder rooms and the arrows on each tile to reorder photos and videos. Visitors swipe through them on mobile and tab through them on desktop."})]}),r?e.jsxs("div",{className:"py-6 text-center text-sm text-muted-foreground",children:[e.jsx(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(Kur,{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(dn,{className:"h-4 w-4 mr-1"})," Add"]})})]})]})}function Kur({room:s,index:t,total:n,userId:r,openHouseId:a,onMoveRoom:i}){const l=SFs(),o=CFs(),c=AFs(),d=EFs(),u=MFs(),h=j.useRef(null),[m,f]=j.useState(!0),[g,x]=j.useState(s.name),[y,v]=j.useState(s.description||""),[b,w]=j.useState(!1),S=j.useMemo(()=>s.media.filter(U=>U.kind==="video"&&U.agent_video_id).map(U=>U.agent_video_id),[s.media]),{data: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 Y={};return V.forEach(X=>{Y[X.id]={status:X.status,thumbnail_url:X.thumbnail_url,preview_url:X.preview_url}}),Y},refetchInterval:U=>{const W=U.state.data;return W?Object.values(W).some(V=>V.status!=="ready"&&V.status!=="failed")?5e3:!1:5e3}}),E=()=>{g.trim()&&g!==s.name&&l.mutate({id:s.id,open_house_id:a,name:g.trim()})},I=()=>{y!==(s.description||"")&&l.mutate({id:s.id,open_house_id:a,description:y.trim()||null})},P=async()=>{await fo(`Delete "${s.name}" and all its media?`)&&o.mutate({id:s.id,open_house_id:a})},R=U=>i(t,U),D=(U,W)=>{const V=U+W;if(V<0||V>=s.media.length)return;const G=s.media.map(Y=>Y.id);[G[U],G[V]]=[G[V],G[U]],u.mutate({open_house_id:a,room_id:s.id,orderedIds:G})},O=async U=>{const W=Array.from(U.target.files||[]);if(!(!W.length||!r)){w(!0);try{for(const V of W){const G=V.type.startsWith("video/"),Y=G?500*1024*1024:15*1024*1024;if(V.size>Y){_a({title:`${V.name} is too large`,description:G?"Videos must be under 500MB":"Photos must be under 15MB",variant:"destructive"});continue}if(G){try{const te=`${s.name} – ${V.name.replace(/\.[^/.]+$/,"")}`,{data:J,error:ce}=await q.functions.invoke("bunny-upload",{body:{action:"create",title:te,isAgentVideo:!0}});if(ce||!J)throw new Error((ce==null?void 0:ce.message)||"Could not start upload");const{videoId:_e,libraryId:he}=J,{data:ue,error:ve}=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:_e,isAgentVideo:!0}});if(ve||!ue)throw new Error((ve==null?void 0:ve.message)||"Could not get upload URL");await new Promise((ke,Be)=>{const Ne=new XMLHttpRequest;Ne.addEventListener("load",()=>{Ne.status>=200&&Ne.status<300?ke():Be(new Error(`Upload failed (${Ne.status})`))}),Ne.addEventListener("error",()=>Be(new Error("Upload failed"))),Ne.open("PUT",ue.uploadUrl),Ne.setRequestHeader("AccessKey",ue.apiKey),Ne.send(V)});const Ee=`https://iframe.mediadelivery.net/embed/${he}/${_e}`,Se=V.size/(1024*1024),{data:Le,error:Fe}=await q.from("agent_videos").insert({owner_user_id:r,bunny_video_id:_e,playback_url:Ee,file_size_mb:Se,title:te,status:"processing",touch_type:"open_house_tour",category:"open_house",page_template:"default"}).select().single();if(Fe)throw Fe;await c.mutateAsync({open_house_id:a,room_id:s.id,kind:"video",url:Ee,sort_order:s.media.length,agent_video_id:Le.id}),_a({title:"Video uploaded",description:"Processing in the background — it’ll appear in your Video Library too."})}catch(te){_a({title:"Video upload failed",description:(te==null?void 0:te.message)||"Try again",variant:"destructive"})}continue}const X=V.name.split(".").pop()||"jpg",ae=`${r}/${a}/rooms/${s.id}-${Date.now()}-${Math.random().toString(36).slice(2,7)}.${X}`,{error: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:ne}=q.storage.from("open-house-tour-media").getPublicUrl(ae);await c.mutateAsync({open_house_id:a,room_id:s.id,kind:"photo",url:ne.publicUrl,sort_order:s.media.length})}}finally{w(!1),h.current&&(h.current.value="")}}};return e.jsxs("div",{className:"rounded-lg border border-border bg-card",children:[e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 border-b border-border",children:[e.jsx(Ug,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("button",{onClick:()=>f(U=>!U),className:"flex-1 text-left text-sm font-medium truncate",children:[s.name," ",e.jsxs("span",{className:"text-muted-foreground font-normal text-xs",children:["· ",s.media.length," ",s.media.length===1?"item":"items"]})]}),e.jsx($,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>R(-1),disabled:t===0,children:e.jsx(yb,{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(Hn,{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(Ls,{value:y,onChange:U=>v(U.target.value),onBlur:I,placeholder:"Optional description — what makes this room special?",rows:2,className:"text-sm"}),s.media.length>0&&e.jsx("div",{className:"grid grid-cols-3 gap-2",children:s.media.map((U,W)=>{const V=U.agent_video_id?A[U.agent_video_id]:void 0,G=V==null?void 0:V.status,Y=U.kind==="video"&&G&&G!=="ready"&&G!=="failed",X=U.kind==="video"&&G==="failed",ae=(V==null?void 0:V.thumbnail_url)||(V==null?void 0:V.preview_url);return e.jsxs("div",{className:"relative aspect-square rounded-md overflow-hidden bg-muted group",children:[U.kind==="video"?e.jsxs(e.Fragment,{children:[ae?e.jsx("img",{src:ae,alt:"",className:"w-full h-full object-cover"}):/iframe\.mediadelivery\.net\/embed\//.test(U.url)?e.jsx("div",{className:"w-full h-full bg-slate-800"}):e.jsx("video",{src:U.url,className:"w-full h-full object-cover"}),!Y&&!X&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/30 pointer-events-none",children:e.jsx(ua,{className:"h-6 w-6 text-white"})}),Y&&e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center bg-black/70 text-white gap-1 pointer-events-none",children:[e.jsx(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(pr,{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(s9,{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 Yur({open:s,onOpenChange:t,openHouse:n}){const r=W7t(),{user:a}=bs(),i=j.useRef(null),l=j.useRef(null),o=j.useRef(null),c=n.kind==="virtual",[d,u]=j.useState(n.auto_forward_to_card??!1),[h,m]=j.useState(n.disclosure_pdf_url??""),[f,g]=j.useState(n.enable_survey??!1),[x,y]=j.useState(n.ask_visitor_intent??!0),[v,b]=j.useState(n.ask_visitor_address??!1),[w,S]=j.useState(n.photo_url??""),[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,Y]=j.useState(n.state??""),[X,ae]=j.useState(n.zip??""),[le,ne]=j.useState((n.event_date??"").slice(0,10)),[te,J]=j.useState((n.start_time??"").slice(0,5)),[ce,_e]=j.useState((n.end_time??"").slice(0,5)),[he,ue]=j.useState(n.hero_video_url??""),[ve,Ee]=j.useState(!1),[Se,Le]=j.useState(n.price!=null?String(n.price):""),[Fe,ke]=j.useState(n.beds!=null?String(n.beds):""),[Be,Ne]=j.useState(n.baths!=null?String(n.baths):""),[Ae,Ce]=j.useState(n.sqft!=null?String(n.sqft):""),[Ve,ze]=j.useState(n.enable_question??!0),[qe,dt]=j.useState(n.enable_showing??!0),[Xe,at]=j.useState(n.enable_disclosures??!0),[rt,Ke]=j.useState(n.enable_offer??!0),[Je,pt]=j.useState(n.brand_color_override??""),[gt,ss]=j.useState(n.property_description??""),[Yt,ts]=j.useState(n.drip_campaign_id??null),ys=async wt=>{var Ss;const gs=(Ss=wt.target.files)==null?void 0:Ss[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 ks=gs.name.split(".").pop()||"mp4",Is=`${a.id}/${n.id}/hero-${Date.now()}.${ks}`,{error:Xs}=await q.storage.from("open-house-tour-media").upload(Is,gs,{upsert:!0,contentType:gs.type});if(Xs){_a({title:"Upload failed",description:Xs.message,variant:"destructive"}),Ee(!1);return}const{data:ds}=q.storage.from("open-house-tour-media").getPublicUrl(Is);ue(ds.publicUrl),Ee(!1),_a({title:"Video uploaded!"})},Bt=async wt=>{var Ss;const gs=(Ss=wt.target.files)==null?void 0:Ss[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 ks=gs.name.split(".").pop()||"jpg",Is=`${a.id}/${n.id}-${Date.now()}.${ks}`,{error:Xs}=await q.storage.from("open-house-photos").upload(Is,gs,{upsert:!0});if(Xs){_a({title:"Upload failed",description:Xs.message,variant:"destructive"}),P(!1);return}const{data:ds}=q.storage.from("open-house-photos").getPublicUrl(Is);S(ds.publicUrl),P(!1),_a({title:"Photo updated!"})},Ft=()=>{S(""),l.current&&(l.current.value="")},as=async wt=>{var ds;const gs=(ds=wt.target.files)==null?void 0:ds[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 ks=`${a.id}/disclosures/${n.id}-${Date.now()}.pdf`,{error:Is}=await q.storage.from("open-house-photos").upload(ks,gs,{upsert:!0});if(Is){_a({title:"Upload failed",description:Is.message,variant:"destructive"}),E(!1);return}const{data:Xs}=q.storage.from("open-house-photos").getPublicUrl(ks);m(Xs.publicUrl),E(!1),_a({title:"PDF uploaded!"})},kt=()=>{m(""),i.current&&(i.current.value="")},Ks=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 wt={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:v,photo_url:w||null,drip_campaign_id:Yt};c&&(wt.hero_video_url=he||null,wt.price=Se.trim()?Number(Se):null,wt.beds=Fe.trim()?parseInt(Fe,10):null,wt.baths=Be.trim()?Number(Be):null,wt.sqft=Ae.trim()?parseInt(Ae,10):null,wt.enable_question=Ve,wt.enable_showing=qe,wt.enable_disclosures=Xe,wt.enable_offer=rt,wt.brand_color_override=Je.trim()||null,wt.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))&&(wt.latitude=null,wt.longitude=null,wt.geocode_status="pending",wt.geocoded_at=null),await r.mutateAsync(wt),_a({title:"Settings saved!"}),t(!1)}catch{_a({title:"Failed to save",variant:"destructive"})}finally{D(!1)}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-md max-h-[85vh] overflow-y-auto",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:c?"Virtual Open House Settings":"Guest Book Settings"}),e.jsx(Pr,{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:wt=>ne(wt.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:wt=>J(wt.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:wt=>_e(wt.target.value),className:"mt-1"})]})]}),e.jsx(ee,{className:"text-sm font-medium",children:"Property Address"}),e.jsx(pe,{value:O,onChange:wt=>U(wt.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:wt=>V(wt.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:wt=>Y(wt.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:wt=>ae(wt.target.value),className:"mt-1"})]})]})]}),c&&e.jsxs(e.Fragment,{children:[n.tour_mode==="single_video"?e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(ua,{className:"h-4 w-4"})," Hero Tour Video"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"The video visitors watch right after they sign in. MP4 recommended (max 200MB)."}),e.jsx("input",{ref:o,type:"file",accept:"video/*",onChange:ys,className:"hidden"}),he?e.jsxs("div",{className:"relative rounded-lg overflow-hidden border border-border bg-black",children:[e.jsx("video",{src:he,controls:!0,className:"w-full max-h-48"}),e.jsxs("div",{className:"absolute top-2 right-2 flex gap-2",children:[e.jsx($,{variant:"secondary",size:"sm",className:"h-8",onClick:()=>{var wt;return(wt=o.current)==null?void 0:wt.click()},disabled:ve,children:ve?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(pr,{className:"h-4 w-4"})})]})]}):e.jsx("button",{type:"button",onClick:()=>{var wt;return(wt=o.current)==null?void 0:wt.click()},disabled:ve,className:"w-full h-32 rounded-xl border-2 border-dashed border-muted-foreground/25 hover:border-muted-foreground/50 flex flex-col items-center justify-center gap-2 text-muted-foreground hover:text-foreground transition-colors",children:ve?e.jsx(Ct,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(ua,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"Upload tour video (max 200MB)"})]})})]}):e.jsx(Wur,{openHouseId:n.id}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-sm font-medium",children:"Property Details"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs text-muted-foreground",children:"Price (USD)"}),e.jsx(pe,{type:"number",value:Se,onChange:wt=>Le(wt.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:wt=>Ce(wt.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:wt=>ke(wt.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:wt=>Ne(wt.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(Ls,{value:gt,onChange:wt=>ss(wt.target.value),placeholder:"Stunning 4-bedroom in the heart of River Oaks. Chef's kitchen, oversized primary suite, and a backyard oasis perfect for entertaining…",rows:5,className:"w-full resize-y"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(ee,{className:"text-sm font-medium",children:"Visitor Actions"}),e.jsx("p",{className:"text-xs text-muted-foreground -mt-1",children:"Choose what visitors can do during the tour."}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"Ask a question"}),e.jsx(Sn,{checked:Ve,onCheckedChange:ze})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"Schedule a private showing"}),e.jsx(Sn,{checked:qe,onCheckedChange:dt})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"Request seller disclosures"}),e.jsx(Sn,{checked:Xe,onCheckedChange: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(Sn,{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:wt=>pt(wt.target.value),className:"h-10 w-14 rounded-md border border-input cursor-pointer bg-transparent"}),e.jsx(pe,{value:Je,onChange:wt=>pt(wt.target.value),placeholder:"#0f172a",className:"flex-1 font-mono text-sm"}),Je&&e.jsx($,{variant:"ghost",size:"sm",onClick:()=>pt(""),children:"Reset"})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5 pt-1",children:["#0f172a","#406E71","#2a4c64","#7c2d12","#1e3a8a","#581c87","#9f1239","#065f46"].map(wt=>e.jsx("button",{type:"button",onClick:()=>pt(wt),className:"w-6 h-6 rounded-full border border-border hover:scale-110 transition-transform",style:{backgroundColor:wt},"aria-label":wt},wt))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-sm font-medium",children:"Property Photo"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Shown on the sign-in screen and printable QR sheet"}),e.jsx("input",{ref:l,type:"file",accept:"image/*",onChange:Bt,className:"hidden"}),w?e.jsxs("div",{className:"relative rounded-lg overflow-hidden border border-border",children:[e.jsx("img",{src:w,alt:"Property",className:"w-full h-40 object-cover"}),e.jsxs("div",{className:"absolute top-2 right-2 flex gap-2",children:[e.jsxs($,{variant:"secondary",size:"sm",className:"h-8",onClick:()=>{var wt;return(wt=l.current)==null?void 0:wt.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(pr,{className:"h-4 w-4"})})]})]}):e.jsx("button",{type:"button",onClick:()=>{var wt;return(wt=l.current)==null?void 0:wt.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(Hur,{value:Yt,onChange:ts}),e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(ee,{className:"text-sm font-medium",children:"Auto-forward to Digital Card"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"After check-in, redirect visitors to your digital business card"})]}),e.jsx(Sn,{checked:d,onCheckedChange:u})]})}),!d&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{className:"text-sm font-medium",children:"Seller's Disclosures (PDF)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Visitors can view or download this on the thank you screen after check-in"}),e.jsx("input",{ref:i,type:"file",accept:"application/pdf",onChange:as,className:"hidden"}),h?e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border border-border bg-muted/30",children:[e.jsx(Jr,{className:"h-5 w-5 text-primary shrink-0"}),e.jsx("span",{className:"text-sm truncate flex-1",children:"Disclosure PDF uploaded"}),e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0",onClick:kt,children:e.jsx(pr,{className:"h-4 w-4"})})]}):e.jsx("button",{type:"button",onClick:()=>{var wt;return(wt=i.current)==null?void 0:wt.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(Sn,{checked:x,onCheckedChange:y})]})}),e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(ee,{className:"text-sm font-medium",children:"Ask for visitor's home address"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Adds an optional address field to the sign-in form — helpful for follow-up and market reports."})]}),e.jsx(Sn,{checked:v,onCheckedChange:b})]})}),e.jsx(Gur,{openHouseId:n.id,enableSurvey:f,onToggleSurvey:g}),e.jsx($,{onClick:Ks,disabled:R,className:"w-full",children:R?"Saving...":"Save Settings"})]})]})})}const Jos={5:"Excellent",4:"Good",3:"Neutral",2:"Bad",1:"Very Bad"};function Zur({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:Jos[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 Xur({openHouseId:s}){const{data:t,isLoading:n}=pFs(s),{data:r}=G7t(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(zg,{className:"h-4 w-4"}),"Survey Results"]})}),e.jsx(Ie,{children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"No survey responses yet."})})]}):e.jsxs(je,{children:[e.jsx(St,{className:"pb-3",children:e.jsxs(Et,{className:"text-base flex items-center gap-2",children:[e.jsx(zg,{className:"h-4 w-4"}),"Survey Results",e.jsxs("span",{className:"text-xs font-normal text-muted-foreground ml-auto",children:[u," respondent",u!==1?"s":""]})]})}),e.jsx(Ie,{children:e.jsxs(ha,{defaultValue:"summary",children:[e.jsxs(ma,{className:"mb-4",children:[e.jsxs(Zt,{value:"summary",className:"text-xs gap-1",children:[e.jsx(Gl,{className:"h-3.5 w-3.5"})," Summary"]}),e.jsxs(Zt,{value:"individual",className:"text-xs gap-1",children:[e.jsx(sl,{className:"h-3.5 w-3.5"})," Per Visitor"]})]}),e.jsxs(Xt,{value:"summary",className:"space-y-6",children:[o.map(h=>e.jsx(Zur,{question:h,responses:l},h.id)),c.map(h=>{const m=l.filter(f=>f.question_id===h.id&&f.text_value);return m.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsx("span",{className:"text-sm font-medium",children:h.question_text}),e.jsx("div",{className:"space-y-1.5 max-h-40 overflow-y-auto",children:m.map(f=>{const g=a[f.visitor_id];return e.jsxs("div",{className:"text-sm p-2 bg-muted/30 rounded-lg",children:[e.jsxs("span",{className:"text-muted-foreground text-xs",children:[g?`${g.first_name} ${g.last_name||""}`.trim():"Visitor",":"]}),e.jsx("p",{className:"mt-0.5",children:f.text_value})]},f.id)})})]},h.id)})]}),e.jsx(Xt,{value:"individual",className:"space-y-4",children:d.map(h=>{const m=a[h],f=l.filter(g=>g.visitor_id===h);return e.jsxs("div",{className:"p-3 rounded-lg border border-border space-y-2",children:[e.jsxs("p",{className:"text-sm font-medium",children:[m?`${m.first_name} ${m.last_name||""}`.trim():"Unknown Visitor",(m==null?void 0:m.email)&&e.jsx("span",{className:"text-xs text-muted-foreground ml-2",children:m.email})]}),e.jsx("div",{className:"space-y-1",children:f.map(g=>{const x=i.find(y=>y.id===g.question_id);return x?e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:x.question_text}),e.jsx("span",{className:"font-medium",children:g.rating_value!=null?Jos[g.rating_value]||g.rating_value:g.text_value})]},g.id):null})})]},h)})})]})})]})}const Qur={question:{label:"Question",icon:eo,color:"text-sky-700 dark:text-sky-300",bg:"bg-sky-100 dark:bg-sky-950"},showing:{label:"Showing",icon:Ta,color:"text-orange-700 dark:text-orange-300",bg:"bg-orange-100 dark:bg-orange-950"},disclosure:{label:"Disclosures",icon:Jr,color:"text-indigo-700 dark:text-indigo-300",bg:"bg-indigo-100 dark:bg-indigo-950"},offer:{label:"Hot Lead",icon:nu,color:"text-emerald-700 dark:text-emerald-300",bg:"bg-emerald-100 dark:bg-emerald-950"}},WEt={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 Jur({openHouseId:s}){const{data:t=[],isLoading:n}=PFs(s),r=IFs(),[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(Uz,{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=Qur[h.action_type],f=m.icon,g=h.payload||{},x=a===h.id,y=h.status==="contacted",v=h.status==="archived";return e.jsxs("li",{className:`transition-colors ${v?"opacity-60":""} ${h.status==="new"?"bg-emerald-50/40 dark:bg-emerald-950/10":""}`,children:[e.jsxs("button",{onClick:()=>i(x?null:h.id),className:"w-full text-left px-4 py-3 flex items-start gap-3 hover:bg-muted/40 transition-colors",children:[e.jsx("div",{className:`w-9 h-9 rounded-lg flex items-center justify-center shrink-0 ${m.bg}`,children:e.jsx(f,{className:`h-4 w-4 ${m.color}`})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-semibold text-sm truncate",children:g.visitor_name||"Visitor"}),e.jsx($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"}),y&&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(da,{className:"h-3 w-3"}),en(new Date(h.created_at),"MMM d, h:mm a")]}),g.email&&e.jsxs("span",{className:"flex items-center gap-1 truncate",children:[e.jsx(mn,{className:"h-3 w-3"}),g.email]}),g.phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Da,{className:"h-3 w-3"}),g.phone]})]})]}),x?e.jsx(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(WEt).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(WEt).map(([b,w])=>{const S=g[b];return S==null||S===""||Array.isArray(S)&&S.length===0?null:e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] text-muted-foreground uppercase tracking-wide",children:w}),e.jsx("div",{className:"font-medium",children:Array.isArray(S)?S.join(", "):String(S)})]},b)})}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 pt-1",children:[g.email&&e.jsx("a",{href:`mailto:${g.email}?subject=${encodeURIComponent("Re: your open house inquiry")}`,children:e.jsxs($,{size:"sm",variant:"default",className:"gap-1.5",children:[e.jsx(mn,{className:"h-3.5 w-3.5"}),"Reply"]})}),g.phone&&e.jsx("a",{href:`tel:${String(g.phone).replace(/[^0-9+]/g,"")}`,children:e.jsxs($,{size:"sm",variant:"outline",className:"gap-1.5",children:[e.jsx(Da,{className:"h-3.5 w-3.5"}),"Call"]})}),!y&&e.jsxs($,{size:"sm",variant:"outline",className:"gap-1.5",onClick:()=>u(h.id,"contacted"),children:[e.jsx(Vr,{className:"h-3.5 w-3.5"}),"Mark contacted"]}),v?e.jsx($,{size:"sm",variant:"ghost",className:"gap-1.5 text-muted-foreground",onClick:()=>u(h.id,"new"),children:"Restore"}):e.jsxs($,{size:"sm",variant:"ghost",className:"gap-1.5 text-muted-foreground",onClick:()=>u(h.id,"archived"),children:[e.jsx(jv,{className:"h-3.5 w-3.5"}),"Archive"]})]})]})]},h.id)})})]})}const KEt=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}`},ehr=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"})},YEt=25;function thr({open:s,onOpenChange:t,openHouse:n,variant:r="tour"}){var dt;const a=r==="rsvp",{isGmailConnected:i,gmailEmail:l}=gy(),{data:o}=sie(),c=!!(o!=null&&o.hasVerifiedSes),d=Sa(),{data:u=[]}=qw(),[h,m]=j.useState([]),[f,g]=j.useState(!1),[x,y]=j.useState("all"),[v,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,Y]=j.useState("platform"),[X,ae]=j.useState(!1),[le,ne]=j.useState(0),[te,J]=j.useState(!1),ce=a?`https://guestbook.relevelup.com/rsvp/${n.slug}`:`https://guestbook.relevelup.com/${n.slug}`,_e=ehr(n.event_date),he=n.start_time?`${KEt(n.start_time)}${n.end_time?` – ${KEt(n.end_time)}`:""}`:"",ue=[_e,he].filter(Boolean).join(" · ");j.useEffect(()=>{s&&(U(a?`You're invited: Open House at ${n.property_address}`:`Take a virtual tour of ${n.property_address}`),V(a?`I'm hosting an open house at ${n.property_address}${_e?` on ${_e}`:""}${he?` from ${he}`:""}. I'd love for you to stop by — tap below to RSVP so I can save you a spot.`:`I wanted to share an immersive virtual tour of ${n.property_address} with you. Step inside from anywhere — explore every room at your own pace.`),S([]),b([]),P([]),E(""),y("all"),ne(0),Y(c?"ses":i?"gmail":"platform"),h.length===0&&ve())},[s,n.id,i,c]);const ve=async()=>{if(d){g(!0);try{const Xe=[];let 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 pt=Ke||[];if(Xe.push(...pt),pt.length<1e3)break;rt+=1e3}m(Xe.map(Ke=>({id:Ke.id,first_name:Ke.first_name,last_name:Ke.last_name,email:Ke.email,tagIds:(Ke.tags||[]).map(Je=>Je.relationship_type_id)})))}catch{re.error("Failed to load contacts")}finally{g(!1)}}},Ee=Xe=>`${Xe.first_name} ${Xe.last_name||""}`.trim(),Se=j.useMemo(()=>{const Xe=R.trim().toLowerCase();return Xe?h.filter(at=>`${Ee(at)} ${at.email||""}`.toLowerCase().includes(Xe)):h},[h,R]),Le=j.useMemo(()=>{const Xe={};return h.forEach(at=>at.tagIds.forEach(rt=>{Xe[rt]=(Xe[rt]||0)+1})),Xe},[h]),Fe=j.useMemo(()=>x==="all"?h:x==="tags"?v.length===0?[]:h.filter(Xe=>Xe.tagIds.some(at=>v.includes(at))):h.filter(Xe=>w.includes(Xe.id)),[x,h,v,w]),ke=j.useMemo(()=>{const Xe=new Set,at=[];return[...Fe.map(rt=>({email:rt.email,name:Ee(rt)})),...I].forEach(rt=>{const Ke=rt.email.toLowerCase();!rt.email||Xe.has(Ke)||(Xe.add(Ke),at.push(rt))}),at},[Fe,I]),Be=()=>{const Xe=A.trim();if(Xe){if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(Xe)){re.error("Invalid email");return}P(at=>[...at,{email:Xe,name:Xe.split("@")[0]}]),E("")}},Ne=Xe=>Xe.replace(/&/g,"&").replace(//g,">"),Ae=n.photo_url&&n.photo_url.includes("/storage/v1/object/public/")?n.photo_url.replace("/object/public/","/render/image/public/")+"?width=1200&height=630&resize=cover":n.photo_url||"",Ce=Xe=>{const at=Xe?`Hi ${Ne(Xe)},`:"Hi there,",rt=[n.city,n.state].filter(Boolean).join(", "),Ke=Ne(W).split(/\n\n+/).map(Je=>`

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

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

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

${Ne(n.property_address)}

${rt?`

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

`:""}
 

When

${Ne(ue)}

${at}

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

Or copy this link:
${ce}

`},Ve=j.useMemo(()=>Ce("Alex"),[W,n.id,Ae,a,ue]),ze=async()=>{var Xe;if(ke.length===0){re.error("Add at least one recipient");return}ae(!0),ne(0);try{if(G==="gmail"&&i){let at=0;for(const rt of ke){const{data:Ke,error:Je}=await q.functions.invoke("gmail-send",{body:{to:rt.email,subject:O,body:Ce((Xe=rt.name)==null?void 0:Xe.split(" ")[0])}});!Je&&(Ke!=null&&Ke.success)&&(at+=1),ne(at)}if(at===0)throw new Error("Gmail send failed");re.success(`Sent to ${at} of ${ke.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(zs,{open:s,onOpenChange:t,children:e.jsxs(Os,{className:"sm:max-w-[900px] w-[calc(100vw-2rem)] max-h-[92vh] overflow-y-auto overflow-x-hidden",children:[e.jsxs(Us,{className:"min-w-0",children:[e.jsxs(Bs,{className:"flex items-center gap-2",children:[e.jsx(mn,{className:"h-5 w-5 text-primary"}),a?"Invite to Open House":"Email Virtual Tour"]}),e.jsx(Pr,{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:qe,className:"shrink-0 h-7 gap-1",children:[te?e.jsx(ca,{className:"h-3.5 w-3.5 text-emerald-600"}):e.jsx(Ha,{className:"h-3.5 w-3.5"}),te?"Copied":"Copy"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ee,{className:"flex items-center gap-1.5",children:[e.jsx(mn,{className:"h-3.5 w-3.5"}),"Send from"]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[c&&e.jsx($,{type:"button",variant:G==="ses"?"default":"outline",size:"sm",onClick:()=>Y("ses"),className:"gap-1.5",children:"Mass Email (your address)"}),i&&e.jsx($,{type:"button",variant:G==="gmail"?"default":"outline",size:"sm",onClick:()=>Y("gmail"),className:"gap-1.5",children:"Gmail"}),e.jsx($,{type:"button",variant:G==="platform"?"default":"outline",size:"sm",onClick:()=>Y("platform"),className:"gap-1.5",children:"LevelUp"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:G==="ses"&&((dt=o==null?void 0:o.verifiedEmails)!=null&&dt[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(ha,{value:x,onValueChange:Xe=>y(Xe),children:[e.jsxs(ma,{className:"grid w-full grid-cols-3",children:[e.jsx(Zt,{value:"all",children:"All contacts"}),e.jsx(Zt,{value:"tags",children:"By tag"}),e.jsx(Zt,{value:"select",children:"Pick people"})]}),e.jsx(Xt,{value:"all",className:"pt-3",children:e.jsx("div",{className:"rounded-lg border p-3 text-sm text-muted-foreground",children:f?"Loading contacts…":e.jsxs(e.Fragment,{children:["Everyone in your database with an email address — ",e.jsx("span",{className:"font-medium text-foreground",children:h.length.toLocaleString()})," contacts."]})})}),e.jsx(Xt,{value:"tags",className:"pt-3",children:e.jsx(uo,{className:"h-[210px] rounded-lg border p-2",children:e.jsxs("div",{className:"space-y-1",children:[u.map(Xe=>{const at=v.includes(Xe.id);return e.jsxs("label",{className:"flex items-center gap-2 rounded-md px-2 py-1.5 hover:bg-muted cursor-pointer",children:[e.jsx(ai,{checked:at,onCheckedChange:()=>b(rt=>at?rt.filter(Ke=>Ke!==Xe.id):[...rt,Xe.id])}),e.jsxs("span",{className:"flex items-center gap-1.5 text-sm flex-1 min-w-0 truncate",children:[e.jsx(Ap,{className:"h-3 w-3 text-muted-foreground shrink-0"}),Xe.name]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Le[Xe.id]||0})]},Xe.id)}),u.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground p-2",children:"No tags yet."})]})})}),e.jsxs(Xt,{value:"select",className:"pt-3 space-y-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Zr,{className:"absolute left-2.5 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(pe,{value:R,onChange:Xe=>D(Xe.target.value),placeholder:"Search contacts...",className:"pl-8 h-9"})]}),e.jsx(uo,{className:"h-[210px] rounded-lg border p-2",children:e.jsxs("div",{className:"space-y-1",children:[Se.slice(0,300).map(Xe=>{const at=w.includes(Xe.id);return e.jsxs("label",{className:"flex items-center gap-2 rounded-md px-2 py-1.5 hover:bg-muted cursor-pointer",children:[e.jsx(ai,{checked:at,onCheckedChange:()=>S(rt=>at?rt.filter(Ke=>Ke!==Xe.id):[...rt,Xe.id])}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"text-sm font-medium truncate",children:Ee(Xe)||"(no name)"}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:Xe.email})]})]},Xe.id)}),Se.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground p-2",children:f?"Loading…":"No contacts found."})]})})]})]}),e.jsxs("div",{className:"flex gap-2 pt-1",children:[e.jsx(pe,{value:A,onChange:Xe=>E(Xe.target.value),placeholder:"Also send to an email...",type:"email",onKeyDown:Xe=>{Xe.key==="Enter"&&(Xe.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(Xe=>e.jsxs($e,{variant:"secondary",className:"gap-1 pl-2 pr-1 py-0.5",children:[e.jsx("span",{className:"text-xs",children:Xe.email}),e.jsx("button",{onClick:()=>P(at=>at.filter(rt=>rt.email!==Xe.email)),className:"hover:bg-muted-foreground/20 rounded p-0.5",children:e.jsx(pr,{className:"h-3 w-3"})})]},Xe.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:Xe=>U(Xe.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ee,{htmlFor:"vt-message",children:"Message"}),e.jsx(Ls,{id:"vt-message",value:W,onChange:Xe=>V(Xe.target.value),rows:6,className:"resize-y"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Each email opens with a personal greeting using the contact's first name."})]})]}),e.jsxs("div",{className:"space-y-2 min-w-0",children:[e.jsxs(ee,{className:"flex items-center gap-1.5",children:[e.jsx(Ca,{className:"h-3.5 w-3.5"}),"Preview"]}),e.jsx("div",{className:"rounded-xl border overflow-hidden bg-muted/20",children:e.jsx("iframe",{title:"Email preview",srcDoc:`${Ve}`,className:"w-full h-[420px] lg:h-[560px] border-0 bg-white",sandbox:""})})]})]}),e.jsxs("div",{className:Pt("flex flex-wrap items-center justify-between gap-3 pt-2 border-t"),children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:[e.jsx("span",{className:"font-semibold text-foreground",children:ke.length.toLocaleString()})," recipient",ke.length===1?"":"s",X&&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||ke.length===0||!O.trim(),className:"gap-2",children:[X?e.jsx(Ct,{className:"h-4 w-4 animate-spin"}):e.jsx(Kr,{className:"h-4 w-4"}),X?"Sending...":`Send${ke.length?` to ${ke.length}`:""}`]})]})]})]})})}function shr({openHouseId:s}){const{data:t=[],isLoading:n}=JFs(s),r=tOs(s),a=sOs(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(xb,{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(ca,{className:"h-3 w-3"}),"Checked in"]}),l.has_agent&&e.jsxs($e,{variant:"outline",className:"text-[10px] gap-1",children:[e.jsx(m2,{className:"h-3 w-3"}),l.working_with_agent_name||"Has an agent"]})]}),e.jsxs("div",{className:"flex items-center gap-3 mt-0.5 text-xs text-muted-foreground flex-wrap",children:[l.email&&e.jsxs("span",{className:"flex items-center gap-1 truncate",children:[e.jsx(mn,{className:"h-3 w-3"}),l.email]}),l.phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Da,{className:"h-3 w-3"}),l.phone]})]}),l.message&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1 italic",children:["“",l.message,"”"]})]}),e.jsx($,{variant:l.checked_in_at?"secondary":"outline",size:"sm",className:"h-8 text-xs",onClick:()=>a.mutate({id:l.id,checkedIn:!l.checked_in_at}),children:l.checked_in_at?"Undo":"Check in"}),e.jsx($,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0 text-muted-foreground hover:text-destructive","aria-label":"Delete RSVP",onClick:()=>r.mutate(l.id),children:e.jsx(Hn,{className:"h-4 w-4"})})]},l.id))})]})}function nhr({summary:s,stats:t,search:n,onSearchChange:r,onCreate:a}){return e.jsx("section",{className:"hub-ink relative overflow-hidden rounded-2xl p-5 sm:p-6",children:e.jsxs("div",{className:"relative flex flex-col gap-5",children:[e.jsxs("div",{className:"flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-xs uppercase tracking-wider hub-ink-muted",children:"Agent OS"}),e.jsx("h1",{className:"mt-1 text-2xl font-bold sm:text-3xl",children:"Guest Book"}),e.jsx("p",{className:"mt-1 text-sm hub-ink-muted",children:s})]}),e.jsxs("div",{className:"flex flex-col items-start gap-2 sm:items-end",children:[e.jsxs("button",{onClick:a,className:"inline-flex items-center gap-2 rounded-full bg-background px-4 py-2 text-sm font-semibold text-foreground shadow-sm transition-transform hover:scale-[1.02]",children:[e.jsx(dn,{className:"h-4 w-4"}),"New Open House"]}),e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-xs hub-ink-muted",children:[e.jsx(Jp,{className:"h-3.5 w-3.5",style:{color:"hsl(var(--hub-glow))"}}),"Every event gets a sign-in page & QR code"]})]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Zr,{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 ZEt={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 rhr({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(Fd,{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("div",{className:"flex gap-1.5",children:[e.jsx(pit,{className:"h-7 text-xs",label:"Mail visitors",build:()=>({source:"guestbook",contactEmails:s.map(a=>(a.email||"").trim().toLowerCase()).filter(Boolean),name:"Open house thank-you",message:`Hi %FIRST_NAME%, Thank you for stopping by the open house! If you have any questions about the home or the neighborhood, I am always happy to help.`})}),e.jsxs($,{variant:"outline",size:"sm",onClick:t,className:"h-7 gap-1 text-xs",children:[e.jsx(xi,{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=ZEt[a.visitor_intent||""]||ZEt.browsing;return e.jsxs("tr",{className:Pt("border-t border-border/50 transition-colors hover:bg-muted/40",i&&"bg-orange-500/[0.06]"),children:[e.jsx("td",{className:"p-2.5",children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:Pt("flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-xs font-bold",i?"bg-orange-500/15 text-orange-700 dark:text-orange-300":"bg-primary/10 text-primary"),children:((c=(o=a.first_name)==null?void 0:o[0])==null?void 0:c.toUpperCase())||"?"}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"truncate font-medium text-foreground",children:[a.first_name,a.last_name?` ${a.last_name}`:""]}),i&&e.jsx("div",{className:"text-[11px] font-medium text-orange-600 dark:text-orange-400",children:"Buyer · no agent"})]})]})}),e.jsxs("td",{className:"hidden p-2.5 text-muted-foreground sm:table-cell",children:[a.email&&e.jsx("div",{className:"max-w-[200px] truncate",children:a.email}),a.phone&&e.jsx("div",{className:"text-xs",children:a.phone}),a.visitor_address?e.jsx("div",{className:"max-w-[200px] truncate text-xs",children:a.visitor_address}):null]}),e.jsx("td",{className:"hidden p-2.5 md:table-cell",children:a.visitor_intent?e.jsx("span",{className:Pt("inline-flex rounded-full border px-2 py-0.5 text-[11px] font-medium capitalize",l),children:a.visitor_intent}):a.partial_signin?e.jsx("span",{className:"inline-flex rounded-full border border-amber-500/20 bg-amber-500/10 px-2 py-0.5 text-[11px] font-medium text-amber-700 dark:text-amber-300",children:"Didn't finish"}):null}),e.jsx("td",{className:"p-2.5 text-xs text-muted-foreground",children:en(new Date(a.created_at),"h:mm a")})]},a.id)})})]})})]})}const kAe="guestbook.relevelup.com";function ahr(){const{data:s,isLoading:t}=cFs(),n=dFs(),r=W7t(),a=uFs(),[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}=bs(),y=Sa(),[v,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:en(new Date,"yyyy-MM-dd"),start_time:"10:00",end_time:"14:00",agent_greeting:"Welcome! Please sign in below.",event_type:"property",kind:"physical",tour_mode:"rooms"}),D=te=>{var ce;const J=(ce=te.target.files)==null?void 0:ce[0];if(J){if(J.size>5*1024*1024){_a({title:"Photo must be under 5MB",variant:"destructive"});return}b(J),S(URL.createObjectURL(J))}},O=()=>{b(null),S(null),I.current&&(I.current.value="")},U=async()=>{if(!P.property_address){_a({title:P.event_type==="community"?"Event name is required":"Address is required",variant:"destructive"});return}let te;if(v&&x){E(!0);const ce=v.name.split(".").pop(),_e=`${y}/${Date.now()}.${ce}`,{error:he}=await q.storage.from("open-house-photos").upload(_e,v,{upsert:!0});if(he){_a({title:"Photo upload failed",description:he.message,variant:"destructive"}),E(!1);return}const{data:ue}=q.storage.from("open-house-photos").getPublicUrl(_e);te=ue.publicUrl,E(!1)}const J=P.kind==="virtual"?{...P,start_time:void 0,end_time:void 0,photo_url:te}:{...P,photo_url:te};await n.mutateAsync(J),l(!1),R({property_address:"",city:"",state:"",zip:"",event_date:en(new Date,"yyyy-MM-dd"),start_time:"10:00",end_time:"14:00",agent_greeting:"Welcome! Please sign in below.",event_type:"property",kind:"physical",tour_mode:"rooms"}),O()},W=te=>{navigator.clipboard.writeText(`https://${kAe}/${te}`),_a({title:"Link copied!"})},V=en(new Date,"yyyy-MM-dd"),G=j.useMemo(()=>{const te=s??[],J=d.trim().toLowerCase(),ce=ke=>!J||[ke.property_address,ke.city,ke.state].filter(Boolean).join(" ").toLowerCase().includes(J),_e=te.filter(ce),he=_e.filter(ke=>ke.kind==="virtual"),ue=_e.filter(ke=>ke.kind!=="virtual"),ve=ue.filter(ke=>ke.event_date===V),Ee=ue.filter(ke=>ke.event_date>V).sort((ke,Be)=>ke.event_date.localeCompare(Be.event_date)),Se=ue.filter(ke=>ke.event_dateBe.event_date.localeCompare(ke.event_date)),Le=te.reduce((ke,Be)=>ke+(Be.visitor_count||0),0),Fe=te.reduce((ke,Be)=>ke+(Be.qr_scan_count||0),0);return{today:ve,upcoming:Ee,past:Se,virtual:he,totalSignIns:Le,totalScans:Fe}},[s,d,V]),Y=G.today.length+G.upcoming.length,X=Y>0?`${Y} upcoming · ${G.totalSignIns.toLocaleString()} total sign-ins`:`${G.totalSignIns.toLocaleString()} total sign-ins collected`,ae=te=>h==="all"||h===te,le=te=>m(J=>J===te?"all":te),ne=te=>e.jsx(ihr,{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(nhr,{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(zs,{open:i,onOpenChange:l,children:[e.jsx(jl,{asChild:!0,children:e.jsx("span",{className:"sr-only",children:"Open create dialog"})}),e.jsxs(Os,{className:"sm:max-w-lg max-h-[90vh] flex flex-col",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"Create Open House"}),e.jsx(Pr,{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(Ls,{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(pr,{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(Sv,{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(wUe,{title:"Happening Today",count:G.today.length,accent:!0}),e.jsx("div",{className:"space-y-4",children:G.today.map(ne)})]}),G.upcoming.length>0&&ae("upcoming")&&e.jsxs("section",{className:"space-y-3",children:[e.jsx(wUe,{title:"Upcoming",count:G.upcoming.length}),e.jsx("div",{className:"space-y-4",children:G.upcoming.map(ne)})]}),G.virtual.length>0&&ae("virtual")&&e.jsxs("section",{className:"space-y-3",children:[e.jsx(wUe,{title:"Virtual Tours",count:G.virtual.length}),e.jsx("div",{className:"space-y-4",children:G.virtual.map(ne)})]}),G.past.length>0&&h==="all"&&e.jsxs("section",{className:"space-y-3",children:[e.jsxs("button",{onClick:()=>g(te=>!te),className:"flex w-full items-center justify-between rounded-xl border border-border bg-card px-4 py-3 text-left transition-colors hover:bg-muted/40",children:[e.jsxs("span",{className:"flex items-center gap-2 text-sm font-semibold text-foreground",children:[e.jsx(Aw,{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(yb,{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(ne)})]}),Y===0&&G.virtual.length===0&&G.past.length===0&&e.jsx(je,{className:"border-dashed",children:e.jsxs(Ie,{className:"py-12 text-center text-sm text-muted-foreground",children:["No open houses match “",d,"”."]})})]}):e.jsx(je,{className:"border-dashed",children:e.jsxs(Ie,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx("div",{className:"w-16 h-16 rounded-2xl bg-primary/10 flex items-center justify-center mb-4",children:e.jsx(Jp,{className:"h-8 w-8 text-primary"})}),e.jsx("h3",{className:"text-lg font-semibold mb-1",children:"No Open Houses Yet"}),e.jsx("p",{className:"text-muted-foreground text-sm max-w-sm mb-6",children:"Create your first open house to get a beautiful, mobile-friendly sign-in page with a shareable link and QR code."}),e.jsxs($,{onClick:()=>l(!0),children:[e.jsx(dn,{className:"h-4 w-4 mr-2"}),"Create Your First Open House"]})]})})]})]})}function wUe({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 ihr({openHouse:s,isExpanded:t,onToggle:n,onCopyLink:r,onToggleActive:a,onDelete:i,isToday:l}){const{data:o}=G7t(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,y]=j.useState(!1),v=j.useRef(null),b=`https://${kAe}/${s.slug}`,w=P=>{if(!P)return"";const[R,D]=P.split(":"),O=parseInt(R),U=O>=12?"PM":"AM";return`${O>12?O-12:O||12}:${D} ${U}`},S=()=>{if(!(o!=null&&o.length))return;const P=["First Name","Last Name","Email","Phone","Address","Intent","Wants Market Updates","Message","Signed In"],R=o.map(V=>[V.first_name,V.last_name||"",V.email||"",V.phone||"",V.visitor_address||"",V.visitor_intent||"",V.wants_market_updates?"Yes":"No",(V.message||"").replace(/"/g,'""'),en(new Date(V.created_at),"MM/dd/yyyy h:mm a")]),D=[P,...R].map(V=>V.map(G=>`"${G}"`).join(",")).join(` `),O=new Blob([D],{type:"text/csv"}),U=URL.createObjectURL(O),W=document.createElement("a");W.href=U,W.download=`${s.property_address.replace(/[^a-zA-Z0-9]/g,"-")}-visitors.csv`,W.click(),URL.revokeObjectURL(U)},A=j.useCallback(()=>{if(!v.current)return;const P=v.current.querySelector("svg");if(!P)return;const R=new XMLSerializer().serializeToString(P),D=document.createElement("canvas");D.width=1024,D.height=1024;const O=D.getContext("2d"),U=new Image;U.onload=()=>{O==null||O.drawImage(U,0,0,1024,1024);const W=document.createElement("a");W.download=`${s.property_address.replace(/[^a-zA-Z0-9]/g,"-")}-qr.png`,W.href=D.toDataURL("image/png"),W.click()},U.src="data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent(R)))},[s.property_address]),E=j.useCallback(()=>{var Ae;if(!v.current)return;const P=v.current.querySelector("svg");if(!P)return;const R=new XMLSerializer().serializeToString(P),D="data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent(R))),O=en(new Date(s.event_date+"T00:00:00"),"EEEE, MMMM d, yyyy"),U=s.start_time?`${w(s.start_time)}${s.end_time?" – "+w(s.end_time):""}`:"",W=[s.city,s.state].filter(Boolean).join(", "),V=s.agent_greeting||"Welcome! Please sign in below.",G=!!s.photo_url,Y=!!c,X=G||Y,ae=G&&Y,le=ae?"0.35in 0.75in 0.3in":"0.55in 0.75in 0.45in",ne=ae?"28px":"34px",te=ae?"0.2in 0.75in":X?"0.3in 0.75in":"0.4in 0.75in",J=X?"0.15in":"0.3in",ce=X?"0.15in":"0.3in",_e=ae?"14px 36px":"22px 44px",he=ae?"20px":"24px",ue=X?"0.2in":"0.35in",ve=ae?"1.8in":"2.4in",Ee=X?"0.15in":"0.3in",Se=ae?"140px":X?"160px":"200px",Le=ae?"16px":"24px",Fe=ae?"10px 20px":"16px 28px",ke=ae?"44px":"56px",Be="0.15in",Ne=window.open("","_blank");Ne&&(Ne.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
`),Ne.document.close(),setTimeout(()=>{Ne.focus(),Ne.print()},500))},[s,b,c]),I=async()=>{y(!0);try{const{error:P}=await q.functions.invoke("guestbook-email-link",{body:{openHouseId:s.id}});if(P)throw P;_a({title:"Email sent!",description:"Check your inbox for the guest book link."})}catch(P){_a({title:"Failed to send",description:P.message,variant:"destructive"})}finally{y(!1)}};return e.jsxs(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(_b,{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(Ca,{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(ci,{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(ji,{className:"h-3 w-3"}),"Community"]})]})]}),e.jsx($,{variant:"ghost",size:"icon",onClick:n,className:"shrink-0 -mr-2 -mt-1",children:t?e.jsx(yb,{className:"h-4 w-4"}):e.jsx(wl,{className:"h-4 w-4"})})]}),e.jsxs(Gn,{className:"flex flex-wrap items-center gap-x-4 gap-y-1 text-xs",children:[s.city&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ci,{className:"h-3 w-3"}),s.city,s.state?`, ${s.state}`:""]}),s.kind==="virtual"?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(da,{className:"h-3 w-3"}),"Always on"]}):e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ta,{className:"h-3 w-3"}),en(new Date(s.event_date+"T00:00:00"),"MMM d, yyyy")]}),s.start_time&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(da,{className:"h-3 w-3"}),w(s.start_time),s.end_time?` – ${w(s.end_time)}`:""]})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-lg bg-muted/60 px-2.5 py-1 text-xs font-semibold text-foreground",children:[e.jsx(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(Jp,{className:"h-3.5 w-3.5 text-primary"}),s.qr_scan_count,e.jsx("span",{className:"font-normal text-muted-foreground",children:"scans"})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs($,{variant:"outline",size:"sm",onClick:()=>window.location.href=`/mission-control/guest-book/live/${s.id}`,className:"h-8 gap-1.5 text-xs text-emerald-600 border-emerald-500/30 hover:bg-emerald-500/10 dark:text-emerald-400",children:[e.jsx(_b,{className:"h-3.5 w-3.5"}),"Live"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:r,className:"h-8 gap-1.5 text-xs",children:[e.jsx(Ha,{className:"h-3.5 w-3.5"}),"Copy Link"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>u(!0),className:"h-8 gap-1.5 text-xs",children:[e.jsx(Jp,{className:"h-3.5 w-3.5"}),"QR Code"]}),s.kind==="virtual"?e.jsxs($,{variant:"outline",size:"sm",onClick:()=>g(!0),className:"h-8 gap-1.5 text-xs text-primary border-primary/30 hover:bg-primary/10",children:[e.jsx(Fd,{className:"h-3.5 w-3.5"}),"Email Tour"]}):e.jsxs(e.Fragment,{children:[e.jsxs($,{variant:"outline",size:"sm",onClick:()=>g(!0),className:"h-8 gap-1.5 text-xs text-primary border-primary/30 hover:bg-primary/10",children:[e.jsx(mn,{className:"h-3.5 w-3.5"}),"Invite"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>window.open(`${b}?kiosk=1`,"_blank"),className:"h-8 gap-1.5 text-xs",children:[e.jsx(aV,{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($u,{children:[e.jsx(Uu,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0","aria-label":"More actions",children:e.jsx(l_,{className:"h-4 w-4"})})}),e.jsxs(Au,{align:"end",className:"w-52",children:[e.jsxs(ja,{onClick:()=>window.open(b,"_blank"),children:[e.jsx(Fr,{className:"mr-2 h-4 w-4"}),"Preview sign-in page"]}),s.kind==="virtual"?e.jsxs(ja,{onClick:()=>window.open(`/guestbook/${s.slug}?preview=1`,"_blank"),children:[e.jsx(Ca,{className:"mr-2 h-4 w-4"}),"Preview tour"]}):e.jsxs(ja,{onClick:()=>window.open(`https://${kAe}/rsvp/${s.slug}`,"_blank"),children:[e.jsx(xb,{className:"mr-2 h-4 w-4"}),"Preview RSVP page"]}),e.jsxs(ja,{onClick:a,children:[s.is_active?e.jsx($g,{className:"mr-2 h-4 w-4"}):e.jsx(Ca,{className:"mr-2 h-4 w-4"}),s.is_active?"Deactivate":"Activate"]}),e.jsx(I0,{}),e.jsxs(ja,{onClick:i,className:"text-destructive focus:text-destructive",children:[e.jsx(Hn,{className:"mr-2 h-4 w-4"}),"Delete"]})]})]})]})]})}),t&&e.jsxs(Ie,{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://",kAe,"/",s.slug]})]}),e.jsx(rhr,{visitors:o??[],onExport:S}),s.kind!=="virtual"&&e.jsx("div",{className:"mt-4",children:e.jsx(shr,{openHouseId:s.id})}),s.kind==="virtual"&&e.jsx("div",{className:"mt-4",children:e.jsx(Jur,{openHouseId:s.id})}),s.enable_survey&&e.jsx("div",{className:"mt-4",children:e.jsx(Xur,{openHouseId:s.id})})]}),e.jsx(zs,{open:d,onOpenChange:u,children:e.jsxs(Os,{className:"sm:max-w-sm",children:[e.jsxs(Us,{children:[e.jsx(Bs,{children:"QR Code"}),e.jsx(Pr,{className:"truncate",children:s.property_address})]}),e.jsxs("div",{className:"flex flex-col items-center gap-4 py-4",children:[e.jsx("div",{ref:v,className:"bg-white p-4 rounded-xl",children:e.jsx(uk,{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(xi,{className:"h-4 w-4 mr-2"}),"Download"]}),e.jsxs($,{variant:"outline",className:"flex-1",onClick:E,children:[e.jsx(RE,{className:"h-4 w-4 mr-2"}),"Print Flyer"]})]}),e.jsxs($,{variant:"default",className:"w-full",onClick:I,disabled:x,children:[e.jsx(mn,{className:"h-4 w-4 mr-2"}),x?"Sending...":"Email Link to Me"]})]})]})}),e.jsx(Yur,{open:h,onOpenChange:m,openHouse:s}),e.jsx(thr,{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 ohr=z2({full_name:vl().trim().min(2,"Please enter your name").max(120),email:vl().trim().email("Please enter a valid email").max(200),brokerage:vl().trim().min(2,"Please enter your brokerage").max(160)}),XEt=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():"",lhr=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 chr(){var S;const{slug:s}=Wi(),[t,n]=j.useState(!0),[r,a]=j.useState(null),[i,l]=j.useState([]),[o,c]=j.useState(!1),[d,u]=j.useState({full_name:"",email:"",brokerage:""}),[h,m]=j.useState(""),[f,g]=j.useState(!1),[x,y]=j.useState(!1);j.useEffect(()=>{let 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 v=async A=>{A.preventDefault(),m("");const E=ohr.safeParse(d);if(!E.success){m(E.error.issues[0].message);return}g(!0);try{const{data:I,error:P}=await q.functions.invoke("resource-kit-unlock",{body:{slug:s,...E.data}});if(P)throw P;if(I!=null&&I.error)throw new Error("Something went wrong. Please try again.");l(I.files??[]),y(!0)}catch(I){m(I.message||"Something went wrong. Please try again.")}finally{g(!1)}};if(t)return e.jsx("div",{className:"min-h-screen bg-slate-950 p-6",children:e.jsxs("div",{className:"max-w-5xl mx-auto space-y-6 pt-16",children:[e.jsx(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=XEt(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(Nn,{className:"h-3.5 w-3.5"})," Instant download"]}),e.jsx("h1",{className:"mt-5 text-4xl md:text-5xl font-black tracking-tight leading-[1.05]",children:r.headline}),b&&e.jsx("p",{className:"mt-5 text-lg text-slate-300 leading-relaxed max-w-xl whitespace-pre-line",children:b}),r.hero_image_url&&e.jsx("div",{className:"mt-8 overflow-hidden rounded-2xl border border-white/10 shadow-2xl",children:e.jsx("img",{src:r.hero_image_url,alt:r.name,loading:"lazy",className:"w-full h-56 md:h-72 object-cover"})}),((S=r.benefits)==null?void 0:S.length)>0&&e.jsx("ul",{className:"mt-8 space-y-3",children:r.benefits.map((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:XEt(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(Jr,{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:lhr(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(xi,{className:"h-3.5 w-3.5 mr-1"})," Download"]})}):e.jsx(pc,{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(xi,{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:v,className:"mt-6 space-y-4",children:[e.jsxs("div",{children:[e.jsx(ee,{htmlFor:"full_name",className:"text-slate-200",children:"Agent name"}),e.jsx(pe,{id:"full_name",value:d.full_name,onChange: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."]})]})]})})})]})]})]})}Bot.workerSrc=$ot;const dhr={signature:_f,initials:oV,date_signed:Wc,printed_name:sl,text:iV},els={signature:"Signature",initials:"Initials",date_signed:"Date signed",printed_name:"Printed name",text:"Text"};function tls(){return new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"2-digit",day:"2-digit",year:"numeric"}).format(new Date)}function uhr(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 hhr(){var G,Y,X,ae;const{token:s}=Wi(),t=Xn(),[n,r]=j.useState(!0),[a,i]=j.useState(null),[l,o]=j.useState(null),[c,d]=j.useState(null),[u,h]=j.useState(null),m=j.useRef(null),f=j.useRef([]),[g,x]=j.useState({}),[y,v]=j.useState({}),[b,w]=j.useState(null),[S,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:ne,error:te}=await q.functions.invoke("forms-sign-public",{body:{action:"load",token:s}});if(!le){if(te||ne!=null&&ne.error)i((ne==null?void 0:ne.error)||"This signing link could not be loaded.");else if(ne.state==="already_signed")d("signed");else{o(ne);const ce={};for(const _e of ne.fields||[])_e.field_kind==="printed_name"&&(ce[_e.id]={value:((J=ne.signer)==null?void 0:J.full_name)||""}),_e.field_kind==="date_signed"&&(ce[_e.id]={value:tls()});x(ce)}r(!1)}})(),()=>{le=!0}},[s]),j.useEffect(()=>{let le=!1;const ne=m.current;if(!(!(l!=null&&l.pdf_url)||!ne))return(async()=>{try{const J=await(await fetch(l.pdf_url)).arrayBuffer(),ce=await yPe({data:J}).promise;if(le)return;ne.innerHTML="",f.current=[];const _e=Math.min(ne.clientWidth-16||700,820);for(let he=1;he<=ce.numPages;he++){const ue=await ce.getPage(he);if(le)return;const ve=ue.getViewport({scale:1}),Ee=_e/ve.width,Se=ue.getViewport({scale:Ee*(window.devicePixelRatio||1)}),Le=document.createElement("div");Le.className="relative mx-auto shadow",Le.style.width=`${_e}px`,Le.style.height=`${ve.height*Ee}px`;const Fe=document.createElement("canvas");Fe.width=Math.floor(Se.width),Fe.height=Math.floor(Se.height),Fe.style.width="100%",Fe.style.height="100%",Fe.className="rounded-md border border-border bg-white",Le.appendChild(Fe),ne.appendChild(Le),f.current[he-1]=Le;const ke=Fe.getContext("2d");ke&&await ue.render({canvasContext:ke,viewport:Se}).promise}le||x(he=>({...he}))}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 ne,te;return le.is_required&&!((ne=g[le.id])!=null&&ne.value)&&!((te=g[le.id])!=null&&te.png)}),U=async()=>{if(!S){re.error("Please agree to sign electronically first.");return}if(O.length){re.error("Please complete every highlighted field.");return}I(!0);try{const{data:le,error:ne}=await q.functions.invoke("forms-sign-public",{body:{action:"submit",token:s,consent:!0,fields:D.filter(te=>g[te.id]).map(te=>{var J,ce;return{mapping_id:te.id,value:(J=g[te.id])==null?void 0:J.value,signature_png:(ce=g[te.id])==null?void 0:ce.png}})}});if(ne||le!=null&&le.error)throw new Error((le==null?void 0:le.error)||(ne==null?void 0:ne.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){re.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,ne)=>{x(te=>({...te,[le.id]:ne})),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(che,{icon:e.jsx(Nu,{className:"h-8 w-8 text-destructive"}),title:"Link unavailable",body:a}):c==="declined"?e.jsx(che,{icon:e.jsx(Nu,{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(che,{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(che,{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 ",(Y=l==null?void 0:l.signer)==null?void 0:Y.full_name]})]})}),((X=l==null?void 0:l.envelope)==null?void 0:X.message)&&e.jsx("div",{className:"mx-auto mt-4 max-w-3xl rounded-lg border bg-white px-4 py-3 text-sm text-slate-600 shadow-sm",children:l.envelope.message}),e.jsxs("div",{className:"mx-auto mt-4 max-w-3xl space-y-4 px-2",children:[e.jsx("div",{ref:m,className:"space-y-4"}),D.map(le=>{const ne=f.current[le.page_index];if(!ne)return null;const te=g[le.id],J=!!(te!=null&&te.png||te!=null&&te.value),ce=dhr[le.field_kind];return e.jsx(QEt,{target:ne,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||els[le.field_kind]]})})},le.id)}),((l==null?void 0:l.data_overlays)||[]).map(le=>{const ne=f.current[le.page_index];return!ne||!le.value?null:e.jsx(QEt,{target:ne,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(mhr,{field:b,signerName:((ae=l==null?void 0:l.signer)==null?void 0:ae.full_name)||"",current:b?g[b.id]:void 0,adopted:y,onAdopt:(le,ne)=>{v(te=>({...te,[le]:ne})),x(te=>{var ce;const J={...te};for(const _e of D)_e.field_kind===le&&!((ce=J[_e.id])!=null&&ce.png)&&(J[_e.id]={png:ne});return J})},onClose:()=>w(null),onApply:V})]})}function che({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 QEt({target:s,children:t}){return vv.createPortal(t,s)}function mhr({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"?tls():"")),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)},y=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()},v=()=>{m.current=!1},b=(w,S)=>{s&&(S&&o&&a(c,w),l(s,{png:w}))};return e.jsx(Gy,{open:!!s,onOpenChange:w=>!w&&i(),children:e.jsxs(my,{side:"bottom",className:"mx-auto max-w-lg rounded-t-2xl",children:[e.jsx(L0,{className:"text-left",children:e.jsx(R0,{className:"text-base",children:(s==null?void 0:s.label)||(s?els[s.field_kind]:"")})}),s&&o&&e.jsxs(ha,{defaultValue:r[c]?"saved":"draw",className:"mt-3",children:[e.jsxs(ma,{className:"grid w-full grid-cols-3",children:[e.jsx(Zt,{value:"draw",children:"Draw"}),e.jsx(Zt,{value:"type",children:"Type"}),e.jsx(Zt,{value:"saved",disabled:!r[c],children:"Saved"})]}),e.jsxs(Xt,{value:"draw",className:"space-y-3 pt-3",children:[e.jsx("canvas",{ref:h,width:640,height:220,className:"h-40 w-full touch-none rounded-lg border bg-white",onPointerDown:x,onPointerMove:y,onPointerUp:v}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{variant:"outline",size:"sm",onClick:()=>{var S;const w=h.current;(S=w==null?void 0:w.getContext("2d"))==null||S.clearRect(0,0,w.width,w.height)},children:[e.jsx(Tq,{className:"mr-1 h-3.5 w-3.5"})," Clear"]}),e.jsxs($,{size:"sm",className:"flex-1 bg-[#406E71] hover:bg-[#355c5f]",onClick:()=>{const w=h.current;w&&b(w.toDataURL("image/png"),!0)},children:["Use this ",s.field_kind==="initials"?"initials":"signature"," everywhere"]})]})]}),e.jsxs(Xt,{value:"type",className:"space-y-3 pt-3",children:[e.jsx(pe,{value:d,onChange:w=>u(w.target.value),placeholder:"Type your name"}),d.trim()&&e.jsx("div",{className:"flex h-24 items-center justify-center rounded-lg border bg-white",children:e.jsx("span",{className:"text-3xl text-[#12233f]",style:{fontFamily:'"Segoe Script","Brush Script MT",cursive'},children:d})}),e.jsx($,{size:"sm",className:"w-full bg-[#406E71] hover:bg-[#355c5f]",disabled:!d.trim(),onClick:()=>b(uhr(d.trim(),s.field_kind==="signature"),!0),children:"Use this everywhere"})]}),e.jsx(Xt,{value:"saved",className:"space-y-3 pt-3",children:r[c]&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex h-24 items-center justify-center rounded-lg border bg-white p-2",children:e.jsx("img",{src:r[c],alt:"Saved signature",className:"max-h-full object-contain"})}),e.jsxs($,{size:"sm",className:"w-full bg-[#406E71] hover:bg-[#355c5f]",onClick:()=>b(r[c],!1),children:["Use saved ",s.field_kind==="initials"?"initials":"signature"]})]})})]}),s&&!o&&e.jsxs("div",{className:"mt-3 space-y-3",children:[e.jsx(pe,{value:f,onChange:w=>g(w.target.value),autoFocus:!0}),e.jsx($,{size:"sm",className:"w-full bg-[#406E71] hover:bg-[#355c5f]",disabled:!f.trim(),onClick:()=>l(s,{value:f.trim()}),children:"Apply"})]})]})})}const JEt="https://dashboard.relevelup.com/trial",fhr=["Full LevelUp Agent OS access","300+ marketing templates & AI tools","Cancel anytime — no risk"];function lQe({variant:s="full",className:t=""}){return s==="compact"?e.jsxs("div",{className:`rounded-2xl border border-amber-400/20 bg-gradient-to-br from-amber-500/10 to-transparent p-5 ${t}`,children:[e.jsxs("div",{className:"inline-flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-widest text-amber-300",children:[e.jsx(Nn,{className:"h-3.5 w-3.5"})," Free trial"]}),e.jsx("h3",{className:"mt-3 text-lg font-bold text-white leading-snug",children:"Try LevelUp free"}),e.jsx("p",{className:"mt-2 text-sm text-slate-300 leading-relaxed",children:"Everything you just read — plus the tools to actually run it. Start your free trial today."}),e.jsxs("a",{href:JEt,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(Nn,{className:"h-3.5 w-3.5"})," Free trial · no credit card hassle"]}),e.jsx("h2",{className:"mt-5 text-3xl md:text-4xl font-black tracking-tight text-white leading-[1.1]",children:"Ready to put this into action?"}),e.jsx("p",{className:"mt-4 max-w-xl text-slate-300 leading-relaxed",children:"LevelUp gives real estate agents the marketing, CRM, and AI tools to win more listings — all in one place. Take it for a spin free."}),e.jsx("ul",{className:"mt-6 grid gap-2 sm:grid-cols-3",children:fhr.map(n=>e.jsxs("li",{className:"flex items-start gap-2 text-sm text-slate-200",children:[e.jsx(ca,{className:"mt-0.5 h-4 w-4 shrink-0 text-amber-400"}),e.jsx("span",{children:n})]},n))}),e.jsxs("a",{href:JEt,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 eTt=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)))},phr=s=>{const t=s.replace(/<[^>]*>/g," ").split(/\s+/).filter(Boolean).length;return Math.max(1,Math.round(t/220))};function ghr(){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(wr,{to:"/",className:"flex items-center gap-2 text-sm font-bold tracking-tight",children:[e.jsxs("span",{className:"text-white",children:["Level",e.jsx("span",{className:"text-amber-400",children:"Up"})]}),e.jsx("span",{className:"font-medium text-slate-500",children:"· Blog"})]}),e.jsxs("header",{className:"mt-10 max-w-3xl",children:[e.jsxs("h1",{className:"text-4xl font-black leading-[1.05] tracking-tight md:text-6xl",children:["Ideas that move your ",e.jsx("span",{className:"text-amber-400",children:"real estate business"})," forward."]}),e.jsx("p",{className:"mt-5 text-lg leading-relaxed text-slate-300",children:"Strategies, systems, and honest lessons from the founder of LevelUp — written for agents who want to grow on purpose."})]}),l.length>2&&e.jsx("div",{className:"mt-8 flex flex-wrap gap-2",children:l.map(u=>e.jsx("button",{onClick:()=>i(u),className:`rounded-full border px-4 py-1.5 text-sm font-medium transition ${a===u?"border-amber-400/40 bg-amber-400/15 text-amber-200":"border-white/10 bg-white/5 text-slate-300 hover:bg-white/10"}`,children:u==="all"?"All articles":u},u))}),n?e.jsx("div",{className:"mt-12 grid gap-6 md:grid-cols-3",children:[0,1,2].map(u=>e.jsx(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(wr,{to:`/blog/${c.slug}`,className:"group mt-12 grid gap-8 overflow-hidden rounded-3xl border border-white/10 bg-white/5 p-6 transition hover:border-amber-400/30 md:grid-cols-2 md:p-8",children:[c.cover_image_url&&e.jsx("div",{className:"overflow-hidden rounded-2xl",children:e.jsx("img",{src:c.cover_image_url,alt:c.title,className:"h-56 w-full object-cover transition duration-500 group-hover:scale-105 md:h-72"})}),e.jsxs("div",{className:"flex flex-col justify-center",children:[e.jsxs("div",{className:"flex items-center gap-3 text-xs text-slate-400",children:[c.category&&e.jsx($e,{className:"border-amber-400/30 bg-amber-400/15 text-amber-200",children:c.category}),e.jsx("span",{children:eTt(c.published_at)}),e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(da,{className:"h-3 w-3"})," ",phr(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(wr,{to:`/blog/${u.slug}`,className:"group flex flex-col overflow-hidden rounded-2xl border border-white/10 bg-white/5 transition hover:border-amber-400/30",children:[u.cover_image_url?e.jsx("img",{src:u.cover_image_url,alt:u.title,loading:"lazy",className:"h-44 w-full object-cover transition duration-500 group-hover:scale-105"}):e.jsx("div",{className:"h-44 w-full bg-gradient-to-br from-amber-500/20 to-slate-900"}),e.jsxs("div",{className:"flex flex-1 flex-col p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-slate-400",children:[u.category&&e.jsx("span",{className:"text-amber-300",children:u.category}),e.jsx("span",{children:eTt(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(lQe,{className:"mt-16"}),e.jsxs("footer",{className:"mt-14 border-t border-white/10 pt-8 text-sm text-slate-500",children:["© ",new Date().getFullYear()," LevelUp · ",e.jsx(wr,{to:"/",className:"hover:text-slate-300",children:"Home"})]})]})]})}const xhr=s=>(s||"LevelUp Member").split(" ").map(t=>t[0]).slice(0,2).join("").toUpperCase(),yhr=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 vhr({postId:s,allowComments:t}){const{user:n}=bs(),[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 y=async(A,E)=>{if(!n){re.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){re.error(I.message);return}c(""),m(""),u(null),re.success("Comment posted"),x()},v=async A=>{const{error:E}=await q.from("blog_comments").delete().eq("id",A);if(E){re.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:xhr((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:yhr(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(xJ,{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:()=>v(A.id),children:[e.jsx(Hn,{className:"h-3 w-3"})," Delete"]})]}),d===A.id&&e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx(Ls,{value:h,onChange:D=>m(D.target.value),placeholder:"Write a reply…",className:"border-white/10 bg-white/5 text-white placeholder:text-slate-500"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{size:"sm",disabled:f,onClick:()=>y(h,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(Ls,{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:()=>y(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(wr,{to:"/auth",className:"font-semibold text-amber-300 hover:underline",children:"Sign in"})," ","to join the conversation — comments are open to all LevelUp members."]}):e.jsx("p",{className:"mt-4 text-sm text-slate-400",children:"Comments are closed on this article."}),i?e.jsxs("div",{className:"mt-8 flex items-center gap-2 text-sm text-slate-400",children:[e.jsx(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 tTt=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)))},bhr=s=>Math.max(1,Math.round(s.replace(/<[^>]*>/g," ").split(/\s+/).filter(Boolean).length/220));function _hr(){var h;const{slug:s=""}=Wi(),[t,n]=j.useState(null),[r,a]=j.useState([]),[i,l]=j.useState(!0);j.useEffect(()=>{(async()=>{l(!0);const{data:m}=await q.from("blog_posts").select("*").eq("slug",s).eq("status","published").maybeSingle();if(n(m||null),l(!1),m){q.rpc("increment_blog_post_views",{_slug:s});const{data:f}=await q.from("blog_posts").select("id, slug, title, excerpt, cover_image_url, category, published_at, content").eq("status","published").neq("slug",s).order("published_at",{ascending:!1}).limit(3);a(f||[])}})()},[s]);const o=typeof window<"u"?`${window.location.origin}/blog/${s}`:"",c=async m=>{const f=encodeURIComponent((t==null?void 0:t.title)||"LevelUp"),g=encodeURIComponent(o),x={facebook:`https://www.facebook.com/sharer/sharer.php?u=${g}`,linkedin:`https://www.linkedin.com/sharing/share-offsite/?url=${g}`,twitter:`https://twitter.com/intent/tweet?url=${g}&text=${f}`,email:`mailto:?subject=${f}&body=${g}`};if(m==="copy"){await navigator.clipboard.writeText(o),re.success("Link copied");return}if(m==="native"&&navigator.share){try{await navigator.share({title:t==null?void 0:t.title,url:o})}catch{}return}window.open(x[m],"_blank","noopener,width=640,height=560")};if(i)return e.jsx("div",{className:"min-h-screen bg-slate-950 p-6",children:e.jsxs("div",{className:"mx-auto max-w-3xl space-y-6 pt-16",children:[e.jsx(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(wr,{to:"/blog",className:"mt-5 inline-block font-semibold text-amber-300 hover:underline",children:"Back to the blog"})]})});const d=(t.seo_title||t.title).slice(0,60),u=(t.seo_description||t.excerpt||t.title).slice(0,155);return e.jsxs("div",{className:"min-h-screen bg-slate-950 text-white",children:[e.jsxs(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(wr,{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:tTt(t.published_at)}),e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(da,{className:"h-3 w-3"})," ",bhr(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(Wd,{className:"h-4 w-4"})}),e.jsx("button",{onClick:()=>c("facebook"),title:"Share on Facebook",className:"rounded-lg p-2 text-slate-400 hover:bg-white/10 hover:text-white",children:e.jsx(Qp,{className:"h-4 w-4"})}),e.jsx("button",{onClick:()=>c("linkedin"),title:"Share on LinkedIn",className:"rounded-lg p-2 text-slate-400 hover:bg-white/10 hover:text-white",children:e.jsx(dy,{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(nee,{className:"h-4 w-4"})}),e.jsx("button",{onClick:()=>c("email"),title:"Share by email",className:"rounded-lg p-2 text-slate-400 hover:bg-white/10 hover:text-white",children:e.jsx(mn,{className:"h-4 w-4"})}),e.jsx("button",{onClick:()=>c("native"),title:"Share",className:"rounded-lg p-2 text-slate-400 hover:bg-white/10 hover:text-white md:hidden",children:e.jsx(Fd,{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(lQe,{className:"mt-14"}),e.jsx(vhr,{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(lQe,{variant:"compact"}),r.length>0&&e.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/5 p-5",children:[e.jsx("div",{className:"text-xs font-semibold uppercase tracking-widest text-slate-400",children:"Keep reading"}),e.jsx("div",{className:"mt-4 space-y-4",children:r.map(m=>e.jsxs(wr,{to:`/blog/${m.slug}`,className:"group block",children:[e.jsx("div",{className:"text-sm font-semibold leading-snug text-slate-100 group-hover:text-amber-300",children:m.title}),e.jsx("div",{className:"mt-1 text-xs text-slate-500",children:tTt(m.published_at)})]},m.id))})]})]})]}),e.jsxs("footer",{className:"mt-16 border-t border-white/10 pt-8 text-sm text-slate-500",children:["© ",new Date().getFullYear()," LevelUp · ",e.jsx(wr,{to:"/blog",className:"hover:text-slate-300",children:"Blog"})]})]})]})}const whr=/^((?:https?:)?\/\/)?((?:www|m|music)\.)?((?:youtube\.com|youtu\.be|youtube-nocookie\.com))(\/(?:[\w-]+\?v=|embed\/|v\/)?)([\w-]+)(\S+)?$/,jhr=/^((?:https?:)?\/\/)?((?:www|m|music)\.)?((?:youtube\.com|youtu\.be|youtube-nocookie\.com))(\/(?:[\w-]+\?v=|embed\/|v\/)?)([\w-]+)(\S+)?$/g,sls=s=>s.match(whr),Nhr=(s,t)=>t?"https://www.youtube-nocookie.com/embed/videoseries?list=":s?"https://www.youtube-nocookie.com/embed/":"https://www.youtube.com/embed/",khr=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,Shr=s=>{var t;const{url:n,allowFullscreen:r,autoplay:a,ccLanguage:i,ccLoadPolicy:l,controls:o,disableKBcontrols:c,enableIFrameApi:d,endTime:u,interfaceLanguage:h,ivLoadPolicy:m,loop:f,modestBranding:g,nocookie:x,origin:y,playlist:v,progressBarColor:b,startAt:w,rel:S}=s;if(!sls(n))return null;if(n.includes("/embed/"))return n;const A=new URL(n),{id:E,isPlaylist:I}=(t=khr(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"),y&&P.searchParams.set("origin",y),v&&P.searchParams.set("playlist",v),w&&P.searchParams.set("start",w.toString()),b&&P.searchParams.set("color",b),S!==void 0&&P.searchParams.set("rel",S.toString()),P.toString()},Chr=Iv.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})=>sls(s.src)?t.insertContent({type:this.name,attrs:s}):!1}},addPasteRules(){return this.options.addPasteHandler?[cJs({find:jhr,type:this.type,getAttributes:s=>({src:s.input})})]:[]},renderHTML({HTMLAttributes:s}){const t=Shr({url:s.src,allowFullscreen:this.options.allowFullscreen,autoplay:this.options.autoplay,ccLanguage:this.options.ccLanguage,ccLoadPolicy:this.options.ccLoadPolicy,controls:this.options.controls,disableKBcontrols:this.options.disableKBcontrols,enableIFrameApi:this.options.enableIFrameApi,endTime:this.options.endTime,interfaceLanguage:this.options.interfaceLanguage,ivLoadPolicy:this.options.ivLoadPolicy,loop:this.options.loop,modestBranding:this.options.modestBranding,nocookie:this.options.nocookie,origin:this.options.origin,playlist:this.options.playlist,progressBarColor:this.options.progressBarColor,startAt:s.start||0,rel:this.options.rel});return s.src=t,["div",{"data-youtube-video":""},["iframe",ep(this.options.HTMLAttributes,{width:this.options.width,height:this.options.height,allowfullscreen:this.options.allowFullscreen,autoplay:this.options.autoplay,ccLanguage:this.options.ccLanguage,ccLoadPolicy:this.options.ccLoadPolicy,disableKBcontrols:this.options.disableKBcontrols,enableIFrameApi:this.options.enableIFrameApi,endTime:this.options.endTime,interfaceLanguage:this.options.interfaceLanguage,ivLoadPolicy:this.options.ivLoadPolicy,loop:this.options.loop,modestBranding:this.options.modestBranding,origin:this.options.origin,playlist:this.options.playlist,progressBarColor:this.options.progressBarColor,rel:this.options.rel},s)]]}}),Ahr=Iv.create({name:"videoEmbed",group:"block",atom:!0,draggable:!0,addAttributes(){return{src:{default:null},poster:{default:null}}},parseHTML(){return[{tag:"video[src]"}]},renderHTML({HTMLAttributes:s}){return["video",ep(s,{controls:"true",playsinline:"true",preload:"metadata",class:"w-full rounded-xl"})]}}),n0=({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 Ehr({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=$6e({extensions:[U6e.configure({heading:{levels:[2,3,4]}}),Eos,V6e.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline"}}),iHt.configure({HTMLAttributes:{class:"rounded-xl w-full"}}),H6e.configure({types:["heading","paragraph"]}),Chr.configure({width:960,height:540,HTMLAttributes:{class:"w-full aspect-video rounded-xl"}}),Ahr],content:s||"",editorProps:{attributes:{class:"prose prose-slate dark:prose-invert max-w-none min-h-[420px] focus:outline-none px-4 py-4"}},onUpdate:({editor:w})=>t(w.getHTML())});j.useEffect(()=>{x&&s!==x.getHTML()&&x.commands.setContent(s||"",!1)},[s]);const y=j.useCallback(async(w,S)=>{var D;const{data:A}=await q.auth.getUser(),E=(D=A.user)==null?void 0:D.id;if(!E)return re.error("You must be signed in"),null;const I=w.name.split(".").pop()||(S==="image"?"jpg":"mp4"),P=`${E}/blog/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${I}`,{error:R}=await q.storage.from("email-assets").upload(P,w,{cacheControl:"31536000",upsert:!1});return R?(re.error(`Upload failed: ${R.message}`),null):q.storage.from("email-assets").getPublicUrl(P).data.publicUrl},[]),v=async(w,S)=>{if(!w||!x)return;m(!0);const A=await y(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(n0,{title:"Bold",active:b.isActive("bold"),onClick:()=>b.chain().focus().toggleBold().run(),children:e.jsx(SE,{className:"h-4 w-4"})}),e.jsx(n0,{title:"Italic",active:b.isActive("italic"),onClick:()=>b.chain().focus().toggleItalic().run(),children:e.jsx(EE,{className:"h-4 w-4"})}),e.jsx(n0,{title:"Underline",active:b.isActive("underline"),onClick:()=>b.chain().focus().toggleUnderline().run(),children:e.jsx(s7,{className:"h-4 w-4"})}),e.jsx("div",{className:"mx-1 h-5 w-px bg-border"}),e.jsx(n0,{title:"Heading",active:b.isActive("heading",{level:2}),onClick:()=>b.chain().focus().toggleHeading({level:2}).run(),children:e.jsx($z,{className:"h-4 w-4"})}),e.jsx(n0,{title:"Subheading",active:b.isActive("heading",{level:3}),onClick:()=>b.chain().focus().toggleHeading({level:3}).run(),children:e.jsx(Dq,{className:"h-4 w-4"})}),e.jsx(n0,{title:"Bullet list",active:b.isActive("bulletList"),onClick:()=>b.chain().focus().toggleBulletList().run(),children:e.jsx(T0,{className:"h-4 w-4"})}),e.jsx(n0,{title:"Numbered list",active:b.isActive("orderedList"),onClick:()=>b.chain().focus().toggleOrderedList().run(),children:e.jsx(u2,{className:"h-4 w-4"})}),e.jsx(n0,{title:"Quote",active:b.isActive("blockquote"),onClick:()=>b.chain().focus().toggleBlockquote().run(),children:e.jsx(h2,{className:"h-4 w-4"})}),e.jsx(n0,{title:"Code block",active:b.isActive("codeBlock"),onClick:()=>b.chain().focus().toggleCodeBlock().run(),children:e.jsx(CE,{className:"h-4 w-4"})}),e.jsx("div",{className:"mx-1 h-5 w-px bg-border"}),e.jsx(n0,{title:"Align left",active:b.isActive({textAlign:"left"}),onClick:()=>b.chain().focus().setTextAlign("left").run(),children:e.jsx(FI,{className:"h-4 w-4"})}),e.jsx(n0,{title:"Align center",active:b.isActive({textAlign:"center"}),onClick:()=>b.chain().focus().setTextAlign("center").run(),children:e.jsx(DI,{className:"h-4 w-4"})}),e.jsx(n0,{title:"Align right",active:b.isActive({textAlign:"right"}),onClick:()=>b.chain().focus().setTextAlign("right").run(),children:e.jsx(OI,{className:"h-4 w-4"})}),e.jsx("div",{className:"mx-1 h-5 w-px bg-border"}),e.jsx(n0,{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(n0,{title:"Insert image",disabled:h,onClick:()=>{var w;return(w=f.current)==null?void 0:w.click()},children:e.jsx(Sv,{className:"h-4 w-4"})}),e.jsx(n0,{title:"Upload video",disabled:h,onClick:()=>{var w;return(w=g.current)==null?void 0:w.click()},children:e.jsx(ua,{className:"h-4 w-4"})}),e.jsx(n0,{title:"Embed YouTube / Vimeo",onClick:()=>{u(""),c(!0)},children:e.jsx(mV,{className:"h-4 w-4"})}),e.jsx(n0,{title:"Divider",onClick:()=>b.chain().focus().setHorizontalRule().run(),children:e.jsx(ZN,{className:"h-4 w-4"})}),e.jsx("div",{className:"mx-1 h-5 w-px bg-border"}),e.jsx(n0,{title:"Undo",onClick:()=>b.chain().focus().undo().run(),children:e.jsx(OE,{className:"h-4 w-4"})}),e.jsx(n0,{title:"Redo",onClick:()=>b.chain().focus().redo().run(),children:e.jsx(DE,{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(B6e,{editor:x,"data-placeholder":n}),e.jsx("input",{ref:f,type:"file",accept:"image/*",className:"hidden",onChange:w=>{var S;v((S=w.target.files)==null?void 0:S[0],"image"),w.target.value=""}}),e.jsx("input",{ref:g,type:"file",accept:"video/*",className:"hidden",onChange:w=>{var S;v((S=w.target.files)==null?void 0:S[0],"video"),w.target.value=""}}),e.jsx(zs,{open:r,onOpenChange:a,children:e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Insert link"})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"URL"}),e.jsx(pe,{value:i,onChange:w=>l(w.target.value),placeholder:"https://…"})]}),e.jsxs(Sr,{children:[e.jsx($,{variant:"outline",onClick:()=>{b.chain().focus().unsetLink().run(),a(!1)},children:"Remove link"}),e.jsx($,{onClick:()=>{i.trim()&&b.chain().focus().extendMarkRange("link").setLink({href:i.trim(),target:"_blank"}).run(),a(!1)},children:"Apply"})]})]})}),e.jsx(zs,{open:o,onOpenChange:c,children:e.jsxs(Os,{children:[e.jsx(Us,{children:e.jsx(Bs,{children:"Embed a video"})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ee,{children:"YouTube or Vimeo URL"}),e.jsx(pe,{value:d,onChange:w=>u(w.target.value),placeholder:"https://youtube.com/watch?v=…"})]}),e.jsx(Sr,{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 dhe=s=>s.toLowerCase().trim().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").slice(0,80),Thr=()=>({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 Mhr(){const{user:s}=bs(),[t,n]=j.useState([]),[r,a]=j.useState(!0),[i,l]=j.useState(null),[o,c]=j.useState(!1),[d,u]=j.useState(""),[h,m]=j.useState(""),[f,g]=j.useState(!1),x=j.useRef(null),[y,v]=j.useState([]),b=async()=>{a(!0);const{data:O,error:U}=await q.from("blog_posts").select("*").order("created_at",{ascending:!1});U&&re.error(U.message),n(O||[]),a(!1)},w=async()=>{const{data:O}=await q.from("blog_comments").select("id, body, created_at, is_hidden, user_id, post_id").order("created_at",{ascending:!1}).limit(200),U=O||[],W=[...new Set(U.map(le=>le.user_id))],V=[...new Set(U.map(le=>le.post_id))],[{data:G},{data:Y}]=await Promise.all([W.length?q.from("profiles").select("id, name, email").in("id",W):Promise.resolve({data:[]}),V.length?q.from("blog_posts").select("id, title, slug").in("id",V):Promise.resolve({data:[]})]),X=new Map((G||[]).map(le=>[le.id,le])),ae=new Map((Y||[]).map(le=>[le.id,le]));v(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){re.error(V.message);return}const G=q.storage.from("email-assets").getPublicUrl(W).data.publicUrl;l(Y=>({...Y||{},cover_image_url:G}))},E=async O=>{if(!i)return;const U=(i.title||"").trim();if(!U){re.error("Give the article a title");return}const W=dhe(i.slug||U),V=O===void 0?i.status||"draft":O?"published":"draft";c(!0);const G={title:U,slug:W,excerpt:i.excerpt||null,content:i.content||"",cover_image_url:i.cover_image_url||null,category:i.category||null,tags:i.tags||[],author_name:i.author_name||"Jeremy Collins",author_title:i.author_title||"Founder, LevelUp",author_avatar_url:i.author_avatar_url||null,status:V,featured:!!i.featured,allow_comments:i.allow_comments!==!1,seo_title:i.seo_title||null,seo_description:i.seo_description||null,published_at:V==="published"?i.published_at||new Date().toISOString():i.published_at||null};let Y;if(i.id)({error:Y}=await q.from("blog_posts").update(G).eq("id",i.id));else{G.created_by=(s==null?void 0:s.id)||null;const X=await q.from("blog_posts").insert(G).select().single();Y=X.error,X.data&&l(X.data)}if(c(!1),Y){re.error(Y.message);return}re.success(V==="published"?"Published":"Saved"),b()},I=async O=>{if(!confirm("Delete this article and its comments?"))return;const{error:U}=await q.from("blog_posts").delete().eq("id",O);if(U){re.error(U.message);return}re.success("Deleted"),(i==null?void 0:i.id)===O&&l(null),b()},P=async O=>{const U=O.status==="published"?"draft":"published",{error:W}=await q.from("blog_posts").update({status:U,published_at:U==="published"?O.published_at||new Date().toISOString():O.published_at}).eq("id",O.id);if(W){re.error(W.message);return}b()},R=async O=>{const{error:U}=await q.from("blog_comments").update({is_hidden:!O.is_hidden}).eq("id",O.id);if(U){re.error(U.message);return}w()},D=async O=>{const{error:U}=await q.from("blog_comments").delete().eq("id",O);if(U){re.error(U.message);return}w()};return i?e.jsxs("div",{className:"container mx-auto max-w-6xl space-y-6 p-4 md:p-6",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs($,{variant:"ghost",onClick:()=>l(null),children:[e.jsx(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(Fr,{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(Ls,{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(Ehr,{content:i.content||"",onChange:O=>l(U=>({...U||{},content:O}))})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(je,{children:e.jsxs(Ie,{className:"space-y-4 pt-6",children:[e.jsxs("div",{children:[e.jsx(ee,{children:"Cover image"}),i.cover_image_url?e.jsxs("div",{className:"mt-2 space-y-2",children:[e.jsx("img",{src:i.cover_image_url,alt:"cover",className:"h-36 w-full rounded-lg object-cover"}),e.jsx($,{variant:"outline",size:"sm",className:"w-full",onClick:()=>l({...i,cover_image_url:null}),children:"Remove"})]}):e.jsxs($,{variant:"outline",className:"mt-2 w-full",disabled:f,onClick:()=>{var O;return(O=x.current)==null?void 0:O.click()},children:[f?e.jsx(Ct,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Sv,{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:dhe(O.target.value||i.title||"")}),placeholder:dhe(i.title||"")||"my-article"}),e.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["/blog/",i.slug||dhe(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(Sn,{id:"featured",checked:!!i.featured,onCheckedChange:O=>l({...i,featured:O})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ee,{htmlFor:"comments",children:"Allow comments"}),e.jsx(Sn,{id:"comments",checked:i.allow_comments!==!1,onCheckedChange:O=>l({...i,allow_comments:O})})]})]})}),e.jsx(je,{children:e.jsxs(Ie,{className:"space-y-4 pt-6",children:[e.jsx("div",{className:"text-sm font-semibold",children:"Author"}),e.jsx(pe,{value:i.author_name||"",placeholder:"Author name",onChange:O=>l({...i,author_name:O.target.value})}),e.jsx(pe,{value:i.author_title||"",placeholder:"Author title",onChange:O=>l({...i,author_title:O.target.value})}),e.jsx(pe,{value:i.author_avatar_url||"",placeholder:"Author photo URL (optional)",onChange:O=>l({...i,author_avatar_url:O.target.value})})]})}),e.jsx(je,{children:e.jsxs(Ie,{className:"space-y-4 pt-6",children:[e.jsx("div",{className:"text-sm font-semibold",children:"SEO"}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"SEO title"}),e.jsx(pe,{className:"mt-1",maxLength:60,value:i.seo_title||"",onChange:O=>l({...i,seo_title:O.target.value})})]}),e.jsxs("div",{children:[e.jsx(ee,{className:"text-xs",children:"Meta description"}),e.jsx(Ls,{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(Thr()),children:[e.jsx(dn,{className:"mr-2 h-4 w-4"})," New article"]})]}),e.jsxs(ha,{defaultValue:"articles",children:[e.jsxs(ma,{children:[e.jsxs(Zt,{value:"articles",children:["Articles (",t.length,")"]}),e.jsxs(Zt,{value:"comments",children:["Comments (",y.length,")"]})]}),e.jsxs(Xt,{value:"articles",className:"mt-4 space-y-3",children:[e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(Zr,{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(Ie,{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(Ie,{className:"flex flex-wrap items-center gap-4 py-4",children:[O.cover_image_url?e.jsx("img",{src:O.cover_image_url,alt:"",className:"h-14 w-20 rounded-md object-cover"}):e.jsx("div",{className:"h-14 w-20 rounded-md bg-muted"}),e.jsxs("button",{className:"min-w-0 flex-1 text-left",onClick:()=>l(O),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"truncate font-semibold",children:O.title}),O.featured&&e.jsx(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($g,{className:"h-4 w-4"}):e.jsx(Ca,{className:"h-4 w-4"})}),O.status==="published"&&e.jsx($,{variant:"ghost",size:"sm",asChild:!0,children:e.jsx("a",{href:`/blog/${O.slug}`,target:"_blank",rel:"noreferrer",children:e.jsx(Fr,{className:"h-4 w-4"})})}),e.jsx($,{variant:"ghost",size:"sm",className:"text-destructive",onClick:()=>I(O.id),children:e.jsx(Hn,{className:"h-4 w-4"})})]})]})},O.id))]}),e.jsx(Xt,{value:"comments",className:"mt-4 space-y-3",children:y.length===0?e.jsx(je,{children:e.jsx(Ie,{className:"py-12 text-center text-sm text-muted-foreground",children:"No comments yet."})}):y.map(O=>{var U,W,V;return e.jsx(je,{children:e.jsxs(Ie,{className:"flex flex-wrap items-start gap-4 py-4",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"text-sm font-semibold",children:[((U=O.author)==null?void 0:U.name)||((W=O.author)==null?void 0:W.email)||"Member",e.jsxs("span",{className:"ml-2 font-normal text-muted-foreground",children:["on “",((V=O.post)==null?void 0:V.title)||"article","”"]})]}),e.jsx("p",{className:"mt-1 whitespace-pre-wrap text-sm text-muted-foreground",children:O.body})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[O.is_hidden&&e.jsx($e,{variant:"secondary",children:"hidden"}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>R(O),children:O.is_hidden?e.jsx(Ca,{className:"h-4 w-4"}):e.jsx($g,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"sm",className:"text-destructive",onClick:()=>D(O.id),children:e.jsx(Hn,{className:"h-4 w-4"})})]})]})},O.id)})})]})]})}const Phr=["What was it like working together?","What moment stood out the most?","Would you recommend me to a friend?"],C5="#16283a",sTt="#f7f5f1";function nls(s){var O,U,W,V,G;const t=s.accentColor||"#c9a24b",n=(O=s.videoPrompts)!=null&&O.length?s.videoPrompts:Phr,r=((U=s.agent)==null?void 0:U.name)||"Your agent",a=((V=(W=s.agent)==null?void 0:W.name)==null?void 0:V.split(" ")[0])||"them",[i,l]=j.useState("none"),[o,c]=j.useState(s.recipientName||""),[d,u]=j.useState(5),[h,m]=j.useState(0),[f,g]=j.useState(""),[x,y]=j.useState(!1),[v,b]=j.useState(!1),[w,S]=j.useState(null),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(Y,X)=>{if(!o.trim()){S("Please add your name first.");return}y(!0),S(null);try{const ae={action:"submit",...s.payloadBase,reviewer_name:o,rating:d,review_text:f||void 0,is_private:!!X};if(Y){const te=Y.type||"video/webm",{data:J,error:ce}=await q.functions.invoke("review-public",{body:{action:"video_upload_url",...s.payloadBase,video_type:te}});if(ce||!(J!=null&&J.path)||!(J!=null&&J.token))throw new Error((J==null?void 0:J.error)||(ce==null?void 0:ce.message)||"Could not start the video upload");const{error:_e}=await q.storage.from(J.bucket||"agent-uploads").uploadToSignedUrl(J.path,J.token,Y,{contentType:te});if(_e)throw new Error(`Video upload failed: ${_e.message}`);ae.video_path=J.path,ae.video_type=te}const{data:le,error:ne}=await q.functions.invoke("review-public",{body:ae});if(ne||le!=null&&le.error)throw new Error((le==null?void 0:le.error)||(ne==null?void 0:ne.message)||"Something went wrong");b(!0)}catch(ae){S(ae.message)}finally{y(!1)}},[s.payloadBase,o,d,f]);return v?e.jsx("div",{className:"min-h-screen flex items-center justify-center p-5 sm:p-6",style:{background:sTt},children:e.jsxs("div",{className:"text-center max-w-md w-full",children:[e.jsx("div",{className:"w-16 h-16 sm:w-20 sm:h-20 rounded-full mx-auto mb-5 sm:mb-6 flex items-center justify-center",style:{background:`${t}1f`},children:e.jsx(Vr,{className:"h-9 w-9 sm:h-10 sm:w-10",style:{color:t}})}),e.jsx("h1",{className:"text-3xl sm:text-4xl font-serif mb-3",style:{color:C5},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:C5},children:[s.ctaLabel||"Visit my website"," ",e.jsx(Qa,{className:"h-4 w-4"})]})]})}):e.jsxs("div",{className:"min-h-screen",style:{background:sTt},children:[e.jsxs("header",{className:"relative overflow-hidden",style:{background:C5},children:[s.heroImageUrl&&e.jsx("img",{src:s.heroImageUrl,alt:"",className:"absolute inset-0 w-full h-full object-cover opacity-25"}),e.jsx("div",{className:"absolute inset-0",style:{background:`radial-gradient(circle at 50% 0%, ${t}33, transparent 62%)`}}),e.jsxs("div",{className:"relative max-w-2xl mx-auto px-4 sm:px-6 pt-12 sm:pt-14 pb-14 sm:pb-16 text-center",children:[((G=s.agent)==null?void 0:G.avatar_url)&&e.jsx("img",{src:s.agent.avatar_url,alt:r,className:"w-20 h-20 sm:w-24 sm:h-24 rounded-full object-cover mx-auto mb-5 shadow-2xl",style:{border:`3px solid ${t}`}}),e.jsx("p",{className:"uppercase tracking-[0.25em] sm:tracking-[0.3em] text-[10px] sm:text-[11px] mb-3",style:{color:t},children:"Client Experience"}),e.jsx("h1",{className:"text-3xl sm:text-4xl md:text-5xl font-serif text-white leading-tight break-words",children:s.headline||`Share your experience with ${r}`}),e.jsx("p",{className:"text-white/70 mt-4 leading-relaxed max-w-lg mx-auto text-sm sm:text-base",children:s.subheadline||"Thank you for your trust. It takes less than 60 seconds — and it helps other families find the right agent."})]}),e.jsx("div",{className:"h-px w-full",style:{background:`linear-gradient(90deg,transparent,${t},transparent)`}})]}),e.jsxs("main",{className:"relative z-10 max-w-2xl mx-auto px-4 -mt-9 pb-[max(4rem,env(safe-area-inset-bottom))]",children:[e.jsxs("div",{className:"bg-white rounded-3xl shadow-xl border border-slate-200/70 px-4 sm:px-6 py-6 sm:py-7 text-center",children:[e.jsx("p",{className:"text-sm font-medium text-slate-500 mb-4",children:"How was your experience?"}),e.jsx("div",{className:"flex justify-center gap-1 sm:gap-1.5",onMouseLeave:()=>m(0),children:[1,2,3,4,5].map(Y=>e.jsx("button",{onClick:()=>u(Y),onMouseEnter:()=>m(Y),"aria-label":`${Y} stars`,className:"p-0.5 transition-transform hover:scale-125 active:scale-95",children:e.jsx(ei,{className:"h-9 w-9 sm:h-10 sm:w-10 transition-colors",style:{fill:Y<=(h||d)?t:"transparent",color:Y<=(h||d)?t:"#cbd5e1"}})},Y))})]}),i==="none"&&P&&e.jsxs("div",{className:"grid gap-4 mt-6",children:[e.jsxs("div",{className:"bg-white rounded-3xl p-6 shadow-xl border border-slate-200/70 text-center",children:[e.jsx("h2",{className:"text-2xl font-serif",style:{color:C5},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(CX,{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(CX,{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(CX,{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(CX,{accent:t,icon:e.jsx(ua,{className:"h-6 w-6",style:{color:t}}),title:"Record a quick video",subtitle:"60 seconds, right from your phone",onClick:()=>l("video")}),e.jsx(CX,{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:Y=>c(Y.target.value),placeholder:"Jane Smith",className:"mt-1.5 h-11"})]}),i==="write"&&e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-slate-700",children:"Your review"}),e.jsx(Ls,{value:f,onChange:Y=>g(Y.target.value),rows:6,placeholder:"Share a few words about your experience...",className:"mt-1.5"}),e.jsxs("div",{className:"rounded-2xl p-4 mt-4",style:{background:`${t}12`},children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide mb-2",style:{color:C5},children:"Need a nudge?"}),e.jsx("ul",{className:"text-sm text-slate-600 space-y-1.5",children:n.map(Y=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx(h2,{className:"h-3.5 w-3.5 mt-1 shrink-0",style:{color:t}}),Y]},Y))})]})]}),i==="private"&&e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-slate-700",children:"What could have been better?"}),e.jsx(Ls,{value:f,onChange:Y=>g(Y.target.value),rows:6,placeholder:"Tell them what happened...",className:"mt-1.5"}),e.jsx("p",{className:"text-xs text-slate-500 mt-2",children:"This message is private. It will not appear on any public page or website."})]}),i==="video"&&e.jsxs("div",{children:[e.jsxs("div",{className:"rounded-2xl p-4 mb-5",style:{background:`${t}12`},children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide mb-2",style:{color:C5},children:"Not sure what to say? Try these"}),e.jsx("ul",{className:"text-sm text-slate-600 space-y-1.5",children:n.map(Y=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx(h2,{className:"h-3.5 w-3.5 mt-1 shrink-0",style:{color:t}}),Y]},Y))})]}),e.jsx(FT,{maxDurationSeconds:60,showBackgroundPicker:!1,onRecordingComplete:Y=>D(Y),onError:Y=>S(Y)})]}),w&&e.jsx("p",{className:"text-sm text-red-600",children:w}),e.jsxs("div",{className:"flex flex-col-reverse sm:flex-row gap-2 sm:gap-3 sm:items-center",children:[e.jsxs($,{variant:"ghost",onClick:()=>l("none"),disabled:x,className:"text-slate-500",children:[e.jsx(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:C5,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:C5,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 CX({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:C5},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:C5},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 Ihr(){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(nls,{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 uhe({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 Lhr(){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-12 sm:py-16 px-4 sm:px-6 text-center",children:[((d=t.agent)==null?void 0:d.avatar_url)&&e.jsx("img",{src:t.agent.avatar_url,alt:i,className:"w-20 h-20 sm:w-24 sm:h-24 rounded-full object-cover mx-auto mb-5 border-4 border-[#c9a24b]/60 shadow-xl"}),e.jsx("h1",{className:"text-3xl sm:text-4xl font-serif break-words",children:i}),((u=t.agent)==null?void 0:u.title)&&e.jsx("p",{className:"text-white/70 mt-1 text-sm sm:text-base",children:t.agent.title}),e.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-x-3 gap-y-1 mt-5",children:[e.jsx(uhe,{rating:Math.round(t.stats.avg_rating),size:"h-5 w-5 sm:h-6 sm:w-6"}),e.jsx("span",{className:"text-xl sm:text-2xl font-semibold",children:t.stats.avg_rating}),e.jsxs("span",{className:"text-white/60 text-sm sm:text-base",children:["· ",t.stats.total_reviews," review",t.stats.total_reviews!==1?"s":""]})]}),t.settings.intro_text&&e.jsx("p",{className:"max-w-xl mx-auto mt-5 text-white/80 leading-relaxed text-sm sm:text-base",children:t.settings.intro_text}),e.jsx("a",{href:`/reviews/${t.settings.slug}/new`,className:"inline-flex items-center justify-center gap-2 mt-7 sm:mt-8 w-full sm:w-auto max-w-xs px-7 py-3.5 rounded-full bg-[#c9a24b] text-[#16283a] font-semibold shadow-lg transition-transform hover:scale-[1.03]",children:"Leave a review"})]}),e.jsxs("main",{className:"max-w-4xl mx-auto px-4 py-10 sm:py-12 space-y-12 sm:space-y-14",children:[l.length>0&&e.jsxs("section",{children:[e.jsxs("h2",{className:"text-xl sm:text-2xl font-serif text-[#2a4c64] mb-5 sm:mb-6 flex items-center gap-2",children:[e.jsx(ua,{className:"h-6 w-6 text-[#c9a24b]"})," Video testimonials"]}),e.jsx("div",{className:"grid sm:grid-cols-2 gap-5 sm:gap-6",children:l.map(h=>e.jsxs("figure",{className:"bg-white rounded-2xl overflow-hidden shadow-sm border border-slate-200",children:[e.jsx("video",{src:h.video_url,controls:!0,playsInline:!0,preload:"metadata",className:"w-full aspect-video bg-black"}),e.jsxs("figcaption",{className:"p-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"font-medium text-[#2a4c64]",children:h.reviewer_name}),h.rating&&e.jsx(uhe,{rating:h.rating})]}),h.review_text&&e.jsx("p",{className:"text-sm text-slate-600 mt-2",children:h.review_text})]})]},h.id))})]}),o.length>0&&e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl sm:text-2xl font-serif text-[#2a4c64] mb-5 sm:mb-6",children:"Google reviews"}),e.jsx("div",{className:"grid sm:grid-cols-2 gap-5 sm:gap-6",children:o.map(h=>{var m,f;return e.jsxs("blockquote",{className:"bg-white rounded-2xl p-5 sm:p-6 shadow-sm border border-slate-200 flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[h.rating&&e.jsx(uhe,{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(IA,{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(OJ,{className:"h-3.5 w-3.5"})," Response from ",(f=(m=t.agent)==null?void 0:m.name)==null?void 0:f.split(" ")[0]]}),e.jsx("p",{className:"text-sm text-slate-600",children:h.reply_text})]})]},h.id)})})]}),c.length>0&&e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl sm:text-2xl font-serif text-[#2a4c64] mb-5 sm:mb-6",children:"Kind words"}),e.jsx("div",{className:"grid sm:grid-cols-2 gap-5 sm:gap-6",children:c.map(h=>e.jsxs("blockquote",{className:"bg-white rounded-2xl p-5 sm:p-6 shadow-sm border border-slate-200",children:[h.rating&&e.jsx(uhe,{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 Rhr(){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(nls,{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 Dhr=[{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"}],jUe=[{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 NUe(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 Fhr=[{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"}],Ohr=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)}`},zhr=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}},jR=(s,t)=>{const{r:n,g:r,b:a}=zhr(s);return`rgba(${n},${r},${a},${t})`},Bhr=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}),$hr=(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)},SAe=(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()}…`},nTt=(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()},qhr=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 Vhr({review:s,open:t,onOpenChange:n}){var ne;const r=Xn(),{data:a}=N6e(),{data:i=[]}=prt(),{timezone:l}=xK(),o=ZHt(),[c,d]=j.useState(!1),[u,h]=j.useState(null),[m,f]=j.useState(null),[g,x]=j.useState("brand"),[y,v]=j.useState(""),[b,w]=j.useState(!1),[S,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,...Fhr],[E]),P=I.find(te=>te.key===g)||E,R=Ohr(a==null?void 0:a.phone),D=(s==null?void 0:s.rating)??5,O=((ne=s==null?void 0:s.reviewer_name)==null?void 0:ne.trim())||"A happy client",U=((s==null?void 0:s.review_text)||"").trim();j.useEffect(()=>{t||(f(null),w(!1),h(null))},[t]),j.useEffect(()=>{t&&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);v(ce.join(` `))},[t,s==null?void 0:s.id,b,R]);const W=j.useCallback(async()=>{if(s){d(!0);try{const te=document.createElement("canvas");te.width=1080,te.height=1080;const J=te.getContext("2d");if(!J)throw new Error("Canvas unavailable");const ce=J.createLinearGradient(0,0,1080,1080);ce.addColorStop(0,P.base),ce.addColorStop(1,jR(P.base,.86)),J.fillStyle=ce,J.fillRect(0,0,1080,1080),J.save();const _e=J.createRadialGradient(880,180,40,880,180,520);_e.addColorStop(0,jR(P.accent,.22)),_e.addColorStop(1,jR(P.accent,0)),J.fillStyle=_e,J.fillRect(0,0,1080,1080),J.restore(),J.fillStyle=P.accent,J.fillRect(72,96,72,3),J.font="600 22px Arial, sans-serif",J.textBaseline="middle";let he=164;const ue=s.source==="google"?"GOOGLE REVIEW":s.source==="video"?"CLIENT VIDEO REVIEW":"CLIENT REVIEW";for(const Ae of ue)J.fillText(Ae,he,98),he+=J.measureText(Ae).width+8;J.fillStyle=P.accent;for(let Ae=0;Ae=ve.length-2||Ae===30))break}Le.length===0&&(J.font="500 30px Georgia, serif",Le=nTt(J,ve,900,10),Se=30),J.fillStyle="#F8FAFC",J.font=`500 ${Se}px Georgia, serif`;let Fe=400;Le.forEach(Ae=>{J.fillText(Ae,90,Fe),Fe+=Se*1.35}),J.fillStyle=P.accent,J.fillRect(90,Fe+30,56,3),J.fillStyle="rgba(248,250,252,0.92)",J.font="600 30px Arial, sans-serif",J.fillText(SAe(J,`— ${O}`,860),168,Fe+16);const ke=J.createLinearGradient(0,880,0,1080);ke.addColorStop(0,jR(P.base,.96)),ke.addColorStop(1,P.base),J.fillStyle=ke,J.fillRect(0,880,1080,200),J.fillStyle=P.accent,J.fillRect(0,880,1080,3);const 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=jR(P.accent,.18),J.fill(),J.lineWidth=6,J.strokeStyle=P.accent,J.stroke(),J.clip();let Ne=!1;if(a!=null&&a.headshotUrl)try{const Ae=await Bhr(a.headshotUrl);$hr(J,Ae,64,920,120,120),Ne=!0}catch{Ne=!1}Ne||(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(SAe(J,Be,R?430:820),212,970),a!=null&&a.brokerageName&&(J.fillStyle=P.accent,J.font="600 20px Arial, sans-serif",J.fillText(SAe(J,a.brokerageName.toUpperCase(),R?430:820),212,1008)),R&&(J.textAlign="right",J.fillStyle=jR(P.accent,.9),J.font="600 16px Arial, sans-serif",J.fillText("CALL · TEXT",1016,958),J.fillStyle="#F8FAFC",J.font="600 38px Arial, sans-serif",J.fillText(R,1016,1008)),f(te.toDataURL("image/png"))}catch(te){console.error("Generate review graphic error",te),re.error("Could not generate graphic")}finally{d(!1)}}},[s,P,a,R,U,D,O]);j.useEffect(()=>{if(!t||!s)return;const te=setTimeout(()=>{W()},250);return()=>clearTimeout(te)},[t,s==null?void 0:s.id,g,a==null?void 0:a.brandColor,a==null?void 0:a.name]);const V=async()=>{var ve;if(!m)throw new Error("No graphic yet");const{data:te}=await q.auth.getUser(),J=(ve=te.user)==null?void 0:ve.id;if(!J)throw new Error("Not signed in");const ce=await(await fetch(m)).blob(),_e=`review-social/${J}/${crypto.randomUUID()}.png`,{error:he}=await q.storage.from("agent-uploads").upload(_e,ce,{contentType:"image/png",upsert:!0});if(he)throw he;const{data:ue}=q.storage.from("agent-uploads").getPublicUrl(_e);return{uid:J,publicUrl:ue.publicUrl}},G=()=>{if(!m)return;const te=document.createElement("a");te.href=m,te.download=`review-${(s==null?void 0:s.id)||"graphic"}.png`,te.click(),re.success("Downloaded!")},Y=async()=>{try{await navigator.clipboard.writeText(y),re.success("Caption copied")}catch{re.error("Copy not supported in this browser")}},X=async()=>{if(m){h("studio");try{const{publicUrl:te}=await V();sessionStorage.setItem("social-studio-seed",JSON.stringify({mediaUrl:te,mediaType:"image",caption:y,source:"other",sourceRef:s==null?void 0:s.id})),n(!1),r("/social-studio"),re.success("Draft ready in Social Studio")}catch(te){console.error("Push to Social Studio failed",te),re.error("Could not send to Social Studio")}finally{h(null)}}},ae=async te=>{if(m){if(S.length===0){re.error("Choose at least one account to post to.");return}h(te);try{const{uid:J,publicUrl:ce}=await V(),_e=te==="schedule"?OTe(qhr(l),l).toISOString():null,{data:he,error:ue}=await q.from("social_posts").insert({user_id:J,caption:y.trim()||null,media_type:"image",media_urls:[ce],source:"other",status:te==="schedule"?"scheduled":"publishing",scheduled_for:_e,timezone:l}).select("id").single();if(ue)throw ue;const ve=i.filter(Se=>S.includes(Se.id)).map(Se=>({post_id:he.id,user_id:J,social_account_id:Se.id,platform:Se.platform,caption_override:null,status:"pending"})),{error:Ee}=await q.from("social_post_targets").insert(ve);if(Ee)throw Ee;if(te==="now"){const{data:Se,error:Le}=await q.functions.invoke("social-publish-post",{body:{post_id:he.id}});if(Le)throw Le;const Fe=Se==null?void 0:Se.status;Fe==="failed"?re.error("Publishing failed. Check the Queue tab in Social Studio."):Fe==="partial"?re.warning("Some accounts failed. Check the Queue tab to retry."):re.success("Posted to your accounts.")}else re.success("Scheduled for tomorrow at 10:00 AM");o(),n(!1)}catch(J){console.error("Review post failed",J),re.error(J instanceof Error?J.message:"Could not create the post")}finally{h(null)}}},le=te=>A(J=>J.includes(te)?J.filter(ce=>ce!==te):[...J,te]);return e.jsx(zs,{open:t,onOpenChange:n,children:e.jsx(Os,{className:"!max-w-[900px] !w-[calc(100vw-2rem)] !p-0 !gap-0 !block overflow-hidden",style:{maxHeight:"calc(100vh - 2rem)"},children:e.jsxs("div",{className:"flex max-h-[calc(100vh-2rem)] flex-col",children:[e.jsxs(Us,{className:"shrink-0 border-b px-5 pb-3 pt-5 text-left",children:[e.jsx(Bs,{className:"text-lg",children:"Share this review"}),e.jsx(Pr,{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:Y,children:[e.jsx(Ha,{className:"h-3.5 w-3.5"})," Copy"]})]}),e.jsx(Ls,{value:y,onChange:te=>{v(te.target.value),w(!0)},rows:11,className:"min-h-[220px] text-sm",placeholder:"Your caption…"}),e.jsxs("div",{className:"mt-4",children:[e.jsx("p",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Post to"}),i.length===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:"No social accounts connected yet — you can still download the graphic or open Social Studio."}):e.jsx("div",{className:"flex flex-wrap gap-2",children:i.map(te=>{const J=O4(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(xi,{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(qg,{className:"h-3.5 w-3.5"}),"Open in Social Studio"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>void ae("schedule"),disabled:!m||u!==null||i.length===0,className:"gap-1.5",children:[u==="schedule"?e.jsx(Ct,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Cu,{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(Kr,{className:"h-3.5 w-3.5"}),"Post now"]})]})]})})})}function rTt({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 aTt(s){return s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,"")}function Hhr(){var Xs,ds,Ss,yn,Js;const{user:s,rolesLoading:t}=bs(),[n,r]=j.useState([]),[a,i]=j.useState([]),[l,o]=j.useState(!0),[c,d]=j.useState({slug:"",intro_text:"",is_published:!1,show_google_reviews:!0,show_video_reviews:!0,headline:"",subheadline:"",accent_color:"#c9a24b",hero_image_url:"",video_prompts:"",thank_you_title:"",thank_you_message:"",cta_label:"",cta_url:"",allow_public_submissions:!0,protection_enabled:!1,protection_threshold:3,hide_google_below_threshold:!1,private_feedback_title:"",private_feedback_message:"",widget_enabled:!1,widget_layout:"carousel",widget_theme:"light",widget_accent:"",widget_title:""}),[u,h]=j.useState(!1),[m,f]=j.useState(!1),[g,x]=j.useState(""),[y,v]=j.useState("email"),[b,w]=j.useState(null),[S,A]=j.useState({}),[E,I]=j.useState(""),[P,R]=j.useState(""),[D,O]=j.useState(""),[U,W]=j.useState("closing_day"),[V,G]=j.useState(!1),[Y,X]=j.useState(null),[ae,le]=j.useState(null),[ne,te]=j.useState(""),[J,ce]=j.useState(!1),[_e,he]=j.useState(!1),[ue,ve]=j.useState(!1),[Ee,Se]=j.useState(null),Le=Ee?Ee.connected:null,[Fe,ke]=gc(),Be=j.useRef(!1),Ne=j.useCallback(async()=>{const{data:Ut,error:hn}=await q.functions.invoke("google-business-oauth",{body:{action:"get_status"}});if(hn||Ut!=null&&Ut.error){Se({connected:!1,email:null,apiAccessPending:!1,hasRefreshToken:!1,connectedAt:null,locations:[]});return}Se(Ut)},[]),Ae=j.useCallback(async()=>{if(!s)return;o(!0);const[{data:Ut},{data:hn},{data:hr}]=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(Ut??[]),i(hn??[]),Ne(),hr){const Rs=Array.isArray(hr.video_prompts)?hr.video_prompts:[];d({id:hr.id,slug:hr.slug??"",intro_text:hr.intro_text??"",is_published:hr.is_published,show_google_reviews:hr.show_google_reviews,show_video_reviews:hr.show_video_reviews,headline:hr.headline??"",subheadline:hr.subheadline??"",accent_color:hr.accent_color??"#c9a24b",hero_image_url:hr.hero_image_url??"",video_prompts:Rs.join(` `),thank_you_title:hr.thank_you_title??"",thank_you_message:hr.thank_you_message??"",cta_label:hr.cta_label??"",cta_url:hr.cta_url??"",allow_public_submissions:hr.allow_public_submissions??!0,protection_enabled:hr.protection_enabled??!1,protection_threshold:hr.protection_threshold??3,hide_google_below_threshold:hr.hide_google_below_threshold??!1,private_feedback_title:hr.private_feedback_title??"",private_feedback_message:hr.private_feedback_message??"",widget_enabled:hr.widget_enabled??!1,widget_layout:hr.widget_layout??"carousel",widget_theme:hr.widget_theme??"light",widget_accent:hr.widget_accent??"",widget_title:hr.widget_title??""})}else{const{data:Rs}=await q.from("profiles").select("name").eq("id",s.id).single(),jr=aTt((Rs==null?void 0:Rs.name)??"");d(kr=>({...kr,slug:kr.slug||jr}))}o(!1)},[s,Ne]);j.useEffect(()=>{Ae()},[Ae]),j.useEffect(()=>{if(Be.current)return;const Ut=Fe.get("google"),hn=Fe.get("google_error");if(!Ut&&!hn)return;if(Be.current=!0,hn)re.error(hn==="access_denied"?"Google connection was cancelled":hn==="invalid_state"?"That connection link expired — please try again":hn==="not_configured"?"Google Business credentials are not configured yet":hn==="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: ${hn}`,hn==="missing_business_permission"?{duration:1e4}:void 0);else{const Rs=Number(Fe.get("locations")??0);re.success(Fe.get("google_pending")?"Google connected — review access is still pending Google approval":`Google Business Profile connected${Rs?` (${Rs} location${Rs>1?"s":""})`:""}`)}const hr=new URLSearchParams(Fe);["google","google_error","google_pending","locations"].forEach(Rs=>hr.delete(Rs)),ke(hr,{replace:!0}),Ne()},[Fe,ke,Ne]);const Ce=async()=>{ve(!0);const{data:Ut,error:hn}=await q.functions.invoke("google-business-oauth",{body:{action:"get_auth_url",returnPath:"/apps/reviews"}});if(hn||Ut!=null&&Ut.error||!(Ut!=null&&Ut.authUrl))return ve(!1),re.error((Ut==null?void 0:Ut.error)||(hn==null?void 0:hn.message)||"Could not start Google connection");window.location.href=Ut.authUrl},Ve=async()=>{const{error:Ut}=await q.functions.invoke("google-business-oauth",{body:{action:"disconnect"}});if(Ut)return re.error("Could not disconnect");re.success("Google Business Profile disconnected"),Ne()},[ze,qe]=j.useState(!1),dt=async()=>{qe(!0);const{data:Ut,error:hn}=await q.functions.invoke("google-business-oauth",{body:{action:"rescan_locations"}});if(qe(!1),hn||Ut!=null&&Ut.error)return re.error((Ut==null?void 0:Ut.error)||(hn==null?void 0:hn.message)||"Could not check Google");(Ut==null?void 0:Ut.success)===!1||!(Ut!=null&&Ut.locationsCount)?re.error((Ut==null?void 0:Ut.message)||"No business locations were found on this Google account.",{duration:1e4}):re.success(Ut.message),Ne()},Xe=j.useMemo(()=>{const Ut=n.filter($n=>$n.status!=="hidden"),hn=Ut.filter($n=>$n.rating),hr=hn.length?hn.reduce(($n,kn)=>$n+(kn.rating??0),0)/hn.length:0,Rs=a.filter($n=>["sent","reminded","clicked"].includes($n.status)).length,jr=a.filter($n=>$n.status==="completed").length,kr=a.length?Math.round(jr/a.length*100):0;return{avg:Math.round(hr*10)/10,total:Ut.length,pending:Rs,responseRate:kr,newCount:n.filter($n=>$n.status==="new").length}},[n,a]),at=async(Ut,hn)=>{const{error:hr}=await q.from("review_responses").update({status:hn}).eq("id",Ut);if(hr)return re.error(hr.message);r(Rs=>Rs.map(jr=>jr.id===Ut?{...jr,status:hn}:jr))},rt=async Ut=>{const{error:hn}=await q.from("review_responses").update({is_pinned:!Ut.is_pinned}).eq("id",Ut.id);if(hn)return re.error(hn.message);r(hr=>hr.map(Rs=>Rs.id===Ut.id?{...Rs,is_pinned:!Ut.is_pinned}:Rs))},Ke=async Ut=>{const hn=!Ut.in_widget,{error:hr}=await q.from("review_responses").update({in_widget:hn}).eq("id",Ut.id);if(hr)return re.error(hr.message);r(Rs=>Rs.map(jr=>jr.id===Ut.id?{...jr,in_widget:hn}:jr))},Je=async()=>{if(!s)return;if(!c.slug)return re.error("Choose a slug for your page");h(!0);const Ut={user_id:s.id,slug:aTt(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(hr=>hr.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:hn}=c.id?await q.from("agent_review_page_settings").update(Ut).eq("id",c.id):await q.from("agent_review_page_settings").insert(Ut);if(h(!1),hn)return re.error(hn.message.includes("unique")?"That slug is taken — try another":hn.message);re.success(c.is_published?"Your reviews page is live":"Settings saved"),Ae()},pt=async()=>{const hn=g.split(` `).map(kr=>kr.trim()).filter(Boolean).map(kr=>{const[$n,kn,Fn]=kr.split(",").map(bn=>bn.trim());return{name:$n,email:kn,phone:Fn}}).filter(kr=>kr.email||kr.phone);if(hn.length===0)return re.error("Add at least one recipient (Name, email, phone — one per line)");if(y==="my_phone"&&!hn.some(kr=>kr.phone))return re.error("Add a mobile number for each person you want to text");G(!0);const{data:hr,error:Rs}=await q.functions.invoke("review-request-send",{body:{recipients:hn,channel:y,message:E||void 0,subject:P||void 0,sms_body:D||void 0}});if(G(!1),Rs||hr!=null&&hr.error)return re.error((hr==null?void 0:hr.error)||(Rs==null?void 0:Rs.message)||"Send failed");if(y==="my_phone"){const kr=hr.prepared??[];if(kr.length===0)return re.error("No mobile numbers to text");A({}),w(kr),f(!1),x(""),Ae();return}const jr=(hr.results??[]).filter(kr=>kr.ok).length;re.success(`${jr} review request${jr!==1?"s":""} sent`),f(!1),x(""),Ae()},gt=(Ut,hn)=>{const Rs=/iPhone|iPad|iPod|Macintosh/.test(navigator.userAgent)?"&":"?";window.location.href=`sms:${Ut.phone}${Rs}body=${encodeURIComponent(Ut.body)}`,A(jr=>({...jr,[hn]:!0}))},ss=async()=>{if(!(!Y||!ne.trim())){if(ce(!0),Y.source==="google"){const{data:Ut,error:hn}=await q.functions.invoke("google-reviews-sync",{body:{action:"reply",review_id:Y.id,text:ne.trim()}});if(hn||Ut!=null&&Ut.error)return ce(!1),re.error((Ut==null?void 0:Ut.error)||(hn==null?void 0:hn.message)||"Reply failed")}else{const{error:Ut}=await q.from("review_responses").update({reply_text:ne.trim(),replied_at:new Date().toISOString()}).eq("id",Y.id);if(Ut)return ce(!1),re.error(Ut.message)}ce(!1),re.success("Reply posted"),X(null),te(""),Ae()}},Yt=async()=>{he(!0);const{data:Ut,error:hn}=await q.functions.invoke("google-reviews-sync",{body:{action:"sync_mine"}});if(he(!1),hn||Ut!=null&&Ut.error)return re.error((Ut==null?void 0:Ut.error)||(hn==null?void 0:hn.message)||"Sync failed");if(Ut!=null&&Ut.needsReconnect)return re.error("Your Google connection expired — click Connect Google to reconnect");re.success(`Synced ${(Ut==null?void 0:Ut.synced)??0} reviews`),Ae()},ts=n.filter(Ut=>Ut.in_widget&&!Ut.is_private&&(Ut.status==="approved"||Ut.status==="featured")),Bt=`